// variables
//
var order = new Object();  // object to store order items in
var root  = new Object();  // selection criteria
var on    = true;
var off   = false;
var sale = false;          // turn on/off %off sale
var cntr  = 0;             // items in object
var opts  = 5;             // number of options to allow
var fship = 999.00;        // purchase amount to get free shipping us high dollar amt = no free shipping, coupon will override
var ifship= 999.00;        // purchase amount to get free shipping on international shipping high dollar amt = no free shipping, coupon will override
var shpr  = function (wt) {return 0;} // what to charge for shipping;
var stxt  = "Thanks for your order!"; // shipping text
var spos  = -1;            // shipping position selector
var ttax  = 0;             // percent for taxes, 0 because it is calculated later in code
var ttxt  = "0";           // tax text
var tpos  = -1;            // tax position selector
var tamt=0,tqty=0,twgt=0,wgt=0,thnd=0;  // totals
var discnt = 0;   // Zero default percent discount
var itemdiscount=0;
var wheeldiscount=0;
var n=0;
// coupon end date,
// this date option controls when coupon will expire
var dd="04"; //Coupon end day at midnite
var mm="4"; //Coupon end month
var yy="2009"; //Coupon end year

// Place coupon codes in this array
var coupons= new Array (  // place to put coupon codes
  "abc",                 // 1st coupon 5% off
  "3212009",                 // 2nd coupon 10% off
  "coup3",                 // 3rd coupon 15% off
  "1XU537",                 // 4th coupon Dealer purchase
  "plokij"                  //5th coupon Free shipping
  );

//the array values below correspond to the coupon entries above
var coupdc= new Array (
  0, // inactive
  10, // 10% off
  0, // inactive
  23.778, // dealer purchase discount
  100 // free shipping
  );

var coupval= "(blanket)"; // what user entered as coupon code by the buyer

// parts listing for special purchases
var hubs= new Array ("80","81","82","84","87");
var wheels= new Array ("92","93");
//

// general shopping values for customer purchases
root.hamt = 2.99;     // amount, below which, handling charge applies
root.hnd = 1.50;     //  handling charge for orders less than hamt
root.fshp = 18.90;  // amount to spend to get free shipping
root.shp  = on;    // shipping selection line
root.tax  = on;    // tax selection line
// place for user-specific options
root.xx_can  = ""; // place for PayPal cancel return path
root.xx_cur  = "USD"; // enter default currency code (or null)
root.xx_id   = "chuck@cadtochrome.com"; // PayPal ID
root.xx_img  = ""; // image URL
root.xx_lc   = "US"; // enter default country code (or null)
root.xx_ret  = ""; // place for PayPal return path
root.xx_sty  = ""; // place for PayPal page style
root.xx_xtra = ""; // place for other PayPal commands
//
function checkForm(coupon){
//alert(coupon);
var dPart = new Array ( );
    dPart[0]=mm;
    dPart[1]=dd;
    dPart[2]=yy;
  var TodayDate = new Date(); // get todays date
  var CouponDate = new Date(); //coupon date
  if(dPart.length==3){
  //alert("month " + dPart[0]);
  //alert("day " + dPart[1]);
  //alert("year " + dPart[2]);
  //alert ("dPart length "+ dPart.length);
    var ftrDate = new Date(dPart[2],dPart[0],dPart[1]);
    //if(!isNaN(ftrDate) && ftrDate.getDate()==dPart[1]&& ftrDate.getMonth()==dPart[0]-1 && ftrDate >= todayDate){
    if(ftrDate.getDate()==dPart[1]&& ftrDate.getMonth()==dPart[0] && ftrDate >= TodayDate){
    //if(CouponDate.getDate()==dPart[1]&& CouponDate.getMonth()+1==dPart[0] && CouponDate >= TodayDate){
      return true;
    }
  }
  alert("Sorry, this coupon has expired");
  return false;
}
//
function CalcRoot () {  // re-set position flags
  if (root.shp) spos=0;
  if (root.tax) tpos=0;
  }
