
var request = null;
var	TotalBeforeShipping=0;
		shipCost=NaN;
		shipRegion="";
		shipCountry="";
		regioncountry="unset";
		deliveryMethod="unset"; 
        findshipping='';
        giftwrapprice=0;
 
 
 try {
  request = new XMLHttpRequest();
 } catch (trymicrosoft) {
  try {
   request = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
   try {
    request = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (failed) {
    request = null;
   }
  }
 }
 
function getval(id) { 
		
		
		//return( document.getElementById(id).value )
	}
	function setval(id,value) {
		// format the number if it's a number or else return the string
		if (isFinite(value)){	document.getElementById(id).value=alterError(value); }
		else				{	document.getElementById(id).value=value};
		return( true )
	}
function CallScript(scName) {
  var url = scName;
  request.open("GET", url, true);
     request.onreadystatechange = updatedata;
  request.send(null);
   }
function updatedata() {
     if (request.readyState == 4) {
       var content = request.responseText;
    if(content){
   document.getElementById("scroll").innerHTML = content;
  }
  else{
   document.getElementById("scroll").innerHTML = "No output";
  }
     }
   }
 

var theprice;
var subtotal;

function alterError(value) {
	value=parseFloat(value);
	if (value<=0.99) {
		newPounds = '0';
	} else {
		newPounds = parseInt(value);
	}
	newPence = parseInt((value+.0008 - newPounds)* 100);
	if (newPence <= 9) newPence='0'+newPence;
	newString = newPounds + '.' + newPence;
	return (newString);
}

//  Both these functions work on fields in the "main" window only.
function getval(id) { 
		return(document.getElementById(id).value )
}
function setval(id,value) {
	// format the number if it's a number or else return the string
	if (isFinite(value)){	document.getElementById(id).value=alterError(value); }
	else				{	document.getElementById(id).value=value};
	return( true )
}


//Generic cookie manipulation functions - writeCookie, readCookie, eraseCookie
function writeCookie(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) {
	writeCookie(name,"",-1);
}

function resetShoppingBasket() {
	eraseCookie("TheBasket");
	shipCost=NaN;
	shipRegion=null;
	deliveryMethod=null;
	//self.location.reload();
   window.location = "http://www.cartengine.anylinuxwork.com/";
}

// showItems() - displays shopping basket in the minibasket window
	function showItems() {

		index = document.cookie.indexOf("TheBasket");
		if (index == -1) {
			writeCookie("TheBasket=","",4)			// Create cookie if it doesn't exist yet
		}
		countbegin = (document.cookie.indexOf("=", index) + 1);
        	countend = document.cookie.indexOf(";", index);
        	if (countend == -1) {
            		countend = document.cookie.length;
        	}
		fulllist = document.cookie.substring(countbegin, countend);
		subtotal = 0;
				
		str='<TABLE CELLSPACING=0 CELLPADDING=0 width="100%" class="text12">';
        itemlist = 0;
		
			for (var i = 0; i <= fulllist.length; i++) {
			if (fulllist.substring(i,i+1) == '[') {
						
				itemstart = i+1;
				thisitem = 1;
			} else if (fulllist.substring(i,i+1) == ']') {
				
				itemend = i;
				thequantity = fulllist.substring(itemstart, itemend);
				itemtotal = 0;
				itemtotal = (theprice*thequantity);
				temptotal = itemtotal * 100;
				subtotal = subtotal + itemtotal;
				itemlist=itemlist+1;
		
			str+='<TR><TD align=left>'+thequantity+' x '+theitem+'</td></tr><TR><TD> &nbsp; </td></tr>';
			} else if (fulllist.substring(i,i+1) == '|') {
				
				if (thisitem==1) theitem = fulllist.substring(itemstart, i);
				if (thisitem==2) theprice = fulllist.substring(itemstart, i);
				if (thisitem==3) theoption = fulllist.substring(itemstart, i);
				thisitem++;
				itemstart=i+1;
			}
	
				}
			val=alterError(subtotal);
		str+='<TR><TD> &nbsp; </td></tr>';
		str+='<TR><TD align=left><b> Total '+val+'</b></td></tr>';
		
		document.getElementById("display").innerHTML = str;
		
		

	}

	
function calculate_price(str,newPrice)

{
	len=str.length;
	index=str.indexOf("(");
	sub=str.substring(index+1,len);
	len1=sub.length;
	prefix =sub.substring(0,1);
	subprice=sub.substring(1,len1);
	newOption=str.substring(0,index);
	switch (prefix)
	{
	case '+':
	newPrice=parseFloat(newPrice)+parseFloat(subprice);
	  break
	case '-':
	newPrice=parseFloat(newPrice)-parseFloat(subprice);
	  break
	case '*':
	newPrice=parseFloat(newPrice)*parseFloat(subprice);
	  break
	case '/':
	newPrice=parseFloat(newPrice)/parseFloat(subprice);
	  break
	 case '%':
	newPrice=parseFloat(newPrice)%parseFloat(subprice);
	  break
	  
	  default:
	newPrice=newPrice;
	  }

	return newPrice;

}

// buyItem - adds an item to the shopping basket
function buyItem(newItem, newPrice, newQuantity, newOption) {
var str=newOption;
	option='';

	checkindex=str.indexOf("(");

if(checkindex>0)
{
	index=str.indexOf("_");

	if(index>0)
	{
	temp = str.split('_');
	templen=temp.length;
	for(i=0;i<templen;i++)
	{
	attribute=temp[i];
	index=attribute.indexOf("(");
	attributesub=attribute.substring(0,index);
	option+=attributesub+'';
	price=calculate_price(temp[i],newPrice);
	newPrice=price;
	newOption=option;

     	}
	   }
	else
		{

	attribute=str;
	index=attribute.indexOf("(");
	attributesub=attribute.substring(0,index);
	option+=attributesub+'';
	price=calculate_price(str,newPrice);
	newPrice=price;
	newOption=option;

	}
	   }

	else
		{
	newOption=newOption;
	}
	if (newQuantity <= 0) {
	rc = alert('You cannot buy a negative number of any item');
	} else {
	if (newQuantity >= 0) {
						   index = document.cookie.indexOf("TheBasket");
							countbegin = (document.cookie.indexOf("=", index) + 1);
							countend = document.cookie.indexOf(";", index);
							if (countend == -1) {
									countend = document.cookie.length;
							}
							basketValue=document.cookie.substring(countbegin, countend)+"["+newItem+"|"+newPrice+"|"+newOption+"|"+newQuantity+"]";
							writeCookie("TheBasket",basketValue,4);
							showItems();	
							document.getElementById("display").style.background='#FFFFFF';
							setTimeout('after1Seconds()',1000)
			}
		}
	}
function after1Seconds() {
document.getElementById("display").style.background='#A88858';


}
function open_window(theURL,winName,features) {
  document.cookie = "Theprice"+"="+escape(subtotal);
  window.open(theURL,winName,features);
}
	function viewBasket() {
	    str1='<TABLE class="text12" border="0" width="100%">';
		  
		var subtotal = 0;
		var	fulllist=readCookie("TheBasket");
		var	itemlist = 0;
		for (var i = 0; i <= fulllist.length; i++) {
			if (fulllist.substring(i,i+1) == '[') {
				itemstart = i+1;
				thisbit = 1;
			
			} else if (fulllist.substring(i,i+1) == ']') {
				itemend = i;
				thequantity = fulllist.substring(itemstart, itemend);			// between the last | and the ]
				itemtotal = 0;
				itemtotal = (eval(theprice*thequantity));
				temptotal = itemtotal * 100;
				subtotal = subtotal + itemtotal;
				itemlist=itemlist+1;
				str1+='<tr ><td width="30%">'+theitem+'</td><td width="20%" align="center">'+theoption+'</td><td width="15%" class="num" align="left">£'+theprice+'</td>';
                str1+='<td align="right" width="15%"><INPUT type=text size="2" ID="quant'+itemlist+'" VALUE="' + thequantity + '" onChange="amendItem('+itemlist+',document.checkoutform.quant'+itemlist+'.value)"></td>';
				str1+='<td width="10%" align="center"><INPUT readonly size="7" id="itemTotal'+itemlist+'"  class="num" value="£'+alterError(itemtotal)+'"></td></tr>';

			} else if (fulllist.substring(i,i+1) == '|') {
				if (thisbit==1) theitem = fulllist.substring(itemstart, i);
				if (thisbit==2) theprice = fulllist.substring(itemstart, i);
				if (thisbit==3) theoption = fulllist.substring(itemstart, i);
				thisbit++;
				itemstart=i+1;
			}
		}
		
		TotalBeforeShipping=subtotal;
		str1+='<tr class="basketrow"><td align="right" colspan=4><b>Total before shipping</b></td>';
		str1+='<td width="10%" align="right"><INPUT readonly id="totalBeforeShipping" type="text" size="7" class="total" value="£'+alterError(TotalBeforeShipping)+'"></td></tr></table>';
		document.write(str1);
	  	document.getElementById("Basketdisplay").innerHTML =str1;
	
	}

function amendItem(itemno, newquant) {
	if (newquant<=0) { deleteItem(itemno); return (true); }
	var	fulllist=readCookie("TheBasket");
	var	newItemList = null;
	var	itemlist = 0;
	var	itemstart = 0;
		TotalBeforeShipping=0;
		for (var i = 0; i <= fulllist.length; i++) {
			if (fulllist.substring(i,i+1) == '[') {					// Start of new product line
				thisbit = 1;										// so set up ready for parsing
				itemstart = i+1;									//  record the position of this item
				fullstart = i+1;
			} else if (fulllist.substring(i,i+1) == ']') {			//  End of product line
				itemend = i;
				itemlist=itemlist+1;
				thequantity = fulllist.substring(itemstart, itemend);			// between the last | and the ]
				itemtotal = 0;
				if (itemlist != itemno) {							// This is not the product we're looking for
					newItemList = newItemList+'['+fulllist.substring(fullstart, itemend)+']';  //  So add it to the basket and keep looking
					itemtotal = (eval(theprice*thequantity));
				} else {											//  This is the one we're after
					newItemList = newItemList + '['+theitem+'|'+theprice+'|'+theoption+'|'+newquant+']';  // so add the updated product line
					itemtotal = theprice*newquant;
					setval(("itemTotal"+itemno),("£"+top.alterError(itemtotal)));	// update the screen as well
				}
				TotalBeforeShipping = TotalBeforeShipping + itemtotal;
			} else if (fulllist.substring(i,i+1) == '|') {			//  We've reached the border of part of a product line
				if (thisbit==1) theitem = fulllist.substring(itemstart, i);
				if (thisbit==2) theprice = fulllist.substring(itemstart, i);
				if (thisbit==3) theoption = fulllist.substring(itemstart, i);
				thisbit++;
				itemstart=i+1;
			}
		}
		//  Now update the mini-basket too.
		index = document.cookie.indexOf("TheBasket");
		writeCookie("TheBasket",newItemList,4);
        //top.frames.basket.location = "basket.htm";
		// and change shipping charges if necessary
		setval("totalBeforeShipping",('£'+top.alterError(TotalBeforeShipping)));
		//calcShipCost();
	}
	function deleteItem(itemno) {
	var	fulllist=readCookie("TheBasket");
	var	newItemList = null;
	var	itemlist = 0;
	var itemstart = 0;
		for (var i = 0; i <= fulllist.length; i++) {
			if (fulllist.substring(i,i+1) == '[') {
				itemstart = i+1;
			} else if (fulllist.substring(i,i+1) == ']') {
				itemend = i;
				theitem = fulllist.substring(itemstart, itemend);
				itemlist=itemlist+1;
				if (itemlist != itemno) {
					newItemList = newItemList+'['+fulllist.substring(itemstart, itemend)+']';
				}
			}
		}
		writeCookie("TheBasket",newItemList,4);
        //top.frames.basket.location = "basket.htm";
		self.location.replace("checkout.php");
	}

function getGiftDetails()

{

GiftDetails=readCookie("giftDetails");

      	if (GiftDetails  != null) {
			elementID=0;
			for (var i = 0; i < GiftDetails.length; i++) {
				if (GiftDetails.substring(i,i+1) == '[') {
					itemstart = i+1;
				} else if (GiftDetails.substring(i,i+1) == ']') {
					itemend = i;
					switch (elementID) {
						case 0:	giftwrapprice = GiftDetails.substring(itemstart, itemend); break;
						}
					elementID++;
				}
			}
		//  Ensure the correct fields are selected (if coming back to this page during a session)

		if(giftwrapprice>0)
			{
			document.checkoutform.giftwrap.checked=true;
			value1= ('£'+alterError(giftwrapprice));

			document.getElementById("giftwrapset").value=value1;

			
			}
			
		}



}

       function	getShipDetails() {
		shipdetails = readCookie("ShipDetails");
		
       	if (shipdetails  != null) {
			elementID=0;
			for (var i = 0; i < shipdetails.length; i++) {
				if (shipdetails.substring(i,i+1) == '[') {
					itemstart = i+1;
				} else if (shipdetails.substring(i,i+1) == ']') {
					itemend = i;
					switch (elementID) {
						case 0:	shipCost = shipdetails.substring(itemstart, itemend); break;
						case 1: shipRegion = shipdetails.substring(itemstart, itemend); break;
						case 2:	shipCountry = shipdetails.substring(itemstart, itemend); break;
						case 3: deliveryMethod = shipdetails.substring(itemstart, itemend);	break;
					}
					elementID++;
				}
			}
		shipRegionCountry = shipRegion + "&" + shipCountry;
		//  Ensure the correct fields are selected (if coming back to this page during a session)
		document.getElementById(deliveryMethod).selected = true;
		document.getElementById(shipRegionCountry).selected = true;
			
		}
	}



function	resetShipDetails() {
		shipdetails = readCookie("ShipDetails");
		
       	if (shipdetails  != null) {
			elementID=0;
			for (var i = 0; i < shipdetails.length; i++) {
				if (shipdetails.substring(i,i+1) == '[') {
					itemstart = i+1;
				} else if (shipdetails.substring(i,i+1) == ']') {
					itemend = i;
					switch (elementID) {
						case 0:	shipCost = shipdetails.substring(itemstart, itemend); break;
						case 1: shipRegion = shipdetails.substring(itemstart, itemend); break;
						case 2:	shipCountry = shipdetails.substring(itemstart, itemend); break;
						case 3: deliveryMethod = shipdetails.substring(itemstart, itemend);	break;
					}
					elementID++;
				}
			}
		shipRegionCountry = shipRegion + "&" + shipCountry;
		//  Ensure the correct fields are selected (if coming back to this page during a session)
		
		}
	
	GiftDetails=readCookie("giftDetails");

      	if (GiftDetails  != null) {
			elementID=0;
			for (var i = 0; i < GiftDetails.length; i++) {
				if (GiftDetails.substring(i,i+1) == '[') {
					itemstart = i+1;
				} else if (GiftDetails.substring(i,i+1) == ']') {
					itemend = i;
					switch (elementID) {
						case 0:	giftwrapprice = GiftDetails.substring(itemstart, itemend); break;
						}
					elementID++;
				}
			}
		//  Ensure the correct fields are selected (if coming back to this page during a session)

					
		}
	
	
	
	}


function writeShipDetails() {
		
		shipDetails="";
		shipDetails = "[" + shipCost + "][" + shipRegion + "][" + shipCountry + "][" + deliveryMethod + "]";
		writeCookie("ShipDetails",shipDetails,0);

	}

function writegiftDetails()
{

       giftDetails="";
		giftDetails = "[" + giftwrapprice + "]";
		writeCookie("giftDetails",giftDetails,0);


}



function calcShipCost() {
		
		
				
		delmethod=	document.checkoutform.deliverymethod.value;
		if (delmethod != "unset") {
		temp = delmethod.split('&');
        deliveryMethod=temp[0];
	    free_shipping_rate=temp[1];
		uk_rate=temp[2];
        europe_rate=temp[3];
        row_rate=temp[4];
		} else {return true};
		regioncountry=document.checkoutform.regioncountry.value;
		if (regioncountry != "unset") {
		shipRegionCountry = regioncountry;
		shipRegion = regioncountry.substr(0,regioncountry.indexOf('&'));
		shipCountry = regioncountry.substr((regioncountry.indexOf('&')+1));
		} else {return true};
		if ((TotalBeforeShipping>=free_shipping_rate) && (shipRegion!="None")){ 
		NewShipCost = 0;
		}
		else if ((TotalBeforeShipping<free_shipping_rate) && (shipRegion!="None")){	
		switch(shipRegion) {
		case "UK": 		NewShipCost=uk_rate; break;
		case "EUROPE": 	NewShipCost=europe_rate; break;
		case "ROW": 	NewShipCost=row_rate; break;
	    default: 		NewShipCost="NaN"; break;				
		}} 
		else {
			NewShipCost="NaN";
		}
			
		if (isNaN(NewShipCost)){
			return(true)
		} else {
			shipCost=NewShipCost;
			value=('£'+alterError(shipCost));
			if (isFinite(value)){	document.getElementById("shipCost").value=alterError(value); }
		    else				{	document.getElementById("shipCost").value=value};
			var sum=parseFloat(TotalBeforeShipping)+parseFloat(shipCost);
			value1= ('£'+alterError(sum));
			if (isFinite(value1)){	document.getElementById("totalCost").value=alterError(value1); }
		    else				{	document.getElementById("totalCost").value=value1};
			// Turn on the full display
			document.getElementById("totalRow").style.display = ""; 
           	//  Display free shipping reminder if getting close
			if (TotalBeforeShipping > free_shipping_rate ) {
				document.getElementById("freeshipconfirm").style.display = ""; 
			} else {
				document.getElementById("freeshipconfirm").style.display="none";
			}
		}
	writeShipDetails();
	writegiftDetails();

	}
	
function clearBasket() {
		
		if (confirm('Empty shopping basket and start again?')) {
			resetShoppingBasket();
			window.location = "http://www.cartengine.anylinuxwork.com/";
		}
	}


//-----------------------------------------------------------------------------------------------------

function ShipCostcalc() {
			
		delmethod=	document.checkoutform.deliverymethod.value;
		regioncountry=document.checkoutform.regioncountry.value;
        if (regioncountry != "unset") {
		shipRegionCountry = regioncountry;
		shipRegion = regioncountry.substr(0,regioncountry.indexOf('&'));
		shipCountry = regioncountry.substr((regioncountry.indexOf('&')+1));
	   } else {return true};
	   if(delmethod != "unset")  
	   {
		temp = delmethod.split('&');
        deliveryMethod=temp[0];
	    shipping_id=temp[1];
		}
       else {return true};
	  if ((delmethod != "unset") &&(regioncountry != "unset")) {
	   ship1(shipping_id,shipRegion);


		} else {return true};
		
		
	}
var request = null;
	try {
		request = new XMLHttpRequest();
	} catch (trymicrosoft) {
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				request = null;
			}
		}
	}

 function ship1(shipping_id,shipRegion)
 {
 
	  var url = 'calculate_shipping.php?delmethod='+shipping_id+'&shipRegion='+shipRegion; 
	//window.open(url);
		request.open("GET", url, true);
	   request.onreadystatechange = findshippingcost;
		
		request.send(null);
 
 }
 


