// create a series of arrays to store the order line items
var line_code = new Array();
var line_name = new Array();
var line_qty = new Array();
var line_price = new Array();
var line_info = new Array();
// store the order information
var order_delivery_fee = 0;
var g_vat=0.14;
var discount=0.05;
var order_lines = 0;
var order_items = 0; //total number of items in order]
var order_cost= 0.00; // total cost of order
var g_maxOrderLines = 50;  // maximum lines in a single order
var in_cart = new Array(); // store the img IDs for the in cart items on the current page
// add the information from the 'orderform' to the shopping
// cart

function Order(orderform)
{
   var line = '';
   var sep = '';
   var props = '';
   var i;
   var obj;
   var name;

   for (i = 0 ; i < orderform.elements.length ; i ++)
   {
      obj = orderform.elements[i];

      switch (obj.name)
      {
        case 'qty': quantity = parseInt(obj.value); 
					if ((quantity == '') || isNaN(quantity))
						quantity = 1;
					break;
        case 'price': price =  obj.value; break;
        case 'code': code = obj.value; break;
        case 'name': name = obj.value;break;
        case 'ord':break;
        default:
           if (typeof(obj) == 'object')
           {
              props += sep + obj.name + ' - ' + obj.options[obj.selectedIndex].text ;
              sep = ', ';
           }
        break;
      }
   }

   //line = '(' + code + ',' + price + ',' + quantity + ',' + props + ')';
   //alert(line);
   order_AddItem(code,name,price,quantity,props);
   //feedback to user that item is ordered
   //eval('document.all.img'+code + '.style.display = \'inline\';');
   //in_cart[in_cart.length] = 'img' + code;
   order_Save();
   // update display and save
   order_DisplaySummary();
}


// order class
// add the item to the order
function order_AddItem(code, name, price, qty, info)
{
  var index = line_code.length;   // index at which to save next line item
  // save the order information
  line_code[index] = code;
  line_name[index] = name;
  line_price[index] = price;
  line_qty[index] = qty;
  line_info[index] = info;
  // update the order totals
  order_lines++;
  order_cost += price * qty;
  order_items += Number(qty);
  // add the delivery fee when the first item is ordered
  if ((order_items == 1) && (order_delivery_fee > 0))
  {
     alert(name + ' has been added to your basket as well as a delivery fee.');
     order_cost += Number(order_delivery_fee);
  }
  else 
  {
	  alert(name + ' has been added to your basket.');
  }
  
}

// initialise the order catalogue from the cookie
function order_Initialise()
{
   order_Load();
}

function order_DisplaySummary()
{
  //alert(order_items);
  // update display
  _findObj('cart_lines').innerHTML = order_lines;
  _findObj('cart_items').innerHTML = order_items;  
  _findObj('cart_amount').innerHTML = NumberFormat(order_cost,2);
}

// delete specified item from the order
function order_DelItem(delcode,delqty,delinfo)
{
  var i = 0;   // escape from infinite while loop if bug in code
  var delprice;
  
  
  for (i = 0; i < line_code.length ; i++)
  {

    if ((line_code[i] == delcode) &&
        (line_qty[i] == delqty) &&
        (line_info[i] == delinfo))
    {  // delete line item
      line_code.splice(i ,1);
      line_name.splice(i ,1);
      delprice = line_price[i];
      line_price.splice(i ,1);
      line_qty.splice(i ,1);
      line_info.splice(i ,1);
      order_lines--;
      if (order_lines == 0)
        order_Reset();
      else
      {
         order_cost -= delprice * delqty;
         order_items -= Number(delqty);
         order_Save();
      }
      break;
    }
  }
  
}

// display the number with the indicated number of decimal places
// works for decimals <= 10
function NumberFormat(num, decimals)
{
   var numstr = String(num);
   var point = numstr.indexOf('.');

   if (point >= 0)
   {
     numstr = String(numstr + '0000000000').substr(0,point+decimals+1);
   }
   else numstr += String('.0000000000').substr(0,decimals+1);

   return numstr;
}
// reset the order information
function order_Reset()
{
   var i;
   order_lines = 0;
   order_items = 0; //total number of items in order]
   order_cost= 0.00; // total cost of order
   line_code.length = 0;
   line_name.length = 0;
   line_qty.length = 0;
   line_price.length = 0;
   line_info.length = 0;
   // hide any in_cart icons that show on the current page
   for (i = 0 ; i < in_cart.length; i++)
   {
       eval('document.all.' + in_cart[i] + '.style.display = \'none\';');
   }
   // clean out all the old order information
   order_Save();
}

