function OptVal(name) {
    return document.Cart.elements[name].options[document.Cart.elements[name].selectedIndex].value;
}

function OptText(name) {
    return document.Cart.elements[name].options[document.Cart.elements[name].selectedIndex].text;
}

function Inp(name) {
    return document.Cart.elements[name].value;
}

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) {	// Is in format "7.90/250g"
		srcPrice = srcPrice.substr(0, srcPrice.indexOf("/"));
	}
*/
	if (srcPrice.indexOf(".") < 0) {
		srcPrice += ".00";
	} else if (srcPrice.length - srcPrice.indexOf(".") == 1) {
		srcPrice += "00";
	} else if (srcPrice.length - srcPrice.indexOf(".") == 2) {
		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();
	var f = eval("document.forms['" + formName + "']");
	var total = 0;
	for (i = 0; i < numInputs; i++) {
		itemKey = eval("f.elements['itemKey" + i + "']").value;
		itemOptions  = parseInt(eval("f.elements['options" + i + "']").value);
		itemQuantity = parseInt(eval("f.elements['quantity" + i + "']").value);
		if (!(itemQuantity >= 0)) {
			itemQuantity = 0;
			eval("f.elements['quantity" + i + "']").value = 0;
		}
		items['itemQuantity'][getItemIndex(itemKey, items)] = itemQuantity;
		eval("f.elements['price" + i + "']").value = toPrice(roundReal(items['itemPrice'][i]) * itemQuantity);
		total += (items['itemPrice'][i]) * itemQuantity;
	}
	f.elements['total'].value = toPrice(roundReal(total, 2));
	writeCookie(items);
	updateCartInfo();
}

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.html. */
	items = readCookie();
	itemString = chgSpaces(arrayToString(items));
	document.location = "http://www.trimbody.com.au/checkout.html?items=" + itemString;
}

function readCookie() {
	/* This function reads the cookie and returns an items array. */
	cString = document.cookie;
	return(stringToArray(cString));
}

function writeCookie(items) {
	/* This function writes the cookie from the items array. */
	cString = "TrimBody=" + arrayToString(items) + "; expires=31-Dec-2019 08:00:00 GMT";
	document.cookie = cString;
}

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();

	cookieIndex = cString.indexOf("TrimBody");
	cookieBegin = cString.indexOf("=",cookieIndex) + 1;
	cookieEnd = cString.indexOf(";",cookieIndex);
	if (cookieEnd == -1) {
		cookieEnd = cString.length;
	}
	entireString = cString.substring(cookieBegin, cookieEnd);
	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);
	updateCartInfo();
}

function openWindow(url,w,h,tb,stb,l,mb,sb,rs)
{
	if (!newWindow || newWindow.closed)
	{
		x = (screen.width - w) / 2; 
		y  = (screen.height - h) / 2;
		var t=(document.layers)? ',screenX='+x+',screenY='+y: ',left='+x+',top='+y;
		tb=(tb)?'yes':'no'; stb=(stb)?'yes':'no'; l=(l)?'yes':'no'; mb=(mb)?'yes':'no'; sb=(sb)?'yes':'no'; rs=(rs)?'yes':'no';
		var newWindow=window.open(url, 'newWin'+new Date().getTime(), 'scrollbars='+sb+',width='+w+',height='+h+',toolbar='+tb+',status='+stb+',menubar='+mb+',links='+l+',resizable='+rs+t);
		newWindow.focus();
	}
	else
	{
	   newWindow.location.href=url;
       newWindow.focus();
    }
}


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 {
		if (confirm("Would you like to add " + itemQuantity + " \"" + itemName + "\" to your shopping cart?")) {
			
		newItem(itemId, itemName, itemPrice, itemOptions, itemQuantity);
		openWindow('cart-info.html',500,210,0,0,0,0,1,0);
		}
	}
}

function addSingleItem(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 {
		if (confirm("Would you like to add \"" + itemName + " to your shopping cart?")) {
		newItem(itemId, itemName, itemPrice, itemOptions, itemQuantity);
		openWindow('cart-info.html',500,210,0,0,0,0,1,0);

		}
	}
}

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);
	document.location.href = "checkout.html";
}

function deleteAll() {
	/* This function resets the cookie. */
	if (confirm("This will delete ALL your items. Are you sure?")) {
		document.cookie = "TrimBody=";
		document.location.href = "checkout.html";
	}
}

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);
}

function displayCartInfo() {
	var html = "<form name=\"CartContents\">\n";
	html    += " <div class=\"CartContents\">\n";
	html    += "  You have <input name=\"CartItems\" type=\"text\" class=\"CartContents\" value=\"\" size=\"7\" readonly> in your cart.<br>\n";
	html    += "  Total cost: <input name=\"CartTotal\" type=\"text\" class=\"CartContents\" value=\"\" size=\"10\" readonly>\n";
	html    += " </div>\n";
	html    += " <div class=\"CartContentsFooter\"><a href=\"checkout.html\" class=\"CartContentsFooter\">PROCEED TO CHECKOUT</a></div>\n";
	html    += "</form>\n";
	document.write(html);
	updateCartInfo();
}

function updateCartInfo() {
/*
	var items = readCookie();
	var numItems = 0;
	var totalCost = 0;
	for (i = 0; i < items['itemName'].length; i++) {
		numItems += parseInt(items['itemQuantity'][i]);
		totalCost += items['itemPrice'][i] * items['itemQuantity'][i];
	}
	totalCost = toPrice(roundReal(totalCost));
	document.CartContents.CartItems.value = numItems + ((numItems==1) ? " item" : " items");
	document.CartContents.CartTotal.value = "$" + totalCost;
*/
}