var url_checkout = 'checkout.html';
var cookie_name = 'MadAboutPlants';


//Used on the final order page only. Exists in cart.js because it will use the toPrice func
function shippingUpdate(sel) {
  var total=0.00;
  total+=document.getElementById('subtotal').value*1;
  total+=sel.options[sel.selectedIndex].value*1;
  document.getElementById('total').value=toPrice(total);
}

// From string1~string2, gets string1
function getFirst(s) {
  return s.substr(0,s.indexOf("~"));
}

// From string1~string2, gets string2
function getSecond(s) {
  return s.substr(s.indexOf("~")+1,s.length);
}

function rnd() {
	rnd.today=new Date();
	rnd.seed=rnd.today.getTime();
        rnd.seed = (rnd.seed*9301+49297) % 233280;
        return rnd.seed/(233280.0);
};

function rand(number) {
        return Math.ceil(rnd()*number);
};

function toPrice(srcPrice) {
	/* This function returns srcPrice with two forced decimal places. */
	srcPrice = srcPrice + "";
	if (srcPrice.indexOf(".") < 0) {
		srcPrice += ".00";
	} else if ((srcPrice.length - 2) == srcPrice.substr(srcPrice.indexOf(".")).length) {
		srcPrice += "0";
	}
	return(srcPrice);
}

function roundReal(srcReal, decPlaces) {
	/* This function returns srcReal rounded to decPlaces decimal places. */
	decPlaces = (!decPlaces ? 2 : decPlaces);
	return(Math.round(srcReal * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces));
}

function updateTotal(formName, numInputs) {
	/* This function gets new quantities from the Buy page and updates the Total and calls writeCookie as a result. */
	var items = readCookie();
//    alert(document.cookie);
	var f = eval("document.forms['" + formName + "']");
	var total = 0;
	for (i = 0; i < numInputs; i++) {
	  if(eval("f.elements['itemKey" + i + "']") == undefined) continue;
		itemKey = eval("f.elements['itemKey" + i + "']").value;
		var itemCookieIndex=getItemIndex(itemKey, items);
		itemQuantity = parseInt(eval("f.elements['quantity" + i + "']").value);
		if (!(itemQuantity >= 0)) {
			itemQuantity = 0;
      eval("f.elements['quantity" + i + "']").value = 0;
		}
		items['itemQuantity'][itemCookieIndex] = itemQuantity;
		eval("f.elements['price" + i + "']").value = toPrice(items['itemPrice'][itemCookieIndex] * itemQuantity);
		total += (items['itemPrice'][itemCookieIndex] * itemQuantity);
		//alert("price"+items['itemPrice'][itemCookieIndex]+"qty"+itemQuantity);
	}
	f.elements['total'].value = toPrice(roundReal(total, 2));

	writeCookie(items,false);  //This was commented: but problems remembering quantities still exist.
}

function chgSpaces(srcString) {
	/* This function converts spaces to %20 and returns converted string. */
	var newString = "";
	for (i = 0; i <= srcString.length; i++) {
		if (srcString.charAt(i) == " ") {
			newString += "%20";
		} else {
			newString += srcString.charAt(i);
		}
	}
	return(newString);
}

function goBuy() {
	/* This function sends the items array as a string to checkout. */
	items = readCookie();
	itemString = chgSpaces(arrayToString(items));
	document.location = url_checkout+"?items=" + itemString;
}


function get_cookie(key) {
  var arg = key + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) {
      var endstr = document.cookie.indexOf(";", j);
      if (endstr == -1)
        endstr = document.cookie.length;
      return unescape(document.cookie.substring(j,endstr));
    }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0)
      break;
  }
  return false;
}

function readCookie() {
	/* This function reads the cookie and returns an items array. */
	cString = get_cookie(cookie_name); //James 2004-02-03 see above
	return(stringToArray(cString));
}

function writeCookie(items,showwarning) {
	/* This function writes the cookie from the items array. */
	var expiryDate = new Date();
	expiryDate.setTime(expiryDate.getTime()+(2*365*24*60*60*1000)); //Expire cookie in 2 years
	cString = cookie_name+"=" + arrayToString(items) + "; expires="+expiryDate.toGMTString()+"; path=/";

	document.cookie = cString;	
	if(document.cookie.length > (3.5 * 1024) && showwarning == true){
	  	alert('Your shopping cart is almost full, please proceed to the checkout.\n\n If you wish to add more items please add them in a second order.');
	}
  // console.log(printCookies());
    //alert(cString+"\n------------------\n"+document.cookie);
}