//
function ChkCoup () { // check user coupon entry
  var i;
  var isValidCouponDate=checkForm(coupval);
if (isValidCouponDate){
  discnt=0;         // set discount to Zero to start
  for (i=0; i<coupons.length; i++) { // pop up right message
    if (coupval == coupons[i]) {
      discnt = coupdc[i];  // remember the discount amt
      switch (discnt){ // display discount type
        case 0: // expired Coupon
          alert ("Expired coupon number! \n\n" + discnt + "% Discount, in effect.");
          break;
        case 5: // 5% discount
          alert ("Valid coupon number! \n\n" + discnt + "% Discount, in effect.");
          break;
        case 10: // 10% discount
          alert ("Valid coupon number! \n\n" + discnt + "% Discount, in effect.");
          break;
        case 100: // free shipping
          alert ("Valid coupon number! \n\n" + discnt + "% Shipping Discount, Free Shipping in effect.");
          break;
        case 23.778: // Dealer discount
          alert ("Valid coupon number! \n\n" + discnt + "% Discount, Dealer Pricing now in effect.");
          break;
        default: // everything else
          alert ("Valid coupon number! \n\n" + discnt + "% Discount now in effect.");
        }
        return;
      }
    }
  alert ("'" + coupval + "'  is not a valid code!");
  }
}
//
var list= new Array();
//
function clearlist(){
  for (x=0; x<list.length; x++){
    list[x]="";
    itemdiscount=0;
    wheeldiscount=0;
    n=0;
    list.length=0;
    discount=0;
    }
  }
//
function checkorder(id){ // check to see if what was purchased for specal was purchased
  nr=id.substring(2);
  for (var i=0; i<wheels.length; i++) {
    //alert("id " + nr);
    //alert("qty " + document.orderform["qty" + nr].value);
    if(id.substring(2)==wheels[i] && document.orderform["qty" + nr].value >= 4) {// check parts array and order qty
      list[i]=(id.substring(2)+",");
      wheeldiscount=1; // give discount
      }
    }

  for (var i=0; i<hubs.length; i++) {
    //alert("id " + nr);
    //alert("qty " + document.orderform["qty" + nr].value);
    if(id.substring(2)==hubs[i] && document.orderform["qty" + nr].value >= 2) {// check parts array and order qty
      list[i]=(id.substring(2)+",");
      //itemdiscount=1; // give discount
      }
    }

    for (i=0; i<list.length; i++){// checks to see if specials were met
    n=n+i;
    }

    if (list.length >=2){
    //alert("disc " + itemdiscount);
      itemdiscount=1; // give discount
      }

  }
//

function DispTots () {  // display totals on the page
var tmp,d;
  d = document.orderform;
  d.sub.value = Dollar (tamt);
  d.wgt.value = twgt;
  if (root.shp) d.shp.value = Dollar(shpr(twgt));
  tmp = tamt * ttax/100;
  if (root.tax) d.tax.value = Dollar (tmp);
  thnd = 0;                    // assume the worst;
  if (d.hnd) d.hnd.value = "0.00";
  if (tamt*1.0 < root.hamt) {  // calculate handling charge (if any)
      thnd = root.hnd ; //* tamt;        // base handling charge set above
      if (d.hnd) d.hnd.value = Dollar(thnd);
  }
  d.tot.value = Dollar (tamt + shpr (twgt) + tmp + thnd);
}
//
function Dollar (val) {     // force to valid dollar amount
var str,pos,rnd=0;
  if (val < .995) rnd = 1;  // for old Netscape browsers
  str = escape (val*1.0 + 0.005001 + rnd);  // float, round, escape
  pos = str.indexOf (".");  // should be one, but OK if not
  if (pos > 0) str = str.substring (rnd, pos + 3);
  return str;               // return valid string
  }
//

//
function GetOrder (id, des, amt, wgt) {  // get all ordered items

var i,nr,val,qty,pos;
var op = new Array ();    // accumulate options here
  tamt=0,tqty=0,twgt=0;   // zero totals
  nr = id.substring (2);  // get number part of ID
  qty = document.orderform["qty" + nr].value;  // get qty
  if (isNaN (qty)) {      // test entry
    alert ("That is not a valid number!  Try again.");
    return;
  }
  for (i=1; i<=opts; i++) {     // see if any options
    if (document.orderform["op" + i + nr]) {
      val = document.orderform["op" + i + nr].value;  // get option
      op[i] = val;
      pos  = val.indexOf ("+"); // price increment?
      if (pos >= 0) amt = amt + val.substring (pos + 1)*1.0;
      if (sale){    // on sale or not
        pos  = val.indexOf ("%"); // percent change? subtract for %off
          if (pos >= 0) amt = amt - (amt * val.substring (pos + 1)/100.0);
        }
      if (discnt >0 && discnt!=100) { // only if discount and no free shipping
        amt = Dollar (amt - (amt * discnt/100.0));
        }
        //("80","81","82","84","87"); parts on sale if other main purchase is made
      if (wheeldiscount) {
        var item = id.substring(2);
          if (item =="80"){amt=Dollar(amt-2.0); }
        else
          if (item =="81"){amt=Dollar(amt-2.0); }
        else
          if (item =="82"){amt=Dollar(amt-2.0); }
        else
          if (item =="84"){amt=Dollar(amt-2.0); }
        else
          if (item =="87"){amt=Dollar(amt-2.0); }
      }
      if (itemdiscount >0 && id.substring(2)=="94") { // only if discount other items purchased.
        //alert ("discount " + discnt);
        amt = Dollar (amt - 2.50);
        //alert(amt);
        }
    }
    else op[i] = "";
  }
  document.orderform["prc" + nr].value = Dollar (qty * amt);
  document.orderform["toz" + nr].value = qty * wgt;
  if (cntr == 0) order = new Object (); // zap object
  cntr = cntr + 1;               // bump counter so no zap next time
  order[id] = new Object ();     // create new entry
  for (i=1; i<=opts; i++)        // load options
    if (op[i] != "") des = des + ", OP" + i + "=" + op[i];
  order[id].des = des;           // load up values
  order[id].amt = Dollar (amt);
  order[id].qty = qty;

  if (wgt) order[id].wgt = wgt;
    else order[id].wgt = 0;
  for (i in order) {             // calc totals we might use
    qty = order[i].qty*1.0;
    tamt = tamt + order[i].amt * qty;  // total amount
    tqty = tqty + qty;                 // total quantity
    twgt = twgt + order[i].wgt * qty;  // total ounces
  }
  twgt = Math.floor ((twgt + 15.99)/16.0);  // get pounds
  DispTots ();                         // calc totals
}

