var blk1  = "https://www.paypal.com/cgi-bin/webscr?cmd=_cart";
var blk1a = "&add=1";
var blk1d = "&display=1";
var blk1u = "&upload=1";
var blk2  = "&business=dapperdiapers%40cox.net";
var blk2a = "&quantity=";
var blk2q = 0;
var blk3  = "&item_name=";
var blk3n = "";
var bcode = "";
var blkcc = "&currency_code=USD";
var op1n  = "";  // option name and value
var op1v  = "";
var op2n  = "";
var op2v  = "";
var blk4  = "&amount=";
var blk4a = "15.00";
var winpar = "width=610,height=390,scrollbars," +
             "location,resizable,status";
var winpar2 = "width=780,height=500,scrollbars," +
             "location,resizable,status";
			 
  var blk6  = "&return=http://www.dapperdiapers.net/thanks.html";
  var blk7  = "&cn=Gift+Enclosure";
  var blk8  = "&no_note=0";
  var blk9 = "&image_url=http://www.dapperdiapers.net/images/paypal_logo.gif";
  

var cmax = 10;      // max items in cart
var stax = 0;       // regional (state) tax percent
var ttax = 0;       // total tax for page
var hand;
var ship;
var tqty;           // the total quantity of item ordered
var qtyd;           // amount of the discount
var cook;           // place to put cart cookies
var root;           // place to put root cookie
var tprc;           // total price of cart
var gtot;           // order grand total

var dqty = new Array ();  // item discount qty breakpoint
var damt = new Array ();  // percent discount
var dn   = 0;             // number of discount brkpts

var hqty = new Array ();  // cart handling qty breakpoints
var hamt = new Array ();  // amount charged
var hn   = 0;             // number of handling brkpts

var sqty = new Array ();  // cart shipping qty breakpoints
var samt = new Array ();  // amount charged
var sn   = 0;             // number of shipping brkpts
var shpm = 1;             // shipping multiplier
var stxt = "";            // text for shipping chgs

var qval = new Array ();  // cart QD breakpoints
var qamt = new Array ();  // amount of discount
var qd   = 0;             // number of qty breakpoints

var coup = -1;            // cart discount coupon not active
var cdis = 0;             // amount of coupon discount
var coupval = "";         // coupon value user entered
var coupons = new Array ();
coupons[0] = "coup1";
coupons[1] = "coup2";

// minimum order code
function minOrder () {
if (tqty < 2) 
    alert ("Please select another choice to complete the 2-pack minimum.");
    return;
  }

function AddDesc (strn) {  // add to current description
var c = "";
  if (blk3n.length > 0) c = ", ";
  blk3n = blk3n + escape (c + strn);
}

function AddOpt1 (val) {  // add to the value in op1v
var c = "";
  if (op1n.length == 0) op1n = "opt1";
  if (op1v.length > 0) c = ", ";
  op1v = op1v + escape (c + val);
}

function AddOpt2 (val) {  // add to the value in op2v
var c = "";
  if (op2n.length == 0) op2n = "opt2";
  if (op2v.length > 0) c = ", ";
  op2v = op2v + escape (c + val);
}

function AddPrcnt (strn) {    // add a percent to the price
  SetPrice (blk4a * (1.0 + strn/100.0));  // add the percent
}

function AddPrice (strn) {  // add to current price
  blk4a = Dollar (blk4a*1.0 + strn*1.0);
}

function CallPay () { // call the PayPal shopping cart
var strn;
if (tqty < 2) {
    alert ("Please continue shopping and select another choice to complete the 2-pack minimum.");
	return;}
   	else 
	strn = blk1 + blk1u + blk2 + blkcc + blk6 + blk7 + blk8 + blk9 + Xbild ();
  ClearAll ();
  window.open (strn, "paypal", winpar);
}

function CallView () { // call the local shopping cart view
  window.open ("cart.html", "local9", winpar);
}

