//=====================================================================||
//              This cart is a modified version of:-                   ||
//                                                                     ||
//=====================================================================||
//               NOP Design JavaScript Shopping Cart                   ||
//                                                                     ||
// For more information on SmartSystems, or how NOPDesign can help you ||
// Please visit us on the WWW at http://www.nopdesign.com              ||
//                                                                     ||
// Javascript portions of this shopping cart software are available as ||
// freeware from NOP Design.  You must keep this comment unchanged in  ||
// your code.  For more information contact FreeCart@NopDesign.com.    ||
//                                                                     ||
// JavaScript Shop Module, V.4.4.0                                     ||
//=====================================================================||

minpp                 = 1.50; //min post & packing
pandp1		      = "2.00";
norder2		      = "6";
pandp2		      = "3.00";
norder3		      = "20";
pandp3		      = "5.00";
epandp1		      = 2.75; //for euro zone
epandp2		      = 5.50;
epandp3		      = 9.50;
wpandp1		      = 3.20; //for rest of world
wpandp2		      = 6.30;
wpandp3		      = 12.50;

//colours for forms - ensure that body and .hdr in style sheet are same
bcol = "#FFEFAA";
hcol = "#FFD300";

var gfTotal         = 0;    //Total cost of order
var gfShipping      = 0;    //Shipping amount

//Language Strings
strAdded  = " added to your shopping cart.";
strRemove = "Click 'Ok' to remove this product from your shopping cart.";
strErrQty = "Invalid Quantity.";
strNewQty = 'Please enter new quantity:';

//Customer details
cname	= "";
cschool	= "";
caddr1 = "";
caddr2 = "";
caddr3 = "";
ccnty = "";
cpostcode = "";
ccntry ="";
ctel = "";
cfax = "";
cemail = "";
czone = 0;
cother = "";

//Number pricing categories for discount - if changed change code below
numcategories = 2;
category = new Array();
cat1 = 0;
cat2 = 0;

//ee - m - ail details
var recipientPart1 = "fah";
var recipientPart2 = "earn";
var URL = "gotadsl";
//var recipientPart1 = "lynm";
//var recipientPart2 = "errick";
//var URL = "tiscali";

//For getting cookie fields
fields = new Array;

//debugging
//wint=open("","test");
//wint.document.open("text/plain");
//wint.document.writeln("test"," ",n," ",category[n]);

