
/////////////////////////////////////////////////////
// orderlib.js
//
// Functions for order form and shopping cart
/////////////////////////////////////////////////////

var orderForm=null;
var urlflag = 0;  // read order info from cookie or url(1)
var pintax = false;

//////////////////////////////////////////
// pinOrder object
/////////////////////////////////////////
function pinOrder(name_, price_, qty_)
{
  this.name = name_;
  this.price = price_;
  if ((qty_==null) || (qty_ == "")) {
    qty_ = "1";
  }
  this.qty = qty_;
}

////////////////////////////////////////////
// retrieve the pin order from the cookie
// Parse into an array of 'pinOrder' objects
////////////////////////////////////////////
//var shipmethod=0;  // normal shipping

function getOrderArray()
{
 var orderCookie=WM_readCookie("pinorder");
 // cookie=/name@price@qty/name@price@qty/...
 var orderInfo = orderCookie;

 // Get order array from url...
 // url= ?pintax=true&pinorder=/name@price@qyt/name@price@qty&shipping=1.50
 if (urlflag == 1)
 {
   orderCookie=unescape(location.search);
   var ndx = orderCookie.indexOf("pinorder=");
   if (ndx >= 0)
   {
     ndx += 9;
   }
 
   // get the start of the order items
   var orderInfo = orderCookie.substr(ndx); 
   
   // get tax selection
   var ndx = orderCookie.indexOf("pintax=true");
   if (ndx >= 0) {
     pintax = true;
   }

    // Not used:
   ndx = orderCookie.indexOf("shipmethod=");
   if (ndx >= 0) 
   {
     ndx += 11;
     //shipmethod = parseFloat(orderCookie.substr(ndx, 2) ); // "1.", "3.", "13"
     //shipmethod = parseInt(orderCookie.substr(ndx, 1) );
   }
 } 
 else 
 {
   // get pintax from cookie
   pintax = WM_readCookie("pintax"); // true or false
   if (pintax == "true") {
     pintax = true;
   }
 }
 var orderItems=orderInfo.split("/"); // array of order items

 var itemNum = 0;   // order items count
 var orderArray = new Array();
 
 for (var i = 0; i<orderItems.length; i++)
 {
   if (orderItems[i].length > 4) {
    //  name@price@qty  |  some angel@14.95@1
    var itemA = orderItems[i].split("@");  // 0name, 1price, 2qty
    if ((itemA[0] != "") && (itemA[1] != "")) // name, price
    {
      var thisitem = new pinOrder(itemA[0], itemA[1], itemA[2]);
      
      orderArray[itemNum] = thisitem;
      itemNum++;
    }
   }
 }
 return orderArray;
 
} 



/////////////////////////////////////////////////////////
// encode the cookie from the array of pin order objects
// cookie=/name@price@qty/name@price@qty/...
// item is not included if qty = 0
//////////////////////////////////////////////////////////
function bakeCookie(orderArray)
{
  var i;
  var newCookie = "";
  
  for (i = 0; i < orderArray.length; i++)
  {
     var thisitem = orderArray[i];
     if (thisitem.qty > 0)
     {
       var itemstr = "/"+thisitem.name + "@" + thisitem.price + "@" + thisitem.qty;       
       newCookie += itemstr;
     }
  }
  WM_setCookie("pinorder", newCookie);
}


function clearOrder()
{

  var ans=confirm("Are you sure you want to clear your order?");
  if (ans)
  {
   WM_killCookie('pinorder');
   //redraw();
   location.reload(true);
  }
}

//////////////////////////////////////////
// format a numeric value to 2 dec places
// Input: numeric, output: string
//////////////////////////////////////////
function formatAmount(numval)
{
    var strval = numval+"";  // convert num to string
    var retval = strval;
    
    var i=strval.indexOf(".");
    if (i == -1)  {
      // 10 -> 10.00
      retval = strval + ".00";
      return retval;
    }
    // 10.  10.0  10.12  10.1234
    var dec = strval.substring(i+1, strval.length);
    if (dec.length == 0) {
      retval = strval + "00";
      return retval;
    }
  
    if (dec.length == 1) {
      retval = strval + "0";
      return retval;
    }
    if (dec.length > 2) {
      var extra = dec.length - 2;
      retval = strval.substr(0,strval.length-extra);
    }
    return retval;
}