function stringToArray(cString) {
	/* This function converts the cookie string to the items array. */
	var items = new Array();
	items['itemKey'] = new Array();
	items['itemId'] = new Array();
	items['itemName'] = new Array();
	items['itemPrice'] = new Array();
	items['itemOptions'] = new Array();
	items['itemQuantity'] = new Array();
   
    entireString = cString;  //James 2004-02-03 see above
    
	var j = 0;
	var allItems = new Array();
	var tempItems = new Array();
	for (i = 0; i <= entireString.length; i++) {
		if (entireString.substring(i,i+1) == "[") {
			itemStart = i + 1;
		} else if (entireString.substring(i,i+1) == "]") {
			itemEnd = i;
			allItems[j] = entireString.substring(itemStart, itemEnd);
			allItems[j] = "|" + allItems[j] + "|";
			j++;
		}
	}
	var i = 0;
	var k = 0;
	for (i = 0; i < allItems.length; i++) {
		lastItem = 0;
		for (j = 1; j < allItems[i].length; j++) {
			if (allItems[i].substring(j,j+1) == "|") {
				itemStart = j;
				tempItems[k] = allItems[i].substring(lastItem + 1, j);
				lastItem = j;
				k++;
			}
		}
		items['itemKey'][i] = tempItems[0];
		items['itemId'][i] = tempItems[1];
		items['itemName'][i] = tempItems[2];
		items['itemPrice'][i] = tempItems[3];
		items['itemOptions'][i] = tempItems[4];
		items['itemQuantity'][i] = tempItems[5];
		k = 0;
	}
	return(items);
}

function arrayToString(items) {
	/* This function converts the items array to a string. */
	var outString = "";
	for (i = 0; i < items['itemKey'].length; i++) {
		if (items['itemKey'][i] != "undefined") {
			outString += "[";
			outString += items['itemKey'][i] + "|";
			outString += items['itemId'][i] + "|";
			outString += items['itemName'][i] + "|";
			outString += items['itemPrice'][i] + "|";
			outString += items['itemOptions'][i] + "|";
			outString += items['itemQuantity'][i];
			outString += "]";
		}
	}

	return(outString);
}

function newItem(itemId, itemName, itemPrice, itemOptions, itemQuantity) {
	/* This function creates a new item and calls writeCookie. */
	// Check if item exists:
	var items = readCookie();
	if (items['itemKey'].length < 1) {
		items = new Array();
		items['itemKey'] = new Array();
		items['itemId'] = new Array();
		items['itemName'] = new Array();
		items['itemPrice'] = new Array();
		items['itemOptions'] = new Array();
		items['itemQuantity'] = new Array();
		itemsLen = 0;
	} else {
		itemsLen = items['itemKey'].length;
	}
	// We have removed code to check for uniqueness: allow dup items.
	items['itemKey'][itemsLen] = rand(1000000);
	items['itemId'][itemsLen] = itemId;
	items['itemName'][itemsLen] = itemName;
	items['itemPrice'][itemsLen] = itemPrice;
	items['itemOptions'][itemsLen] = itemOptions;
	items['itemQuantity'][itemsLen] = itemQuantity;
	// Write items to cookie:
	writeCookie(items,true);

	
}

function addItem(itemId, itemName, itemPrice, itemOptions, itemQuantity) {
	/* This function checks if users wants to add item, then calls newItem. */
	if (itemQuantity <= 0) {
		alert("Please enter a quantity.");
	} else {
	    var qtyStr=(itemQuantity==1) ? "" : itemQuantity + " ";
		var optionsStr=(itemOptions=="") ? "" : " (" + itemOptions + ")";
		//if (confirm("Would you like to add " + qtyStr + itemName + ((itemQuantity > 1) ? "s" : "") + optionsStr + " to your shopping cart?")) {
		  newItem(itemId, itemName, itemPrice, itemOptions, itemQuantity);
		//}
	}
}

function ID(id) {
  return document.getElementById(id);
}

function deleteItem(itemKey) {
	/* This function deletes an item and calls writeCookie. */
	var items = readCookie();
	itemIndex = getItemIndex(itemKey, items);
	if (itemIndex != -1) {
		items = deleteArrayElement(items, itemKey);
	}
	writeCookie(items,false);
	//alert();
	//alert(document.getElementById('Buy'));
	document.getElementById('itemKey_' + itemKey).parentNode.removeChild(document.getElementById('itemKey_' + itemKey));
  // document.location.href = url_checkout;
  document.getElementById('cart-items-update').innerHTML = checkoutCartContents();
	updateTotal('buy', numItems);
}

function deleteAll() {
	/* This function resets the cookie. */
	if (confirm("This will delete ALL your items. Are you sure?")) {
		document.cookie = cookie_name+"=; expires=Thursday, 1-Jan-1970 08:00:00 GMT; path=/";
		document.location = url_checkout;
	}
}