function order_Header(count,lines,amount)
{
  var start_index = document.cookie.indexOf('<head>');
  var end_index = document.cookie.indexOf('</head>');
  var head = '<head><count>'+count+'</count><lines>'+lines+'</lines><amount>'+amount+'</amount></head>';

  if ((start_index >= 0) &&
      (end_index > start_index))
  {  // remove the header if it already exists
     document.cookie = document.cookie.substr(0,start_index + 6) +
                       document.cookie.substr(end_index + 6);
  }

  document.cookie += head;
}
// save the order in a cookie
function order_Save()
{
// save the order in the cookie

  var orderxml = String('');
  if (line_code.length > 0)
  {
     var i;
     for (i = 0 ; i < line_code.length ; i++)
     {
        orderxml += '<line><code>' + line_code[i] + '</code><name>' +
               line_name[i] + '</name><price>' +
               line_price[i] + '</price><qty>' + line_qty[i] + '</qty><info>'+
               line_info[i] + '</info></line>';
     }
  }
  //alert(orderxml);
  // replace <order>..</order> in cookie
   createCookie('order_details',orderxml,30); 
}

// load the order information from the cookie into the order variables
function order_Load()
{
 // extract <order>..</order> in cookie
  var orderxml = String();
  orderxml = readCookie('order_details');
//alert(orderxml);
  // empty the variables before loading the order in
  order_lines = 0;
  order_items = 0; //total number of items in order]
  order_cost= 0.00; // total cost of order
  line_code.length = 0;
  line_name.length = 0;
  line_qty.length = 0;
  line_price.length = 0;
  line_info.length = 0;

  var linexml = String();
  var i = 0;   // escape from infinite while loop if bug in code
  linexml = xml_FetchField('line',orderxml);
  
  while (linexml.length > 0)
  {

      // extract line information for array
      line_code[i] = xml_FetchField('code',linexml);
      line_name[i] = xml_FetchField('name',linexml);
	 // alert(i + ' - ' + xml_FetchField('qty',linexml));
      line_qty[i] = xml_FetchField('qty',linexml);
      order_items += Number(line_qty[i]);
      line_price[i] = xml_FetchField('price',linexml);
      order_cost += line_qty[i] * line_price[i];
      line_info[i] = xml_FetchField('info',linexml);
      order_lines++;
      // remove line from order xml and then fetch next line
      orderxml = xml_SetField('line',orderxml,'');
      linexml = xml_FetchField('line',orderxml);
      i++;
      if (i > g_maxOrderLines)
        break;
  }

  if ((order_delivery_fee > 0) && (order_items > 0))
     order_cost += Number(order_delivery_fee);

}