//---------------------------------------------------------------------||
// FUNCTION:    AddToCart                                              ||
// PARAMETERS:  Form Object                                            ||
// RETURNS:     Cookie to user's browser, with prompt                  ||
// PURPOSE:     Adds a product to the user's shopping cart             ||
//---------------------------------------------------------------------||
function AddToCart(thisForm) {
   var iNumberOrdered = 0;
   var bAlreadyInCart = false;
   var notice = "";
   var discount = "";
   iNumberOrdered = GetCookie("NumberOrdered");

   //Get values from form fields for this product
   if ( iNumberOrdered == null )
      iNumberOrdered = 0;
   if ( thisForm.ID_NUM == null )
      strID_NUM    = "";
   else
      strID_NUM    = thisForm.ID_NUM.value;
   if ( thisForm.QUANTITY == null )
      strQUANTITY  = "1";
   else
      strQUANTITY  = thisForm.QUANTITY.value;
   if ( thisForm.PRICE == null )
      strPRICE     = "0.00";
   else
      strPRICE     = thisForm.PRICE.value;
   if ( thisForm.NAME == null )
      strNAME      = "";
   else
      strNAME      = thisForm.NAME.value;
   if ( thisForm.SHIPPING == null )
      strSHIPPING  = "0.00";
   else
      strSHIPPING  = thisForm.SHIPPING.value;
   if ( thisForm.DISQ1 == null )
   { strDISQ1 = "0"; strDISR1  = "0.00"; }
   else
   { strDISQ1  = thisForm.DISQ1.value; strDISR1  = thisForm.DISR1.value;}
   if ( thisForm.DISQ2 == null )
   { strDISQ2 = "0"; strDISR2  = "0.00"; }
   else
   { strDISQ2  = thisForm.DISQ2.value; strDISR2  = thisForm.DISR2.value; }
   //Reduction
   //if (thisForm.REDUCE.checked) 
	//strREDUCTION = thisForm.REDUCTION.value;
   //else
	strREDUCTION = "0.00";
   if ( thisForm.CAT == null )
      strCAT     = "0.00";
   else
      strCAT     = thisForm.CAT.value;
  
   //Is this product already in the cart?  If so, increment quantity instead of adding another.
   for ( i = 1; i <= iNumberOrdered; i++ ) {
      NewOrder = "Order." + i;
      database = "";
      database = GetCookie(NewOrder);
      GetCookieFields(database);

      //Same ID already in cart
      if ( fields[0] == strID_NUM) 
      {
         bAlreadyInCart = true;
         dbUpdatedOrder = strID_NUM    + "|" +
                          (parseInt(strQUANTITY)+parseInt(fields[1]))  + "|" +
                          strPRICE     + "|" +
                          strNAME      + "|" +
                          strSHIPPING + "|" +
			  strDISQ1 + "|" + strDISR1 + "|" +
			  strDISQ2 + "|" + strDISR2 + "|" +
                          strREDUCTION + "|" + 
                          strCAT;

         strNewOrder = "Order." + i;
         DeleteCookie(strNewOrder, "/");
         SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
         notice = strQUANTITY + " " + strNAME + strAdded;
         break;
      }
   }

   //Same ID not already in cart - new product order
   if ( !bAlreadyInCart ) {
      iNumberOrdered++;
      dbUpdatedOrder = strID_NUM    + "|" + 
                          strQUANTITY  + "|" +
                          strPRICE     + "|" +
                          strNAME      + "|" +
                          strSHIPPING  + "|" +
			  strDISQ1 + "|" + strDISR1 +"|" +
			  strDISQ2 + "|" + strDISR2 + "|" +
                          strREDUCTION + "|" + 
                          strCAT;
         strNewOrder = "Order." + iNumberOrdered;
         SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
         SetCookie("NumberOrdered", iNumberOrdered, null, "/");
         notice = strQUANTITY + " " + strNAME + strAdded;
   }

   //Show what has been added
   alert(notice);
}

//---------------------------------------------------------------------||
// FUNCTION:    RemoveFromCart                                         ||
// PARAMETERS:  Order Number to Remove                                 ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Removes an item from a users shopping cart             ||
//---------------------------------------------------------------------||
function RemoveFromCart(RemOrder) {
   if ( confirm( strRemove ) ) {
      NumberOrdered = GetCookie("NumberOrdered");
      for ( i=RemOrder; i < NumberOrdered; i++ ) {
         NewOrder1 = "Order." + (i+1);
         NewOrder2 = "Order." + (i);
         database = GetCookie(NewOrder1);
         SetCookie (NewOrder2, database, null, "/");
      }
      NewOrder = "Order." + NumberOrdered;
      SetCookie ("NumberOrdered", NumberOrdered-1, null, "/");
      DeleteCookie(NewOrder, "/");
      location.href=location.href;
   }
}

//---------------------------------------------------------------------||
// FUNCTION:    ChangeQuantity                                         ||
// PARAMETERS:  Order Number to Change Quantity                        ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Changes quantity of an item in the shopping cart       ||
//---------------------------------------------------------------------||
function ChangeQuantity(OrderItem,NewQuantity) {

   //if new quantity not numeric show error else process
   if ( isNaN(NewQuantity) ) {
      alert( strErrQty );
   } else {
      NewOrder = "Order." + OrderItem;
      database = "";
      database = GetCookie(NewOrder);
      GetCookieFields(database);

      //Create newstring with just the quantity changed	
      dbUpdatedOrder = fields[0] + "|" +
                       NewQuantity + "|" +
                       fields[2] + "|" +
                       fields[3] + "|" +
                       fields[4] + "|" +
                       fields[5] + "|" + fields[6] + "|" +
                       fields[7] + "|" + fields[8] +  "|" +
                       fields[9] + "|" +
                       fields[10];

      //write string to cookie	
      strNewOrder = "Order." + OrderItem;
      DeleteCookie(strNewOrder, "/");
      SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
      location.href=location.href;      
   }
}

