//-----------------------------------------------------------------------------
//---Project: ShopJS The Ross Online JavaScript Shopping Solution
//---Date: 1/22/98
//---Author: Ross Noe
//---Location: http://www.anweb.com/shopjs
//---Email: developer@anweb.com
//---Usage: This script is free as long as you don't remove the credits
//---Extended by Jason McLachlan

subt = 0; 				//--- subt is the subtotal
addtax = 0;  			//--- addtax is the tax
tot = 0; 				//--- tot is the total
disc = 0;				//--- discount percentage
prodcount = 0;			//--- total number of products in order (combo treated as multiple)
itemcount = 0;			//--- total number of products in order (combo treated as one)
var tax = 0.00; 			//--- tax percentage
var aQuant = new Array();	//--- aQuant, aPrice, and aDescr store the quantity, price & description
var aPrice = new Array();
var aDescr = new Array();
var aForms = new Array();
var aCrncy = new Array();
var timeOutId = 0;
var orderCookieName = "NarhexAustraliaOrder";
var countryCookieName = "NarhexAustraliaCountry";
var locationCookieName = "NarhexAustraliaLocation";
var currencyCookieName = "NarhexAustraliaCurrency";
var loyaltyCookieName = "NarhexAustraliaLoyaltyDiscount";
var identityCookieName = "NarhexAustraliaIdentity";
var currencyCode = 0;
var loyaltyDiscount = 0;
var loyaltyDiscountAmount = 0;
var newwindow;
var aProducts = new Array("Postage","Purifying Water Soluble Gel Cleanser","Moisturiser Type 2, 8% AHA","Eye Cream 3% NarElastin","Facial Treatment 1% NarElastin","Facial Lift 4% NarElastin + collagen","Comb. 1 - Age Up to 26 Years","Comb. 2 - Age 26 to 35 Years","Comb. 3 - Mature / Sun Damaged Skin","Nuvoderm 15% AHA + Vitamin E");
var aAUDPrices = new Array("950","2500","3800","6500","5600","9800","10300","23400","33200","7500");
var aUSDPrices = new Array("1200","1875","2850","4875","4200","7350","7725","17550","24900","5625");
var aCADPrices = new Array("1350","2110","3210","5525","4730","8280","8735","19750","28021","6337");
var aEURPrices = new Array("500","1475","2240","3835","3300","5780","6075","13806","19588","4425");
var aNZDPrices = new Array("1125","2960","4500","7695","6630","11600","12195","27706","39309","8880");
var aGBPPrices = new Array("645","1000","1530","2620","2255","3950","4150","9360","13280","3022");
var aRMBPrices = new Array("95","150","228","390","336","588","618","1404","1992","450");
var aJPYPrices = new Array("1400","2190","3325","5685","4895","8570","9010","20498","29083","6560");
var aProdCounts = new Array(0,1,1,1,1,1,2,3,4,1);
var aAllPrices = new Array(aAUDPrices, aUSDPrices, aCADPrices, aEURPrices, aNZDPrices, aGBPPrices, aRMBPrices, aJPYPrices);
var aAllSymbols = new Array("$","$","$","\u20ac","$","\u00a3","\u5143","\u00a5");
var aAllDecimals = new Array(2,2,2,2,2,2,0,0);
var aAllCurrency = new Array("AUD$ (Australian Dollars)", "USD$ (US Dollars)", "CAD$ (Canadian Dollars)", "EUR&#8364; (European Union Euro)", "NZD$ (New Zealand Dollars)", "GBP&#163; (Great Britain Pounds)", "RMB&#20803; (Chinese Renminbi - Yuan)", "JPY&#165; (Japanese Yen)");
var aCurrency = new Array("AUD (Australian Dollars)", "USD (US Dollars)", "CAD (Canadian Dollars)", "EUR (European Union Euro)", "NZD (New Zealand Dollars)", "GBP (Great Britain Pounds)", "RMB (Chinese Renminbi - Yuan)", "JPY (Japanese Yen)");


function cancelBack()
{
	if ((event.keyCode == 8 ||
		 (event.keyCode == 37 && event.altKey) ||
		 (event.keyCode == 39 && event.altKey))
		&& 
		(event.srcElement.form == null || event.srcElement.isTextEdit == false))
	{
		event.cancelBubble = true;
		event.returnValue = false;
	}
}