function ChkCoup (amt) {  // check for a discount coupon
var i;
  coup = -1;          // assume the worst
  val = coupval.toLowerCase ();
  for (i=0; i<coupons.length; i++) {
    if (val == coupons[i]) {
      coup = 1;       // user hit the coupon value
      cdis = amt;     // remember the discount amt
      root.coup = coup;
      root.cdis = cdis;
      root.store ();
      alert ("\n\nValid coupon number  \n\n");
      return;
    }
  }
  alert ("\n\n'" + val + "'  not a valid code!  \n\n");
}

function ChkFlg (temp) {     // check for special flag char
var pos;
  pos  = temp.indexOf ("@"); // is there a initial value?  
  if (pos > 0) SetPrice (temp.substring (pos + 1));
  pos  = temp.indexOf ("+"); // is there a price adjustment?  
  if (pos > 0) AddPrice (temp.substring (pos + 1));
  pos  = temp.indexOf ("%"); // is there a percent adjustment?  
  if (pos > 0) AddPrcnt (temp.substring (pos + 1));
}

function ClearAll () {  // wipe out the last entry
  blk2q = "";  // quantity
  blk3n = "";  // name
  blk4a = "0"; // price
  bcode = "";  // item number
  op1n  = "";  // clear options
  op1v  = "";
  op2n  = "";
  op2v  = "";
  dn    = 0;
}

function ClearCart () {  // zap all the cookies
var i;
  for (i=1; i<cmax; i++) {  // the data cookies
    ClearEntry (i);
  }
}

function ClearEntry (i) {  // knock out a specific entry
  cook = new Cookie (document, "paycart" + i);
  InitData ();
}

function Cookie(document, name, hours, path, domain, secure) {
  this.$document = document;  // required
  this.$name = name;          // required
  if (hours) this.$expiration = 
      new Date((new Date()).getTime() + hours * 3600000);
  else this.$expiration = null;
  if (path)   this.$path   = path;   else this.$path   = null;
  if (domain) this.$domain = domain; else this.$domain = null;
  if (secure) this.$secure = true;   else this.$secure = false;
}

function _Cookie_store() {  // store method of cookie object
var cookieval = "";  // clear actual cookie value
  for(var prop in this) {  // Ignore "$" properties, and methods
    if ((prop.charAt(0) == '$') || 
        ((typeof this[prop]) == 'function')) 
        continue;
    if (cookieval != "") cookieval += '&';
    cookieval += prop + ':' + escape(this[prop]);
  }

var cookie = this.$name + '=' + cookieval;
  if (this.$expiration)
      cookie += '; expires=' + this.$expiration.toGMTString();
  if (this.$path) cookie += '; path=' + this.$path;
  if (this.$domain) cookie += '; domain=' + this.$domain;
  if (this.$secure) cookie += '; secure';

  this.$document.cookie = cookie;  // store with magic property
}

function _Cookie_load() {  // cookie load function
var i;
var allcookies = this.$document.cookie;
  if (allcookies == "") return false;

  // Now extract just the named cookie from that list.
var start = allcookies.indexOf(this.$name + '=');
  if (start == -1) return false;   // Cookie not defined for this page.
  start += this.$name.length + 1;  // Skip name and equals sign.
var end = allcookies.indexOf(';', start);
  if (end == -1) end = allcookies.length;
var cookieval = allcookies.substring(start, end);

var a = cookieval.split('&');  // array of name/value pairs.
  for(i=0; i < a.length; i++)  // Break each pair into an array.
    a[i] = a[i].split(':');

  for(i=0; i<a.length; i++)
    this[a[i][0]] = unescape(a[i][1]);

  return true;     // We're done, so return the success code.
}

function _Cookie_remove() {  // the remove method
var cookie;
  cookie = this.$name + '=';
  if (this.$path) cookie += '; path=' + this.$path;
  if (this.$domain) cookie += '; domain=' + this.$domain;
  cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

  this.$document.cookie = cookie;  // magic store
}