// display full cart information
// del - true if delete is allowed on cart
function order_DisplayCart(del)
{ 
	 //Display colum headers
   var table = String('<table class=cart width="100%" cellpadding="0" cellspacing="0" border="0">\n<tr class=\"cartheading\">\n');
    if (del)
   {
     table += '<td>&nbsp;</td>\n';
     tableColumns = 6
   }
   else
   {
     tableColumns = 4;
   }
   table += '<td>PRODUCT NAME</td><td>QTY</td><td>UNIT PRICE</td><td>AMOUNT</td>\n';
  
   table += '</tr\n>';
   var orderxml = readCookie('order_details');
   if (orderxml.length > 0)
   {
     var linexml = String();
     var i = 0;   // escape from infinite while loop if bug in code
     var total = 0;
     var disc;
	 var code;
     var qty;
     var price;
     var cost;
     var info;
     var name;
	 var vat =0;
	 var newname;




     linexml = xml_FetchField('line',orderxml);

     while (linexml.length > 0)
     {

         // extract line information for array
         code = xml_FetchField('code',linexml);
         name = xml_FetchField('name',linexml);
         qty = xml_FetchField('qty',linexml);
         price = xml_FetchField('price',linexml);
         cost = qty * price;
         total += Number(cost);
         info = xml_FetchField('info',linexml);

         if ((i % 2) == 0)
            rowclass='cartline1';
         else rowclass='cartline2';

      
         //***row begin
		 
		 //remove button
		 if (del)
         {
			 
           table += '<tr class="' + rowclass + '"><td><img class="add_to_basket" onMouseOver="changeImages(\'button_remove'+i+'\',\'images/button-remove-over.jpg\');return true" onMouseOut="changeImages(\'button_remove'+i+'\',\'images/button-remove.jpg\');return true"id="button_remove'+i+'"  src="images/button-remove.jpg" onclick="order_DelItem(\'' + code + '\',' + qty + ',\'' + info + '\'); order_DisplayCart(' + del + ');"></td>';
         
		 
		 //default del button
		 <!--table += '<td><input type=button value="Del" onclick="order_DelItem(\'' + code + '\',' + qty + ',\'' + info + '\'); order_DisplaySummary(); order_DisplayCart(' + del + ');"></td>';-->
		 }
		 else table += '<tr class="' + rowclass + '">';
		 
		    //name
		
		//name = name.toLowerCase().replace(/\b\w/g, function(match){return match.toUpperCase();});
		table += '<td>'+ code + ' - '+ name;
        

		 
		 //Info
		 if (info.length > 0)
           table += '<br> ' + info + '</td>';
         else
	       table += '</td>';
         
		 //Quantity
		 //if (del)
		 //table += '<td> <input name="qty" type="text" value="'+ qty+'" size="5"></td>';
		 //else
		 table += '<td>' + qty + '</td>\n';
		
		//Unit Price
		 table+= '<td> R  ' + NumberFormat(price,2) + '</td>';
         
		 
		 //amount ( qty x unit price)
		 table += '<td> R  ' + NumberFormat(cost,2) + '</td>\n';
         
		//remove button ex
		
     
		 table += '</tr>';
		  //***row end
		 		 
		  //display order description		           	 		  		
		       
		 // remove line from order xml and then fetch next line
         order_Save();
		 //order_DisplayCart(true);
		 //order_DisplayCart();
		 orderxml = xml_SetField('line',orderxml,'');
         linexml = xml_FetchField('line',orderxml);
         i++;
         if (i > 50)
            break;
      }
      
	  //add line break 
	  table+= '<tr><td>&nbsp;</td></tr>';
  
	  
	     //display discount
        // if (order_delivery_fee = 0)
        //{
         /*disc = total * discount;
		 total = total - disc;
		 
		 if ((i % 2) == 0)
            rowclass='cartline1';
         else rowclass='cartline1';
	 	 table += '<tr class=' + rowclass + '><td colspan=';
         if (del)
         {
          table += (tableColumns-4);
         }
         else table += (tableColumns-3);
         table += '>&nbsp;</td><td colspan="2">*Members Discount ( ' + (discount * 100 ) + '% )</td><td> R  ' + NumberFormat(disc,2) + '</td>\n';
         if (del)
         {
            table += '<td>&nbsp;</td>';
         }
         table += '</tr>';*/
		
		
		
		
		//display shipping charge
        // if (order_delivery_fee = 0)
        //{
    	if ((i % 2) == 0)
            rowclass='cartline1';
         else rowclass='cartline1';
	 	 table += '<tr class=' + rowclass + '><td colspan=';
         if (del)
         {
          table += (tableColumns-3);
         }
         else table += (tableColumns-2);
         table += '>&nbsp;</td><td colspan="1">Delivery</td><td> R  ' + NumberFormat(order_delivery_fee,2) + '</td>\n';
         if (del)
         {
            table += '<td>&nbsp;</td>';
         }
         table += '</tr>';
		 
		 //Sub total
		  total += order_delivery_fee;
		  
		  table += '<tr class=' + rowclass + '><td colspan=';
		  if (del)
		  {
			 table += (tableColumns-3);
		  }
		  else table += (tableColumns-2);
         table += '>&nbsp;</td><td colspan="1">Sub Total</td><td> R  ' + NumberFormat(total,2) + '</td>\n';
         if (del)
         {
            table += '<td>&nbsp;</td>';
         }
         table += '</tr>';
		 
		 //VAT(14%)		   
		  /*vat = g_vat * total;
		  table += '<tr class=' + rowclass + '><td colspan=';
		  if (del)
		  {
			 table += (tableColumns-3);
		  }
		  else table += (tableColumns-2);
         table += '>&nbsp;</td><td colspan="1">VAT (at 14%)</td><td> R  ' + NumberFormat(vat,2) + '</td>\n';
         if (del)
         {
            table += '<td>&nbsp;</td>';
         }
         table += '</tr>';*/
		 
		 
		 
       
      //}
	  //Display the Sub Total plus VAT
	   //total += vat;

      table += '<tr class=carttotal><td colspan=';
      if (del)
      {
         table += (tableColumns-3);
      }
      else table += (tableColumns-2);
      table += '>&nbsp;</td><td colspan="1">TOTAL</td><td> R  ' + NumberFormat(total,2) + '</td>';
      if (del)
      {
         table += '<td></td>';
      }
      table += '</tr>\n';
   }

   //If no items in cart display message:
   else table += '<tr><td colspan=' + tableColumns + ' align=center>Your shopping cart is empty.</td></tr>\n';
   table += '</table>';
   _findObj('divcart').innerHTML = table;
}

// ------------- XML style storage class --------------------- //
// retrieve the value of the field specified by fieldname form the xml
// provided
function xml_FetchField(fieldname, xml)
{
   var xmlfield = String();

   var start = xml.indexOf('<' + fieldname + '>');
   var end = xml.indexOf('</' + fieldname + '>');

   if ((start >= 0) &&
       (end > start))
   {
      xmlfield = xml.substr(start + fieldname.length + 2, end - start - fieldname.length-2);
   }

   return (xmlfield);
}

// set the specified field in the xml to have the given value
function xml_SetField(fieldname, xml, value)
{
 // alert(' xml_SetField (\nfieldname ' + fieldname + '\nxml ' + xml + '\nvalue ' + value);
  // replace <order>..</order> in cookie
  var start = xml.indexOf('<' + fieldname + '>');
  var end = xml.indexOf('</' + fieldname + '>');
  var newxml = xml;

  if ((start >= 0) &&
      (end > start))
  { // delete current field from xml
    newxml = xml.substr(0,start) + xml.substr(end + fieldname.length + 3);
  }

  newxml += '<' + fieldname + '>' + value + '</' + fieldname + '>';
  return (newxml);
}

function createCookie(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 '';
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function _findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}



