/* Initializing and Globals =============================================================================================*/
subt = 0; 
tot = 0; 
//--- Style number, Quantity, Price, Description and Size variables are global.
var aName = new Array();
var aStyle = new Array();
var aQuant = new Array();
var aPrice = new Array();
var aDescr = new Array();
var aSize = new Array();

//--- the timeOutID is necessary so that people don't add or remove items in too
//---	rapid a sequence. 
var timeOutId = 0;
//--- Declare pageLoad variable as global. Use this variable to set the calling page's filename for use in the backLoadPage function.
var pageLoad ="";
var ShopCartHasItems = false;
var ShopTaxTitle = '';
var TaxTotal = 0;
var ShopShippingTotal = 0;
// Shop Defaults - Place Somewhere else ?
var ShopDefaultCurrency = 'AU$';
var ShopDefaultOptionGroup = '';
var ShopShippingOption = 'Australia';
var ShopShippingAustralia = 0;
var ShopShippingOverseas = 1500;
var ShopDefaultQuantityMax = 10; 
var ShopProductTaxPercent = 10; // Percentage of tax applicable
var ShopProductTaxAdded = true; // Has Tax been added to prices
var ShopOptionTitle = "Style"; // Has Tax been added to prices
//var ShopOptionStyle = ' class="ShopOptionSelect"'; Netscape can't handle styless for this.
//var ShopQuantityStyle = ' class="ShopQuantitySelect"';
var ShopOptionStyle = '';
var ShopQuantityStyle = '';
var ShopLastQuantityMax = 0;
var ShopLastQuantityOptions = '';
var ShopCartTable = ' width="400" border=0 cellpadding=2 cellspacing=1 ';
var ShopCartHeaderRow = ' bgcolor="#ffa500" ';
var ShopCartProductRow = ' bgcolor=#ffcc99 ';
var ShopCartOptionsRow = ' bgcolor=#fff8dc ';
var ShopCartSubTotalRow = ' bgcolor=#ffa500 ';
var ShopCartTotalRow = ' bgcolor="#ffa500" ';

var ShopProductTable = ' align="center" width="300" bgcolor="#2e8b57" cellspacing="0" cellpadding="2" ';
var ShopProductHeaderFont = ' size="-1" color="White" face="Verdana,Arial" ';
var ShopProductHeaderRow = ' bgcolor="#87cefa" ';
var ShopProductHeaderTextSingle = 'Order this Item Online';
var ShopProductHeaderTextMultiple = 'Order these Items Online';
var ShopProductTitleRow = ' bgcolor="wheat" ';
var ShopProductTitleFont = ' size="-1" color="Black" face="Verdana,Arial" ';
var ShopProductOptionsRow = ' bgcolor="#fffbeb" ';
var ShopProductOptionsFont = ' size="-2" color="Black" face="Verdana,Arial" ';
var ShopBrowserErrorText = '<font size="-1" color="#ff0000" face="Verdana,Arial">N.B. This demo Online Shopping System Requires a Javascript & Cookies enabled browser.</font><br><br><font size="-1" color="#000080" face="Verdana,Arial">For help ordering these products please contact us by:<br>Phone:+61 2 4268 2922<br>Fax:+61 2 4268 2944<br>Email:info@core.com.au<br></font>';
var ShopNoItemsText = '<font size="-1" color="Black" face="Verdana,Arial">There are currently no items in your shopping cart.<br><br><a href="void(0);" onClick="self.window.close();return false;">Click here to close this window.</a><br></font>';

// Cart Viewing Options
var ShopCartURL = "http://www.core.com.au/products/ShopViewCart.htm";
var ShopCheckoutURL = "http://www.core.com.au/products/ShopCheckout.htm";
var ShopCartTarget = "self";
var ShopCartRemote = true; // Open cart in a popup?
var ShopCartAutoView = true; // Automatically view cart after adding products.
var ShopCartRemoteOptions = 'toolbar=no,width=440,height=460,directories=no,status=yes,scrollbars=yes,resizable,menubar=no,screenX=20,screenY=10,left=20,top=10';
var ShopCartShowLink = '';
// Build Show Cart Link from above
if(ShopCartRemote){
	ThisOpenString = "'"+ShopCartURL+"','"+ShopCartTarget+"','"+ShopCartRemoteOptions+"'";
	ShopCartShowLink = "<a href=\"javascript:void(0);\" onClick=\"javascript:window.open("+ThisOpenString+");return false;\">Show Cart</a>"
} else {
	ShopCartShowLink = '<a href="' + ShopCartURL+ '" target="'+ShopCartTarget+'">Show Cart</a>';
}
// Initialize Products & Options Arrays
var ShopProducts = new Array();
var ShopOptionGroups = new Array();


