var appversion=parseInt(navigator.appVersion); 
no_of_order_pages = 200; //the number of possible product pages selected for ordering  
var itemid_array = new makeArray(no_of_order_pages);
var itemname_array = new makeArray(no_of_order_pages);
var descript_array = new makeArray(no_of_order_pages);
var sku_array = new makeArray(no_of_order_pages);
var promo_array = new makeArray(no_of_order_pages);  // on promotion or not
var price_array = new makeArray(no_of_order_pages);
var price1_array = new makeArray(no_of_order_pages);
var price10_array = new makeArray(no_of_order_pages);
var price100_array = new makeArray(no_of_order_pages);
var unit_array = new makeArray(no_of_order_pages);  // measurement unit
var quantity_array = new makeArray(no_of_order_pages);
var taxable_array = new makeArray(no_of_order_pages);        // a bitmap that tells whether this item is taxable
var shipping_array = new makeArray(no_of_order_pages);  // shipping cost per item
var weight_array = new makeArray(no_of_order_pages);  // weight for calculating shipping cost
var subtotal = 0; //subtotal or order
var order = ''; //the printed result to show the customer's order
var model_array = new makeArray(no_of_order_pages);

function openOrderForm()  
{
  var cart =window.open(document.location,"_self"); 
  if(navigator.appName == "Netscape")
  {
    cart.focus();
  }
}

function getCookieVal (offset) {
 var endstr = document.cookie.indexOf (";", offset);
 if (endstr == -1)
  endstr = document.cookie.length;
 return document.cookie.substring(offset, endstr);
}

function GetCookie (name)
{
 var arg = name + "=";
 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)
  {
	return getCookieVal (j);
  }
  i = document.cookie.indexOf(" ", i) + 1;
  if (i == 0) break; 
 }
 return null;
}

function SetCookie (name,value,expires,path,domain,secure) 
{
 document.cookie = name + "=" + escape (value) +
  ((expires) ? "; expires=" + expires : '') +
  ((path) ? "; path=" + path : '') +
  ((domain) ? "; domain=" + domain : '') +
  ((secure) ? "; secure" : '');
}
function makeArray(n) 
{
 this.length = n;
 for (var k = 1; k <= n; k++) 
 {
  this[k] = 0;
 }
 return this;
} 
function addtoCookieArray(cookieName, info)
{
    var tmpString=GetCookie(cookieName);
    if(GetCookie(cookieName) !=null)
    {
      tmpString = GetCookie(cookieName) + info + ",";
      //append to the current cookie values
      document.cookie = cookieName + "=" + tmpString + "; path=/";
    }
    else
    {
      tmpString = info + ",";
      document.cookie = cookieName + "=" + tmpString + "; path=/";
// alert("cookieNo:"+cookieName + "=" + tmpString);
    }
}
/* this defines an array for holding the user configuration
cookie contents when parsed out. Increase the count if you need to store more
but don't forget that the limitation is 4096 bytes */

function parseIt(cookieName, array) 
{
 config=GetCookie(cookieName);
 config+='';           // make it a string if it wasn't before
 var y = 1;
 while(config.indexOf(",") >= 0) 
 {
   var pos = config.indexOf(",");
   if (pos==0)
     array[y]="";
   else
     array[y]=unescape(config.substring(0,pos));
   y++;
   config=config.substring(pos+1,config.length);
 }
 return y-1;
}

function fmtPrice(value)   
{   
 result=Math.floor(value)+".";   
 var cents=100*(value-Math.floor(value))+0.5;   
 result += Math.floor(cents/10);   
 result += Math.floor(cents%10);   
 return result; 
}

function displaySum(index)
{
 eval("document.getElementById('basket').sum"+index+".value=fmtPrice("+quantity_array[index]*price_array[index]+")");
 document.getElementById('basket').formsubtotal.value=fmtPrice(subtotal);
}

function isInt(elm) 
{
    var elmstr = '' + elm; 
    if (elmstr == '')
        return false;
    for (var i = 0; i < elmstr.length; i++)
    {
        if (elmstr.charAt(i) < "0" || elmstr.charAt(i) > "9")
            { return false; }
    }
    return true;
}
function RoundQty(elm)
{
    var elmstr = "" + elm;
    if (elmstr == "")
        return 0;
    DotExist=0;
    DigitAfterDecimal=0;
    for (var i = 0; i < elmstr.length; i++)
    {
        if (elmstr.charAt(i) < "0" || elmstr.charAt(i) > "9") { 
            if ((elmstr.charAt(i) == ".")&&(DotExist == 0))
                DotExist = 1;
            else
                return 0; 
        }
        else if (DotExist == 1){
            if (DigitAfterDecimal < 2)
                DigitAfterDecimal = DigitAfterDecimal + 1 ;
            else {
                if (elmstr.charAt(i)>="5"){
                   var sTmp100 = elmstr.substring(0, i-3) + elmstr.substring(i-2, i);
     nTmp = Number( sTmp100 ) ;
     nTmp = nTmp + 1;
           var sTmp = "" + nTmp;
     if (sTmp.length < 2)
   sTmp = sTmp.substring(0, sTmp.length - 2) + ".0" + sTmp.substring(sTmp.length - 2, sTmp.length );
     else
   sTmp = sTmp.substring(0, sTmp.length - 2) + "." + sTmp.substring(sTmp.length - 2, sTmp.length );
                   return sTmp ;
                }
                else               
                   return Number( elmstr.substring(0, i) );
            }
        }       
    }

    return elm;
}


