/*************************************************
**************************************************
* JavaScript functions used in the shopping cart *
**************************************************
*************************************************/


/********************************************************
* Writes data to a cookie, expiring in a number of days *
********************************************************/
function setCookie(name, content, days){
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	expires = date.toGMTString();
	document.cookie = name+'='+escape(content)+'; expires='+expires+'; path=/;';
	return (unescape(readCookie(name)) == content);
}

/******************************************
* Reads data from a cookie given the name *
******************************************/
function readCookie(name){
	var nameEQ = name+'=';
	var string = document.cookie.split(';');
	for(var i = 0;i < string.length;i++){
		var c = string[i];
		while(c.charAt(0) == ' '){
			c = c.substring(1, c.length);
		}
		if(c.indexOf(nameEQ) == 0){
			return c.substring(nameEQ.length,c.length);
		}
	}
}

/*****************************************************
* Adds an item to the cookie given the name of 		 *
* the form containing the price and quantity details *
*****************************************************/
function addItemToBasket(form){
	existingData = unescape(readCookie(form.site.value));
	var content = '';
	if(existingData != 'null' && existingData != '' && existingData != 'undefined'){
		var data = unescape(existingData).split('#');
		var storage = new Array();
		storage[0] = '';
		var currentItemStored = 0;
		for(var i=0; i<data.length; i++){
			var item = data[i].split(':');
			if(item[0] == form.item_number.value && item[1] == form.item_option.value){
				var currentItem = item[0]+':'+item[1]+':'+(parseInt(item[2], 10)+parseInt(form.quantity.value, 10));
				storage[1] = currentItem;
				currentItemStored = 1;
			}
			else{
				if(storage[0] != ''){
					storage[0] = storage[0]+'#'+data[i];
				}
				else{
					storage[0] = data[i];
				}
			}
		}
		if(currentItemStored && storage[0] != ''){
			content = storage[0]+'#'+storage[1];
		}
		else if(storage[0] != ''){
			content = storage[0]+'#'+form.item_number.value+':'+form.item_option.value+':'+form.quantity.value;
		}
		else{
			content = storage[1];
		}
	}
	else{
		content = form.item_number.value+':'+form.item_option.value+':'+form.quantity.value;
	}
	return setCookie(form.site.value,content,7)
}

/***************************
* Deletes the named cookie *
***************************/
function deleteCookie(name){
	setCookie(name, '', -1);
}

/********************************** 
* Create payment and photo id data *
**********************************/
function purchaseItem(photos_id, payment_id, quantity){
	this.id = photos_id;
	this.payment_id = payment_id;
	this.quantity = quantity;
}

/***************************************************************************
* Update the payment submission form with the price and item description    *
* When a user selects an option from the list                              *
***************************************************************************/
function updateCartValue(form,id) {
	form.item_option.value = id;
}

/* The array of items read from the cookie */
var arrayOfItems = null;

/*******************************************
* Takes string of data from the cookie and *
* reads it into the arrayOfItems		   *
*******************************************/
function getListOfDataInCookie(string){
	arrayOfItems = new Array();
	if(string != undefined){
		var data = unescape(string).split('#');
		for(var i=0; i<data.length; i++){
			var item = data[i].split(':');
			arrayOfItems[i] = new purchaseItem(item[0], item[1], item[2]);
		}
	}
}

/*****************************************
* Writes the arrayOfItems into a cookie, *
* named as the argument					 *
*****************************************/
function writeItemsArrayToCookie(name){
	var content = '';
	for(var j=0; j<arrayOfItems.length; j++){
		if(content == ''){
			content = arrayOfItems[j].id+':'+arrayOfItems[j].payment_id+':'+arrayOfItems[j].quantity;
		}
		else{
			content = content+'#'+arrayOfItems[j].id+':'+arrayOfItems[j].payment_id+':'+arrayOfItems[j].quantity;
		}
	}
	if(content != ''){
		setCookie(name,content,7)
	}
	else{
		deleteCookie(name)
	}
}