//---------------------------------------------------------------------||
//    Change postage zone as GB, Europe or world                       ||
// PARAMETERS:  UK or EU from select value                             ||
//---------------------------------------------------------------------||
function setzone(sel) 
{
  var pval=0;
  var tval=0;

  //Allow print order option for UK only
  //if (document.getElementById("otype").value="P") return; 

  //set postage and total according to selected zone
  if (sel.selectedIndex==0)
  {
	strval = "£" + moneyFormat(gfShipping);
  	document.getElementById("pandp").innerHTML = strval;
  	strval = "£" + moneyFormat(gfTotal);
  	document.getElementById("total").innerHTML = strval;

	//set input fields to UK
	document.order.cntry.value="UK";
	document.eorder.cntry.value="UK";
	document.porder.cntry.value="UK";
  }
  else
  {
	//if input fields set to UK then blank but do not remove any deliberate entry
	if (document.order.cntry.value=="UK") document.order.cntry.value="";
	if (document.eorder.cntry.value=="UK") document.eorder.cntry.value="";
	if (document.porder.cntry.value=="UK") document.porder.cntry.value="";

       	if (sel.selectedIndex==1)
  	{
		if (gfShipping==pandp1)
			pval = epandp1;
		else	
			if (gfShipping==pandp2)
				pval = epandp2;
			else
				if (gfShipping==pandp3) pval = epandp3;
  		strval = "£" + moneyFormat(pval);
  		document.getElementById("pandp").innerHTML = strval;
		tval = gfTotal + (pval - gfShipping);
        	strval = "£" + moneyFormat(tval);
        	document.getElementById("total").innerHTML = strval;
  	} 
        else
        {
		if (gfShipping==pandp1)
			pval = wpandp1;
		else	
			if (gfShipping==pandp2)
				pval = wpandp2;
			else
				if (gfShipping==pandp3) pval = wpandp3;
  		strval = "£" + moneyFormat(pval);
  		document.getElementById("pandp").innerHTML = strval;
		tval = gfTotal + (pval - gfShipping);
        	strval = "£" + moneyFormat(tval);
        	document.getElementById("total").innerHTML = strval;
	}
  }

  //copy to "real" control to allow refresh  without losing value
  document.getElementById("zone").value = sel.selectedIndex;
}