function showOrderBanner()
{
	var message;
	readOrderCookie();
	readCurrencyCookie();
    readLoyaltyCookie();
	calcDiscount();
	if (itemcount == 0) {
		message = "";
	} else {
		if (itemcount == 1) {
			message = "Your order contains one item at a total cost of "+aAllSymbols[eval(currencyCode)]+AddDecimal(eval(tot),currencyCode)+".";
		} else {
			message = "Your order contains "+eval(itemcount)+" items at a total cost of "+aAllSymbols[eval(currencyCode)]+AddDecimal(eval(tot),currencyCode)+".";
		}
	}
    
    if (loyaltyDiscount > 0) {
        message = message + " A bonus loyalty discount of "+eval(loyaltyDiscount)+"% may also apply to your order!";
    }
    
    if (message == "") {
        message = ".";
    }
    var head1 = document.getElementById("orderbanner");
    head1.firstChild.nodeValue=message;
}

function updateEmailAddress(sFormName) {
	var ExistingEmail;
	ExistingEmail = readCookie(identityCookieName);
	FormEmail = document.forms[sFormName].email.value;
	if (FormEmail != ExistingEmail && FormEmail != "") {
		createCookie(identityCookieName, FormEmail, 365);
	}
	showLoyaltyForm('./nh_loyalty_status.php', sFormName)
}

function showProduct(code)
{
	document.write(aProducts[eval(code)]);
}

function readLoyaltyCookie() {
	loyaltyDiscount = readCookie(loyaltyCookieName);
	if (loyaltyDiscount == null || loyaltyDiscount == "deleted") {
		loyaltyDiscount = 0;
	}	
}


function readCurrencyCookie() {
	currencyCode = readCookie(currencyCookieName);
	if (currencyCode == null) {
		// If no currency code exists, assume we're in AUS
		setCurrencyCode('0');
		currencyCode = '0';
	}	
}

function setCurrencyCode() {
	code = document.forms["currency-selector"].currency_selector.value;
	createCookie(currencyCookieName, code, 1000);
	window.location.reload();
}

function showCurrencyDescr() {
	currencyCode = eval(readCookie(currencyCookieName));
	sMessage = "* All prices are shown in " + aAllCurrency[currencyCode];
	if (currencyCode == 0) {
		sMessage = sMessage + " and includes GST.";
	} else {
		sMessage = sMessage + ".";
	}
	document.write(sMessage);
}

function showCurrencyList() {
	currencyCode = eval(readCookie(currencyCookieName));
	document.write("<form name=currency-selector>");
	document.write("<select onchange=setCurrencyCode(); name=currency_selector style=\"font-size:7pt;font-family:arial-narrow,arial;background-color:#eff0f0;text-decoration:none;border-color:#eff0f0;\">");
	iCurrency = 0
	for (iCurrency = 0; iCurrency <= 7; iCurrency++) {
		if (iCurrency == currencyCode) {
			document.write("<option selected value="+iCurrency+">"+aAllCurrency[iCurrency]+"</option>");
		} else {
			document.write("<option value="+iCurrency+">"+aAllCurrency[iCurrency]+"</option>");
		}
	}
	document.write("</select></form>");
}

function showPrice(code)
{
	readCurrencyCookie();
	var priceList = aAllPrices[eval(currencyCode)];
	document.write(aAllSymbols[eval(currencyCode)]+AddDecimal(priceList[eval(code)],currencyCode));
}

function getShipping()
{
	readCurrencyCookie();
	var priceList = aAllPrices[eval(currencyCode)];
	return eval(priceList[0]);
}

function showDiscPrice(code, disc)
{
	readCurrencyCookie();
	var priceList = aAllPrices[eval(currencyCode)];
	document.write(aAllSymbols[eval(currencyCode)]+AddDecimal(priceList[eval(code)] * (100 - disc)/100,currencyCode));
}

function showPriceAus(code)
{
// Previous requirement to show AUD price updated to show discount.
//	readCurrencyCookie();
//	if (currencyCode == '0') {
//		document.write("includes GST");
//	} else {
//		var priceList = aAllPrices[eval('0')];
//		document.write("AUD$"+AddDecimal(priceList[eval(code)],'0'));
//	}
// Pretend to add the item to an order and calculate what discount
// will be applied. Show the discounted price of that item, based
// on what items the customer has in their order already.
	readCurrencyCookie();
	readOrderCookie();
	iExistingCount = countItems();
	iCountAfter = iExistingCount + aProdCounts[eval(code)];
	iDiscount = calcDiscountPercent(iCountAfter);
	if (iDiscount > 0) {
		showDiscPrice(code, iDiscount);
		document.write(" discounted");
	}
}

function showLoyaltyForm(url, sFormName)
{
    url = url+"?refresh="+eval(Math.round(Math.random()*999999));
	newwindow=window.open(url,'name','scrollbars=yes,toolbar=no,height=300,width=400');
	// if (window.focus) {newwindow.focus()}
	//newwindow.focus();
}