function Dollar (val) {  // force to valid dollar amount
var str,pos;
  str = escape (val*1.0 + 0.005001);  // float, round, escape
  pos = str.indexOf (".");            // should be one
  if (pos > 0) str = str.substring (0, pos + 3);
  return str;
}

function InitData () {  // zap a data cookie
  cook.qty = 0;
  cook.cod = "";
  cook.des = "";
  cook.op1n = "";  // option name and value
  cook.op1v = "";
  cook.op2n = "";
  cook.op2v = "";
  cook.prc = 0;
  cook.lbs = 0;
  cook.ozs = 0;
  cook.store();    // stash it off
}

function InitRoot () {  // zap the root cookie
  root.stax = stax;
  root.coup = coup;
  root.cdis = cdis;
  root.sn   = sn;
  root.sqty = sqty;
  root.samt = samt;
  root.shpm = shpm;
  root.stxt = stxt;
  root.hn   = hn;
  root.hqty = hqty;
  root.hamt = hamt;
  root.qd   = qd;
  root.qval = qval;
  root.qamt = qamt;
  root.store();
}

function PrintCart () {  // print out entire cart
var i;
  tprc = 0;             // total price of cart
  gtot = 0;             // Grand total
  ttax = 0;             // total cart tax
  tqty = 0;             // total qty of items

  ReadRoot ();          // make sure we have root
  for (i=1; i<cmax; i++) {  // print all entries
    cook = new Cookie (document, "paycart" + i);
    cook.load();
    if (cook.qty > 0) {
      PrintItem (i);
    }
  }

  tprc = Dollar (tprc);
  ttax = Dollar (tprc * stax/100.0);

  hand = 0;                        // cart-wide handling?
  for (i=hn-1; i>=0; i--) {        // run the table (if one)
    if (tqty >= hqty[i]*1.0) {     // Check the price
      hand = hamt[i];              // yep, set it
      break;                       // a-dios, mo-fo
    }
  }

  ship = 0;                        // cart-wide shipping?
  for (i=sn-1; i>=0; i--) {        // run the table (if one)
    if (tqty >= sqty[i]*1.0) {     // Check the price
      ship = samt[i];              // yep, set it
      break;                       // a-dios, mo-fo
    }
  }

  qtyd = 0;                        // cart-wide qty discount
  for (i=qd-1; i>=0; i--) {
    if (tqty >= qval[i]*1.0) {
      qtyd = qamt[i];
      break;
    }
  }

  gtot = Dollar (tprc*1.0 + hand*1.0 +
                 ship*1.0 + ttax*1.0 - qtyd*1.0);
}

function PrintItem (i) {  // make one entry in cart
var wt,lb,oz,tm;
  document.writeln ('<tr bgcolor="#FFFFFF"');
  document.writeln ('    align = "center">');
  document.writeln ('  <td>');
  document.writeln ('    <input type  = "checkbox" ');
  document.writeln ('           value = "BOX1"');
  document.writeln ('           onclick = "ClearEntry (',
    i, ');');
  document.writeln ('                      location.reload ();" />');
  document.writeln ('  </td>');
  document.writeln ('  <td align = "center"><font size="2" face="Arial, Helvetica, sans-serif">',
    cook.qty,'</font></td>');
  document.writeln ('  <td align = "center"><font size="2" face="Arial, Helvetica, sans-serif">',
    cook.cod,'</font></td>');
  document.writeln ('  <td align = "left"><font size="2" face="Arial, Helvetica, sans-serif">',
    unescape (cook.op1v + ' ' +
              cook.op2n + ' ' +
              cook.op2v),'</font></td>');
  tm = Dollar (cook.prc);
  document.writeln ('  <td align = "right"><font size="2" face="Arial, Helvetica, sans-serif">',
    tm,'</font></td>');
  tm = Dollar (cook.qty*cook.prc);
  tprc = tprc*1.0 + tm*1.0;
  tqty = tqty + cook.qty*1.0;
  document.writeln ('  <td align = "center"><font size="2" face="Arial, Helvetica, sans-serif">',
    tm,'</font></td>');
  document.writeln ('</tr>');
}