//---------------------------------------------------------------------||
// FUNCTION:    ManageCart                                             ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page          ||
//---------------------------------------------------------------------||
function ManageCart( ) {
   var iNumberOrdered = 0;    //Number of products ordered
   var strTotal       = "";   //Total cost formatted as money
   var strShipping    = "";   //Total shipping formatted as money
   var strOutput      = "";   //String to be written to page
   var fTotal=0.0;
   var fShipping=0.0;

   //Not filled in counts as zero
   iNumberOrdered = GetCookie("NumberOrdered");
   if ( iNumberOrdered == null ) iNumberOrdered = 0;

   //Write the product report header followed by blank line
   strOutput += "<TABLE CLASS='ord' border=1 bordercolor=black cellspacing=0><TR>" +
                "<TD class='hdr' style='width:90px'><p>Product ID</p></TD>" +
                "<TD class='hdr' style='width:300px'><p>Product Name</p></TD>" +
                "<TD class='hdr' style='width:80px'><p>Quantity</p></TD>" +
                "<TD class='hdr' style='width:80px'><p>Cost each</p></TD>" +
                "<TD class='hdr' style='width:134px'><p>Price</p></TD>" +
                "<TD class='hdr' style='width:100px'><p id='rem'>Remove</p></TD></TR>"

   //For each product check numbers in each category
   for ( i = 1; i <= numcategories; i++ ) category[i] = 0;
   for ( i = 1; i <= iNumberOrdered; i++ ) {
      NewOrder = "Order." + i;
      database = "";
      database = GetCookie(NewOrder);
      GetCookieFields(database);
      n = parseInt(fields[10]);
      category[n] += parseInt(fields[1]);
   }

   //For each product
   fTotal=0;
   for ( i = 1; i <= iNumberOrdered; i++ ) {
      NewOrder = "Order." + i;
      database = "";
      database = GetCookie(NewOrder);
      GetCookieFields(database);

      //Apply any quantity discount to unit price
      n = parseInt(fields[10]); 
      cattotal = category[n];
      if ( (fields[7] != 0) && (cattotal >= parseInt(fields[7])))
	  fields[2] -= fields[8];
      else
          if ( (fields[5] != 0) && (cattotal >= parseInt(fields[5]))) fields[2] -= fields[6];

      //Apply any one off reduction (cost of 1 item not each)
      red = parseInt(fields[9]); strRed="";
      if (red>0.0) strRed="-Red"
  
      //Add this product to totals	
      fTotal     += (parseInt(fields[1]) * parseFloat(fields[2]) );
      fTotal = fTotal - red;
      strTotal    = moneyFormat(fTotal);
	
      //Write a row for each item ordered - code, description, number, price each, total cost+ remove button 
      strOutput += "<TR><TD class='con'>&nbsp;"  + fields[0] + "</TD>";
      strOutput += "<TD class='con'>&nbsp;"  + fields[3] + "</TD>";
      strOutput += "<TD class='con'><P><INPUT TYPE=TEXT NAME=Q SIZE=2 VALUE='"  + fields[1] + "' onChange=ChangeQuantity(" + i + ",this.value)></P></TD>";
      strOutput += "<TD class='con'><P>£" + moneyFormat(fields[2]) + "</P></TD>";
      strOutput += "<TD class='con'><P>£" + moneyFormat(fields[1] * fields[2]) + "</P></TD>";
      strOutput += "<TD class='con'><P><input type=button value='remove' onClick=RemoveFromCart(" + i +")></P></TD></TR>";
   }

   //min postage applies to total
   //if (fShipping < minpp) fshipping = minpp;

   //Postage based on total
   if ( iNumberOrdered == 0 )
	fShipping = 0.0;
   else
   {
      fShipping = pandp1;
      if (fTotal >= norder3)
	   fShipping = pandp3;
      else
   	   if (fTotal >= norder2) fShipping = pandp2;
   }
   strShipping = moneyFormat(fShipping);

   //Total includes postage
   fTotal += 1*fShipping;
   strTotal    = moneyFormat(fTotal);  

   //write postage line
   strOutput +=   "<TR><TD class='hdr' COLSPAN=2 ROWSPAN=2><SPAN>Postage area&nbsp;&nbsp;&nbsp;" +
		  "<select id=csel onChange='setzone(this)'>" +
                  "<option selected value='UK'>UK<option value='EU'>Europe<option value='OE'>Outside Europe</select></SPAN></TD>" +
                  "<TD class='hdr' COLSPAN=2>Post and packing</TD><TD class='con'><P ID='pandp'>£" + strShipping + "</P></TD>" +
                  "<TD clss='hdr' ROWSPAN=2>&nbsp;</TD></TR>"

   //write total line
   strOutput +=   "<TR><TD  class='hdr' COLSPAN=2>Total</TD><TD class='con'><P ID='total'>£" + moneyFormat((fTotal)) + 
                  "</P></TD></TR></TABLE>"

   //set globals after each calulation
   gfShipping=fShipping;
   gfTotal=fTotal;

   document.write(strOutput);
   document.close();
}

// checkout methods
// These set colour white for print normal for others
// show relevant input div and hide others
// checkout method selection
function checkoutprint() 
{
	copyflds();
        document.body.style.backgroundColor = "white";
	changecolor("white");
	document.getElementById("P").style.visibility="visible";
	document.getElementById("E").style.visibility="hidden";
	document.getElementById("W").style.visibility="hidden";
	document.getElementById("P").style.top = document.getElementById("marker").offsetTop;
	document.getElementById("otype").value="P";
	pasteflds();
        //if print option for UK only
	//document.getElementById("csel").selectedIndex = 0;
        //setzone(document.getElementById("csel"));
}
function checkoutemail() 
{
	copyflds();
	document.body.style.backgroundColor = bcol;
	changecolor(hcol);
	document.getElementById("P").style.visibility="hidden";
	document.getElementById("E").style.visibility="visible";
	document.getElementById("W").style.visibility="hidden";
	document.getElementById("E").style.top = document.getElementById("marker").offsetTop;
	document.getElementById("rem").innerHTML="Remove";
	document.getElementById("otype").value="E";
	pasteflds();
	CheckoutCart(); 
}
function checkoutwp() 
{
	copyflds();
	document.body.style.backgroundColor = bcol;
	changecolor(hcol);
	document.getElementById("P").style.visibility="hidden";
	document.getElementById("E").style.visibility="hidden";
	document.getElementById("W").style.visibility="visible";
	document.getElementById("W").style.top = document.getElementById("marker").offsetTop;
	document.getElementById("rem").innerHTML="Remove";
	document.getElementById("otype").value="W";
	pasteflds();
}

