var blk1  = "https://www.paypal.com/cgi-bin/webscr?cmd=_cart";
var blk1a = "&add=1";
var blk1d = "&display=1";
var blk2  = "&business=sales@playwrites.com";
var blk2a = "&quantity=";
var blk2q = "";
var blk3  = "&item_name=";
var blk3n = "Test";
var blk4  = "&amount=";
var blk4a = "6.66";
var bcode = "";  // item number
var btax  = "";  // tax override
var bshp  = "1.25";  // shipping override
var bshp2 = "";  // shipping2 override
var bmisc = "";  // misc data
var blkcc = "&currency_code=USD";
var op1n  = "";  // option name and value
var op1v  = "";
var op2n  = "";
var op2v  = "";
var winpar = "width=600,height=400,scrollbars," +
             "location,resizable,status";

var aqty = new Array ();  // quantity amount breakpoint
var aamt = new Array ();  // amount to charge
var an   = 0;             // number of discount brkpts

var dqty = new Array ();  // quantity discount breakpoint
var damt = new Array ();  // percent discount
var dn   = 0;             // number of discount brkpts

var sqty = new Array ();  // shipping breakpoints
var samt = new Array ();  // amount charged
var sn   = 0;             // number of ship brkpts
var shpm = 1;             // shipping multiplier
var stxt = "";            // text for shipping mult

var hqty = new Array ();  // handling breakpoints
var hamt = new Array ();  // amount charged
var hn   = 0;             // number hand bkpts

var coup = false;         // discount coupon not active
var cdis = 0;             // amount of coupon discount
var cval = "";            // coupon value user entered
var coupons = new Array ();
coupons[0] = "coup1";
coupons[1] = "coup2";

var taxp = 0;             // tax percent for site
var crdc = 0;             // site-wide discount percent

function AddDesc (strn) { // add to current description
var c = "";
  if (blk3n.length > 0) c = ",+";
  blk3n = blk3n + escape (c + Coder (strn));
}

function AddMisc (strn) { // add extra stuff to PayPal params
var s = "&";
  if (strn.substring(0,1) == "&") s = "";
  bmisc = bmisc + s + Coder (strn);
}

function AddOpt1 (val) {  // add to the value in op1v
var c = "";
  if (op1n.length == 0) op1n = "opt1";
  if (op1v.length > 5) c = ",+";
  op1v = op1v + escape (c + Coder (val));
}

