//Global Variables
//browser check here to account for differences in each browsers DOM

isNS4 = (document.layers) ? true : false;
isIE4 = (document.all && !document.getElementById) ? true : false;
isIE5plus_Op5 = (document.all && document.getElementById) ? true : false;
isNS6plus_Op6plus = (!document.all && document.getElementById) ? true : false;
isMac = (navigator.userAgent.indexOf("Mac") != -1) ? true: false;

//End Global




function FormatNumber(Number,Decimals,Separator)
{
 // **********************************************************
 // Placed in the public domain by Affordable Production Tools
 // March 21, 1998
 // Web site: http://www.aptools.com/
 //
 // November 24, 1998 -- Error which allowed a null value
 // to remain null fixed. Now forces value to 0.
 //
 // October 28, 2001 -- Modified to provide leading 0 for fractional number
 // less than 1.
 //
 // This function accepts a number to format and number
 // specifying the number of decimal places to format to. May
 // optionally use a separator other than '.' if specified.
 //
 // If no decimals are specified, the function defaults to
 // two decimal places. If no number is passed, the function
 // defaults to 0. Decimal separator defaults to '.' .
 //
 // If the number passed is too large to format as a decimal
 // number (e.g.: 1.23e+25), or if the conversion process
 // results in such a number, the original number is returned
 // unchanged.
 // **********************************************************
 Number += ""          // Force argument to string.
 Decimals += ""        // Force argument to string.
 Separator += ""       // Force argument to string.
 if((Separator == "") || (Separator.length > 1))
  Separator = "."
 if(Number.length == 0)
  Number = "0"
 var OriginalNumber = Number  // Save for number too large.
 var Sign = 1
 var Pad = ""
 var Count = 0
 // If no number passed, force number to 0.
 if(parseFloat(Number)){
  Number = parseFloat(Number)} else {
  Number = 0}
 // If no decimals passed, default decimals to 2.
 if((parseInt(Decimals,10)) || (parseInt(Decimals,10) == 0)){
  Decimals = parseInt(Decimals,10)} else {
  Decimals = 2}
 if(Number < 0)
 {
  Sign = -1         // Remember sign of Number.
  Number *= Sign    // Force absolute value of Number.
 }
 if(Decimals < 0)
  Decimals *= -1    // Force absolute value of Decimals.
 // Next, convert number to rounded integer and force to string value.
 // (Number contains 1 extra digit used to force rounding)
 Number = "" + Math.floor(Number * Math.pow(10,Decimals + 1) + 5)
 if((Number.substring(1,2) == '.')||((Number + '')=='NaN'))
  return(OriginalNumber) // Number too large to format as specified.
 // If length of Number is less than number of decimals requested +1,
 // pad with zeros to requested length.
 if(Number.length < Decimals +1) // Construct pad string.
 {
  for(Count = Number.length; Count <= Decimals; Count++)
   Pad += "0"
 }
 Number = Pad + Number // Pad number as needed.
 if(Decimals == 0){
  // Drop extra digit -- Decimal portion is formatted.
  Number = Number.substring(0, Number.length -1)} else {
  // Or, format number with decimal point and drop extra decimal digit.
 Number = Number.substring(0,Number.length - Decimals -1) +
          Separator +
          Number.substring(Number.length - Decimals -1,
          Number.length -1)}
 if((Number == "") || (parseFloat(Number) < 1))
  Number="0"+Number // Force leading 0 for |Number| less than 1.
 if(Sign == -1)
  Number = "-" + Number  // Set sign of number.
 return(Number)
}






//checks to ensure that a valid quanity has been entered into the quantity field
function badQty(qtyString) {
	if ((qtyString <= 0) || isNaN(qtyString) || isNaN(parseInt(qtyString))) {
		//qty is <= zero or not a number, so not valid.
		return true;
	}
	for ( i = 0; i < qtyString.length; i++ ) {
		chk = qtyString.substring(i, i+1);
	       if (chk == '.') {
	       	//decimal point found, so not valid quantity.
	       	return true;
	       }
	}
	if (qtyString.length > 5) {
		//quantity is greater than 5 characters, e.g. 100001, only accepts
		//1 - 99999 max quantity of one product on any one order line
		return true;
	}

	//if none of the above are met then return false as quantity is valid.
	return false;

}

