//MrTitanium version
//cart.js contains code for setting and retrieving cookies,
// and processing lists of items selected
// for shopping cart, name="MrTItems" with list of Qty:Item-Qty:Item etc
// Copyright A Daniel Klarmann 1/27/2002
// added country pulldown code 2/16/2004
// added path to cookie, removed pop-up behavior  8/31/2004
// Changed to use PayPal cart submission 1/12/05
// Added vacation 5/2007
//removed shipping to PayPal, and Grand total  2/29/2008 (leap day)

var AllItemsData = new Array();

var dNow = new Date();
var expires = new Date();
expires.setTime(expires.getTime() + 1000*60*60*24*5); // cookies expire in 5 days
var NumItemsInCart = 0;

var CartSubTotal = 0;
var CartQtyTotal = 0;
var CartState = '';

var StateTaxes = "MO 6.475";// StateCode percent

var strRutileBeads = ' <a href="rutile.htm" target="art4sale" onMouseOver="overlib(\'Read about these Natural Titanium Crystals\');" onMouseOut="nd();">Rutilated Quartz beads</a> ';
var strEarWires = '(Earring length does not include the ear wire drop distance of &frac12;&quot;.)<br />Hypoallergenic Titanium ear hook style, embellishments, and color may vary. Please specify if you desire particular colors.'
var strShipNotice = 'Most items are sent via U.S. Mail<br />You will be emailed the tracking info when I place the shipment.';

// set to a future Date to hide Express, and to display delay message
var OnVacationUntil = new Date("3/30/2008 21:00"); //set to 0 if not on vacation

var bOnVacation = (OnVacationUntil.valueOf() >= dNow.valueOf()); // true if date is in future

//alert(OnVacationUntil.toDateString());
//alert(OnVacationUntil.valueOf > dNow.valueOf());

function TwoDecimals(inStr){
  var s = "";
  s += Math.round(parseFloat(inStr) * 100 ) / 100 ;
  // add trailing zeros as needed
  if (s.indexOf(".") == -1)
    s += ".00";
  else if (s.indexOf(".") == s.length - 2)
    s += "0";
  return s;
}// TwoDecimals()