function findshippingcost() {

	 if (request.readyState == 4) {
       var shippingcost = request.responseText;
	   if(shippingcost!=""){
			
			findshipping=shippingcost;
			temp1 = findshipping.split(':');
			
			free_shipping_rate=temp1[1];
			//---------------------------------------------------------------------------------------
 if(free_shipping_rate!='')
		   {		
 if ((TotalBeforeShipping>=free_shipping_rate) && (shipRegion!="None")){ 
		NewShipCost = 0;
		}
		
		
		else if ((TotalBeforeShipping<free_shipping_rate) && (shipRegion!="None")){	
		NewShipCost=temp1[0]; 			
		}
		
		else {
			NewShipCost="NaN";
		}
			
		   }
		
else {
NewShipCost=temp1[0]; 
}
		
		if (isNaN(NewShipCost)){
			return(true)
		} else {
			shipCost=NewShipCost;
			value=('£'+alterError(shipCost));
			if (isFinite(value)){	document.getElementById("shipCost").value=alterError(value); }
		    else				{	document.getElementById("shipCost").value=value};
			
			if(giftwrapprice>0)
				{
			var sum=parseFloat(TotalBeforeShipping)+parseFloat(shipCost)+parseFloat(giftwrapprice);
				}
			else
				{
				var sum=parseFloat(TotalBeforeShipping)+parseFloat(shipCost);
				}
			value1= ('£'+alterError(sum));
			if (isFinite(value1)){	document.getElementById("totalCost").value=alterError(value1); }
		    else				{	document.getElementById("totalCost").value=value1};
			// Turn on the full display
			document.getElementById("totalRow").style.display = ""; 
           	//  Display free shipping reminder if getting close
			
			
			if(free_shipping_rate!='')
		   {	
			if (TotalBeforeShipping > free_shipping_rate ) {
				document.getElementById("freeshipconfirm").style.display = ""; 
			} 
		   }
			
			
			
			else {
				document.getElementById("freeshipconfirm").style.display="none";
			}
		}
		     
				writeShipDetails();
	
		if(giftwrapprice>0)
	{
		writegiftDetails();
	}	
		}
		else{
			NewShipCost="NaN";
      if (isNaN(NewShipCost)){
			return(true)
		}
			//findshipping = "";
			//document.getElementById("check").innerHTML = classCode;
		
		}

	 
	 }
   }