//decodes the ecom cookie, see the encode method as this method reversing the replacement
//of the special characters and splits the ecom cookie into the individual fields
function decode(encoded_string){
	var Fields = encoded_string.split("|")
	regexp1 = /____/gi;
	regexp2 = /___/gi;
	regexp3 = /__/gi;
	regexp4 = /_/gi;
	for(var i=0;i<Fields.length;i++){
		while(regexp1.test(Fields[i]))
			Fields[i] = Fields[i].replace(regexp1 , "|");
		while(regexp2.test(Fields[i]))
			Fields[i] = Fields[i].replace(regexp2 , ";");
		while(regexp3.test(Fields[i]))
			Fields[i] = Fields[i].replace(regexp3 , ",");
		while(regexp4.test(Fields[i]))
			Fields[i] = Fields[i].replace(regexp4 , " ");
	}
	return Fields;
}

//encodes the individual fields into one order line to be stored in the ecom cookie, replacing
//special characters using regular expressions
function encode(ProductCode, ProductName, Price, Tax, Currency, Quantity ) {
	Fields = [ProductCode, ProductName,Price,Tax,Currency,Quantity];

	//regexp1 test means match either "_" "(" "-" "+" ")" or "white space" or "line feed"
	//and replace it with an "_"
	//the "/g" means to do a global match
	regexp1 = /_(_+)|\s|\n/g;

	//regexp2 means match "," replace it with "__", match ";" replace with "___" or match
	//"|" and replace with "____"
	//the "/g" means to do a global match
	regexp2 = /,|;|\|/g;

	for(i=0;i<Fields.length;i++){
		while(regexp1.test(Fields[i]))
			Fields[i] = Fields[i].replace(/_(_+)|\s|\n/g , "_");
		while(regexp2.test(Fields[i])){
			Fields[i] = Fields[i].replace(/,/g , "__");
			Fields[i] = Fields[i].replace(/;/g , "___");
			Fields[i] = Fields[i].replace(/\|/g , "____");
		}
	}
	return Fields.join("|");
}


// If this changes, clone of this function in EcomCode.js must be equally changed
// checks the fields contain valid values
	function areFieldsConstrained(ProductCode, ProductName, Price, Tax, Currency, Quantity){
 	       regexp = /_|\n/gi;
  	     //
	 	if (regexp.test(ProductCode + ProductName + Price + Tax + Currency + Quantity) || 
   	         encode(ProductCode,ProductName,Price,Tax,Currency,Quantity).length > 500)
    	            return false;
     	   else
      	         return true;
	}          