/* Products Setup - Displaying, Initilizing Product Arrays =============================================================================================*/
// Array Constructors - Place somewhere else?
function ShopProduct(ProductArray) {
	//alert(ProductArray.length);
	this.Name = ProductArray[0];
	this.Title = ProductArray[1];  
	this.Description = (ProductArray[2]) ? ProductArray[2] : '';  
	this.Price = (ProductArray[3]) ? ProductArray[3] : 0;
	this.Status =(ProductArray[4]) ? ProductArray[4] : 1;  
	this.Currency =(ProductArray[5]) ? ProductArray[5] : ShopDefaultCurrency;
	this.OptionGroup =(ProductArray[6]) ? ProductArray[6] : '';
	this.ProductGroup =(ProductArray[7]) ? ProductArray[7] : '';
	this.QuantityMax =(ProductArray[8]) ? ProductArray[8] : ShopDefaultQuantityMax;
	this.ImageSmall =(ProductArray[9]) ? ProductArray[9] : '';
	this.ImageLarge =(ProductArray[10]) ? ProductArray[10] : ''; 
	/*
	this.Name = Name;
	this.Title = Title;  
	this.Description = (Description) ? Title : '';  
	this.Price = (Price) ? Price : 0;
	this.Status =(Status) ? Status : 1;  
	this.Currency =(Currency) ? Currency : ShopDefaultCurrency;
	this.OptionGroup =(OptionGroup) ? OptionGroup : ShopDefaultOptionGroup;
	this.ProductGroup =(ProductGroup) ? ProductGroup : '';
	this.QuantityMax =(QuantityMax) ? QuantityMax : ShopDefaultQuantityMax;
	this.ImageSmall =(ImageSmall) ? ImageSmall : '';
	this.ImageLarge =(ImageLarge) ? ImageLarge : ''; */
	
}

function AddShopProduct(ProductArray){
	ThisProductName =ProductArray[0];
	NextIndex = ShopProducts.length;
	ShopProducts[NextIndex] = new ShopProduct(ProductArray);
	//alert(ShopProducts[NextIndex].Name+ " " + ShopProducts[NextIndex].Title);
}
function AddShopOptionGroup(OptionArray){
	ThisOptionGroup =OptionArray[0];
	NextIndex = ShopOptionGroups.length;
	ShopOptionGroups[NextIndex] = new Array();
	ShopOptionGroups[NextIndex] = OptionArray;
}

/* Items Management - Adding/Removing Items =============================================================================================*/
//--- compute function adds items to cart. qindex -selected index of quanity. sindex -selected index of sizes.
function compute(price,descr,name,Form,OptionGroup)
{
GetItemsCookie();
	//alert(eval("self.document." +Form + "." + name + "_Quantity.selectedIndex"));
	//alert(eval("document." +Form + "." + name + "_Quantity"));
  //qindex = eval("parent.content.document.itemForm." + name + "Quantity.selectedIndex");
  //sindex = eval("parent.content.document.itemForm." + name + "Style.selectedIndex");
  qindex = eval("document." +Form + "." + name + "_Quantity.selectedIndex");
  quantity = parseInt(eval("document." +Form + "." + name+ "_Quantity.options[" + qindex + "].value"));
  if(OptionGroup != ''){
	  sindex = eval("document." +Form + "." + name + "_Style.selectedIndex");
	  style = eval("document." +Form + "." + name+ "_Style.options[" + sindex + "].value");
	  ConfirmStyle = ' ('+style+') ';
	} else {
	style = '';
	ConfirmStyle = '';
	}
  //--- Increment the array so that we don't get a [Netscape 2] array length error
  aQuant.length = aQuant.length + 1;
  //--- Confirm that they want to add items to their cart.
  if (confirm("Add " +quantity+ " " + descr + ConfirmStyle +" to your shopping cart?")) {
  	// Reload Items from cookie. Avoid problems where people try to add again from the same page
	// after using remote.
  	
	//alert(aName.length);
	  // If we already have an item with same product + style. Just add to it.
	  m = aQuant.length - 1;
	  n = m + 1;
	  for(i=0; i < aName.length; i++) {
			if((aName[i]== name)&&(aStyle[i]==style)){
				n = i;
				OldQuanity = parseInt(aQuant[i]);
				quantity += OldQuanity;
				break;
			}
		}
		 
	  aName[n] = name;
	  aDescr[n] = descr;
	  aStyle[n] = style;
	  aQuant[n] = quantity;
	  aPrice[n] = price;
	 	  
	  subt = (eval(subt) + (eval(price) * eval(qindex)));
	  // Save Items Arrays to a cookie
	  SetItemsCookie();
		return true;
	} else {
		// User cancelled
		return false;
	}
}