//Changes colour for last specific (hdr) style rule
//this is browser dependent
function changecolor(str) 
{
var formats = new Array();
var browser=navigator.userAgent.toLowerCase();
if (browser.indexOf("msie") != -1)
	formats = document.styleSheets[0].rules;
else
	formats = document.styleSheets[0].cssRules;
formats[formats.length-1].style.backgroundColor = str;
}

//Copy customer data from one form to another
function copyflds() 
{	
val=document.getElementById("otype").value;
if (val=="W")
    frm = document.order; 
else
   if (val=="E")
	frm = document.eorder; 
   else
	frm = document.porder; 
with (frm)
{
    cname = name.value;
    cschool = school.value;
    caddr1 = addr1.value;
    caddr2 = addr2.value;
    caddr3 = addr3.value;
    ccnty = cnty.value;
    cpostcode = postcode.value;
    ccntry = cntry.value;
    ctel = tel.value;
    cfax = fax.value;
    cemail = email.value;
    cother = other.value;
}
}
function pasteflds() 
{
val=document.getElementById("otype").value;
if (val=="W")
    frm = document.order; 
else
   if (val=="E")
	frm = document.eorder; 
   else
	frm = document.porder; 
with (frm)
{
    name.value = cname;
    school.value = cschool;
    addr1.value = caddr1;
    addr2.value = caddr2;
    addr3.value = caddr3;
    cnty.value = ccnty;
    postcode.value = cpostcode;
    cntry.value = ccntry;
    tel.value = ctel;
    fax.value = cfax;
    email.value = cemail;
    other.value = cother;
}
}

//Validate customer details for Worldpay or email
function validateform(thisform) 
{
var errmsg = "";
var result = true;
with (thisform)
{
  //check details
  if (name.value == "" && school.value== "")
	{errmsg += "\nPlease enter a name or organisation"; result = false;}
  if (addr1.value == "" || addr2.value == "" || addr3.value == "")
	{errmsg += "\nPlease enter 3 address lines"; result = false;}
  if (email.value == "")
	{errmsg += "\nPlease enter a valid email address"; result = false;}
  if (postcode.value == "") {errmsg += "\nPlease enter a postcode"; result = false;}
  if (cntry.value == "") {errmsg += "\nPlease enter a country"; result = false;}

  // Message if incomplete
  if (result == false)
  	window.alert("Some required fields are missing:\n"+errmsg);

  //otherwise create wp fields and submit
  else
  {	
	CheckoutCart();
  	thisform.submit();
  }
}	
}