//  writes the html cart to the page
// Note that the header and footer are only used when there are items in the cart.
function htmlCart(siteid){

//browser check, if using unsupported old version of IE, Netscape or Opera, 
//show warning and provide links to get new browser
var browser_name = navigator.appName;
var browser_version = parseFloat(navigator.appVersion);

if ((browser_name == "Microsoft Internet Explorer" && browser_version < 4.0) || 
(browser_name == "Netscape" && browser_version < 4.0) || 
(browser_name == "Opera" && browser_version < 5.0)) {
	html = "<h4>***** EZ Shop Error: Unsupported Old Browser Detected! *****</h4>";
	html += "<h4>Use one of the following links to download an up to date browser.</h4>";
	html += "<p><a href=\"http://www.microsoft.com/windows/ie/default.asp\">";
	html += "Internet Explorer</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	html += "<a href=\"http://home.netscape.com/computing/download/index.html?cp=brigubdwn\">";
	html +="Netscape</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	html +="<a href=\"http://www.opera.com/download/\">Opera</a></p>";
	html +="<a href=\"http://www.microsoft.com/mac/products/ie/ie_default.asp\">";
	html += "Internet Explorer (Mac)</a>";
	html +="<h4>***** End of Error Report *****</h4>";

	return html;
}

	//test to see if user has cookies enabled in their browser
	if (document.cookie == "" || document.cookie == null) {
		Set_Cookie("cookietest", "true", null, "/");
		var cookiesOn = Get_Cookie("cookietest");
		if (cookiesOn != "true") {
			//cookies are not enabled
			html = "<h4>***** Shop Error: Cannot Write Cookies! *****</h4>";
			html += "<h4>Please enable Cookies in your browser settings.</h4>";
			html +="<h4>***** End of Error Report *****</h4>";
			return html;
		}	
		Delete_Cookie("cookietest", "/");
	}


		var header = "<table border='1' bordercolorlight='silver' cellspacing='0' cellpadding='1'><tr class='headerRow'>" +
					"<td class='productCodeColumn'><font class='headerRow'>Product Code</font></td>" +
					"<td class='productColumn'><font class='headerRow'>Product Name</font></td>" +
					"<td class='quantityColumn'><font class='headerRow'>Quantity</font></td>" +
					"<td class='itemPriceColumn'><font class='headerRow'>Price per Item</font><br><font class='exTaxText'> (inc. VAT)</font></td>" +
					"<td class='orderPriceColumn'><font class='headerRow'>Price of Order</font><br><font class='exTaxText'> (inc. VAT)</font></td>" +
					"<td class='removeColumn'><font class='headerRow'>Remove</font></td></tr>";
		var footer = "</table>";
	
	//gets the delivery value cookie
	iDelVal = 0;
	iDelVal = Get_Cookie("DelVal");
	if (iDelVal == null) {
		iDelVal = "Not set";
	}
	
	//gets the order number cookie
	iOrderNo = 0;
   	iOrderNo = Get_Cookie("OrderNo");

   	html = header;
	var subTotal = 0.0;
	var taxTotal = 0.0;
	var total = 0.0;

	//decodes and splits the ecom cookie holding the order details into the individual fields
   	if ((iOrderNo != null) && (iOrderNo > 0)) {
   	
   	for ( i = 1; i <= iOrderNo; i++ ) {
      NewOrder = "ecom" + siteid + i;
      NOCookie = "";
      NOCookie = Get_Cookie(NewOrder);

      CookiePart0 = NOCookie.indexOf("|", 0);
      CookiePart1 = NOCookie.indexOf("|", CookiePart0+1);
      CookiePart2 = NOCookie.indexOf("|", CookiePart1+1);
      CookiePart3 = NOCookie.indexOf("|", CookiePart2+1);
      CookiePart4 = NOCookie.indexOf("|", CookiePart3+1);
      CookiePart5 = NOCookie.indexOf("|", CookiePart4+1);

      fields = new Array;
      fields[0] = NOCookie.substring( 0, CookiePart0 );
      fields[1] = NOCookie.substring( CookiePart0+1, CookiePart1 );
      fields[2] = NOCookie.substring( CookiePart1+1, CookiePart2 );
      fields[3] = NOCookie.substring( CookiePart2+1, CookiePart3 );
      fields[4] = NOCookie.substring( CookiePart3+1, CookiePart4 );
      fields[5] = NOCookie.substring( CookiePart4+1, CookiePart5 );
      fields[6] = NOCookie.substring( CookiePart5+1, NOCookie.length );

	var item = decode(fields[6]);
	html += "<tr>";

		// item[2] represents the price field
		if (item.length >=2 && isNaN(item[2])==false){
			var quantity;
			// item[5] represents the quantity field				
		   	if (item.length >=5 && isNaN(item[5])==false){
				    quantity = parseFloat(item[5]);
				}else{
					quantity = 1;
			}
			
				var temp = Math.pow(10,2);
				var orderPrice = Math.round((item[2] * quantity) * temp) / temp;
				subTotal += orderPrice;
				orderPrice = Math.round((item[2] * quantity) * temp) / temp;
				orderPrice = FormatNumber(orderPrice,2,'.');
			}
			
		//writes the fields to the page
		if (item[4] == "x") {
		item[4] = "\u20AC";
		}
		html += "<td class='productCodeColumn'><font class='productCodeText'>" + item[0] + "</font></td>";
		html += "<td class='productColumn'><font class='productText'>" + item[1] + "</font></td>";
		html += "<td class='quantityColumn'><font class='quantityText'>" + item[5] + "</font></td>";
		html += "<td class='itemPriceColumn'><font class='itemPriceText'><b>" + item[4] + "</b>" + item[2] + "</font></td>";
		html += "<td class='orderPriceColumn'><font class='orderPriceText'><b>" + item[4] + "</b>" + orderPrice + "</font></td>";
			
			html += "<td class='removeColumn'><font class='removeText'>"			
			if (item.length>=4){
			   	html += "<A class=\"removeLink\" HREF=\"javascript: removeFromCart('" + siteid + "', '" +i+ "','"
			+ item[0] + "','" + item[1] +"','" + item[2] + "','" + item[3] + "','" + item[4] +
				"'); refreshMain(); \">Remove</A>";
			}else{
				html += "<! Can't add remove link due to an insufficient number\of fields available>";
			}
			html += "</font></td></tr>";
			
		//writes the fields to hidden fields in order to send order details in e-mail
		html += "\n";
		html += "<input type=\"hidden\" name=\"ProductCode_" + i + "\" value=\"" + item[0] + "\">";
		html += "<input type=\"hidden\" name=\"ProductName_" + i + "\" value=\"" + item[1] + "\">";
		html += "<input type=\"hidden\" name=\"Quantity_" + i + "\" value=\"" + item[5] + "\">";
		html += "<input type=\"hidden\" name=\"PricePerItem_" + i + "\" value=\"" + item[2] + "\">";
		html += "<input type=\"hidden\" name=\"PriceOfOrder_" + i + "\" value=\"" + orderPrice + "\">";
		html += "\n";
					
		}
		
		//checks if the delivery value has been set or not
		taxVal = item[3];
		if (iDelVal == "Not set") {
			taxTotal = (taxVal / 100) * subTotal;
			total = taxTotal + subTotal;
		}
		else {
			iDelVal = Math.round(iDelVal * 100) / 100;
			taxTotal = (taxVal / 100) * (subTotal + iDelVal);
			total = taxTotal + subTotal + iDelVal;
		}
	
		html +="<tr></tr><tr></tr>";
		
		//writes the totals
		   var temp = Math.pow(10,2);
	       subTotal = Math.round(subTotal * temp) / temp;
	       taxTotal = Math.round(taxTotal * temp) / temp;
	       total = Math.round(total * temp) / temp;
	       subTotal = FormatNumber(subTotal,2,'.');
	       total = FormatNumber(total,2,'.');
		html += "<tr><td class='productCodeColumn'>&nbsp;</td>";
	       html += "<td class='productColumn'>&nbsp;</td><td class='quantityColumn'>&nbsp;</td><td colspan='2'>";
	       html += "<table border='0' cellspacing='0' cellpadding='1'>";	       
	       html += "<tr><td class='totalsLabels'><font class='subTotalLabel'>Sub Total</font></td><td class='totalsValues'><font class='subTotalValue'>" + item[4] + subTotal + "</font></td></tr>"
		
		   iDelVal = FormatNumber(iDelVal,2,'.');
		   
		   html += "<tr><td class='totalsLabels'><font class='deliveryLabel'>Delivery included</td><td class='totalsValues'><font class='deliveryValue'>" + "</font></td></tr>"
		
		//html += "<tr><td class='totalsLabels'><font class='deliveryLabel'><a class=\"deliveryLink\" href=\"javascript: setDelivery()\">Delivery</a></font></td><td class='totalsValues'><font class='deliveryValue'>" + item[4] + iDelVal + "</font></td></tr>"
		
		
		//html += "<tr><td class='totalsLabels'><font class='taxLabel'>Tax @ " + taxVal + "%</font></td><td class='totalsValues'><font class='taxValue'>" + item[4] + taxTotal + "</font></td></tr>"
		
		html += "<tr><td class='totalsLabels'><font class='taxLabel'>VAT Included" + "</font></td><td class='totalsValues'><font class='taxValue'></font></td></tr>"
		
		html += "<tr><td class='totalsLabels'><font class='totalCostLabel'>Total Cost</font></td><td class='totalsValues'><font class='totalCostValue'>" + item[4] + total + "</font></td></tr>"
		html += "</table></td><td class='removeColumn'>&nbsp;</td></tr>";
		html += footer;
		
		//writes the totals to hidden fields to be sent in the e-mail
		html += "<input type=\"hidden\" name=\"Currency\" value=\"" + item[4] + "\">";
		html += "<input type=\"hidden\" name=\"SubTotal\" value=\"" + subTotal + "\">";
		html += "<input type=\"hidden\" name=\"Delivery\" value=\"" + iDelVal + "\">";
		html += "<input type=\"hidden\" name=\"Tax\" value=\"" + taxTotal + "\">";
		html += "<input type=\"hidden\" name=\"TotalCost\" value=\"" + total + "\">";
		
	}else{
		//writes that the cart is empty if nothing has been bought yet
		html = "<font class='emptyCartText'>Your shopping cart is empty.</font><BR>";
		Delete_Cookie("DelVal", "/");
	}
    return html;
}