function stripTags(strIn){ //returns strIn with all html tags removed, and quotes converted to &quot;
  var str = strIn.replace(/<[^>]+>/g,' '); // replace all tags with spaces
  str = str.replace(/"/g,"&quot;");        // remove double quotes
  str = str.replace(/&frac(\d)(\d);/ig,"$1/$2"); // fix &frac's
  return str;
}//stripTags

function setCookie(name, value) {
  document.cookie = name + "=" + escape(value) + "; path=/; expires=" + expires.toGMTString() + ";";
}//setCookie()

function getCookie(Name) {
  var search = Name + "=";
  if (document.cookie.length > 0) { // if there are any cookies
    offset = document.cookie.indexOf(search);
    if (offset != -1) { // if cookie exists
      offset += search.length; // set index of beginning of value
      end = document.cookie.indexOf(";", offset);  // set index of end of cookie value
      if (end == -1)
        end = document.cookie.length;
      return unescape(document.cookie.substring(offset, end));
    } else {
      return '';
    }//endif Name exists
  } else { //no cookie
    return '';
  }//endif any cookies
}//getCookie()


function emptyCart(){//remove all itmes from cart
  document.cookie='MrTItems=;expires=;';
  document.cookie='cart=;expires=;';
}

function addToCart(Qty, Name){
   // read all items into array
   var sAllItems = getCookie("MrTItems");
   var aAllItems;
   if (sAllItems.length > 0){
      aAllItems = sAllItems.split('-');
   } else {
      aAllItems = new Array(); //empty
   }
   if (Qty.length <= 0) return;
   if (parseInt(Qty) <= 0) Qty = 0;
   if (Name.length <= 0) return;

   // change existing instance of item Name
   var offset=0;
   var found = false;
   for (var i = 0; i<aAllItems.length; i++){
     offset = aAllItems[i].indexOf(':'+Name);
     if (offset != -1){ //change qty
       aAllItems[i] = Qty + ':' + Name;
       found = true;
     }
   }
   if (! found) {   // add new item
      aAllItems[aAllItems.length] = Qty + ':' + Name;
      NumItemsInCart++;
   }

   //assemble items
   sAllItems = '';
   var iCount = 0;
   for (var i = 0; i < aAllItems.length; i++){
     if (aAllItems[i].substring(0, aAllItems[i].indexOf(':') ) != '0'){ // only keep if not a zero qty
       if (iCount > 0)
         sAllItems += '-';

       sAllItems += aAllItems[i];
       iCount++;
     }
   }

   // write to cookie
   setCookie('MrTItems', sAllItems);
}//addToCart

function addOneToCart(Name){
  addToCart(1, Name);
  window.location="/cart.cgi"; // jump to shopping cart
}//addOneToCart()

function updateCartItem(Qty, Code){
  addToCart(Qty, Code);
  if (getCookie("MrTItems").length <= 2){
    emptyCart();
  }
  window.location.reload();
}

function setState(strState){
  CartState = strState;
}//setState()

function getState(){
  return CartState;
}//getState()

function newStateTotals(orderForm){
  setState(orderForm.state.value);
  if (orderForm.tax){
    orderForm.tax.value = TaxCost(CartState);
  }

  orderForm.grandtotal.value = TwoDecimals(CartSubTotal + TaxCost(CartState));
}//newStateTotals

function getItemDesc(Code){  // description
   for (var i = 0; i<AllItemsData.length; i++){
      if (AllItemsData[i].Code.toLowerCase() == Code.toLowerCase()){
         return AllItemsData[i].Name;
      }
   }
   return "invalid code: " + Code;
}//getItemDesc();
function GetItemCost(Code){
   for (var i = 0; i<AllItemsData.length; i++){
      if (AllItemsData[i].Code == Code){
         return AllItemsData[i].Price;
      }
   }
   return 0;
}//GetItemCost()
function isUnique(Code){ // returns true unless specCodes contains 'qty'
   for (var i = 0; i<AllItemsData.length; i++){
      if (AllItemsData[i].Code == Code){
         if (AllItemsData[i].specCodes.length > 0){ // extra codes
            if (AllItemsData[i].specCodes.indexOf('qty') >= 0){
               return false;
            }
         }
      }
   }
   return true;
} //isUnique

function stripOptionsFromCode(strCode){ // removes stuff delimited by "."
   var a = strCode.split(".");
   return a[0];
}

function FillCheckoutRows(bFinal){

   var sAllItems = getCookie("MrTItems");
   var re = /Express/;
   var bHaveExpress = re.test(sAllItems);

   if (sAllItems.length >0){
      var aAllItems = sAllItems.split('-');
   } else {
      var aAllItems = new Array(); //empty
   }
   with (document){
   write('<form name="cart"><center>');

   write('<table align="center" border="0" cellspacing="0" cellpadding="3">');
   // itemcode, description, qty, each, total
   write('<tr><td>Code</td><td>Description</td><td class="right">Qty</td><td align="right">Each</td><td align="right">Total</td></tr>');

   for (var i=0; i<aAllItems.length; i++){
     var colon = aAllItems[i].indexOf(':');
     var Qty = aAllItems[i].substring(0,colon);
     var Code = aAllItems[i].substring(colon+1);


     write('<tr><td valign="top">',Code,'</td>');
     // description and picture field
     writeln('<td width="400" valign="top" class="left"><a href="ShowItems.cgi?',Code,'"><img src="jewelry/A4S',stripOptionsFromCode(Code),'.jpg" height="40" align="right" /></a>', stripTags(getItemDesc(Code)));

     // qty field
     if ( bFinal || isUnique(Code)){
       write('</td><td align="right" valign="top"> ', Qty);
     } else { // not final or unique item, allow qty change
       write('</td><td align="right" valign="top"><input class="right" type="text" size="2" value="' + Qty +'"');
       write(' name="Qty' + i + '"');
       write(' onChange="updateCartItem(this.value,\'' + Code + "');\" \\>" );
     }

     writeln('</td><td class="right" valign="top">'+TwoDecimals(GetItemCost(Code)));
     writeln('</td><td class="right" valign="top">' + TwoDecimals(parseFloat(GetItemCost(Code)) * parseInt(Qty)));
     if ( ! bFinal ){
       writeln('</td><td valign="top"><a href="javascript:updateCartItem(\'0\',\'', Code, '\');"> remove from cart </a>');
     }//endif final
     writeln('</td></tr>');

     CartSubTotal += parseFloat(GetItemCost(Code)) * parseInt(Qty);
     CartQtyTotal += parseInt(Qty);
  }// for all items

  writeln('<tr><td colspan="2" class="right">');
  
  if ( (! bOnVacation) && (! bHaveExpress)) {
     writeln('<a href="javascript:addOneToCart(\'Express\');" onMouseOver="overlib(getItemDesc(\'Express\'));" onMouseOut="nd();">Add Express Shipping and Handling for $15</a>&nbsp; &nbsp; ');
  }

  writeln('Sub Totals:</td>');

  write('<td class="right">'+CartQtyTotal+'</td><td>&nbsp;</td><td class="right">'+TwoDecimals(CartSubTotal));
  writeln('</td></tr>');

  // shipping, tax and total

//    var taxValue = TaxCost(CartState);
//    write('<tr>');
//    write('<td class="right" colspan="4">Tax (MO):</td><td class="right"><input class="right" type="text" name="tax" size="7" value="0.00" readonly onChange="newStateTotals(order);" />' );
//    write('</td></tr>');

  write('<tr>');
  write('<td class="right" colspan="4">');
  writeln('<a class="cart" href="javascript:void(0);" onMouseOver="overlib(strShipNotice,CENTER);" onMouseOut="nd();">Shipping &amp; Handling</a> ');
  writeln('U.S. incl. Military Bases<br>International');	
  write('</td><td class="right">$5.00<br>$15.00');
  if (! bFinal) {
    write('</td><td>Shipping Cost<br>is Added<br>at PayPal');
  } else {
    write('</td><td>Please Add<br>Appropriate<br>Shipping Amt<br>to Total on check');
  }
  write('</td></tr>');
  
  write('</table>');

  write('</form>');// cart
  focus();

  if (bOnVacation){
    write('<table border=2 cellpadding=5 cellspacing=0><tr><td bgcolor="#602000"><font>I\'m out of the shop until <b>' + OnVacationUntil.toDateString() + '</b><br>Please go ahead and check out<br>Your order <i>will</i> be shipped as soon as I get back</font></td></tr></table>\n');
  }

  } // endwith (document)

  if (parseInt(CartQtyTotal) == 0) {
    emptyCart();
  }
}//fillCheckoutRows


function writePayPalCartItems(){ //12/2/2005

   var sAllItems = getCookie("MrTItems");
   var i;
   if (sAllItems.length >0){
      var aAllItems = sAllItems.split('-');
   } else {
      var aAllItems = new Array(); //empty
   }

   with (document){

     for (i=0; i<aAllItems.length; i++){
        var colon = aAllItems[i].indexOf(':');
        var Qty = aAllItems[i].substring(0,colon);
        var Code = aAllItems[i].substring(colon+1);

        var Desc = stripTags(getItemDesc(Code)).replace(/&quot;/g,""); //remove quotes to avoid js error at PayPal
        var aWords = Desc.split(" ");

        // limit to 125 characters
        var shortDesc = Desc.substr(0,125);
        if (shortDesc.length == 125){
           var sp = shortDesc.lastIndexOf(' '); //last space
           shortDesc = shortDesc.substr(0,sp - 1) + '...';
        }
		  write('<input type="hidden" name="item_name_',i+1,'" value="',shortDesc,'">');
        write('<input type="hidden" name="item_number_',i+1,'" value="',Code,'">');
        write('<input type="hidden" name="amount_',i+1,'" value="',parseFloat(GetItemCost(Code)),'">');
        write('<input type="hidden" name="quantity_',i+1,'" value="',Qty,'">');
		  
		  //if (i==0) { // add total shipping to first item on list, zero all others
			//write('<input type="hidden" name="shipping_',i,'" value="',ShipCost(),'">');
		  //} else {
			//write('<input type="hidden" name="shipping_',i,'" value="0">');
		  //}
     }// for all items
     
   } //endwith document
} //writePayPalCartItems

function writeBuyButtons(){ //adk 1/4/2003 last modified 12/1/2005 23:35
  with (document){

// <!-- Begin PayPal Logo -->
//   writeln('<form action="showpost.cgi" method="post" />');
   writeln('<form action="https://www.paypal.com/cgi-bin/webscr" method="post" name="PayPalCheckout" />');
   writeln('<input type="hidden" name="cmd" value="_cart">');
   writeln('<input type="hidden" name="upload" value="1">');
   writeln('<input type="hidden" name="business" value="Dan@MrTitanium.com" />');
   writeln('<input type="hidden" name="custom" value="',getCookie('MrTItems'),'" />');

   writePayPalCartItems();

   writeln('<input type="hidden" name="return" value="http://mrtitanium.com/thx.html" />');
   writeln('<input type="hidden" name="cancel_return" value="http://mrtitanium.com/cart.cgi" />');
   writeln('&gt;&gt;&gt; <input type="image" align="center" src="http://images.paypal.com/images/x-click-but26.gif" border="1" name="submit" alt="Make payments with PayPal - it\'s fast, free and secure!" /> &lt;&lt;&lt;');
   writeln('</form>');
// <!-- End PayPal Logo -->

   writeln('Click above for PayPal checkout.<br>');
   writeln('Use a <b>Credit Card</b> or even your <b>Checking Account</b> securely through PayPal!<br>');
   write('<a href="JavaScript:document.forms.PayPalCheckout.submit();" onMouseOver="overlib(\'Click above for PayPal checkout<br>Use a <b>Credit Card</b> or even your <b>Checking Account</b> securely through PayPal!\',CENTER,OFFSETY,20);" onMouseOut="nd();">');
   writeln('<img src="images/check.gif" border="0" width="60" height="25" hspace="5" /><img src="images/ccard.gif" border="0" width="150" height="26" />');
   writeln('</a><br><br>');
   writeln('<a href="checkout.htm"> Click here for the Mail-in Money order checkout form</a>');

  }//endwith
}//writeBuyButtons()

function CartTotal(){ // returns CartSubTotal value, and sets CartQtyTotal
   var sAllItems = getCookie("MrTItems");
   if (sAllItems.length >0){
      var aAllItems = sAllItems.split('-');
   } else {
      var aAllItems = new Array(); //empty
   }
   CartSubTotal = 0;
   CartQtyTotal = 0;
   for (var i=0; i<aAllItems.length; i++){
     var colon = aAllItems[i].indexOf(':');
     var Qty = aAllItems[i].substring(0,colon);
     var Code = aAllItems[i].substring(colon+1);
     CartSubTotal += parseFloat(GetItemCost(Code)) * parseInt(Qty);
     CartQtyTotal += parseInt(Qty);
   }

   return CartSubTotal;
} //cartTotal

function TaxCost(strState){ // Assumes valid CartSubTotal
  var findState = -1;
  var taxRate = 0;// NEED correct tax rates in var StateTaxes (in items.js)
  if (typeof (strState) != 'string'){
    return 0;
  } else if (strState.length <=0){
    return 0;
  } else {
    findState = StateTaxes.indexOf(strState.toUpperCase());
    if (findState > -1){
        taxRate = parseFloat(StateTaxes.substring(findState + 3, 8)) / 100; // convert to %
    }
  }
  return TwoDecimals(CartSubTotal * taxRate);
}//TaxCost()

function showCartValue(){
   with (document){
		var cartCookie = getCookie('cart');
		if (cartCookie != ''){
        writeln('Cart Contains<br>', cartCookie);
      } else {
        writeln('Cart is Empty');
      }
      writeln('<br /><a class="cart" href="cart.cgi" target="_top">View Cart');
      writeln('<img src="images/cart1.gif" border="0" align="middle" width="19" height="16" alt="cart"></a>');
   } //endwith
} //showCartValue

/// *** Begin Items specific Code
var AllItemsData = new Array();

// structure to keep data together
function ItemData(){//Code, Name, Size, Price, [specCodes]
  this.Code = ItemData.arguments[0];
  this.Name = ItemData.arguments[1];
  this.Size = ItemData.arguments[2];
  this.Price = ItemData.arguments[3];
  this.specCodes = '';
  if (arguments.length > 4){
    this.specCodes = ItemData.arguments[4];
  }
}

/// *** End Items specific code

window.name='art4sale';