/*********************************************
* Updates the quantity of an item stored	 *
* in the array on the page and in the cookie *
*********************************************/
function updateQuantity(form, id, payment_id, quantity){
	if(isPositive(quantity) && isInteger(quantity)){
		if(quantity == ''){quantity = 0;}
		for(var i=0; i<arrayOfItems.length; i++){
			if(arrayOfItems[i].id == id && arrayOfItems[i].payment_id == payment_id){
				arrayOfItems[i].quantity = quantity;
				break
			}
		}
		writeItemsArrayToCookie(form.site.value);
	}
}

/***********************************************
* Removes an item from the arrayOfItems on the *
* page and writes the ammended array out to	   *
* the cookie								   *
***********************************************/
function removeItem(form, id, payment_id){
	for(var i=0; i<arrayOfItems.length; i++){
		if(arrayOfItems[i].id == id && arrayOfItems[i].payment_id == payment_id){
			for(var j=i+1; j<arrayOfItems.length; j++){
				arrayOfItems[i].id = arrayOfItems[j].id
				arrayOfItems[i].payment_id = arrayOfItems[j].payment_id
				arrayOfItems[i].quantity = arrayOfItems[j].quantity
				i++;
			}
			arrayOfItems.pop();
		}
	}
	try{
		// For pages using Transitional DTD
		writeItemsArrayToCookie(form.site.value);
	}
	catch(e){
		// For pages using Strict DTD
		var site = document.forms[form].site.value;
		writeItemsArrayToCookie(site);
	}	
}

/**************************************
* Tests whether the input is a number *
**************************************/
function isNumber(input){
	var number = new Number(input);
	if(number.toString() == 'NaN'){
		return 0;
	}
	else{
		return 1;
	}
}

/****************************************
* Tests whether the input is an integer *
****************************************/
function isInteger(input){
	if(!isNumber(input)){
		return 0;
	}
	else{
		if(input.indexOf('.') != -1){
			return 0;
		}
		else{
			return 1;
		}
	}
}

/***********************************************
* Tests whether the input is a positive number *
***********************************************/
function isPositive(input){
	if(isNumber(input)){
		var number = new Number(input);
		if(number >= 0){
			return 1;
		}
		else{
			return 0;
		}
	}
	else{
		return 0;
	}
}

/*******************************************
* Returns the multiple of the input 	   *
* parameters as a float in monetary format *
*******************************************/
function totalPrice(price, quantity){
	return parseFloat(price*quantity).toFixed(2);
}

/********************************************************
* Returns the total price of all the items in the array *
********************************************************/
function orderTotal(){
	var total = 0;
	for(var i=0; i<arrayOfItems.length; i++){
		if(arrayOfItems[i].payment_id != 0){
			//payment_id = getArrayIndex(paymentOptions, arrayOfItems[i].payment_id);
			payment_id = arrayOfItems[i].payment_id;
			price = paymentOptions[payment_id].price;
		}
		else{
			//id = getArrayIndex(photos, arrayOfItems[i].id);
			id = arrayOfItems[i].id;
			price = photos[id].item_price;
		}
		total = parseFloat(total) + parseFloat(totalPrice(price, arrayOfItems[i].quantity));
	}
	return parseFloat(total).toFixed(2);
}

/***********************************
* Sets the innerHTML of an element *
* to the value passed in		   *
***********************************/
function setHTML(id, value){
	try{
		document.getElementById(id).innerHTML = value;
	}
	catch(e){
		document.all[id].innerHTML = value;
	}
}

/***********************************
* Gets the position in an array of *
* a particular ID				   *
***********************************/
function getArrayIndex(array, id){
	for(var i=0; i<array.length; i++){
		if(array[i].id == id){
			return i;
		}
	}
}