//removes an order line from the cart
function removeFromCart(siteid, DelOrder, ProductCode, ProductName, Price, Tax, Currency){
	if (!areFieldsConstrained(ProductCode, ProductName, Price, Tax, Currency, 1)){
		alert("An ecommerce engine error has occured.");
		return false;
	}

	if ( confirm("Click 'Ok' to remove this product from your shopping cart.") ) {
		OrderNo = Get_Cookie("OrderNo");
      		for ( i=DelOrder; i < OrderNo; i++ ) {
			var j = 1 + parseInt(i);
			NewOrder1 = "ecom" + siteid + j;
   	 	   	NewOrder2 = "ecom" + siteid + i;
    	 	  	NO1Cookie = Get_Cookie(NewOrder1);
	      		Set_Cookie(NewOrder2, NO1Cookie, null, "/");
      		}
      		NewOrder = "ecom" + siteid + OrderNo;
			if (OrderNo == 1) {
				Delete_Cookie("OrderNo", "/");
			} else {
	       		Set_Cookie("OrderNo", OrderNo-1, null, "/");
			}
      		Delete_Cookie(NewOrder, "/");
	}
}


//adds an order line to the cart
function addToCart(siteid,ProductCode,ProductName, Price, Tax, Currency, Quantity){
	if (!areFieldsConstrained(ProductCode, ProductName, Price, Tax, Currency, Quantity)){
		alert("An ecommerce engine error has occured.");
		return false;
	}

	if (badQty(Quantity)) {
		alert("Please enter a valid quantity, must be a number between 1 and 99999");
		return false;
	}

	productExists = false;
	iOrderNo = 0;
	iOrderNo = Get_Cookie("OrderNo");
	if (iOrderNo == null) {
		//if first order, set order number to zero as previous get cookie would have
		//returned null
		iOrderNo = 0;
	}
	
	for ( i = 1; i <= iOrderNo; i++ ) {
		NewOrder = "ecom" + siteid + i;
		NOCookie = "";
		NOCookie = Get_Cookie(NewOrder);

		CookiePart0 = NOCookie.indexOf("|", 0);
		CookiePart1 = NOCookie.indexOf("|", CookiePart0+1);
 		CookiePart2 = NOCookie.indexOf("|", CookiePart1+1);
  		CookiePart3 = NOCookie.indexOf("|", CookiePart2+1);
  		CookiePart4 = NOCookie.indexOf("|", CookiePart3+1);
		CookiePart5 = NOCookie.indexOf("|", CookiePart4+1);

  		fields = new Array;
  		fields[0] = NOCookie.substring( 0, CookiePart0 );
  		fields[1] = NOCookie.substring( CookiePart0+1, CookiePart1 );
  		fields[2] = NOCookie.substring( CookiePart1+1, CookiePart2 );
  		fields[3] = NOCookie.substring( CookiePart2+1, CookiePart3 );
  		fields[4] = NOCookie.substring( CookiePart3+1, CookiePart4 );
		fields[5] = NOCookie.substring( CookiePart4+1, CookiePart5 );
   		fields[6] = NOCookie.substring( CookiePart5+1, NOCookie.length );

		var item = decode(fields[6]);
		var existsQuantity = parseFloat(item[5]);
	
		if ((item[0] == ProductCode) && (item[1] == ProductName) && 
			(item[2] == Price) && (item[3] == Tax) && (item[4] == Currency)) {

			productExists = true;		
			Delete_Cookie(NewOrder, "/");
			var newQuantity = parseInt(Quantity) + parseInt(existsQuantity);
			if (Currency == "x") {
			Currency = "\u20AC";
			}
			Set_Cookie("ecom" + siteid + i,encode(ProductCode, ProductName, Price, Tax, Currency, newQuantity ), null, "/");
		}
			
	}

	if (!productExists) {	
		
		if (iOrderNo == '18') {
			//due to cookie restrictions can only have max of 18 order lines, so prompt user
			//to process their current order before ordering any more
			alert("Your shopping cart is full! Please proceed to checkout to submit your " +
				"order, before placing another order.");
			return false; 
		}

		iOrderNo++;
		Set_Cookie("ecom" + siteid + iOrderNo,encode(ProductCode, ProductName, Price, Tax, Currency, Quantity ), null, "/");
		Set_Cookie("OrderNo", iOrderNo, null, "/");
	}

	if (Currency == "x") {
	Currency = "\u20AC";
	}
	alert(Quantity + " " + ProductCode + ": " + ProductName + " @ " + Currency + Price + " added to your cart.");
	return;
}