//------------------------------------------------------------------------------------------------------



function paymentinfo() {
		fulllist = readCookie("TheBasket");
		subtotal = 0;
		itemtotal = 0;
		itemlist = 0;
		totprice = 0;
		itemString = '';
		shipString = '';
		itemadd='';
		giftString='';
		for (var i = 0; i <= fulllist.length; i++) {
			if (fulllist.substring(i,i+1) == '[') {
				thisitem = 1;
				itemstart = i+1;
			} else if (fulllist.substring(i,i+1) == ']') {
				itemend = i;
				thequantity = fulllist.substring(itemstart, itemend);
				itemtotal = (theprice*thequantity);
				temptotal = itemtotal * 100;
				subtotal = subtotal + itemtotal;
				itemlist=itemlist+1;
				itemString = itemString + ":" + theitem + ' ' + theoption + ":" + thequantity + ":" + ":" + ":" + theprice + ":" + top.alterError(itemtotal);
			     
				itemadd = itemadd + ":" + theitem + ' ' + theoption + ":" + thequantity + ":" +  theprice + ":" + top.alterError(itemtotal)+'_';
			      
			
			
			} else if (fulllist.substring(i,i+1) == '|') {
				if (thisitem==1) theitem = fulllist.substring(itemstart, i);
				if (thisitem==2) theprice = fulllist.substring(itemstart, i);
				if (thisitem==3) theoption = fulllist.substring(itemstart, i);
				thisitem++;
				itemstart=i+1;
			}
		}
// add shipping to item list
		shipString = ":" + " Shipping Method " +deliveryMethod + " delivery to " + shipRegion + ":shipping cost:::" + top.alterError(shipCost) + ":" + top.alterError(shipCost);
	
		
		itemlist = itemlist + 1;
		itemString = itemlist + itemString + shipString;
		subtotal = subtotal + parseFloat(shipCost)+parseFloat(giftwrapprice);		
		totprice = (Math.round(subtotal*100)/100);

//	Set up transaction time with leading zeroes in month and date field.  Ensure they are strings		
		var TXTime = (new Date());
		var TXMonth = "";
		var TXDate = "";
		if (TXTime.getMonth() < 9) {
			TXMonth = "0" + (TXTime.getMonth() + 1);
		}	else {
			TXMonth = (TXTime.getMonth() + 1) + "";
		}
		if (TXTime.getDate() < 10) {
			TXDate = "0" + TXTime.getDate() + "-";
		}	else {
			TXDate = TXTime.getDate() + "-";
		}
		setval("inputamount",top.alterError(totprice));
		setval("encode",itemString);
		setval("order_product",itemadd);
		TXCode = TXTime.getYear()+ TXMonth + TXDate + TXTime.getHours() + "" + TXTime.getMinutes() + "" + TXTime.getSeconds() + "" + TXTime.getMilliseconds() + "-aerolatte";
		setval("VendorTxCode", TXCode);
		setval("shippingmethod", deliveryMethod);
	
	
	}