//---------------------------------------------------------------------||
// FUNCTION:    CheckoutCart                                           ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page for      ||
//              checkout.                                              ||
//---------------------------------------------------------------------||
function CheckoutCart( ) 
{
   var iNumberOrdered = 0;    //Number of products ordered
   var strTotal       = "";   //Total cost formatted as money
   var strShipping    = "";   //Total shipping formatted as money
   var strOutput      = "";   //String to be written to page
   var strPP          = "";   //Payment Processor Description Field
   var pdes           = "";   //Description
   var cback          = "";   //Callback string
   var s              = "";   //temp string
   var q              = "";   //temp amount
   var method=""; //order method worldpay etc
   var fTotal=0;
   var fShipping=0;

   //Initialise fields
   //Order details in callback field and description on WP page 
   with (document.order)
   {
     M_desc.value = '';	
     MC_desc.value = '\n';	
   }
   document.eorder.E_order.value = "\n";

   //No order filled in counts as zero	
   iNumberOrdered = GetCookie("NumberOrdered");
   if ( iNumberOrdered == null )
      iNumberOrdered = 0;

   //For each product check numbers in each category
   for ( i = 1; i <= numcategories; i++ ) category[i] = 0;
   for ( i = 1; i <= iNumberOrdered; i++ ) {
      NewOrder = "Order." + i;
      database = "";
      database = GetCookie(NewOrder);
      GetCookieFields(database);
      n = parseInt(fields[10]);
      category[n] += parseInt(fields[1]);
   }


   //For each product
   for ( i = 1; i <= iNumberOrdered; i++ ) 
   {
      NewOrder = "Order." + i;
      database = "";
      database = GetCookie(NewOrder);
      GetCookieFields(database);

      //Apply any quantity discount to unit price
      n = parseInt(fields[10]); 
      cattotal = category[n];
      if ( (fields[7] != 0) && (cattotal >= parseInt(fields[7])))
	  fields[2] -= fields[8];
      else
          if ( (fields[5] != 0) && (cattotal >= parseInt(fields[5]))) fields[2] -= fields[6];

      //Apply any one off reduction (cost of 1 item not each)
      red = parseInt(fields[9]); strRed="  ";
      if (red>0.0) strRed="-R"

      //Add this product to the totals
      //Apply any one off reduction (cost of 1 item not each)
      fTotal     += (parseInt(fields[1]) * parseFloat(fields[2]));
      fTotal = fTotal - red;
      strTotal    = moneyFormat(fTotal);

     //fields[] 0=product code, 1=number ordered, 2=price each, 3=full description

     //product code eg AUK 01us - always 8 chars
     cod = new String(fields[0]);	 

     //Description in customer mail - one for each product eg "Animals UK 1 user"
     des = new String(fields[3]);
     //while (des.length<35) des = des + ' ';	 

     //number ordered
     ord = new String(fields[1]);
     //while (ord.length<4) ord = ord + ' ';	 

     //price each - prefix by £ would be nice but how so it displays consistently, no idea
     pre = moneyFormat(fields[2]);
     //while (pre.length<8) pre = pre + ' ';	 

     //*****reduction not used at mo 
     //strRed;

     //total - prefix £
     tot =   moneyFormat(fields[1] * fields[2]);
     //while (tot.length<9) tot = tot + ' ';	 


     //Worldpay	 lines
     //Create the various strings sent
     with (document.order)	
     {

		//complete line
         	M_desc.value =  M_desc.value + cod + ': qty=' + ord + ' ea=' + pre + ' amt=' + tot + '\n';
         	MC_desc.value =  MC_desc.value + ord + ' ' + des + ': ' + pre + ' each, total = ' + tot + '\n';		
     }

     //email	 lines
     //Create the various strings sent
     with (document.eorder)	
     {

                E_order.value =  E_order.value + ord + ' ' + des + ': ' + pre + ' each, total = ' + tot + '\n';		
     }       

   }

   //if outside UK add extra postage
   p1=pandp1;  p2=pandp2;  p3=pandp3;
   sel=document.getElementById("csel").selectedIndex;
   if (sel==1) {p1=epandp1;  p2=epandp2;  p3=epandp3;}
   if (sel==2) {p1=wpandp1;  p2=wpandp2;  p3=wpandp3;}

   //Postage based on total
   fShipping = p1;
   if (fTotal >= norder3)
	  fShipping = p3;
   else
   	  if (fTotal >= norder2) fShipping = p2;

   //min postage applies
   //if (fShipping < minpp) fshipping = minpp;

   strShipping = moneyFormat(fShipping);

   //Total includes postage
   sub = moneyFormat(fTotal);
   fTotal += 1*fShipping;

   //Worldpay	 lines
   //Create the various strings sent
   with (document.order)
   {	

	      //description on order page
              desc.value =  "Educational materials";

	      // Cart ID - use same eg "Mrs Hack @ St Mings"
	      cartId.value  = name.value  + " @ " + school.value;

	      // Address - separate into lines
	      address.value = addr1.value + '&#10;' + addr2.value + '&#10;' + addr3.value + '&#10;' + cnty.value + '&#10;';
	      //address.value = caddr1 + '\n' + caddr2 + '\n' + caddr3 + '\n' + ccnty + '\n';

	      // Final total inc.post and VAT
	      amount.value =  moneyFormat(fTotal);
		
	      // Callback. Eeeh-male is split to avoid too easy pick up for sp ammers
	      // Newline in front of order is for format on callback mail
	      M_recipient.value = recipientPart1 + recipientPart2 + "@" + URL + ".co.uk";
	      M_subject.value = "Order for " + cartId.value;
	      M_name.value = name.value;
	      M_school.value = school.value;
	      M_orderaddr.value = addr1.value + '\n' + addr2.value + '\n' + addr3.value + '\n' + cnty.value + '\n' + postcode.value +
                    '\n' + cntry.value;
	      M_email.value = email.value;
	      M_tel.value = tel.value;
	      M_fax.value = fax.value;
	      M_instructions.value = other.value;  if (M_instructions.value=="") M_instructions.value="none";
              M_postage.value = strShipping;
              M_total.value = amount.value;
	      M_zone.value = document.getElementById("csel").selectedIndex;

	      //finish customer order details
	      MC_desc.value = MC_desc.value + "Sub total " + sub + '\n';
	      MC_desc.value = MC_desc.value + "Postage " + strShipping + '\n';
	      MC_desc.value = MC_desc.value + "Total " + amount.value + " GBP";		
   }

   //email	 lines
   //Create the various strings sent
   with (document.eorder)
   {	
	    E_order.value = E_order.value + "Sub total " + sub + '\n';
	    E_order.value = E_order.value + "Postage " + strShipping + '\n';
	    E_order.value = E_order.value + "Total " + moneyFormat(fTotal) + " GBP";		
            Postage.value = strShipping;
            TotalExcVAT.value = moneyFormat(fTotal);
   }        

//with (document.order)
//{
//  wint=open("","test");
//  wint.document.open("text/plain");
//  wint.document.writeln("inst ID  ",instId.value);
//  wint.document.writeln("cart ID  ",cartId.value);
//  wint.document.writeln("country  ",country.value);
//  wint.document.writeln("currency  ",currency.value);
//  wint.document.writeln("desc ",desc.value);
//  wint.document.writeln("address ",address.value);
//  wint.document.writeln("amount ",amount.value);
//  wint.document.writeln("M my mail ",M_recipient.value);
//  wint.document.writeln("M subject ",M_subject.value);
//  wint.document.writeln("M order ",M_order.value);
//  wint.document.writeln("Tst mode ",testMode.value);
//}
}