// function to open a popup window and center it
function openCenterWin( windowURL, windowName, theWidth, theHeight, windowFeatures ) {
	if (theWidth >= screen.availWidth) {
		var theLeft = screen.availLeft;
		theWidth = screen.availWidth;
	}
	else {
		var theLeft = (screen.width/2) - (theWidth/2);
	}
	
	if (theHeight >= screen.availHeight) {
		var theTop = screen.availTop;
		theHeight = screen.availHeight;
	}
	else {
		var theTop = (screen.height/2) - (theHeight/2);
	}
	
	var features = 'height=' + theHeight + ',width=' + theWidth + ',top=' + theTop +
		',left=' + theLeft + windowFeatures;
	theWin = window.open(windowURL, windowName, features);

	theWin.resizeTo(theWidth,theHeight);
	theWin.focus();
}


//reads the delivey cookie to check if a delivery value has been chosen, if not then opens
//delivery window on the checkout page to prompt user to first choose delivery before
//filling in any form data
function checkDelivery() {
	iDelVal = 0;
	iDelVal = Get_Cookie("DelVal");
	iOrderNo = 0;
   	iOrderNo = Get_Cookie("OrderNo");
	if ((iOrderNo != null && iOrderNo != 0 && iOrderNo != '0') && (iDelVal == null || iDelVal == "Not set")) {
		alert("Please choose a Delivery method before proceeding with your order.");
		setDelivery();
	}
}