function PrintItem2 (i) {  // make one entry in cart
var wt,lb,oz,tm;
  document.writeln ('<tr valign = "top"');
  document.writeln ('    align = "right">');
  document.writeln ('  <td>');
  document.writeln ('    <input type  = "checkbox" ');
  document.writeln ('           value = "BOX1"');
  document.writeln ('           onclick = "ClearEntry (',
    i, ');');
  document.writeln ('                      location.reload ();" />');
  document.writeln ('  </td>');
  document.writeln ('  <td align = "right">',
    cook.qty,'</td>');
  document.writeln ('  <td align = "left">',
    cook.cod,'</td>');
  document.writeln ('  <td align = "left">',
    unescape (cook.op1v + ' ' +
              cook.op2n + ' ' +
              cook.op2v),'</td>');
  tm = Dollar (cook.prc);
  document.writeln ('  <td>',
    tm,'</td>');
  tm = Dollar (cook.qty*cook.prc);
  tprc = tprc*1.0 + tm*1.0;
  tqty = tqty + cook.qty*1.0;
  document.writeln ('  <td>',
    tm,'</td>');
  document.writeln ('</tr>');
}

function ReadForm (obj1) { //get form data for PayPal
var i,j,obj,temp,pos,val,nam3,nam4;
var qty  = 0;              // default value
var dis  = 0;              // quantity discount
  for (i=0; i<obj1.length; i++) {     // run whole form
    obj = obj1.elements[i];           // ref particular element
    nam3 = obj.name.substring (0, 3); // 3-char name (maybe)
    nam4 = obj.name.substring (3, 4); // where to store it
    if (obj.type == "select-one") {   // dropdowns
      pos = obj.selectedIndex;        // which option selected
      val = obj.options[pos].value;   // get selection
      ChkFlg (val);                   // check for flag char
      if (nam3 == "opt") {            // user says where to store
        Where (val, nam4);            // stash it
      } else {
        AddDesc (val);                // add to data
      }
    } else
    if (obj.type == "select-multiple") {     // one or more
      for (j=0; j<obj.options.length; j++) { // run all options
        if (obj.options[j].selected) {
          val = obj.options[j].value;
          ChkFlg (val);                   // flag chars?
          if (nam3 == "opt") {            // user says where to store
            Where (val, nam4);            // stash it
          } else {
            AddDesc (val);                // add to data
          }
        }
      }
    } else
    if (obj.type == "checkbox" ||    // boxes
        obj.type == "radio") {
      if (obj.checked) {             // was selected
        val = obj.value;
        ChkFlg (val);                // flag chars?
        if (nam3 == "opt") {         // user says where to store
          Where (val, nam4);         // stash it
        } else {
          AddDesc (val);             // add to data
        }
      }
    } else
    if (obj.type == "text") {  // user input fields
      val = obj.value;         // get input
      if (qty == 0) {          // this is 1st time
        qty = val;             // get user input
        if (qty == "" || qty < 1 || isNaN (qty)) {  // test
          alert ("\n\n  Enter a valid integer quantity!  \n\n");
          return;
        }
      } else {
        if (nam3 == "opt") { // user says where to store
          Where (val, nam4); // stash it
        } else {
          AddDesc (val);     // add to data
        }
      }
    }
  }
  if (qty == 0) qty = 1;     // make sure we have something
  blk2q = qty;               // record for posterity

  dis = 0;                   // any qty discounts?
  for (i=dn-1; i>=0; i--) {  // run backwards
    if (qty >= dqty[i]) {    // qty brkpt
      dis = damt[i];         // set qty amount
      break;                 // get out, now
    }
  }
  if (coup > 0) {            // any valid coupons?
    dis = dis*1.0 + cdis*1.0;
    AddDesc ("COUP");        // mark it
  }
  if (dis > 0) {             // there is an item discount, here
    AddPrcnt (-dis);         // apply the discount
    AddDesc ("QTY=" + qty + ", DIS=" + dis + "%.");  // mark it
  }
  StoreCart ();
}