//---------------------------------------------------------------------||
// FUNCTION:    RadioChecked                                           ||
// PARAMETERS:  Radio button to check                                  ||
// RETURNS:     True if a radio has been checked                       ||
// PURPOSE:     Form fillin validation                                 ||
//---------------------------------------------------------------------||
function RadioChecked( radiobutton ) {
   var bChecked = false;
   var rlen = radiobutton.length;
   for ( i=0; i < rlen; i++ ) {
      if ( radiobutton[i].checked )
         bChecked = true;
   }    
   return bChecked;
} 


//---------------------------------------------------------------------||
// FUNCTION:    QueryString                                            ||
// PARAMETERS:  Key to read                                            ||
// RETURNS:     value of key                                           ||
// PURPOSE:     Read data passed in via GET mode                       ||
//---------------------------------------------------------------------||
QueryString.keys = new Array();
QueryString.values = new Array();
function QueryString(key) {
   var value = null;
   for (var i=0;i<QueryString.keys.length;i++) {
      if (QueryString.keys[i]==key) {
         value = QueryString.values[i];
         break;
      }
   }
   return value;
} 

//---------------------------------------------------------------------||
// FUNCTION:    QueryString_Parse                                      ||
// PARAMETERS:  (URL string)                                           ||
// RETURNS:     null                                                   ||
// PURPOSE:     Parses query string data, must be called before Q.S.   ||
//---------------------------------------------------------------------||
function QueryString_Parse() {
   var query = window.location.search.substring(1);
   var pairs = query.split("&"); for (var i=0;i<pairs.length;i++) {
      var pos = pairs[i].indexOf('=');
      if (pos >= 0) {
         var argname = pairs[i].substring(0,pos);
         var value = pairs[i].substring(pos+1);
         QueryString.keys[QueryString.keys.length] = argname;
         QueryString.values[QueryString.values.length] = value;
      }
   }
}

//---------------------------------------------------------------------||
// FUNCTION:    getCookieVal                                           ||
// PARAMETERS:  offset                                                 ||
// RETURNS:     URL unescaped Cookie Value                             ||
// PURPOSE:     Get a specific value from a cookie                     ||
//---------------------------------------------------------------------||
function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);

   if ( endstr == -1 )
      endstr = document.cookie.length;
   return(unescape(document.cookie.substring(offset, endstr)));
}


//---------------------------------------------------------------------||
// FUNCTION:    FixCookieDate                                          ||
// PARAMETERS:  date                                                   ||
// RETURNS:     date                                                   ||
// PURPOSE:     Fixes cookie date, stores back in date                 ||
//---------------------------------------------------------------------||
function FixCookieDate (date) {
   var base = new Date(0);
   var skew = base.getTime();

   date.setTime (date.getTime() - skew);
}