// reads the delivery value cookie and sets the delivery value in the select list in the delivery window
// to the correct value previously chosen
function retrieveDelivery() {
	var oldDelVal = Get_Cookie("DelVal");
	if (oldDelVal != null) {
		var newDelVal = oldDelVal.toString();
		for (var i = 0; i < document.DeliveryForm.user_Delivery.options.length; i++) {
			if (document.DeliveryForm.user_Delivery.options[i].value == newDelVal) {
				document.DeliveryForm.user_Delivery.selectedIndex = i;
			}
		}		
	}
}


// updates the delivery cookie with the new value chosen from the select list in the delivery window
function doDelivery() {
	var selectedVal = document.DeliveryForm.user_Delivery.options[document.DeliveryForm.user_Delivery.selectedIndex].value;
	Set_Cookie("DelVal", selectedVal, null, "/");
	refreshDel();
	//if only 1 delivery type and this is Free with a value of zero, then auto set to this and close the window
	if (document.DeliveryForm.user_Delivery.length == 1 && 
		document.DeliveryForm.user_Delivery.options[document.DeliveryForm.user_Delivery.selectedIndex].value == "0" &&
		document.DeliveryForm.user_Delivery.options[document.DeliveryForm.user_Delivery.selectedIndex].text == "Free") {
			alert('Delivery is free on all orders!');
			window.close();
	}
}


// refresh functions which handles different browser requirements
function refreshDel() {
	isNS4 = (document.layers) ? true : false;
	isIE4 = (document.all && !document.getElementById) ? true : false;
	isIE5plus_Op5 = (document.all && document.getElementById) ? true : false;
	isNS6plus_Op6plus = (!document.all && document.getElementById) ? true : false;
	isMac = (navigator.userAgent.indexOf("Mac") != -1) ? true: false;

	if (isMac) {
		if (isIE5plus_Op5) {
			opener.location.reload(true);
		}
		else {
			opener.history.go(0);
		}
	}
	else {
		if (isNS4 || isNS6plus_Op6plus || isIE5plus_Op5) {
			opener.location.href = opener.location.href;
		}
		else {
			opener.history.go(0);
		}
	}
}

function refreshMain() {
	if (isMac) {
		if (isIE5plus_Op5) {
			window.location.reload(true);
		}
		else {
			window.history.go(0);
		}
	}
	else {
		if (isNS4 || isNS6plus_Op6plus || isIE5plus_Op5) {
			window.location.href = window.location.href;
		}
		else {
			window.history.go(0);
		}
	}
}

// STANDARD FUNCTIONS for interacting with cookies using javascript 
function Get_Cookie(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;
	if (isMac && (isIE4 || isIE5plus_Op5)) {
		return document.cookie.substring(len,end);
	}
	else {
    		return unescape(document.cookie.substring(len,end));
	}
}