function Invoicedetails() {
	if (document.getElementById("Del_is_invoice").checked) { 
		document.getElementById('InvoiceDetails').style.display="none"; 
		document.getElementById("DelEquals").value = "YES"; 	// Set flag for prepare_for_PROTX page
		}
	else {
		document.getElementById('InvoiceDetails').style.display="";
		document.getElementById('company').focus();				// Move cursor to first field
		document.getElementById('company').scrollIntoView();
		document.getElementById("DelEquals").value = "NO";	// Set flag for prepare_for_PROTX page
		 }
}

function Forminfo() {
	orderform = readCookie("OrderForm");
	if (orderform  != null) {
		neworderform = false;		// the order form details already exist
		elementID=0;
		for (var i = 0; i < orderform.length; i++) {
			if (orderform.substring(i,i+1) == '[') {
				itemstart = i+1;
			} else if (orderform.substring(i,i+1) == ']') {
				itemend = i;
				document.OrderForm.elements[elementID].value = orderform.substring(itemstart, itemend);			// between the last | and the ]
				elementID++;
			}
		}
	} 
}

//	saveForm()  keeps details of this form in a cookie for retrieval if we come back to this page
function saveForm() {

	elementID=0;
	orderform="";
	for (var i = 0; i < document.OrderForm.elements.length; i++) {
		orderform = orderform + "[" + document.OrderForm.elements[elementID].value + "]";
		elementID++;
	}
	
	writeCookie("OrderForm",orderform,0);
}