function AddOpt2 (val) {  // add to the value in op2v
var c = "";
  if (op1n.length == 0) {  // fill 1st field 1st
    alert ("\n\n  Error - filling opt1 first!  \n\n");
    AddOpt1 (val);
    return;
  }
  if (op2n.length == 0) op2n = "opt2";
  if (op2v.length > 5) c = ",+";
  op2v = op2v + escape (c + Coder (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;             // where to build the PayPal string
  strn = blk1 + blk1a + blk2 + blk2a + blk2q + 
         blk3 + blk3n + blk4 + blk4a + blkcc + bcode +
         op1n + op1v + op2n + op2v +
         btax + bshp + bshp2 + bmisc;
  ClearAll ();        // clear all the data
  if (taxp < 0) {
    alert ("Select applicable tax rate!");
    return;
  }
  window.open (strn, "paypal", winpar);
}

function CallView () { // call the PayPal shopping cart view
  window.open (blk1 + blk1d + blk2, "paypal", winpar);
}

function ChkCoup (amt) {  // check for a discount coupon
var i;
  coup = false;       // assume the worst
  val = cval.toLowerCase ();
  for (i=0; i<coupons.length; i++) {
    if (val == coupons[i]) {
      coup = true;    // user hit the coupon value
      cdis = amt;     // remember the discount amt
      cval = val;
      cook.coup = coup;  // stash it off in the coupon
      cook.cdis = cdis;
      cook.cval = cval;
      cook.store ();
      alert ("\n\n   Valid 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 ChkTaxer () {   // see if we need to input tax rate
var i;
  if (taxp < 0) return;  // yes - leave the select there
  if (document.layers) return;  // NN4.7 won't work, here
  for (i=0; i<document.forms.length; i++) {  // zap, if we can
    if (document.forms[i].taxer) {
      document.forms[i].taxer.style.display = "none";  // die!
    }
  }
}

function ClearAll () {  // wipe out the last entry
  blk2q = "";  // quantity
  blk3n = "";  // name
  blk4a = "";  // price
  bcode = "";  // item number
  op1n  = "";  // clear options
  op1v  = "";
  op2n  = "";
  op2v  = "";
  btax  = "";
  bshp  = "";
  bshp2 = "";
  bmisc = "";
  an    = 0;   // zap item amount discounts
  sn    = 0;   // zap shipping charges
  hn    = 0;   // handling bkpts
  shpm  = 1;   // shipping multiplier
  dn    = 0;   // and item qty discounts
}

function Coder (strn) {     //replace spaces with "+"
var aray = new Array ();    // we need array support stuff
  aray = strn.split (" ");  // delete all spaces
  return aray.join ("+");   // replace with "+"
}

function Cookie(document, name, hours, path, domain, secure) {
/* special cookie prototype functions
 document: The Document object that the cookie is stored for. Required.
 name:     A string that specifies a name for the cookie. Required.
 hours:    An optional number, the number of hours from now
            that the cookie should expire.
 path:     An optional string for the cookie path attribute.
 domain:   An optional string for the cookie domain attribute.
 secure:   An optional Bool, if true, requests a secure cookie.
*/
  this.$document = document;
  this.$name = name;
  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]);

  // We're done, so return the success code.
  return true;
}

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,rnd=0;
  if (val < 1) rnd = 1;
  str = escape (val*1.0 + 0.005001 + rnd);  // float, round, escape
  pos = str.indexOf (".");
  if (pos > 0) str = str.substring (rnd, pos + 3);
  return str;
}

function SetCartDC (val) {  // set site-wide percent discount
  crdc = val;       // the discount percent
  cook.crdc = crdc; // remember in cookie
  cook.store ();
}

function SetCode (cd) { // set product code
  bcode = "&item_number=" + escape (Coder (cd));
}

function SetDesc (strn) {  // set the desc field
  blk3n = escape (Coder (strn));
}

function SetHN (q1, c1) {      // set handling bkpts
var i;
  hn = 0;                      // count of breakpoints
  for (i=0; i<arguments.length; i=i+2) {
    hqty[hn] = arguments[i];   // quantity
    hamt[hn] = arguments[i+1]; // amount
    hn = hn + 1;               // number of handling bkpts
  }
}

function SetOpt1 (nam, val) {  // set the value of 1st option
  op1n = "&on0=" + escape (Coder (nam));
  op1v = "&os0=" + escape (Coder (val));
}

function SetOpt2 (nam, val) {  // set the value of 2nd option
  if (op1n == "") {
    alert ("\n\n  Fill option1 first!  \n\n");
    SetOpt1 (nam, val);
    return;
  }
  op2n = "&on1=" + escape (Coder (nam));
  op2v = "&os1=" + escape (Coder (val));
}

function SetPrice (strn) {  // set the current price
  blk4a = 0;
  AddPrice (strn);
}

function SetQtyA (q1, d1) {    // set qty amount breakpoints
var i;
  an = 0;                      // count of breakpoints
  for (i=0; i<arguments.length; i=i+2) {
    aqty[an] = arguments[i];   // quantity
    aamt[an] = arguments[i+1]; // amount
    an = an + 1;               // number of discount bkpts
  }
}

function SetQtyD (q1, d1) {    // set 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 SetSH (q1, c1) {      // set qty shipping bkpts
var i;
  sn = 0;                      // count of breakpoints
  for (i=0; i<arguments.length; i=i+2) {
    sqty[sn] = arguments[i];   // quantity
    samt[sn] = arguments[i+1]; // amount
    sn = sn + 1;               // number of shipping bkpts
  }
}

function SetShp (val) {
  bshp = "&shipping=" + Dollar (val);
}

function SetShp2 (val) {
  bshp2 = "&shipping2=" + Dollar (val);
}

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
}

function SetTax (val) {  // set the tax override
  btax = "&tax=" + Dollar (val);
}

function SetTX (obj1) {  // Set tax percent for this order
var pos;
  pos  = obj1.selectedIndex;           // which item selected
  taxp = obj1.options[pos].value*1.0;  // float it
  cook.taxp = taxp;
  cook.store ();
}

// site specific code
function ReadForm (obj1) { // get form data for PayPal
var i,j,obj,pos,val,nam3,nam4;
var qty  = 0;              // default value
var dis  = 0;              // quantity discount
var sah  = 0;              // shipping and handling chgs
var acnt = 0;              // textarea count (for storage)
  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
        }
      }
    } else
    if (obj.type == "textarea" &&  // textarea stuff (beware)
        obj.value.length > 0) {
      acnt = acnt + 1;            // areas encountered
      if (acnt > 2) {  // too many areas
        alert ("\n\n  Only 2 textareas may be input!  \n\n");
        return;
      }
      if (acnt == 1) {  // something there, check size
        if (obj.value.length + op1v.length > 200) {
          alert ("\n\n  Too many textarea1 characters!  \n\n");
          return;
        }
        if (op1n.length == 0) {     // nothing in 1st field
          SetOpt1 ("TextArea 1", obj.value);
        } else
          AddOpt1 (obj.value);
      } else
      if (acnt == 2) {
        if (obj.value.length + op2v.length > 200) {
          alert ("\n\n  Too many textarea2 characters!  \n\n");
          return;
        }
        if (op2n.length == 0) {     // nothing in second field
          SetOpt2 ("TextArea 2", obj.value);
        } else
          AddOpt2 (obj.value);
      }
    }
  }

  if (qty < 1 || isNaN(qty) || qty == "") qty = 1;
  blk2q = qty;           // record for posterity
  AddDesc ("QTY=" + qty);

  for (i=an-1; i>=0; i--) {  // set qty-based amount?
    if (qty >= aqty[i]) {
      SetPrice (aamt[i]);    // force price
      AddDesc ("QTYA=" + Dollar (aamt[i]));
      break;
    }
  }

  dis = 0;                   // any qty discounts?
  for (i=dn-1; i>=0; i--) {  // run backwards
    if (qty >= dqty[i]) {    // qty brkpt
      dis = damt[i]*1.0;     // set qty amount
      AddDesc ("QTYD=" + damt[i] + "%");
      break;                 // get out, now
    }
  }
  if (crdc > 0) {            // site-wide discount
    dis = dis*1.0 + crdc*1.0;
    AddDesc ("CART" + crdc + "%");        // mark it
  }
  if (coup) {                // any valid coupons?
    dis = dis*1.0 + cdis*1.0;
    AddDesc ("COUP=" + cdis + "%");        // mark it
  }
  if (dis > 0) {             // something going on
    AddPrcnt (-dis);         // apply the discount
    AddDesc ("DIS=" + dis + "%");  // mark it
  }

  for (i=sn-1; i>=0; i--) {  // shipping charges
    if (qty >= sqty[i]) {    // qty brkpt
      sah = samt[i] * shpm;  // set qty amount
      AddMisc ("shipping=" + Dollar (sah));
      if(shpm != 1) AddDesc (stxt);
      break;                 // get out, now
    }
  }

  for (i=hn-1; i>=0; i--) {  // handling charges
    if (qty >= hqty[i]) {    // qty brkpt
      sah = hamt[i];         // set qty amount
      AddMisc ("handling=" + Dollar (sah));
      break;                 // get out, now
    }
  }

  if (obj1.taxer) {                    // are we setting taxes
    if (taxp >= 0) {                   // only where taxer is
      SetTax (taxp/100.0 * qty * blk4a); // set the tax amount
      ChkTaxer ();
    }
  }
}

function Where (val, loc) {  // store val at opt[loc]
  if (loc < 1 || loc > 2) {
    alert ("\n\nYour name is wrong - storing in OPT1!  \n\n");
    AddOpt1 (val);
    return;
  }
  if (loc == 1) AddOpt1 (val);
  else          AddOpt2 (val);
}

// 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;

var cook = new Cookie (document, "autocart0");  // special root cookie
if (!cook.load () ||
    !cook.taxp) {          // we need to set this sucker
  cook.coup = coup;
  cook.cdis = cdis;
  cook.cval = cval;
  cook.crdc = crdc;
  cook.taxp = taxp;
  cook.store ();
} else {                   // load up globals
  coup = cook.coup;
  cdis = cook.cdis;
  cval = cook.cval;
  crdc = cook.crdc;
  taxp = cook.taxp;
}