//---------------------------------------------------------------------||
// FUNCTION:    GetCookie                                              ||
// PARAMETERS:  Name                                                   ||
// RETURNS:     Value in Cookie                                        ||
// PURPOSE:     Retrieves cookie from users browser                    ||
//---------------------------------------------------------------------||
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                                              ||
// PARAMETERS:  name, value, expiration date, path, domain, security   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Stores a cookie in the users browser                   ||
//---------------------------------------------------------------------||
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:    DeleteCookie                                           ||
// PARAMETERS:  Cookie name, path, domain                              ||
// RETURNS:     null                                                   ||
// PURPOSE:     Removes a cookie from users browser.                   ||
//---------------------------------------------------------------------||
function DeleteCookie (name,path,domain) {
   if ( GetCookie(name) ) {
      document.cookie = name + "=" +
                        ((path) ? "; path=" + path : "") +
                        ((domain) ? "; domain=" + domain : "") +
                        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
   }
}


function GetCookieFields(database)
{
//Each field is separated by | - this finds position of separators
Token0 = database.indexOf("|", 0);
Token1 = database.indexOf("|", Token0+1);
Token2 = database.indexOf("|", Token1+1);
Token3 = database.indexOf("|", Token2+1);
Token4 = database.indexOf("|", Token3+1);
Token5 = database.indexOf("|", Token4+1);
Token6 = database.indexOf("|", Token5+1);
Token7 = database.indexOf("|", Token6+1);
Token8 = database.indexOf("|", Token7+1);
Token9 = database.indexOf("|", Token8+1);

//Get all fields
fields[0] = database.substring( 0, Token0 );			  // Product ID
fields[1] = database.substring( Token0+1, Token1 );		  // Quantity	
fields[2] = database.substring( Token1+1, Token2 );		  // Price
fields[3] = database.substring( Token2+1, Token3 );		  // Product Name/Description
fields[4] = database.substring( Token3+1, Token4 );		  // Shipping Cost
fields[5] = database.substring( Token4+1, Token5 );          	  // Discount quantity 1
fields[6] = database.substring( Token5+1, Token6 );          	  // Discount reduction 1
fields[7] = database.substring( Token6+1, Token7 );         	  // Discount quantity 2
fields[8] = database.substring( Token7+1, Token8 );         	  // Discount quantity 2
fields[9] = database.substring( Token8+1, Token9 );             // One off reduction
fields[10] = database.substring( Token9+1,  database.length );   // category
}

//---------------------------------------------------------------------||
// FUNCTION:    CKquantity                                             ||
// PARAMETERS:  Quantity to                                            ||
// RETURNS:     Quantity as a number, and possible alert               ||
// PURPOSE:     Make sure quantity is represented as a number          ||
//---------------------------------------------------------------------||
function CKquantity(checkString) {
   var strNewQuantity = "";

   for ( i = 0; i < checkString.length; i++ ) {
      ch = checkString.substring(i, i+1);
      if ( (ch >= "0" && ch <= "9") || (ch == '.') )
         strNewQuantity += ch;
   }

   if ( strNewQuantity.length < 1 )
      strNewQuantity = "1";

   return(strNewQuantity);
}

//---------------------------------------------------------------------||
// FUNCTION:    MoneyFormat                                            ||
// PARAMETERS:  Number to be formatted                                 ||
// RETURNS:     Formatted Number                                       ||
// PURPOSE:     Reformats Pound Amount to #.## format                 ||
//---------------------------------------------------------------------||
function moneyFormat(input) {
   var pounds = Math.floor(input);
   var tmp = new String(input);

   for ( var decimalAt = 0; decimalAt < tmp.length; decimalAt++ ) {
      if ( tmp.charAt(decimalAt)=="." )
         break;
   }

   var pence  = "" + Math.round(input * 100);
   pence = pence.substring(pence.length-2, pence.length)
           pounds += ((tmp.charAt(decimalAt+2)=="9")&&(pence=="00"))? 1 : 0;

   if ( pence == "0" )
      pence = "00";

   return(pounds + "." + pence);
}

//=====================================================================||
//               END NOP Design SmartPost Shopping Cart                ||
//=====================================================================||