function Set_Cookie(name,value,expires,path,domain,secure) {
	if (isMac && (isIE4 || isIE5plus_Op5)) {
		var cookieVal = value;
	}
	else {
		var cookieVal = escape(value);
	}
    document.cookie = name + "=" + cookieVal +
        ( (expires) ? ";expires=" + expires.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") + 
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
}


function Delete_Cookie(name,path,domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" +
        ( (path) ? ";path=" + path : "") +
        ( (domain) ? ";domain=" + domain : "") +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// END STANDARD FUNCTIONS


// validates the checkout page form, depending on which one used
function validateCheckout(form) {
	iOrderNo = 0;
   	iOrderNo = Get_Cookie("OrderNo");
   	if ((iOrderNo == null) || (iOrderNo == 0) || (iOrderNo == '0')) {
   		alert("Please add something to your shopping cart that you wish to order.");
   		return false;
   	}

	var credSet = "0123456789";
	var numSet = "0123456789+-() ";
	var alphaSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ()- ";
	var invalid = false;
	
	//check if this field exists to determine which checkout form is being validated
	if (form.user_cardIssue) {

	if ((form.user_cardIssue.value != "") && (validateField(form.user_cardIssue.value, credSet) != true)) {
		if (!isNS4) {
		getDocRef('crdisstd').style.color = 'red';
		getDocRef('crdissinput').style.backgroundColor = '#FFFFCC';
		}
		form.user_cardIssue.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('crdisstd').style.color = 'black';
		getDocRef('crdissinput').style.backgroundColor = 'white';
		}
	}
	
	if (form.user_endYY.options[form.user_endYY.selectedIndex].value == "yyyy") {
		if (!isNS4) {
		getDocRef('extd').style.color = 'red';
		getDocRef('endYYinput').style.backgroundColor = '#FFFFCC';
		}
		form.user_endYY.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('extd').style.color = 'black';
		getDocRef('endYYinput').style.backgroundColor = 'white';
		}
	}

	if (form.user_endMM.options[form.user_endMM.selectedIndex].value == "mm") {
		if (!isNS4) {
		getDocRef('extd').style.color = 'red';
		getDocRef('endMMinput').style.backgroundColor = '#FFFFCC';
		}
		form.user_endMM.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {	
		getDocRef('extd').style.color = 'black';
		getDocRef('endMMinput').style.backgroundColor = 'white';
		}
	}

	if ((form.user_cardName.value == "") || (validateField(form.user_cardName.value, alphaSet) != true)) {
		if (!isNS4) {
		getDocRef('crdnametd').style.color = 'red';
		getDocRef('crdnameinput').style.backgroundColor = '#FFFFCC';
		}
		form.user_cardName.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('crdnametd').style.color = 'black';
		getDocRef('crdnameinput').style.backgroundColor = 'white';
		}
	}

	if ((form.user_cardNumber.value == "") || (validateField(form.user_cardNumber.value, credSet) != true)) {
		if (!isNS4) {
		getDocRef('cdnumtd').style.color = 'red';
		getDocRef('cdnuminput').style.backgroundColor = '#FFFFCC';
		}
		form.user_cardNumber.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('cdnumtd').style.color = 'black';
		getDocRef('cdnuminput').style.backgroundColor = 'white';
		}
	}

	if (form.user_cardtype.options[form.user_cardtype.selectedIndex].value == "NotChosen") {
		if (!isNS4) {
		getDocRef('cardtd').style.color = 'red';
		getDocRef('cardinput').style.backgroundColor = '#FFFFCC';
		}
		form.user_cardtype.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('cardtd').style.color = 'black';
		getDocRef('cardinput').style.backgroundColor = 'white';
		}
	}

	}

	if (form.user_country.options[form.user_country.selectedIndex].value == "NotChosen") {
		if (!isNS4) {
		getDocRef('ctytd').style.color = 'red';
		getDocRef('ctyinput').style.backgroundColor = '#FFFFCC';
		}
		form.user_country.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('ctytd').style.color = 'black';
		getDocRef('ctyinput').style.backgroundColor = 'white';
		}
	}

	if ((form.user_email.value == "") || (checkEmail(form.user_email.value) != true)) {
		if (!isNS4) {
		getDocRef('emtd').style.color = 'red';
		getDocRef('eminput').style.backgroundColor = '#FFFFCC';
		}
		form.user_email.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('emtd').style.color = 'black';
		getDocRef('eminput').style.backgroundColor = 'white';
		}
	}

	//if ((form.user_postzip.value == "") || ((checkPostcode(form.user_postzip.value) != true) &&
		//(checkZipcode(form.user_postzip.value) != true))) {
		//if (!isNS4) {
		//getDocRef('pztd').style.color = 'red';
		//getDocRef('pzinput').style.backgroundColor = '#FFFFCC';
		//}
		//form.user_postzip.focus();
		//invalid = true;
	//}
	//else {
		//if (!isNS4) {
		//getDocRef('pztd').style.color = 'black';
		//getDocRef('pzinput').style.backgroundColor = 'white';
		//}
	//}

	if ((form.user_fax.value != "") && (validateField(form.user_fax.value, numSet) != true)) {
		if (!isNS4) {
		getDocRef('faxtd').style.color = 'red';
		getDocRef('faxinput').style.backgroundColor = '#FFFFCC';
		}
		form.user_fax.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('faxtd').style.color = 'black';
		getDocRef('faxinput').style.backgroundColor = 'white';
		}
	}

	if (form.user_county.value == "") {
		if (!isNS4) {
		getDocRef('cntd').style.color = 'red';
		getDocRef('cninput').style.backgroundColor = '#FFFFCC';
		}
		form.user_county.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('cntd').style.color = 'black';
		getDocRef('cninput').style.backgroundColor = 'white';
		}
	}
	
	if ((form.user_mobile.value != "") && (validateField(form.user_mobile.value, numSet) != true)) {
		if (!isNS4) {
		getDocRef('mobtd').style.color = 'red';
		getDocRef('mobinput').style.backgroundColor = '#FFFFCC';
		}
		form.user_mobile.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('mobtd').style.color = 'black';
		getDocRef('mobinput').style.backgroundColor = 'white';
		}
	}
	
	if (form.user_town.value == "") {
		if (!isNS4) {
		getDocRef('tctd').style.color = 'red';
		getDocRef('tcinput').style.backgroundColor = '#FFFFCC';
		}
		form.user_town.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('tctd').style.color = 'black';
		getDocRef('tcinput').style.backgroundColor = 'white';
		}
	}

	if ((form.user_phone.value == "") || (validateField(form.user_phone.value, numSet) != true)) {

	if (!isNS4) {
		getDocRef('phtd').style.color = 'red';
		getDocRef('phinput').style.backgroundColor = '#FFFFCC';
		}
		form.user_phone.focus();

	invalid = true;
	}
	else {

	if (!isNS4) {
		getDocRef('phtd').style.color = 'black';
		getDocRef('phinput').style.backgroundColor = 'white';
		}
	}


	if (form.user_address1.value == "") {
		if (!isNS4) {
		getDocRef('ad1td').style.color = 'red';
		getDocRef('ad1input').style.backgroundColor = '#FFFFCC';
		}
		form.user_address1.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('ad1td').style.color = 'black';
		getDocRef('ad1input').style.backgroundColor = 'white';
		}
	}
	
	if ((form.user_surname.value == "") || (validateField(form.user_surname.value, alphaSet) != true)) {
		if (!isNS4) {
		getDocRef('sntd').style.color = 'red';
		getDocRef('sninput').style.backgroundColor = '#FFFFCC';
	}
		form.user_surname.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('sntd').style.color = 'black';
		getDocRef('sninput').style.backgroundColor = 'white';
		}
	}
	
	if ((form.user_firstname.value == "") || (validateField(form.user_firstname.value, alphaSet) != true)) {
		if (!isNS4) {
		getDocRef('fntd').style.color = 'red';
		getDocRef('fninput').style.backgroundColor = '#FFFFCC';
		}
		form.user_firstname.focus();
		invalid = true;
	}
	else {
		if (!isNS4) {
		getDocRef('fntd').style.color = 'black';
		getDocRef('fninput').style.backgroundColor = 'white';
		}
	}
	
	// if any of the fields are invalid, highlights those fields and doesn't allow a submit
	if (invalid) {
		if (!isNS4) {
			alert("Please correct the highlighted fields and then re-submit");
		} else {
			alert("Please ensure all fields you have entered data in are valid and you have completed the fields marked with an *.  Then re-submit");
		}
		return false;
	}
	else {
		return true;
	}
}