function SetCartHN (q1, c1) {  // set cart hand breakpoints
var i;
  hn = 0;                      // count of breakpoints
  for (i=0; i<arguments.length; i=i+2) {
    hqty[hn] = arguments[i];   // price breakpoint
    hamt[hn] = arguments[i+1]; // discount amount
    hn = hn + 1;               // number of bkpts
  }
  root.hn = hn;                // stash that bad boy off
  root.hqty = hqty;
  root.hamt = hamt;
  root.store();                // remember forever...
}

function SetCartQD (q1, c1) {  // set cart qty dis breakpoints
var i;
  qd = 0;                      // count of breakpoints
  for (i=0; i<arguments.length; i=i+2) {
    qval[qd] = arguments[i];   // price breakpoint
    qamt[qd] = arguments[i+1]; // discount amount
    qd = qd + 1;               // number of bkpts
  }
  root.qd = qd;                // stash that bad boy off
  root.qval = qval;
  root.qamt = qamt;
  root.store();                // remember forever...
}

function SetCartSH (q1, c1) {  // set cart shp qty breakpoints
var i;
  sn = 0;                      // count of breakpoints
  for (i=0; i<arguments.length; i=i+2) {
    sqty[sn] = arguments[i];   // price breakpoint
    samt[sn] = arguments[i+1]; // handling charge
    sn = sn + 1;               // number of bkpts
  }
  root.sn = sn;                // stash that bad boy off
  root.sqty = sqty;
  root.samt = samt;
  root.store();                // remember forever...
}

function SetCartTX (obj1) {    // set cart tax value
var i,pos;
  pos  = obj1.selectedIndex;   // which item selected
  stax = obj1.options[pos].value;
  root.stax = stax;
  root.store();                // remember forever...
}

function SetCode (cd) { // set product code
  bcode = escape (cd);
}

function SetDesc (strn) {  // set the desc field
  blk3n = escape (strn);
}

function SetOpt1 (nam, val) {  // set the value of 1st option
  op1n = escape (nam);
  op1v = escape (val);
}

function SetOpt2 (nam, val) {  // set the value of 2nd option
  op2n = escape (nam);
  op2v = escape (val);
}

function SetPrice (strn) {  // set the current price
  blk4a = 0;
  AddPrice (strn);
}

function SetQtyD (q1, d1) {    // set item qty discount breakpoints
var i;
  dn = 0;                      // count of breakpoints
  for (i=0; i<arguments.length; i=i+2) {
    dqty[dn] = arguments[i];   // quantity
    damt[dn] = arguments[i+1]; // percent
    dn = dn + 1;               // number of discount bkpts
  }
}

function SetSM (obj1) {  // set the shipping multiplier
var pos;
  pos  = obj1.selectedIndex;           // selection
  shpm = obj1.options[pos].value*1.0;  // float it
  stxt = obj1.options[pos].text;       // text value
  root.shpm = shpm;                    // stash that bad boy off
  root.stxt = stxt;
  root.store();                // remember forever...
}