function cookieValues(cookie1, cookie2, cookie3, cookie4){
	var tempString=GetCookie(cookie1);
	var tempString2=GetCookie(cookie2);
	var tempString3=GetCookie(cookie3);
	var tempString4=GetCookie(cookie4);
	alert(tempString);
	alert(tempString2);
	alert(tempString3);
	alert(tempString4);
}

function updatePrice(inputQuantity, index){
	if (inputQuantity < 10){
		delCookie("price");
		price_array[index]=price1_array[index];
		for (i=1; eval(price_array[i])!= 0; i++) {
		addtoCookieArray("price", price_array[i]);
		}
		//cookieValues("price", "price1", "price10", "price100");		
	}
	else if (inputQuantity < 100){
		delCookie("price");
		price_array[index]=price10_array[index];
		for (i=1; eval(price_array[i])!= 0; i++) {
		addtoCookieArray("price", price_array[i]);
		}
		//cookieValues("price", "price1", "price10", "price100");
	}
	else {
		delCookie("price");
		price_array[index]=price100_array[index];
		for (i=1; eval(price_array[i])!= 0; i++) {
		addtoCookieArray("price", price_array[i]);
		}
		//cookieValues("price", "price1", "price10", "price100");
	}
}

function delCookie(name){
	document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/";
}


function test(){
	//basket.submitbutton.disabled = true;
}

function updateQuantity(newQuantity, index, acceptZero)
{
	Qty=RoundQty(newQuantity);

	if (!acceptZero && (Qty>=10000 || Qty==0 || newQuantity==0))
	{
		alert("Input must be a valid number greater than 1 and less than 10000!");
		eval("document.getElementById('basket').quan"+index+".value=quantity_array[index]");
	}
    else
    {
		if (Qty!=0)
		{
			updatePrice(newQuantity, index);
		}
		
		quantity_array[index]=Qty;
		
		// remove existing cookie
		//document.cookie = "quantity=; expires=Thu, 01-Jan-70 00:00:01 GMT";
		delCookie("quantity");
	
		// convert from array to cookie
		for (i=1; eval(price_array[i])!= 0; i++) 
			addtoCookieArray("quantity", quantity_array[i]);
  		
		// update hidden variable as well
		document.getElementById('basket').quantity.value=GetCookie("quantity");
		calcNow();
		displaySum(index);
	}
	openOrderForm();
}