var orderItems;// global
var orderSubTotal = 0;
var totalBooks = 0;
var totalPins = 0;
var shipping = 0;

//////////////////////////////////////////////////
// printOrderForm
//////////////////////////////////////////////////
function printOrderForm(form, urlflag_)
{
  orderForm = form;
  
  
  urlflag = urlflag_;
  orderItems=getOrderArray();

  var val = WM_readCookie("shipmethod");
  if ((val == 1) || (val == 0))
    form.shipmethod.selectedIndex = val;

  var text = "<table  border=2  width='70%'>";
  text += "<tr><th>Item name</th><th>Item price</th><th>Quantity</th><th>Item total</th>";
  var i = 0;
  var orderTotal = 0;

  if (orderItems.length == 0) {
    document.write("<em>Your Shopping Cart is empty</em>");
    return;
  }

  // Print a line item for each item in the order
  for (i = 0; i < orderItems.length; i++)
  {
    var iname = i+1; // for field names to begin at 1
    var itemQty = orderItems[i].qty;
    var itemName = orderItems[i].name;
    var itemPrice = orderItems[i].price;
    
    var price = parseFloat(itemPrice);
    var qty = parseInt(itemQty);
    var itemTot = price*qty;
    orderTotal += itemTot;
    
    if (itemName.indexOf("book") == 0) {
      totalBooks += qty;
    }
    else {
      totalPins += qty;
    }

    text += "<input type=hidden  name='item"+ iname +"' value='"+itemName+"'>";
    text += "<tr>";
    text += "<td>" + itemName +"</td><td>$" + itemPrice + "</td>";
    text += "<td align=center>";
    
    
    if (urlflag == 1)
    {
      // qty is text+hidden fields
      text += "<input type=hidden  name='qty"+iname+"'  value='"+itemQty + "'>"+itemQty+"</td>";
    }
    else 
    {
      // qty is user input
      text += "<input type='text' name='qty"+iname+"'  size=3 maxlength=3 value='"+itemQty + "'></td>";
    }
    
    itemTot = formatAmount(itemTot);
    text += "<td>$<input type=text  name='itemtotal"+ iname +"' value='"+itemTot+"'></td>";
    text += "<input type=hidden  name='itemprice"+ iname +"' value='"+itemPrice+"'>";   
    text += "</tr>";
  }
  
  orderSubTotal = orderTotal;  // total for tax computation
  // TAX
  // Calc Tax if selected
  var istax="";
  var tax = 0;
  if (pintax==true)
  {
    istax = "checked";
    tax = calctax();
  }
  orderTotal += tax;
  tax = formatAmount(tax);
  //text += "<input type=hidden  name='tax'  value='"+tax+"'>";

  // TAX Row
  text += "<tr><th align=right colspan=3>";
  text += "Arizona Residents check here ";
  text += "<input type=checkbox name=arizona onClick='recalcTotal()'" + istax + ">";
  text += "(7.5% sales tax)&nbsp;&nbsp;</th><td>$";
  //text += tax
  text += "<input type=text  name='tax'  size=5 maxlength=5 value='"+tax+"'>";
  text += "</td></tr>";

  // Shipping
  
  text += "<tr><th align=right  colspan=3>Shipping&nbsp;&nbsp;";
  orderTotal += shipping;
  var shipping_s = formatAmount(shipping);
  text += "</th>";//<td>$" + shipping_s + "</td></tr>";
  text += "<td >$<input type=text  name='shipping' size=7 maxlength=7 value='"+shipping_s+"'></td>";

  // Order Total
  orderTotal = formatAmount(orderTotal);
  text += "<tr><th align=right colspan=3>Total&nbsp;&nbsp;</th><td>$";
  text += "<input type=text name='totalprice'  fabled size=7 maxlength=7  value='"+orderTotal+"'>";
  text += "</td></tr>";
  text += "</table>";
  //text += "<input type=hidden  name='totalprice' value='"+orderTotal+"'>";
  document.write(text);

  recalcTotal();
 return i; // number of items in list
}