function validateForm() {
	email= document.getElementById('email').value ;
    verifyemail=document.getElementById('verifyemail').value ;
	Bname=document.getElementById('Bname').value ;
	
	if (email != verifyemail) {
		alert("Your e-mail addresses did not match.  Please check them and re-enter.\n\nWe need your e-mail address to send confirmation of your purchase.\nWe do not retain your e-mail address for any other purpose.");
		document.getElementById('email').focus();
		
		return(false);
	} 
	//  Remove postcode if it's been repeated in the delivery address
	postcode = document.getElementById('Del_postcode').value ;
	address	= document.getElementById('address').value ;
	if (address != "") {setval("address",address.replace(postcode, ""))};
	//  Remove postcode if it's been repeated in the billing address
	postcode = document.getElementById('zip').value ;
	address	= document.getElementById('Baddress').value ;
phone=document.getElementById('phone').value ;
daddress	= document.getElementById('address').value ;
delpostcode = document.getElementById('Del_postcode').value ;
if(Bname=="")

{
alert('Please enter name');		
	return(false);	
}

else if(email=="")
	{
alert('Please enter email');
return(false);	

}
else if(phone=="")
	{
alert('Please enter phone number');
return(false);	

}
else if(daddress=="")
	{
alert('Please enter delivery address');
return(false);	
}
else if(delpostcode=="")
		{

alert('Please enter delivery Post code');		
	return(false);	

}

else if (document.getElementById("Del_is_invoice").checked==false) 
	{

if(address=="")

{
alert('Please enter billing address')		
	return(false);	
}
else if(postcode=="")
{

alert('Please enter billing Post code');		
	return(false);	

}

}

if (address != "") {setval("Baddress",address.replace(postcode, ""))};
	return(true);
}