function showOrderForm(url)
{
	newwindow=window.open(url,'name','scrollbars=yes,toolbar=yes,height=600,width=800');
	if (window.focus) {newwindow.focus()}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') 
			c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) 
			return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function writeOrderCookie()
{
	m = aQuant.length - 1;
	n = m + 1; 
	cookie = "";
	for (i=0 ; i < n; i++)
	{
	  	if((aQuant[i] != null)&&(aQuant[i] != 0))
		{
			cookie = cookie+aQuant[i]+"|"+aPrice[i]+"|"+aDescr[i]+"|"+aForms[i]+"|"+aCrncy[i]+"~"
		}	
	}
	if (cookie != "") {
		createCookie(orderCookieName, cookie, 1);
	} else {
		eraseCookie(orderCookieName);
	}
}

function readOrderCookie()
{
	aQuant.length = 0;
	aPrice.length = 0;
	aDescr.length = 0;

	iCurrentCookie = 0;

	readCurrencyCookie();
	orderCookie = readCookie(orderCookieName);
	if (orderCookie != null) {
		var item = orderCookie.split('~');
		for(var i=0;i < item.length;i++) {
			var details = item[i].split('|');
			if ((details[0] != null)&&(details[0] != 0)) {
				aQuant[iCurrentCookie] = details[0];
				aPrice[iCurrentCookie] = details[1];
				aDescr[iCurrentCookie] = details[2];
				aForms[iCurrentCookie] = details[3];
				aCrncy[iCurrentCookie] = details[4];
				iCurrentCookie++;
			}
		}
	}

	// Check to see if any order items need converting to new currency
	for (var i=0; i < iCurrentCookie; i++) {
		if (aCrncy[i] != currencyCode) {
			aNewPrices = aAllPrices[eval(currencyCode)];
			iNewPrice = aNewPrices[eval(aForms[i])];
			aPrice[i] = iNewPrice;
			aCrncy[i] = currencyCode;
		}
	}
	writeOrderCookie();
}

function clearOrder() 
{
	sMessage = "Would you like to clear your order?";
	if (confirm(sMessage)) {
		aQuant.length = 0;
		aPrice.length = 0;
		aDescr.length = 0;
		aForms.length = 0;
		aCrncy.length = 0;

		eraseCookie(orderCookieName);	
		calcDiscount();
		showOrder();
		showOrderBanner();
	}
}

function countItems()
{
	count = 0;
	itemcount = 0;
	m = aQuant.length - 1;
	n = m + 1; 
	for (i=0 ; i < n; i++) {
		iProductNum = 0
		for (iProductNum=0; iProductNum < aProducts.length; iProductNum++) {
			if (aDescr[i] == aProducts[iProductNum]) {
				iProdCount = aProdCounts[iProductNum];
			}
		}
		count = eval(count) + eval(iProdCount) * eval(aQuant[i]);
		itemcount = eval(itemcount) + eval(aQuant[i]);
	}
	return count;
}

function calcDiscountPercent(items)
{
	if (items == 2) 
	{
		return 5;
	} else { 
		if (items >= 3) 
		{
			return 10;
		} else {
			return 0;
		}
	}
}

function calcDiscount()
{
    readLoyaltyCookie();
	itemcount = 0;
	count = countItems();
	prodcount = count;
	disc = calcDiscountPercent(count);
}

function AddDecimal(number, currency_code)
{
	var num;
	iDecimals = eval(aAllDecimals[eval(currency_code)]);
	num = number / (Math.pow(10,iDecimals));
	withdecimal = num.toFixed(iDecimals);
	return withdecimal;
}

function addToOrder(list_index,forms,dispconf)
{
	readCurrencyCookie();
	readOrderCookie();
	descr = aProducts[eval(forms)];
	prices = aAllPrices[eval(currencyCode)];
	price = prices[eval(forms)];

	m = aQuant.length - 1;
	n = m + 1; 
	existingQuant = 0;
	for (i=0 ; i < n; i++) {
		if((aPrice[i] == price)&&(aDescr[i] == descr)) {
			existingQuant = aQuant[i];
			i = n;
		}
	}

	sindex = list_index;
	aQuant.length = aQuant.length + 1;

	if (existingQuant > 0) {
		if (sindex == 1) {
			sMessage = "Your order already contains " + descr + ".\nWould you like to add another?"
		} else {
			sMessage = "Your order already contains " + descr + ".\nWould you like to add another " + sindex + " of these?"
		}
	} else {
		if (sindex == 1) {
			sMessage = "Would you like to add " + descr + " to your order?"
		} else {
			sMessage = "Would you like to add " + sindex + " of the " + descr + " products to your order?"
		}
	}

	response = false;
	if (dispconf) {
		response = confirm(sMessage);
	} else {
		response = true;
	}

	if (response) {
		m = aQuant.length - 1;
		n = m + 1; 
		itemFound = 0;
		for (i=0 ; i < n; i++) {
			if ((aPrice[i] == price) && (aDescr[i] == descr)) {
				itemFound = 1;
				aQuant[i] = eval(aQuant[i]) + eval(sindex);
				i = n;
			}
		}
		if (itemFound == 0) {
			m = aQuant.length - 1;
			n = m + 1; 
			aQuant[n] = sindex;
			aPrice[n] = price;
			aDescr[n] = descr;
			aForms[n] = forms;
			aCrncy[n] = currencyCode;
		}
		writeOrderCookie();
		readOrderCookie();
		calcDiscount();
		if (!dispconf) {
			showOrder();
		} else {
			calcTotals();
		}
		showOrderBanner();	
	}
}