function SendCart () {  // send the cart to PayPal
var frst = true;  // 1st pass thru items.
var winpar = "width=710,height=390,scrollbars," + "location,resizable,status";
var strn   = "https://www.paypal.com/cgi-bin/webscr?cmd=_cart" +
             "&upload=1" +
             "&business=" + root.xx_id + root.xx_xtra;
var i,j=0,des;
  if (root.xx_cur.length > 0)
    strn = strn + "&currency_code=" + root.xx_cur;
  if (root.xx_lc.length > 0)
    strn = strn + "&lc=" + root.xx_lc;
  if (root.xx_can.length > 0)
    strn = strn + "&cancel_return=" + root.xx_can;
  if (root.xx_ret.length > 0)
    strn = strn + "&return=" + root.xx_ret;
  if (root.xx_sty.length > 0)
    strn = strn + "&page_style=" + root.xx_sty;
  if (root.xx_img.length > 0)
    strn = strn + "&image_url=" + root.xx_img;
  if (tpos > 0) strn = strn + "&tax_cart=" + Dollar (tamt*ttax/100);
  for (i in order) {  // send all valid data
    if (order[i].qty > 0) {
      j = j + 1;
      des = order[i].des;
      if (j == 1) {  // put in descriptions for 1st item
        des = des + ", SHP=" + stxt;
        des = des + ", TAX=" + ttxt;
        strn = strn + "&handling_cart=" + Dollar (thnd);
      }
      strn = strn + "&item_name_"    + j + "=" + escape (des) +
                    "&item_number_"  + j + "=" + i +
                    "&quantity_"     + j + "=" + order[i].qty +
                    "&amount_"       + j + "=" + order[i].amt;
      if (spos >= 0) {  // there is some shipping activity
        if (frst) {     // first time thru
          strn = strn + "&shipping_" + j + "=" + Dollar (shpr(twgt));
        }
        else {        // every other time thru
          //alert("here 2");
          strn = strn + "&shipping_" + j + "=0";
        }
      }
      frst = false;
    }
  }
  if (j > 0) window.open (strn, "paypal", winpar);
}

function SetShp (obj) {  // set shipping on user selection
  shpr = function (wt) {return 0;}  // zap it
  spos = obj.selectedIndex;  // which option selected
  stxt = obj.options[spos].text;
  // set various shipping functions.
  if (spos == 1) shpr = function (wt) {return wt * 5.00;}
  //alert("amount spent < required 18.90");
    if (tamt >= fship || discnt == 100){ // give free shipping on total amt over fship or coupon for free ship
      shpr = function (wt) {return wt * 0.00;}
      //alert("Purchase hit >= 18.90");
      }
  if (spos == 2) shpr = function (wt) {return wt * 13.50;}
    if (tamt >= ifship || discnt == 100){ // give free shipping on total amt over fship or coupon for free ship
    shpr = function (wt) {return wt * 0.00;}
    //alert("Purchase hit >= 27.00");
    }
  if (spos == 3) shpr = function (wt) {return wt * 4.50;}
  if (spos == 4) shpr = function (wt) {return wt * 5.50;}
  DispTots ();
}

function SetTax (obj) {
  tpos = obj.selectedIndex;  // which option selected
  ttxt = obj.options[tpos].text;
  ttax = obj.options[tpos].value*1.0;
  DispTots ();
}