var request = null;
	try {
		request = new XMLHttpRequest();
	} catch (trymicrosoft) {
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				request = null;
			}
		}
	}
function checkmail() {
	 var email = document.getElementById('email').value ;
	 var class1Id ;
	 var classId ='0';
	 var id;
	 	var url = "email_check.php?email="+email; 
		request.open("GET", url, true);
	    request.onreadystatechange = updatePagebyClassCode;
		request.send(null);
	 }
   
function updatePagebyClassCode() {
     
	 if (request.readyState == 4) {
       var classCode = request.responseText;
	   if(classCode!=" "){
			
			document.getElementById("mail").innerHTML = classCode;
		   document.OrderForm.email.focus(); 
		    
		}
		else{
			
			document.getElementById("mail").innerHTML = "";
		}
     }
   }


 function setCountry()
 {	
 	shipdetails = readCookie("ShipDetails");
		if (shipdetails  != null) {
			elementID=0;
			for (var i = 0; i < shipdetails.length; i++) {
				if (shipdetails.substring(i,i+1) == '[') {
					itemstart = i+1;
				} else if (shipdetails.substring(i,i+1) == ']') {
					itemend = i;
					switch (elementID) {
						case 0:	shipCost = shipdetails.substring(itemstart, itemend); break;
						case 1: shipRegion = shipdetails.substring(itemstart, itemend); break;
						case 2:	shipCountry = shipdetails.substring(itemstart, itemend); break;
						case 3: deliveryMethod = shipdetails.substring(itemstart, itemend);	break;
					}
					elementID++;
				}
			}
		shipRegionCountry = shipRegion + "&" + shipCountry;
		//  Ensure the correct fields are selected (if coming back to this page during a session)
		
		}
	// the cookie with saved form didn't exist so populate ship country 
	
			setval("country", shipCountry);
			setval("Dcountry", shipCountry);  // hidden field that gets passed
			setval("Bill_country", shipCountry);
			document.getElementById("Del_is_invoice").checked = true;
		
		if (shipCountry!=document.getElementById("country").value) {
			//  if ship-to country no longer matches what has been paid for then change it
			setval("country", shipCountry);
			setval("Dcountry", shipCountry);  // hidden field that gets passed
		}
 
 }

 function check()
 {
 status=validateForm();

check="true";
 if(status==check) 
	 
 {

  saveForm();
  document.OrderForm.submit();
	 
 } 
 
 }

 function getOrder() 
 {
alert('in get order');
return itemString;
 }


 function emptyShoppingBasket() {
	eraseCookie("TheBasket");
	shipCost=NaN;
	shipRegion=null;
	deliveryMethod=null;
	//self.location.reload();
   
}



function setgift(giftwrap)

{

if(document.checkoutform.giftwrap.checked)
{
giftwrap1= ('£'+alterError(giftwrap));
giftwrapprice=giftwrap;

if (isFinite(giftwrap1)){	document.getElementById("giftwrapset").value=alterError(giftwrap1); }
 else				{	document.getElementById("giftwrapset").value=giftwrap1};

if(shipCost)
{
var sum=parseFloat(TotalBeforeShipping)+parseFloat(shipCost)+parseFloat(giftwrap);
value1= ('£'+alterError(sum));

if (isFinite(value1)){	document.getElementById("totalCost").value=alterError(value1); }
 else				{	document.getElementById("totalCost").value=value1};
}
writegiftDetails();
}

else{

eraseCookie("giftDetails");

document.getElementById("giftwrapset").value="";
if(shipCost)
{
var sum=parseFloat(TotalBeforeShipping)+parseFloat(shipCost);
value1= ('£'+alterError(sum));

if (isFinite(value1)){	document.getElementById("totalCost").value=alterError(value1); }
 else				{	document.getElementById("totalCost").value=value1};

}
else
{
document.getElementById("totalCost").value=""; 

}


}
	
}