//--- The uncompute2 function is for removing items from the cart when it is displayed.
//function RemoveItem(
function uncompute2(quantity,price,descr,name,style)
{	
	var undescr = unescape(descr); 
	/* Make sure the subtotal is not zero. After all why would someone need to remove
	something if there is nothing in their cart.Confirm that they want to remove items provided
	 the subtotal is not zero */
	if((subt != 0)&&(confirm("Remove " + quantity + " of the " + undescr + " product from your shopping cart"))) {
	    subt = (eval(subt) - (eval(price) * eval(quantity)));		
		//-------------------------------------
		for(i=0; i < aQuant.length; i++) {
			if((aName[i]== name)&&(aQuant[i]==quantity)&&(aStyle[i]==style)){
				aQuant[i]=0;
				break;
			}
		}
		// Save Items Arrays to a cookie
		SetItemsCookie();
		timeOutId = setTimeout("RefreshCart(self)",100);
				  		
	} else {
	 	return;
	}				
}
	
/* Items Saving And Loading from Cookies =============================================================================================*/
// SetShipping - Updates country related options.
// RefreshCart -[true|]false] Reload cart?
function SetCountry(Country,RefreshCartOK){
	// Save options
	SetCookie('ShopShippingOption',Country);
	SetCookie('ShopShippingCountry',Country);
	// refesh Cart?
	if(RefreshCartOK) {
		timeOutId = setTimeout("RefreshCart(self)",100);
	}
}

// Remove all items
function RemoveAllItems(){
	if(confirm("Remove all items from your shopping cart")){
		DeleteCookie('aName');
		DeleteCookie('aDescr');
		DeleteCookie('aStyle');
		DeleteCookie('aQuant');
		DeleteCookie('aPrice');
		DeleteCookie('ShopShippingOption');
		timeOutId = setTimeout("RefreshCart(self)",100);
		// Clear Item Arrays
		
	}
}
// Load Arrays from Cookie
function GetItemsCookie(){
	if(IsBrowserOK()){
		aName = new Array;
		aStyle = new Array;
		aQuant = new Array;
		aPrice = new Array;
		aDescr = new Array;
		aSize = new Array;

		NameList = GetCookie('aName');
		DescrList= GetCookie('aDescr');
		StyleList = GetCookie('aStyle');
		QuantList = GetCookie('aQuant');
		PriceList = GetCookie('aPrice');
		SavedShippingOption = GetCookie('ShopShippingOption');
		SavedShippingCountry = GetCookie('ShopShippingCountry');
		// Fill Arrays if we have values
		if(NameList != null) {aName = NameList.split("|");}
		if(DescrList != null) { aDescr = DescrList.split("|"); }
		if(StyleList != null) { aStyle = StyleList.split("|"); }
		if(QuantList != null) { aQuant = QuantList.split("|"); }
		if(PriceList != null) { aPrice = PriceList.split("|"); }
		if(SavedShippingOption != null) {ShopShippingOption = SavedShippingOption; }
 		if(SavedShippingCountry != null) {
			ShopShippingCountry = SavedShippingCountry;
		} else {
			ShopShippingCountry = ShopShippingOption;
		}
		//alert(ShopShippingCountry);
	// Calculate Subtotals
	if(aName != null && aName.length){
		//alert(aName.length+"-"+NameList);
		for(var i = 0; i < aName.length; i++) {
			ThisCost = aPrice[i] * aQuant[i];
			subt = subt + (aPrice[i] * aQuant[i]);
		} 
	// Work out GST
	/*if(ShopShippingOption == 'Australia'){
		// Shipping
		ShopShippingTotal = ShopShippingAustralia;
		if(ShopProductTaxAdded == false){
			TaxTotal = (subt + ShopShippingTotal) *ShopProductTaxPercent;
		}
	} else {
		
	}*/
		// Is this user in Australia?
		if(ShopShippingOption == 'Australia' || ShopShippingOption == 'AU'){
			// Shipping?
			ShopShippingTotal = ShopShippingAustralia;
			
			// Deal With GST
			// Have we already added GST to prices?
			if(ShopProductTaxAdded) {
				ShopTaxTitle = 'Prices include GST(10%)';
				TaxTotal = 0;
			} else {
				ShopTaxTitle = '10% GST(Applicable in Australia)';
				TaxTotal = (subt + ShopShippingTotal) / ((ShopProductTaxPercent+100) / ShopProductTaxPercent);
			}
		} else {
			// Add Shipping
			ShopShippingTotal = ShopShippingOverseas;
			// Deal With GST
			// Have we already added GST to prices?
			if(ShopProductTaxAdded) {
				ShopTaxTitle = 'GST(10%) Removed from Prices';
				TaxTotal = -(parseInt((subt + ShopShippingTotal) / ((ShopProductTaxPercent+100) / ShopProductTaxPercent)));
				//TaxTotal = -((subt + ShopShippingTotal) / 11);
			} else {
				ShopTaxTitle = 'GST(10%) NA Outside of Australia';
				TaxTotal = 0;
			}
		}
		// Update totals
		tot = subt + TaxTotal + ShopShippingTotal;
		
	// Nothing in 
	} else {
	
	}
	
	if(subt >0) {
		ShopCartHasItems = true;
	}
		
	}
}
// Save Arrays to Cookie
function SetItemsCookie(){
	var date = new Date();
    date.setTime(date.getTime()+ (2*24*60*60*1000));
	//Split array so we can store multiple values in one cookie
	SetCookie('aName', aName.join("|"), date);
	SetCookie('aDescr', aDescr.join("|"), date);
	SetCookie('aStyle', aStyle.join("|"), date);
	SetCookie('aQuant', aQuant.join("|"), date);
	SetCookie('aPrice', aPrice.join("|"), date);
	SetCookie('ShopSubTotal', subt, date);
	SetCookie('ShopTotal', tot, date);
	SetCookie('ShopShippingOption', ShopShippingOption, date);
	SetCountry(ShopShippingOption,false)
	
}