function reclose()
{
  // reclose the doc to avoid dangling hourglass (IE only)
  var n=navigator.appVersion;
  if (n.indexOf('MSIE') >= 0) {
   document.write("closed");
   top.location.href="javascript:void(document.close())";
  }
}
 
/////////////////////////////////////////////////
// Calc tax  shipping...
/////////////////////////////////////////////////
function checktax()
{
  var box= orderForm.arizona;
  var is = box.checked;
  var tax = 0;
  
  if (is) {
    WM_setCookie("pintax","true"); 
    tax =calctax();

  } else {
    WM_setCookie("pintax","false");
  }
    orderForm.tax.value= formatAmount(tax);
    orderForm.tax.defaultValue= formatAmount(tax);
}

/////////////////////////////////////////////////
// calcShipping
// set global 'shipping' value
// Method: 0:normal($3 or $6)   1:priority($6)
//////////////////////////////////////////////////
function calcShipping(totalPins, totalBooks, method)
{
  var rate = 3.00; 
  if (method == 0)
  {
      if (totalPins > 3)
      {
    	rate = 6.00;
      }
  }
  
  if (method == 1)
  {
  	rate = 6.00;
  }
  
  //var np = Math.floor((totalPins - 1)/3)+1;  // per 3 pins (obsolete)
  var shipping = rate;
  
  shipping += totalBooks * 2; // $2 per book shipping

  orderForm.shipping.value = formatAmount(shipping);

  return shipping;
}

function calctax()
{
  var t = orderSubTotal * 0.075;
  return t;
 
}


// recalc tax and totals
function recalcTotal()
{
  orderSubTotal = 0;
  totalPins = 0;
  
  for (var i = 0; i < orderItems.length; i++)
  {
    var qtyName = "qty"+(i+1); // name of the qty field, start at 1
    //var newQty = eval("shoppingForm."+qtyName+".value");
    var newQty = orderForm.elements[qtyName].value;
    var iQty=0;
    var priceName = "itemtotal"+(i+1);
    
    var itemPrice = orderItems[i].price;
    var price = parseFloat(itemPrice);
    var qty = parseInt(newQty);
    totalPins += qty;
    
    var itemTot = price*qty;
    orderForm.elements[priceName].value = formatAmount(itemTot);
    orderSubTotal += itemTot;
   
    if (newQty != "")
    {
      // put new qty in if it's not 0 or blank  '
      iQty = parseInt(newQty);
      if (isNaN(iQty)) {
        alert("Item quantity "+ newQty +" is not a valid number");
        orderForm.elements[qtyName].value=0;
        orderForm.elements[qtyName].select();
        return;
      }
    }
    orderItems[i].qty = iQty;
  }

  //var list = orderForm.shipmethod;
  var ndx = orderForm.shipmethod.selectedIndex;
  var method = ndx; // 0;normal shipping   1:priority
  WM_setCookie("shipmethod",ndx); // save in cookie

  var shipping = calcShipping(totalPins, totalBooks, method);

  checktax();
  //alert(orderSubTotal);
  var total = orderSubTotal + parseFloat(orderForm.tax.value) + shipping;
  //alert(total);
  orderForm.totalprice.value = formatAmount(total);
  orderForm.totalprice.defaultValue = formatAmount(total);
}


////////////////////////////////////////////////////////////
// read new quantities entered by user and encode the cookie
////////////////////////////////////////////////////////////
function readQtys()
{
  for (var i = 0; i < orderItems.length; i++)
  {
    var qtyName = "qty"+(i+1); // name of the qty field, start at 1
    //var newQty = eval("shoppingForm."+qtyName+".value");
    var newQty = orderForm.elements[qtyName].value;
    var iQty=0;

    if (newQty != "")
    {
      // put new qty in if it's not 0 or blank  '
      iQty = parseInt(newQty);
      if (isNaN(iQty)) {
        alert("Item quantity "+ newQty +" is not a valid number");
        orderForm.elements[qtyName].select();
        return false;
      }
    }
    orderItems[i].qty = iQty;
  }

  bakeCookie(orderItems);
  return true;
}


function keepShopping()
{
  if (readQtys() ) {
   history.back();
  }
}

function redraw()
{
  if (readQtys())
  {
    //location.href="shoppingcart.htm";
    location.reload(true);
  }
}