function removeFromOrder(list_index,forms)
{
	readCurrencyCookie();
	readOrderCookie();
	descr = aProducts[eval(forms)];
	prices = aAllPrices[eval(currencyCode)];
	price = prices[eval(forms)];

	m = aQuant.length - 1;
	n = m + 1; 
	itemFound = 0;
	for (i=0 ; i < n; i++) {
		if ((aPrice[i] == price) && (aDescr[i] == descr)) {
			itemFound = 1;
			if (aQuant[i] > 0) {
				aQuant[i] = eval(aQuant[i]) - 1;
			}
			i = n;
		}
	}
	writeOrderCookie();
	readOrderCookie();
	calcDiscount();
	showOrder();	
	showOrderBanner();
}

function calcTotals()
{
	subt = 0;
	m = aQuant.length - 1;
	n = m + 1; 
	for (i=0 ; i < n; i++) {
		subt = eval(subt) + (eval(aQuant[i]) * eval(aPrice[i]));
	}
	subdisc = Math.round(subt * disc / 100);
      loyaltyDiscountAmount = Math.round(subt * loyaltyDiscount / 100);
	addtax = Math.round((eval(subt) - eval(subdisc)) * tax);  
	tot = (eval(subt) - eval(subdisc) + eval(addtax) + eval(getShipping()));
}

function showOrder()
{
	readCurrencyCookie();
	//--- clear the existing table
	for (i=1 ; i <= 9; i++) {
		document.forms["currentorder"].elements["quantity_0"+i].value = "";
		document.forms["currentorder"].elements["price_0"+i].value = "";
		document.forms["currentorder"].elements["cost_0"+i].value = "";
	}
	calcTotals();
	m = aQuant.length - 1;
	n = m + 1; 
	for (i=0 ; i < n; i++) {
		document.forms["currentorder"].elements["quantity_"+aForms[i]].value = PadString(aQuant[i],2);
		document.forms["currentorder"].elements["price_"+aForms[i]].value = PadString(AddDecimal(eval(aPrice[i]),currencyCode),7);
		document.forms["currentorder"].elements["cost_"+aForms[i]].value = PadString(AddDecimal(eval(aQuant[i] * aPrice[i]),currencyCode),7);
		document.forms["currentorder"].elements["desc_"+aForms[i]].value = aDescr[i];		
	}
	document.forms["currentorder"].elements["subtotal"].value = PadString(AddDecimal(eval(subt),currencyCode),7);
	document.forms["currentorder"].subtotal.value = PadString(AddDecimal(subt,currencyCode),7);
	document.forms["currentorder"].discount.value = PadString(AddDecimal(-subdisc,currencyCode),7);
	document.forms["currentorder"].loyalty.value = PadString(AddDecimal(-loyaltyDiscountAmount,currencyCode),7);
	document.forms["currentorder"].shipping.value = PadString(AddDecimal(getShipping(),currencyCode),7);
	document.forms["currentorder"].currency.value = aCurrency[currencyCode];
	if (document.forms["currentorder"].subtotal.value == 0.00) {
		tot = 0;
		document.forms["currentorder"].total.value = PadString(AddDecimal(0,currencyCode),7);
	} else {
		document.forms["currentorder"].total.value = PadString(AddDecimal(tot - loyaltyDiscountAmount,currencyCode),7);
	}		
	
	//--- Create summary string
	summary = "Subtotal "+aAllSymbols[eval(currencyCode)]+AddDecimal(eval(subt - subdisc - loyaltyDiscountAmount),currencyCode);
	summary = summary + " plus "+aAllSymbols[eval(currencyCode)] + AddDecimal(getShipping(),currencyCode) + " postage & handling";
	var head1 = document.getElementById("ordersummary");
	head1.firstChild.nodeValue=summary;
}

function PadString(content, length) {
	var padded = "";
	var spaces = "                  ";
	padded = spaces.substring(0, (length - content.length)*2) + content;
	return padded;
}