/*********************************
* Sets the opacity of an element *
* to the value passed in (0-100) *
*********************************/
function opacity(id, value){
	var objectStyle = null;
	try{
		objectStyle = document.getElementById(id).style;
	}
	catch(e){
		objectStyle = document.all[id].style;
	}
	objectStyle.filter = 'alpha(opacity='+value+')';
	objectStyle.opacity = value/100;
	objectStyle.MozOpacity = value/100;
	objectStyle.KhtmlOpacity = value/100;
}

/**********************************************
* Fades an element in by changing its opacity *
**********************************************/
function fadeIn(id, speed){
	var timer = 1;
	if(speed == null){
		speed = 6;
	}
	for(var i=0; i<=100; i++){
		setTimeout('opacity(\''+id+'\', '+i+')', (speed*timer));
		timer++;
	}
}

/***********************************************
* Fades an element out by changing its opacity *
***********************************************/
function fadeOut(id, speed){
	var timer = 1;
	if(speed == null){
		speed = 6;
	}
	for(var i=100; i>=0; i--){
		setTimeout('opacity(\''+id+'\', '+i+')', (speed*timer));
		timer++;
	}
}

/********************************************
*	Ajax functions to send data to server	*
********************************************/

var xmlHttp;

function ajaxFunction(){	
	try{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e){
		// Internet Explorer
		try{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e){
			try{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){
				alert("Your browser doesn\'t support AJAX!");
				return false;
			}
		}
	}	
}

/*******************************************************
* Runs when the 'Remove' button on the form is clicked *
*******************************************************/
function confirmRemove(removeText, form, row_num, photos_id){

	if(confirm(removeText)){
	
		removeItem(form, photos_id, arrayOfItems[parseInt(row_num)-1].payment_id);
			
		// To combat problem of empty text fields persisting when page reloads.	
		if(navigator.userAgent.indexOf('Safari') == -1){
			window.location.replace(unescape(window.location.href));
		}
		else{
			window.location.reload(false);	
		}
	}
}

/*********************************************************
* Tests whether the DIV whose ID is passed in is showing *
* i.e. whether its opacity is greater than zero			 *
*********************************************************/
function divShowing(divId){
	var opacity = null;
	
	try{
		for(var i=0; i<document.styleSheets[0].cssRules.length; i++){
			if(document.styleSheets[0].cssRules[i].selectorText == 'div#'+divId){
				opacity = document.styleSheets[0].cssRules[i].style.opacity;
			}
		}
	}
	catch(e){
		try{
			for(var i=0; i<document.styleSheets[0].cssRules.length; i++){
				if(document.styleSheets[0].cssRules[i].selectorText == 'div#'+divId){
					opacity = document.styleSheets[0].cssRules[i].style.MozOpacity;
				}
			}
		}
		catch(e){
			for(var i=0; i<document.styleSheets[0].rules.length; i++){
				if(document.styleSheets[0].rules[i].selectorText == 'DIV#'+divId){
					var opacityIEtmp = document.styleSheets[0].rules[i].style.filter;
					var array = opacityIEtmp.split('=');
					if(array.length > 1){
						var array2 = array[1].split(')');
						opacity = array2[0];
					}
				}
			}
		}
	}
	
	var inlineOpacity = null;
	var inlineOpacityMoz = null;
	var inlineOpacityIE = null;
	
	inlineOpacity = document.getElementById(divId).style.opacity;
	inlineOpacityMoz = document.getElementById(divId).style.MozOpacity;
	var inlineOpacityIEtmp = new String(document.getElementById(divId).style.filter);
	
	if(inlineOpacityIEtmp != 'undefined'){
		var array = inlineOpacityIEtmp.split('=');
		if(array.length > 1){
			var array2 = array[1].split(')');
			inlineOpacityIE = array2[0];
		}
	}
	if(opacity > 0 || inlineOpacity > 0 || inlineOpacityMoz > 0 || inlineOpacityIE > 0){
		return 1;
	}
	else{
		return 0;
	}
}