/* Tools
=============================================================================================*/
// Check Browser is up to the task of our Shopping cart.
function IsBrowserOK() {
	//CookiesOK = IsCookiesEnabled();
	if(!IsCookiesEnabled()){return false;}
	if(!IsBrowserOK.arguments){return false;}
	ShopCartHasItems = false;
	return true;
}
//--- The AddDecimal function adds a decimal point to the prices and subtotal.
function AddDecimal(number)
{
	var withdecimal = "";
	var num = "" + number;
	if (num.length == 0){
	    withdecimal += "0";
	} else if(num.length == 1) {
	    withdecimal += "0.0" + num;
	} else if(num.length == 2) {
	    withdecimal += "0." + num;
	} else {
	 withdecimal += num.substring(0, num.length - 2);
	 withdecimal += "."
	 withdecimal += num.substring(num.length - 2, num.length);
	}
	return withdecimal;
}

// Open Window to convert price
function CurrencyPopup(convertPrice) { 
	CurrencyWindow = window.open ("http://www.xe.net/ecc/input.cgi?Template=sw&"+ "Amount=" + convertPrice + "&From=AUD", "CurrencyRemote", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,height=170,width=600");
	CurrencyWindow.location.href = "http://www.xe.net/ecc/input.cgi?Template=sw&"+ "Amount=" + convertPrice + "&From=AUD";
}

// Cookie Functions
function IsCookiesEnabled(){
  var expDate = new Date();
  //valid 2 days
  expDate.setTime( expDate.getTime() + ( 2*24*60 * 1000 ) );
  SetCookie( "CookiesEnabled", "Yes", expDate );
  CookiesEnabled = GetCookie( "CookiesEnabled" );

  if (CookiesEnabled == "Yes" ) {
    return true;
  } else {
    return false;
  }
}

function SetCookie(name,value,expires,path,domain,secure) {
    document.cookie = name + "=" +escape(value) +
        ( (expires) ? ";expires=" + expires.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") + 
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
}
function GetCookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

function DeleteCookie(name) {
 // var expdate = new Date();
  //expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
  var date = new Date();
    date.setTime(date.getTime()+
    (-1*24*60*60*1000))
 //   var expires = "; expires="+
 //   date.toGMTString()
    
  SetCookie(name, "");
}


/* OnLoad Actions
=============================================================================================*/
// Load Items from Cookie
GetItemsCookie();