function calcNow()
{
 //update information from the ordering cookies
 parseIt("productID", itemid_array);
 parseIt("product", itemname_array);
 parseIt("description", descript_array);
 parseIt("sku", sku_array);
 parseIt("promotion", promo_array);
 parseIt("price", price_array);
 parseIt("price1", price1_array);
 parseIt("price10", price10_array);
 parseIt("price100", price100_array);
 parseIt("unit", unit_array);
 parseIt("quantity", quantity_array);
 parseIt("taxable", taxable_array);
 parseIt("shipping", shipping_array);
 parseIt("weight", weight_array);
 parseIt("model", model_array);
 //clear global calculation variables
 subtotal = 0;
 order = '';
 currency = "&pound;";
 
 order += '<table cellspacing="0" cellpadding="0" class="form" width="100%">';
 order += '<tr>' +
	   '<th class="head ref">Reference</th>' +
	   '<th class="head">Description</th>' +
	   '<th class="head">Qty</th>' +
	   '<th class="head">Amount (&pound;)</th>' +
	   '<th class="head">&nbsp;</th>' +
	   '</tr>';
										
 rows = 0;
 for (x=1; eval(price_array[x]) != 0; x++)
 {
//  order +=  quantity_array[x] + " of " + itemname_array[x] +
//   "(" + descript_array[x] + "), price=" + price_array[x] + " " + unit_array[x] +
//   "; promo=" + promo_array[x] +
//   "; taxable=" + taxable_array[x] +
//   "; shipping=" + shipping_array[x] +
//   "; weight=" + weight_array[x];

   

if (quantity_array[x]!=0)
{

//update subtotal depending on quantity
if (quantity_array[x]<10){
	price_array[x]=price1_array[x];
}
else if (quantity_array[x]<100){
	price_array[x]=price10_array[x];
}
else {
	price_array[x]=price100_array[x];
}
order += '<tr>' +
				'<td>' + sku_array[x] + '</td>' +
				'<td>' + unescape(model_array[x]) + ' ' + unescape(itemname_array[x]) + '<br/>' + 
				'Unit Price: ' + unit_array[x] + ' @ ' + currency + '' + fmtPrice(price_array[x]) + '</td>' +
				'<td><input type="text" name="quan' + x + '" size="3" value="' + quantity_array[x] +
				'" onfocus="test();" onchange="updateQuantity(this.value,' + x + ',false)" maxlength="7"/></td>' +
				'<td><input type="text" name="sum' + x + '" size="7" value="' + 
				fmtPrice(price_array[x] * quantity_array[x]) + '" onchange="displaySum('+ x + ')"></td>' +
				'<td class="basket"><input type="button" onclick="updateQuantity(0,' + x + ',true); openOrderForm()" class="button" value="Remove">' +
				'</td>' +
			'</tr>';

rows = rows + 1;


//calculate the subtotal for the whole lot of products
if (price_array[x] == "")
        price_array[x] = "0";
		subtotal+= eval(price_array[x]) * eval(quantity_array[x]);
 }
}

//add basket empty message...
if (rows <= 0)
{
	order += '<tr><td colspan="5"><p>Your basket is currently empty</p></td></tr>';
}

order += '<tr>'+
			'<td colspan="5"><hr size="1" width="100%" color="black" noshade></td>' +
			'</tr><tr>' +
			'<td align="right" colspan="3">SUBTOTAL ' + currency + '&nbsp;</td>' +
			'<td align="left" colspan="2"><input type="text" size="10" name="formsubtotal" value="' +
			fmtPrice(subtotal) +
			'" onchange="document.getElementById(\'basket\').formsubtotal.value=fmtPrice(subtotal)"></td>' + 
		 '</tr>';

order = order + "</table>";
}
function clearOrder() 
{
 //  ----------- EXPIRES THE COOKIES ( which makes them read null ) ----------
 emptyStr = "=; expires=Thu, 01-Jan-70 00:00:01 GMT";

 document.cookie = "productID" + emptyStr;
 document.cookie = "product" + emptyStr;
 document.cookie = "description" + emptyStr;
 document.cookie = "sku" + emptyStr;
 document.cookie = "promotion" + emptyStr;
 document.cookie = "price" + emptyStr;
 document.cookie = "price1" + emptyStr;
 document.cookie = "price10" + emptyStr;
 document.cookie = "price100" + emptyStr;
 document.cookie = "unit" + emptyStr;
 document.cookie = "quantity" + emptyStr;
 document.cookie = "taxable" + emptyStr;
 document.cookie = "shipping" + emptyStr;
 document.cookie = "weight" + emptyStr;
 document.cookie = "model" + emptyStr;
 openOrderForm();
}

function initHiddens()
{
 // Set hidden variables with values of cookies
 document.getElementById('basket').itemid.value = '' + GetCookie("productID");
 document.getElementById('basket').itemname.value = '' + GetCookie("product");
 document.getElementById('basket').itemdescription.value = '' + GetCookie("description");
 document.getElementById('basket').itemcode.value = '' + GetCookie("sku");
 document.getElementById('basket').itempromotion.value = '' + GetCookie("promotion");
 document.getElementById('basket').itemprice.value = '' + GetCookie("price");
 document.getElementById('basket').itemunit.value = '' + GetCookie("unit");
 document.getElementById('basket').quantity.value = '' + GetCookie("quantity");
 document.getElementById('basket').taxable.value = '' + GetCookie("taxable");
 document.getElementById('basket').shipping.value = '' + GetCookie("shipping");
 document.getElementById('basket').weight.value = '' + GetCookie("weight");
 document.getElementById('basket').model.value = '' + GetCookie("model");
}


function update_address(checked)
{
	if (checked)
	{
		//put the invoice address details in the delivery address fields
		document.getElementById('processOrderForm').recipient.value = document.getElementById('processOrderForm').title.value + " " + document.getElementById('processOrderForm').forename.value + " " + document.getElementById('processOrderForm').surname.value;
		document.getElementById('processOrderForm').del_orgname.value = document.getElementById('processOrderForm').orgname.value;
		document.getElementById('processOrderForm').del_line1.value = document.getElementById('processOrderForm').line1.value;
		document.getElementById('processOrderForm').del_line2.value = document.getElementById('processOrderForm').line2.value;
		document.getElementById('processOrderForm').del_line3.value = document.getElementById('processOrderForm').line3.value;
		document.getElementById('processOrderForm').del_town.value = document.getElementById('processOrderForm').town.value;
		document.getElementById('processOrderForm').del_county.value = document.getElementById('processOrderForm').county.value;
		document.getElementById('processOrderForm').del_postcode.value = document.getElementById('processOrderForm').postcode.value;
	}
	else
	{
		//clear the fields
		document.getElementById('processOrderForm').recipient.value = "";
		document.getElementById('processOrderForm').del_orgname.value = "";
		document.getElementById('processOrderForm').del_line1.value = "";
		document.getElementById('processOrderForm').del_line2.value = "";
		document.getElementById('processOrderForm').del_line3.value = "";
		document.getElementById('processOrderForm').del_town.value = "";
		document.getElementById('processOrderForm').del_county.value = "";
		document.getElementById('processOrderForm').del_postcode.value = "";
	}
}
