/*************************************************
**************************************************
* JavaScript functions used in the shopping cart *
**************************************************
*************************************************/

var sep = '::';//Separator for item properties.
var itemSep = '##';//Separator for items.

/********************************************************
* 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(id,array,cookieName,quantity,option_id){
	array = array || photos;
	var newItem = array[id];
	if(newItem.payment_id != 0 && option_id != 0){
		option = paymentOptions[option_id].payment_option;
		price = paymentOptions[option_id].price;
	}
	else{
		option = photos[id].purchase_instruction;
		price = photos[id].item_price;
	}
	ref = newItem.photo_ref?newItem.photo_ref:id;
	name = newItem.caption;
	itemQuantity = quantity?quantity:1;//If quantity is passed in use that otherwise 1.

	existingData = unescape(readCookie(cookieName));
	
	var content = '';
	if(existingData != 'null' && existingData != '' && existingData != 'undefined'){
		var data = unescape(existingData).split(itemSep);
		
		var storage = new Array();
		storage[0] = '';
		var currentItemStored = 0;
		
		for(var i=0; i<data.length; i++){
			
			var item = data[i].split(sep);
			
			if(item[0] == id && item[3] == option){
				
				var currentItem = item[0]+sep+item[1]+sep+item[2]+sep+item[3]+sep+item[4]+sep+(parseInt(item[5], 10)+itemQuantity);
				storage[1] = currentItem;
				currentItemStored = 1;
				
			}
			else{
				if(storage[0] != ''){
					storage[0] = storage[0]+itemSep+data[i];
				}
				else{
					storage[0] = data[i];
				}
			}
		}
		
		if(currentItemStored && storage[0] != ''){
			content = storage[0]+itemSep+storage[1];
		}
		else if(storage[0] != ''){
			content = storage[0]+itemSep+id+sep+ref+sep+name+sep+option+sep+price+sep+itemQuantity;
		}
		else{
			content = storage[1];
		}
	}
	else{
		content = id+sep+ref+sep+name+sep+option+sep+price+sep+itemQuantity;
	}
	return setCookie(cookieName,content,7)
}

/***************************
* Deletes the named cookie *
***************************/
function deleteCookie(name){
	setCookie(name, '', -1);
}

/********************************** 
* Create payment and photo id data *
**********************************/
function purchaseItem(id,ref,name,option,price,quantity){
	this.id = id;
	this.ref = ref;
	this.name = name;
	this.option = option || name || ref;
	this.price = parseFloat(price).toFixed(2);
	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(itemSep);
		for(var i=0; i<data.length; i++){
			var item = data[i].split(sep);
			arrayOfItems[i] = new purchaseItem(item[0], item[1], item[2], item[3], item[4], item[5]);
		}
	}
}

/********************************************
* Takes the name of a cookie, gets the data *
* and returns the total number of items and *
* total price for the order.			    *
********************************************/
function getOrderDetails(name){
	getListOfDataInCookie(readCookie(name));
	data = {quantity:0,price:0};
	for(var item in arrayOfItems){
		data.quantity += parseInt(arrayOfItems[item].quantity);
	}
	data.price = orderTotal();
	return data;
}

/**
* Takes the name of a cookie and the ID of a link, gets the data 
* and displays the results in the html elements in the content 
* section. If there are no items then the link to the shopping cart 
* gets hidden.
*/
function dspOrderDetails(name,id){
	var data = getOrderDetails(name);
	$('#shopping-cart-total-quantity').html(data.quantity);
	$('#shopping-cart-total-price').html(data.price);
	if(data.quantity == 0 && id){
		$('#'+id).hide();
	}
}

/*****************************************
* Writes the arrayOfItems into a cookie, *
* named as the argument					 *
*****************************************/
function writeItemsArrayToCookie(name){
	var content = '';
	for(var j=0; j<arrayOfItems.length; j++){
		var item = '';
		item += arrayOfItems[j].id+ sep;
		item += arrayOfItems[j].ref+ sep;
		item += arrayOfItems[j].name+ sep;
		item += arrayOfItems[j].option+ sep;
		item += arrayOfItems[j].price+ sep;
		item += arrayOfItems[j].quantity;
		if(content == ''){
			content = item;
		}
		else{
			content = content+itemSep+item;
		}
	}
	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(cookieName, id, option, 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].option == option){
				arrayOfItems[i].quantity = quantity;
				break
			}
		}
		writeItemsArrayToCookie(cookieName);
	}
}

/***********************************************
* Removes an item from the arrayOfItems on the *
* page and writes the ammended array out to	   *
* the cookie								   *
***********************************************/
function removeItem(siteCode, row_num){
	arrayOfItems.splice(row_num,1);
	writeItemsArrayToCookie(siteCode);	
}

/**************************************
* 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;--change to arrayOfItems[i].price;
			price = 6.99;
		}*/		
		total = parseFloat(total) + parseFloat(totalPrice(arrayOfItems[i].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, siteCode, row_num){

	if(confirm(removeText)){
		removeItem(siteCode, row_num);
			
		// 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;
	}
}