function StoreCart () {  // store data in local cart
var i;
  for (i=1; i<cmax; i++) {      //check for dup entry
    cook = new Cookie (document, "paycart" + i);  // run
    cook.load();                // get values
    if (cook.qty*1.0 > 0) {     // check it out - combine dups
      if (cook.cod == bcode &&  // check everything!!!
          cook.des == blk3n &&
          cook.prc*1.0 == blk4a*1.0 &&
          cook.op1n == op1n &&
          cook.op1v == op1v &&
          cook.op2n == op2n &&
          cook.op2v == op2v) {
        cook.qty = cook.qty*1.0 + blk2q*1.0;  // combine
        cook.store();
        ClearAll ();
        return;                 // th-th-thats all, folks
      }
    }
  }
  for (i=1; i<cmax; i++) {  // find empty entry
    cook = new Cookie (document, "paycart" + i);
    cook.load();
    if (cook.qty*1.0 == 0 ||
        isNaN (cook.qty)) {
      cook.qty = blk2q;
      cook.cod = bcode;
      cook.des = blk3n;
      cook.op1n = op1n;
      cook.op1v = op1v;
      cook.op2n = op2n;
      cook.op2v = op2v;
      cook.prc = blk4a;
      cook.store();
      ClearAll ();
      if (i == cmax - 1)
        alert ("\n\n Warning - that was your last cookie! \n\n");
      return;      
    }
  }
  alert ("\n\n  Error 1 - out of cookies! \n\n");
}

function Where (val, loc) {  // store val at opt[loc]
  if (loc == 1) AddOpt1 (val);
  else          AddOpt2 (val);
}

function Xbild () {  // build the PayPal string
var i,j;
var tot = 0;   // price total
var frst = 1;  // first loop flag
var str = "";  // string to PayPal
var disc = 0;  // price per item to subtract for discount
  if (qtyd*1.0 > 0) {  //Set to apply qty discounts
    disc = qtyd/tqty;  // discount per item
  }

  j = 0;       // starting suffix
  for (i=1; i<cmax; i++) {  // run all the data cookies
    cook = new Cookie (document, "paycart" + i);
    cook.load();         // get contents
    if (cook.qty > 0) {  // something here
      j = j + 1;         // bump suffix
      str = str + "&quantity_"    + j + "=" + cook.qty;
      str = str + "&item_name_"   + j + "=" + cook.des;
      str = str + "&amount_"      + j + "=" + 
                   Dollar (cook.prc*1.0 - disc);
      if (cook.op1n.length > 0) {    // 1st option present
        str = str + "&on0_"       + j + "=" + cook.op1n;
        str = str + "&os0_"       + j + "=" + cook.op1v;
      }
      if (cook.op2n.length > 0) {    // 2nd option present
        str = str + "&on1_"       + j + "=" + cook.op2n;
        str = str + "&os1_"       + j + "=" + cook.op2v;
      }
      if (cook.cod != "")
        str = str + "&item_number_" + j + "=" + cook.cod;
      if (frst > 0 &&
          (hand*1.0 + ttax*1.0 > 0)) {
        str = str + "&handling_"  + j + "=" + 
          Dollar (hand*1.0 + ttax*1.0);
      }
      if (ship*1.0 > 0) {
        str = str + "&shipping_"  + j + "=" + 
          Dollar (ship * shpm);
      }
      frst = 0;  // reset flag
    }    
  }
  return str;
}

function ReadRoot () {
  root = new Cookie (document, "paycart0");  // special root cookie
  if (!root.load () ||
      !root.coup) {
    InitRoot ();                  // gotta create it
  } else {                        // load up globals
    stax = root.stax;
    coup = root.coup;
    cdis = root.cdis;
    sn   = root.sn;
    sqty = root.sqty.split(",");
    samt = root.samt.split(",");
    shpm = root.shpm;
    stxt = root.stxt;
    hn   = root.hn;
    hqty = root.hqty.split(",");
    hamt = root.hamt.split(",");
    qd   = root.qd;
    qval = root.qval.split(",");
    qamt = root.qamt.split(",");
  }
}


// executed at load time.
new Cookie ();  // create, release (backward compatibility)
Cookie.prototype.store  = _Cookie_store;   // load proto methods
Cookie.prototype.load   = _Cookie_load;
Cookie.prototype.remove = _Cookie_remove;

ReadRoot ();
for (var i=1; i<cmax; i++) {  // load or init data cookies
  cook = new Cookie (document, "paycart" + i);
  if (!cook.load () ||
      !cook.des) {
    InitData ();              // create it
  }
}