// routine to validate an e-mail field using a regular expression
function checkEmail(emailVal) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailVal))
		return (true);
}


// routine to validate a postcode field
function checkPostcode(postcodeVal) {
	pcode = postcodeVal; 
	size = pcode.length;
	count1 = pcode.indexOf(" ");
	count2 = pcode.lastIndexOf(" ");
  	
  	if ((size < 6 || size > 8)  || (!(isNaN(pcode.charAt(0)))) || (isNaN(pcode.charAt(size-3))) ||
  		(!(isNaN(pcode.charAt(size-2)))) || (!(isNaN(pcode.charAt(size-1)))) || (!(pcode.charAt(size-4) == " ")) ||
  		(count1 != count2)) {
  		return false;
  	}
  	else {
  		return true;
  	}
}


// routine to validate a zipcode field
function checkZipcode(zipcodeVal) {
	var valid = "0123456789-";
	var hyphencount = 0;
	if (zipcodeVal.length != 5 && zipcodeVal.length != 10) {
		return false;
	}
	for (var i=0; i < zipcodeVal.length; i++) {
		temp = "" + zipcodeVal.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1") {
			return false;
		}
		if ((hyphencount > 1) || ((zipcodeVal.length==10) && ""+ zipcodeVal.charAt(5)!="-")) {
			return false;
   		}
	}
	return true;
}


// routine to validate a field according to a variable containing valid characters
function validateField(fieldVal, validChars) {
	var temp;
	for (var i=0; i<fieldVal.length; i++) {
		temp = "" + fieldVal.substring(i, i+1);
		if (validChars.indexOf(temp) == -1) return false;
	}
	return true;
}


//browser check here to account for differences in each browsers DOM
function getDocRef(elm) {
	if (isIE4) {
		var docRef = document.all[elm];
	}
	else if (isIE5plus_Op5 || isNS6plus_Op6plus) {
		var docRef = document.getElementById(elm);
	}
	return docRef;
}