function deleteAllQuiet() {
  document.cookie = cookie_name+"=; expires=Thursday, 1-Jan-1970 08:00:00 GMT; path=/";
}

function deleteArrayElement(items, itemKey) {
	/* This function deletes an element from the items array given an itemKey. Returns -1 if not found; items array if found. */
	// Get index:
	itemIndex = getItemIndex(itemKey, items);
	var aLen = items['itemKey'].length;
	if ((itemIndex >= aLen) || (itemIndex < 0)) {
		return(-1);
	}
	for (i = itemIndex; i < aLen; i++) {
		items['itemKey'][i] = items['itemKey'][i + 1];
		items['itemId'][i] = items['itemId'][i + 1];
		items['itemName'][i] = items['itemName'][i + 1];
		items['itemPrice'][i] = items['itemPrice'][i + 1];
		items['itemOptions'][i] = items['itemOptions'][i + 1];
		items['itemQuantity'][i] = items['itemQuantity'][i + 1];
	}
	items['itemKey'].length--;
	items['itemId'].length--;
	items['itemName'].length--;
	items['itemPrice'].length--;
	items['itemOptions'].length--;
	items['itemQuantity'].length--;
	return(items);
}

function getItemIndex(itemKey, items) {
	/* This function returns the index of an item given the itemKey, or -1 if not found. */
	var itemIndex = -1;
	for (j = 0; j < items['itemKey'].length; j++) {
		if (items['itemKey'][j] == itemKey) {
			itemIndex = j;
		}
	}
	return(itemIndex);
}

function addOrder() {
	var formBuy = eval("document.forms['buy']");
	var htmlString = "";
	if (formBuy.numItems) {
	    	for (i = 0; i < formBuy.numItems.value; i++) {
    			inputRef = eval("formBuy.elements['itemName" + i + "']");
    			htmlString += "<input type=\"hidden\" name=\"Order_ItemName_" + i + "\" value=\"" + inputRef.value + "\">\n";
	    		inputRef = eval("formBuy.elements['quantity" + i + "']");
    			htmlString += "<input type=\"hidden\" name=\"Order_Quantity_" + i + "\" value=\"" + inputRef.value + "\">\n";
	    		inputRef = eval("formBuy.elements['options" + i + "']");
    			htmlString += "<input type=\"hidden\" name=\"Order_Options_" +  i + "\" value=\"" + inputRef.value + "\">\n"; 
	    		inputRef = eval("formBuy.elements['price" + i + "']");
    			htmlString += "<input type=\"hidden\" name=\"Order_Price_" + i + "\" value=\"" + toPrice(inputRef.value) + "\">\n";
	    	}
    		inputRef = eval("formBuy.elements['total']");
		htmlString += "<input type=\"hidden\" name=\"Order_Total\" value=\"" + toPrice(inputRef.value) + "\">\n";
	}
    htmlString += "<input type=\"hidden\" name=\"cookie_backup\" value=\""+document.cookie+"\" >\n";
	document.write(htmlString);
}

//Code for ozimages gallery

function getPrice(id)
{
    var r=document.Cart.elements[id];
    if (!r) return false;
    var val=getSelectedRadioValue(r);
    return val.substr(val.indexOf('~')+1);
}

function getDims(id)
{
    var r=document.Cart.elements[id];
    if (!r) return false;
    var val=getSelectedRadioValue(r);
    return val.substr(0,val.indexOf('~'));
}

// Invoked in Design a Hamper page
function Inp(name) {
    var p=parseInt(document.Cart.elements[name].value);
	if (!(p > 0)) {
		return p="1";
	} else {
	    return p;
	}
}

function getSelectedRadio(buttonGroup) {
   if (buttonGroup[0])
     for (var i=0; i<buttonGroup.length; i++)
       if (buttonGroup[i].checked)
         return i;
   else
     if (buttonGroup.checked)
       return 0;
   return -1;
}

function getSelectedRadioValue(buttonGroup) {
   var i=getSelectedRadio(buttonGroup);
   if (i==-1)
     return false;
   else
   {
     if (buttonGroup[i])
        return buttonGroup[i].value;
     else
        return buttonGroup.value;
   }
}
function printCookies(w){
	cStr = "";
	pCOOKIES = new Array();
	pCOOKIES = document.cookie.split('; ');
	for(bb = 0; bb < pCOOKIES.length; bb++){
		NmeVal  = new Array();
		NmeVal  = pCOOKIES[bb].split('=');
		if(NmeVal[0]){
			cStr += NmeVal[0] + '=' + unescape(NmeVal[1]) + '; ';
		}
	}
	return cStr;
}
