// Comfr.js -- common code, front-side
// Include this after site-specific config.js file and after common.js
// ----------------------------------------------------------------------------
var cycletotal = -1;
var loadtotal = -1;

//onerror = handleerror;
var aProds = new Array();
var aHN = new Array();
var aOptions = new Array();
var aValues = new Array();
var aOP = new Array();
var aCat = new Array();
var aCart = new Array();
var aOpEdit = new Array();
var aChk = new Array();
var aQO = new Array();
var aCalc = new Array();
var aShip = new Array();
var msgup = 0;
var msgresult = "";
var statstr = "";
var usecolortheme = false;
var pagetheme1 = "";
var pagetheme2 = "";
var pagetheme3 = "";
var pagetheme4 = "";
var pagetheme5 = "";
var pagetheme6 = "";

//res = window.clipboardData.setData("Text",x);

var dbg = 0;
var imghead = "<img src='../i/s.gif' height='11' width='";
var imgarrow = "<img src='../i/arrownav.gif'>";
//var symExpanded = "<img src='../i/userminus.gif' border='0' onMouseOver='chgcursor(this,1,-1)'  onMouseOut='chgcursor(this,0,-1)' hspace='0' vspace='0' ";
//var symCollapsed = "<img src='../i/userplus.gif' border='0' onMouseOver='chgcursor(this,1,-1)'  onMouseOut='chgcursor(this,0,-1)' hspace='0' vspace='0' ";
var symExp = "<img src='../i/userminus.gif' border='0' hspace='1' vspace='0' ";
var symColl = "<img src='../i/userplus.gif' border='0' hspace='1' vspace='0' ";
//var symNoS = "<img src='../i/userdot.gif' border='0' hspace='1' vspace='2' ";
var symNoS = "<img src='../i/s.gif' border='0' hspace='1' vspace='0' height='"+navsymbolheight+"' width='"+navsymbolwidth+"' ";
var symSubArrow = "<img src='../i/arrowsub.gif' border='0' hspace='1' vspace='0' ";
var symNoth = "<img src='../i/usernone.gif' border='0' hspace='1' vspace='0' ";
var catmsg = "&nbsp;&nbsp;(Click to manage this category)&nbsp;";
var noproductmsg = "There are no items available at this time for ";
var state = 0;
var divisup = 0;
var hdivisup = 0;
var timeron = 0;
var rpidx = 0;
var genrp = true;
var cm=null;
rnd.today=new Date();
rnd.seed=rnd.today.getTime();

document.onclick = new Function("divshow(null)");

var alphaStr = "0123456789ABCDEF";
var alphaArr = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
var RGB = [0,0,0];

function fronthand(o) {
    // changes cursor to hand if not in admin (front-side only)
    // inadmin is global defined at top
    if (o.style) {
        var ostyle = o.style;
    } else {
        var ostyle = o;
    }
    if (inadmin) {
        ostyle.cursor = "default";
    } else {
        ostyle.cursor = (is.pointer)?"pointer":"hand";
    }
}

function removehand(o) {
    var ok = 0;
    for (var i=0;i<aCart.length;i++) {
        if (aCart[i].remove == 1) {
            ok += 1;
            break;
        }
    }
    if (o.style) {
        var ostyle = o.style;
    } else {
        var ostyle = o;
    }
    if (ok==1) {
        ostyle.cursor = (is.pointer)?"pointer":"hand";
    } else {
        ostyle.cursor = "default";
    }
}

function tblcursor(o,xmode,bgc) {
    if (o.style) {
        var ostyle = o.style;
    } else {
        var ostyle = o;
    }
//  var oname = o.id;
//  var catid = oname.replace("xtbl","");
//  var arrcell = "xarr" + catid;
//  var xar = new getObj(arrcell);
    if (xmode==1) {
        ostyle.cursor = (is.pointer)?"pointer":"hand";
        var xback = "CCCCCC";
    } else {
        ostyle.cursor = "default";
        var xback= bgc;
    }
    ostyle.backgroundColor = xback;
//  if (xar.obj) {
//      xar.obj.backgroundColor = xback;
//  }
}

function chgcursor(o,xmode,lvl) {
    if (o.style) {
        var ostyle = o.style;
    } else {
        var ostyle = o;
    }
    switch (xmode) {
        case 1:
            ostyle.cursor = (is.pointer)?"pointer":"hand";
            break;
        case 2:
            ostyle.cursor = "default";
            break;
    }

    var havebulletimg = (navbulletimg.length > 0)?true:false;
    if (havebulletimg) {
        var xid = o.id;
        xid = xid.replace("xc","");

        var x = new getObj("vnbullet" + xid);

        if (x.obj) {
            x.obj.src = (xmode==1)?navbulletover:navbulletimg;
        }
    }

    if (lvl >= 0) {
        newcolor = colornavrollover;        // defined in config.js
        basecolor = (lvl == 0)?colortextlight:colortextdark;
        ostyle.color = (xmode==1)?newcolor:basecolor;
    }
}

function HEX_to_DEC(hx)
        {
        var n_ = alphaStr.indexOf(hx.substring(0,1));
        var _n = alphaStr.indexOf(hx.substring(1,2));
        return n_ * 16 + _n;
        }

function DEC_to_HEX(dec)
        {
        var n_ = Math.floor(dec / 16);
        var _n = dec - n_ * 16;
        return alphaArr[n_] + alphaArr[_n];
        }

function RGB_from_HEX(hx)
        {
        RGB[0] = HEX_to_DEC(hx.substring(0,2));
        RGB[1] = HEX_to_DEC(hx.substring(2,4));
        RGB[2] = HEX_to_DEC(hx.substring(4,6));
        }

function HEX_from_RGB()
        {
        document.bgColor = DEC_to_HEX(RGB[0]) + DEC_to_HEX(RGB[1]) + DEC_to_HEX(RGB[2]);
        }

function newImage(arg) {
    if (document.images) {
        rslt = new Image();
        rslt.src = arg;
        return rslt;
    }
}

function changeImages() {
  if (document.images && (preloadFlag == true)) {
    for (var i=0; i<changeImages.arguments.length; i+=2) {
      document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
    }
  }
  return true;
}

var preloadFlag = false;
function preloadImages() {
    if (document.images) {
        btn_new = newImage("../i/btn_new.gif");
        btn_spot = newImage("../i/btn_spot.gif");
        btn_sale = newImage("../i/btn_sale.gif");
        // custom adds for Chef Tools - make dynamic
      the_kitchen_over = newImage("../i/the_kitchen-over.gif");
      the_tools_over = newImage("../i/the_tools-over.gif");
      the_food_over = newImage("../i/the_food-over.gif");
      the_table_over = newImage("../i/the_table-over.gif");
      the_clothes_over = newImage("../i/the_clothes-over.gif");
      the_books_over = newImage("../i/the_books-over.gif");
      the_recipes_over = newImage("../i/the_recipes-over.gif");
      cust_service_over = newImage("../i/cust_service-over.gif");
        preloadFlag = true;
    }
}

function calcnode(cartidx) {
    // Price calculation for a single item
    // Calling functions load aCalc[] with inputs and get results from internal properties
    // All numbers are in numeric form - calling functions using results must format them
    // Cartidx, if present, designates aCart[] index, to find form objects (eg, "qcell3") to update
    // If cartidx = -1, this call is from order context and we know object names there

    this.cartidx = cartidx;

    this.prodid = aCalc[0];
    this.catid = aCalc[1];
    this.pversion = aCalc[2];
    this.pstrat = aCalc[3];
    this.qstrat = aCalc[4];
    this.rprice = aCalc[5];
    this.sprice = aCalc[6];
    this.optionlist = aCalc[7];         // ?
    this.optionpricing = aCalc[8];
    this.opchoices = aCalc[9];
    this.qoptions = aCalc[10];
    this.qty = aCalc[11];
    this.qid = aCalc[12];
    this.notax = aCalc[13];
    this.nametag = aCalc[14];
    this.instructions = aCalc[15];    

    this.shipping = 0;
    this.tax = 0;
    this.finalpriceperitem = 0;
    this.finaltotal = 0;
    this.regtotal = 0;
    this.savings = 0;
    this.cartdata = "";
    this.qword = "item";
    this.pexplain = "";
    this.deposit = false;
    this.remainder = 0;

    if (typeof(this.rprice) == "string") {
        this.rprice = parseFloat(this.rprice.replace("$",""));
    }
    if (typeof(this.sprice) == "string") {
        this.sprice = parseFloat(this.sprice.replace("$",""));
    }

    // use memvars for calculation
    var pxx = "";
    var rprice = this.rprice;
    var sprice = this.sprice;
    var pstrat = this.pstrat;
    var qstrat = this.qstrat;
    var qty = this.qty;
    var olist = this.optionlist;                        // ?
    var ochoices = this.opchoices;
    var olist = this.optionlist;
    var oplist = this.optionpricing;

    var cprice = rprice;
    var pxlead = "<li>";
    var px = "<ul><li>The Regular price is  <span class='currencysmall'>" + toFormatted(rprice) + " </span>";
    pxx += "1:" + toFormatted(rprice) + "~";
    var onsale = (sprice > 0)?true:false;
    if (onsale) {
        salediscount = rprice - sprice;
        if (pstrat < 3 ) {
            cprice = sprice;
            px += pxlead + "Our Sale price is  <span class='currencysmall'>" + toFormatted(cprice)+ " </span>";
            pxx += "2:" + toFormatted(cprice) + "~";
        }
    }

    var deposit = false;
    a_op = oplist.split("/");
    if (oplist.length > 0) {
        for (var iter=0;iter<3;iter++) {
            // 3 iterations, first =, then $ deltas, then %
            for (i=0;i<a_op.length;i++) {
                xopitem = a_op[i];
                if (xopitem.length == 0) {
                    continue;
                }
                xov = xopitem.substring(0,xopitem.indexOf(":"))
                xoid = xov.substring(0,xov.indexOf(","));
                xvalueid = xov.substring(xov.indexOf(",")+1,xov.length);
                testxov = xoid + ":" + xvalueid + ",";
                testochoices = "," + ochoices + ",";
                if (rprice > 0 && testochoices.indexOf(testxov) >= 0) {
                    colon = xopitem.indexOf(":");
                    delta = xopitem.substring(colon+1);
                    method = delta.substring(0,2);
                    if (iter == 0 && method.indexOf("=$") < 0) {
                        continue;
                    }
                    if (iter == 1 && method.indexOf("+$") < 0 && method.indexOf("-$") < 0) {
                        continue;
                    }
                    if (iter == 2 && method.indexOf("%") < 0) {
                        continue;
                    }
                    optname = "";
                    xval = "";
                    // aOptions and aValues arrays are visible from either calling context
                    for (k=0;k<aOptions.length;k++) {
                        if (aOptions[k].optid==xoid) {
                            optname = aOptions[k].optname;
                            if (optname=="Deposit" || optname=="Down Payment") {
                                deposit=true;
                                this.deposit = true;
                            }
                            break;
                        }
                    }
                    for (k=0;k<aValues.length;k++) {
                        if (aValues[k].valueid==xvalueid) {
                            xval = aValues[k].strvalue;
                            break;
                        }
                    }
                    deltastr = parseFloat(delta.substring(2,99));
                    deltafmt = toFormatted(deltastr);
                    deltadisplay = "<span class='currencysmall'>" +deltafmt + " </span>";
                    calcprice = 0;
                    px += pxlead + optname + " selected is <u>" + xval + "</u>, ";
                    pxx += "3:" + optname + ":" + xval + ",";
                    switch (method) {
                        case "+$":
                            calcprice = rprice + deltastr;
                            px += "<br>add " + deltadisplay + " per item";
                            pxx += "+" + deltafmt;
                            break;
                        case "-$":
                            calcprice = rprice - deltastr;
                            px += "<br>deduct " + deltadisplay + " per item";
                            pxx += "-" + deltafmt;
                            break;
                        case "+%":
                            calcprice = rprice * (1 + (deltastr/100));
                            px += "<br>add " + deltastr + "%" + " per item";
                            pxx += "+" + deltastr + "%";
                        break;
                        case "-%":
                            calcprice = rprice * (1 - (deltastr/100));
                            px += "<br>deduct " + deltastr + "%" + " per item";
                            pxx += "-" + deltastr + "%";
                            break;
                        case "=$":
                            calcprice = deltastr;
                            px += "new price is " + deltadisplay;
                            pxx += "=" + deltafmt;
                            break;
                    }
                    cdelta = calcprice - rprice;
                    cprice = cprice + cdelta;
                    px += " =  <span class='currencysmall'>" + toFormatted(cprice) + "</span>";
                    pxx += "," + toFormatted(cprice) + "~";
                }
            }
        }
    }

    if (onsale) {
        switch (pstrat) {
            case 1:
                // sale price overrides option pricing
                cprice = sprice;
                px += pxlead + "Sale price overrides other adjustments =  <span class='currencysmall'>" + toFormatted(sprice) + "</span>";
                pxx += "4:" + toFormatted(sprice) + "~";
                break;
            case 2:
                // start with sale price, then apply option pricing
                // nothing to do, this is the result of above calculation
                break;
            case 3:
                // apply option pricing, then deduct sale price discount
                cprice = cprice - salediscount;
                px += pxlead + "On sale, deduct sale price reduction of $" + salediscount + " =  <span class='currencysmall'>" + toFormatted(cprice) + "</span>";
                pxx += "5:" + salediscount + "," + toFormatted(cprice) + "~";
                break;
        }
    }

    // We now have an adjusted unit price based on the product pricing strategy
    // Now apply benefit of quantity discounts, if any, based on quantity strategy

    var qadjprice = 0;
    var qid = this.qid;
    var prid = this.prodid;
    var oArr = new Array();
    var opArr = new Array();
    opchoices = this.opchoices;
       
    if (opchoices.lastIndexOf(",") == opchoices.length-1) {
    	opchoices = opchoices.substring(0,(opchoices.length-1));
    }
    if(opchoices != "" ) oArr = opchArr(opchoices);

    if (qid > 0) {
        // user has chosen a bulk quantity, find it in aQO[]
        qqty = 0;
        qprice = 0;
        qname = "";
        qdiscount = 0;
        afl = 0;
        for (var i=0; i<aQO.length;i++) {
		if(aQO[i].qoprice != "" ) opArr = oprArr(aQO[i].qoprice);
		if (aQO[i].qid == qid && aQO[i].prodid == prid) {
			                qqty = aQO[i].qty;			                
			                qprice = aQO[i].qprice;
					if(opchoices != "" && aQO[i].qoprice != "") {
						for (var j=0; j < oArr.length;j++) {						
							if (aQO[i].qoid == oArr[j][0]) {							
								for (var n=0; n<opArr.length;n++) {								
									if (oArr[j][1] == opArr[n][0]) {			
										qprice = opArr[n][1];							
										this.qword = aQO[i].qname;
				                				break;						
									}
								}
							}
						}
					}
			                this.qword = aQO[i].qname;
			                break;
		}
        }
        if (qqty > 0 && qprice > 0) {
            if (qstrat == 1) {
                qadjprice = qprice;
                px += pxlead + "Volume price overrides other adjustments =  <span class='currencysmall'>" + toFormatted(qextended) + "</span>";
                pxx += "6:" + toFormatted(qextended) + "~";
            } else {
                regprice = rprice * qqty;
                qdiscount = (regprice - qprice)/qqty;

                // this is the discounted amount on a $ per item basis
                // apply to adjusted price

                newprice=qprice/qqty; 
                qadjprice = newprice * qqty;
                px += pxlead + "Volume discount, deduct <span class='currencysmall'>" + toFormatted(qdiscount) + " </span> per item =  <span class='currencysmall'>" + toFormatted(newprice) + "</span>";
                px += pxlead + "Adjusted price for " + this.qword + " is  <span class='currencysmall'>" + toFormatted(qadjprice) + "</span>";
                pxx += "7:" + toFormatted(qdiscount) + "," + toFormatted(newprice)  + "," + this.qword + "," + toFormatted(qadjprice) + "~";
            }
        }
    }
    if (qadjprice > 0) {
        // if bulk quantities, apply qty desired to qadjprice, else to cprice
        qtotalprice = qty * qadjprice;
        regtotal = (rprice * qqty) * qty;
        this.finalpriceperitem = qadjprice;
    } else {
        qtotalprice = qty * cprice;
        regtotal = qty * rprice;
        this.finalpriceperitem = cprice;
    }
    this.finaltotal = qtotalprice;
    this.regtotal = regtotal;
    if (this.deposit==true) {
        this.remainder = Math.max(0,this.regtotal - this.finaltotal);
    } else {
        this.savings = Math.max(0,this.regtotal - this.finaltotal);
    }
    this.finaltotal = parseFloat(this.finaltotal.toFixed(2));
    this.regtotal = parseFloat(this.regtotal.toFixed(2));
    this.savings = parseFloat(this.savings.toFixed(2));
    this.remainder = parseFloat(this.remainder.toFixed(2));
    this.finalpriceperitem = parseFloat(this.finalpriceperitem.toFixed(2));

    qtotaldisplay = "<span class='currencysmall'>" + toFormatted(this.finaltotal) + "</span>";
    ft = this.finaltotal;
    fpi = this.finalpriceperitem;

    if (qty > 1) {
        qw = this.qword;
        lastchar = qw.charAt(qw.length-1);
        if (lastchar == "s") {
        } else {
            this.qword += "s";
        }
    }
//  this.qword = qword;
    if (px.length > 0) {
        px += pxlead + "Your specified Quantity is  " + qty + " " + this.qword;
        px += pxlead + "For a Total of  " + qtotaldisplay;
        pxx += "8:" + qty + "," + this.qword + "," + toFormatted(this.finaltotal) + "~";
        if (this.savings > 0) {
            px += pxlead + "With a Savings of  <span class='currencysmall'>" + toFormatted(this.savings) + "</span>";
            pxx += "9:" + toFormatted(this.savings) + "~";
        }
        if (this.remainder > 0) {
            px += pxlead + "With a Remainder Due of  <span class='currencysmall'>" + toFormatted(this.remainder) + "</span>";
            pxx += "9:" + toFormatted(this.remainder) + "~";
        }
        px += "</ul>";
        this.pexplain = pxx;
    }

    // update cartdata, because calc'd total may have changed
//  xe = escape(this.pexplain);
    xe = this.pexplain;
    var savrem = (this.remainder>0)?this.remainder:this.savings;
    this.cartdata = this.prodid + "|" + this.catid + "|" + qty + "|" + qid + "|" + fpi + "|" + ft + "|" + savrem + "|" + this.pversion + "|" + this.opchoices + "|" + xe + "|" + this.notax + "|" + this.nametag + "|" + this.instructions;
}

function opchArr (ostr) {
	var k = 0;
	var opArr = new Array();
	var otmp1 = ostr.split(",");
	for (var i=0; i< otmp1.length; i++) {
		var otmp2 = otmp1[i].split(":");
		opArr[k]=new Array();
		opArr[k][0] = otmp2[0]; // selected option
		opArr[k][1] = otmp2[1]; // selected option value	
		k += 1;
	}
	return opArr;
}

function oprArr (pstr) {
	var m = 0;
	var pArr = new Array();
	ptmp1 = pstr.split(",");
	for (var i=0; i< ptmp1.length; i++) {
		ptmp2 = ptmp1[i].split("=");
		pArr[m]=new Array();
		pArr[m][0] = ptmp2[0]; // value id
		pArr[m][1] = ptmp2[1]; // price
		m += 1;
	}
	return pArr;
}

function pricecalc(e) {
  var ocount = -1;
  var qty = 1;
  
  // Currently, only some of the UI in catalog/id.asp hands in its events to
  // this function, so a little sophistery is in order. "qcell" may still be in
  // use on other pages. Chris 28/03/06
  if (e) {
    var x = {obj: EventUtils.getTarget(e)};
  } else {
    var x = new getObj("qcell");
  }

  if (x.obj) {
    qty = parseInt(x.obj.value);
    if (qty <= 0 || isNaN(qty)) {
      qty = 1;
      x.obj.value = qty;
    }
  }

  oplist = "";
  olist = "";
  ochoices = "";
  qoptions = "";

  for (var i = 0; i < aOptions.length; i++) {
    olist += aOptions[i].optid + ":" + aOptions[i].optvals + "/";
    if (aOptions[i].valchoice > 0) {
      ochoices += aOptions[i].optid + ":" + aOptions[i].valchoice + ",";
      ocount += 1;
    }
  }
  for (var i = 0; i < aOP.length; i++) {
    oplist += aOP[i].oid + "," + aOP[i].vid + ":" + aOP[i].delta + "/";
  }

  for (var i = 0; i < aQO.length; i++) {
    qoptions += aQO[i].qid + ":" + aQO[i].qty + "," + aQO[i].qprice + "|" + aQO[i].exceptions + "/";
  }

  aCalc[0] = afx[0].prodid;
  aCalc[1] = afx[0].catid;
  aCalc[2] = afx[0].pv;
  aCalc[3] = afx[0].pstrat;
  aCalc[4] = afx[0].qstrat;
  aCalc[5] = afx[0].rprice;
  aCalc[6] = afx[0].sprice;
  aCalc[7] = olist;
  aCalc[8] = oplist;
  aCalc[9] = ochoices;
  aCalc[10] = qoptions;
  aCalc[11] = qty;
  aCalc[12] = afx[0].qid;
  aCalc[13] = afx[0].notax;
  aCalc[14] = foreman.getRawData("nameTag");
  aCalc[15] = foreman.getRawData("specialInst");

  oprice = new calcnode(-1);

  savword = "";
  savingsdisplay = "";
  savearea = 2;

  savings = oprice.savings;
  remainder = oprice.remainder;
  if (savings > 0) {
    if (oprice.deposit == true) {
      savword = "Remainder:&nbsp;";
      savingsdisplay = toFormatted(remainder);
    } else {
      if (afx[0].sprice > 0) {                    // only show savings if on sale
        savword = "Savings:&nbsp;";
        savingsdisplay = toFormatted(savings);
      }
    }
  }

  savword2 = savword;
  savamount2 = savingsdisplay;

  totaldisplay = toFormatted(oprice.finaltotal);
  var xprice = new getObj("priceCell");
    
  if (xprice.obj) {
    xprice.obj.innerHTML = totaldisplay;
  } else {
    alert("Error 0x64F8E448 : Failed to trap price cell");
  }

  var xsavamt2 = new getObj("savamt2");
  if (xsavamt2.obj) {
    var xsavelabel2 = new getObj("savelabel2");
    if (xsavelabel2.obj) {
        xsavelabel2.obj.style.visibility = "visible";
        xsavelabel2.obj.innerHTML = savword2;
    }
    xsavamt2.obj.style.visibility = "visible";
    xsavamt2.obj.innerHTML = savamount2;
  }

  afx[0].pex = oprice.pexplain;
  var xpriceexplain = new getObj("priceexplain");
  if (xpriceexplain.obj) {
    xpriceexplain.obj.style.visibility = "visible";
  }

  afx[0].xc = oprice.cartdata;

  // Didn't we get this once already? Called it x?
  // var xqcell = new getObj("qcell");
  var xqcell = x;
  if (ocount == aOptions.length-1 || aOptions[0].optid == 0) {
    offercart(1);
    var vqc = "";
    if (xqcell.obj) {
      vqc = xqcell.obj.value;
      if (vqc.length == 0) {
        xqcell.obj.value = 1;
      }
    }
  } else {
    offercart(0);       // withdraw cart
  }
}

function pexplain(idx) {
    // get raw pexplain data
    if (idx >= 0) {
        var px = aCart[idx].pexplain;
        var pname = aCart[idx].prodname;
    } else {
        var px = afx[0].pex;
        var pname = afx[0].prodname;
    }
    if (px.length == 0) {
        return;
    }
    xtotal = "";
    xsavings = "";

    // interpret data to show message
    aex = px.split("~");
    var pxlead = "<li>";
    var x = "<ul>";
    var deposit = false;
    var savingsapplies = true;
    for (var i=0;i<aex.length;i++) {
        ex = aex[i];
        xcode = ex.substring(0,ex.indexOf(":"));
        ex = ex.substring(ex.indexOf(":")+1,ex.length);
        switch (xcode) {
            case "1":
                // regular price
                x += pxlead + "The Regular price is  <span class='currencysmall'>" + ex + " </span>";
                break;
            case "2":
                // sale price
                x += pxlead + "Our Sale price is  <span class='currencysmall'>" + ex + " </span>";
                break;
            case "3":
                // xopitem
                optname = ex.substring(0,ex.indexOf(":"));
                if (optname=="Deposit" || optname=="Down Payment") {
                    deposit = true;
                }
                ex = ex.substring(ex.indexOf(":")+1,ex.length);
                xval = ex.substring(0,ex.indexOf(","));
                ex = ex.substring(ex.indexOf(",")+1,ex.length);
                delta = ex.substring(0,ex.indexOf(","));
                result = ex.substring(ex.indexOf(",")+1,ex.length);
                deltameth = delta.substring(0,2);
                if (deltameth=="=$") {
                    savingsapplies = false;
                    x += pxlead + optname + " selected is <u>" + xval + "</u>, price per item  =  <span class='currencysmall'>" + result + "</span>";
                } else {
                    deltaword = (delta.substring(0,1)=="+")?"add":"deduct";
                    x += pxlead + optname + " selected is <u>" + xval + "</u>, " + deltaword + " " + delta.substring(1) + " per item  =  <span class='currencysmall'>" + result + "</span>";
                }
                break;
            case "4":
                // pstrat 1 override
                x += pxlead + "Sale price overrides other adjustments =  <span class='currencysmall'>" + ex + "</span>";
                break;
            case "5":
                // pstrat 3 override
                salediscount = ex.substring(0,ex.indexOf(","));
                result = ex.substring(ex.indexOf(",")+1,ex.length);
                x += pxlead + "On sale, deduct sale price reduction of $" + salediscount + " =  <span class='currencysmall'>" + result + "</span>";
                break;
            case "6":
                // qstrat 1 override
                x += pxlead + "Volume price overrides other adjustments =  <span class='currencysmall'>" + ex + "</span>";
                break;
            case "7":
                // volume discount
                qdiscount = ex.substring(0,ex.indexOf(","));
                ex = ex.substring(ex.indexOf(",")+1,ex.length);
                newprice = ex.substring(0,ex.indexOf(","));
                ex = ex.substring(ex.indexOf(",")+1,ex.length);
                qword = ex.substring(0,ex.indexOf(","));
                result = ex.substring(ex.indexOf(",")+1,ex.length);
                x += pxlead + "Volume discount, deduct <span class='currencysmall'>" + qdiscount + " </span> per item =  <span class='currencysmall'>" + newprice + "</span>";
                x += pxlead + "Adjusted price for " + qword + " is  <span class='currencysmall'>" + result + "</span>";
                break;
            case "8":
                // qty, total
                qty = ex.substring(0,ex.indexOf(","));
                ex = ex.substring(ex.indexOf(",")+1,ex.length);
                qword = ex.substring(0,ex.indexOf(","));
                result = ex.substring(ex.indexOf(",")+1,ex.length);
                x += pxlead + "Your specified Quantity is <span class='currencysmall'>" + qty + "</span> " + qword;
                xtotal = pxlead + "<b>For a Total of  <span class='currencysmall'>" + result + " </span></b>";
                break;
            case "9":
                // savings
                if (deposit==true) {
                    xsavings = pxlead + "With a Remainder Due of <span class='currencysmall'>" + ex + " </span>";
                } else {
                    if (savingsapplies==true) {
                        xsavings = pxlead + "With a Savings of <span class='currencysmall'>" + ex + " </span>";
                    }
                }
                break;
        }
    }
    x += xsavings + xtotal;
    x += "</ul>";

    msgshow(x,"Pricing Calculation Summary",pname);
}

function qexplain(idx) {
    // get raw qexplain data
    if (idx >= 0) {
        var qx = aCart[idx].qexplain;
        var pname = aCart[idx].prodname;
    } else {
        var qx = afx[0].qex;
        var pname = afx[0].prodname;
    }

    if (qx.length == 0) {
        return;
    }
    // interpret data to show message
    aex = qx.split("~");
    var qexlead = "&nbsp;&nbsp;&nbsp;&nbsp;";
    var x = "<ul>";
    for (var i=0;i<aex.length;i++) {
        ex = aex[i];
        if (ex.length == 0) {
            continue;
        }
        aq = ex.split("|");
        x += "<li>" + aq[0] + " of <span class='currencysmall'>" + aq[1] + "</span> for <span class='currencysmall'>$" + aq[2] + "</span>";
        if (aq[3].length == 0) {
            var qav = "all options";
        } else {
            var qav = ": <br>" + aq[3];
        }
            if (aOptions[0].optid > 0) {
                x += "<br>" + "Available for " + qav;
            }
    }
    x += "</ul>";
    msgshow(x,"Bulk Discount Options Summary",pname);
}


function viewcart() {
    afx[0].act= "../cart/vieworder.asp";
    submitform();
}


function ClearSession() {
    // debug only - ends current session, causes load of new session
    xloc = window.top.location.href;
    xadmin = xloc.indexOf("/admin/");
    if (xadmin == -1) {
        dslash = xloc.indexOf("//");
        if (dslash >= 0) {
            xloc2 = xloc.substring(dslash+2);
        }
        slash = xloc2.indexOf("/");
        if (slash >= 0) {
            slash = dslash + 2 + slash;
            xloc = xloc.substring(0,slash);
        }
        newloc = xloc + "/Catalog/abandon.asp";
        window.location = newloc;
    }
}

function showacalc(msg) {
    x = msg + "\n\n";
    x += "prodid = " + aCalc[0] + "\n";
    x += "catid = " + aCalc[1] + "\n";
    x += "Version = " + aCalc[2] + "\n";
    x += "Pstrat = " + aCalc[3] + "\n";
    x += "Qstrat = " + aCalc[4] + "\n";
    x += "Rprice = " + aCalc[5] + "\n";
    x += "Sprice = " + aCalc[6] + "\n";
    x += "optionlist = " + aCalc[7] + "\n";
    x += "optionpricing = " + aCalc[8] + "\n";
    x += "opchoices = " + aCalc[9] + "\n";
    x += "qoptions = " + aCalc[10] + "\n";
    x += "qty = " + aCalc[11] + "\n";
    x += "qid = " + aCalc[12] + "\n";
    x += "notax = " + aCalc[13] + "\n";
    alert(x);
}

function showoprice(o,msg) {
    x = msg + "\n\n";
    x += "prodid = " + o.prodid + "\n";
    x += "catid = " + o.catid + "\n";
    x += "Version = " + o.pversion + "\n";
    x += "Pstrat = " + o.pstrat + "\n";
    x += "Qstrat = " + o.qstrat + "\n";
    x += "Rprice = " + o.rprice + "\n";
    x += "Sprice = " + o.sprice + "\n";
    x += "optionlist = " + o.optionlist + "\n";
    x += "optionpricing = " + o.optionpricing + "\n";
    x += "opchoices = " + o.opchoices + "\n";
    x += "qoptions = " + o.qoptions + "\n";
    x += "qty = " + o.qty + "\n";
    x += "qid = " + o.qid + "\n";
    x += "shipping = " + o.shipping + "\n";
    x += "tax = " + o.tax + "\n";
    x += "finalpriceperitem = " + o.finalpriceperitem + "\n";
    x += "finaltotal = " + o.finaltotal + "\n";
    x += "regtotal = " + o.regtotal + "\n";
    x += "savings = " + o.savings + "\n";
    x += "cartdata = " + o.cartdata + "\n";
    x += "qword = " + o.qword + "\n";
    x += "explain = " + o.pexplain + "\n";
    alert(x);
}

function showmsg(mcode) {
  var xmp = new getObj("msgpanel");
  if (xmp.obj) {
    // generate contents for div
    xmp.obj.innerHTML = gen_msg();
    xmp.style.top  =200;
    xmp.style.left  =200;
    xmp.style.visibility = "visible";
 }
}

function gen_msg(mcode) {
  var x = "<table background='../i/opdivfade.gif' class='iframetext' cellspacing='2' cellpadding='0' border='0' width='100%'><tr><td>";
  x += "Hello world inside a table.";
  x += "</td></tr>"
  x += "<tr><td><input type='button' value='OK' onclick='closemsg()'></td></tr></table>";

  return x;
}

function closemsg() {
  document.msgpanel.style.visibility = "hidden";
}

function linkover(el,scode) {
  var cls = "pagelinkover";
  if (scode==1) {
      cls = "pagelinkboldover";
  }
  el.className = cls;
  chgcursor(el,1,-1);
}

function linkout(el,scode) {
  var cls = "pagelink";
  if (scode==1) {
    cls = "pagelinkbold";
  }
  el.className = cls;
}

function handleerror(msg, url, line) {
  var errstr = 'Problem:   ' + msg + '\n\n' + 'URL:   ' + url + '\n' + 'Line:   ' + line;
  var errstr2 = escape(msg + "|" + url + "|" + line + "|" + new Date() + "|");
  alert(errstr); 

  var x = "<html><head><title>Script Problem</title><meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'></head><body>";
  x += "<form name='eform' method='post' action='http://www.1degree.com/errors.asp'>";
  x += "<input type='hidden' name='errmsg' value='" + errstr2 + "'>" + errstr2;
  x += "<br><br><center><input type='button' value='Close window' onClick='alert(document.eform.errmsg.value);document.eform.submit();'></form></center></body></html>";

  if (ie) {
    var xMax = screen.width, yMax = screen.height;
  } else {
    if (ns) {
      var xMax = window.outerWidth, yMax = window.outerHeight;
    } else {
      var xMax = 640, yMax=480;
    }
  }
  var xOffset = (xMax - 300)/2, yOffset = (yMax - 200)/2;
  return true;
}

function rnd() {
  rnd.seed = (rnd.seed*9301+49297) % 233280;
  return rnd.seed/(233280.0);
}

function rand(digits) {
  var rx = Math.pow(10,digits);
  var res = "";
  do {
    res += Math.ceil(rnd()*rx);
    if (res.length > 5) {
      res = res.substring(0,5);
      break;
    }
  } while (res.length < 5) ;
  return res;
}

function modalmsg(mcode, x1, x2, x3) {
    // calls msgshow() modally to interact with user
    var xcode = "";
    var xtitle = "";
    var xbtns = "";
    switch (mcode) {
        case 0:
            // add to cart, item already in cart - get instructions
            xtitle = "Add to Order";
            sltr = (x2>1)?"s":"";
            xcode = "<u>" + x1 + "</u> is already in your order<br>(" + x2 + " item" + sltr + ", total = " + toFormatted(x3) + "). What would you like to do?<br><ul><li>Add to the quantity ordered<li>Treat this as a new line item<li>Cancel</ul><br>";
            xbtns = "Add to Quantity,New Item,Cancel";
            break;
    }

    if (xcode != "") {
        var res = msgshow(xcode, xtitle, "", "", mcode, xbtns);
    }
}

function modalresult(mcode,mres) {
    switch (mcode) {
        case 0:
            // add to cart instructions
            if (mres != 2) {
                afx[0].act= "../catalog/orderadd.asp";
                afx[0].gc.value = afx[0].catid;
                afx[0].gp.value = afx[0].prodid;
                afx[0].addflag= 1;
                afx[0].addmode= mres;
                // addmode - 0=increase qty, 1=separate line item (default), 2=cancel
                savee();
                submitform();
            }
            break;
    }
}

function cycletime(startcycle,rend) {
    cycletotal = -1;
    loadtotal = rend;
    if (startcycle>-1) {
        var timenow = new Date();
        timenow = timenow.getTime();
        cycletotal = (timenow - startcycle);
    }
}

function stats() {
    if (statstr.length > 0) {
        var x = "Page metrics:\n\n";
        astat = statstr.split("|");
        var cacheused = astat[0];
        if (cacheused=="0") {
            x += "Cached navigation trees were used.\n";
        } else {
            x += "Navigation trees were re-generated.\n";
        }

        if (astat[27]=="0") {
            x += "User id was known.\n";
        } else {
            x += "New user id was generated.\n";
        }

        var prec1 = new Number(cycletotal/1000);
        var prec2 = new Number(astat[1]);
        var prec3 = new Number(loadtotal/1000);
        var ct1 = ((cycletotal/1000) - astat[1]);
        var ct2 = (ct1 - (loadtotal/1000));
        var prec4 = new Number(ct2);

        if (cycletotal == -1) {
            x += "\nTotal time to load new page: (unknown)";
            x += "\nTime spent at server: " + prec2.toPrecision(5);
            x += "\nTime spent rendering page: " + prec3.toPrecision(5);
            x += "\nEstimated network time: (unknown)\n";
        } else {
            x += "\nTotal time to load new page: " + prec1.toPrecision(5) + " seconds";
            x += "\nTime spent at server: " + prec2.toPrecision(5);
    //      x += "\nTime spent in header: " + astat[3];
            x += "\nTime spent rendering page: " + prec3.toPrecision(5);
            x += "\nEstimated network time: " + prec4.toPrecision(5) + "\n";
        }

        if (false) {
        x += "\nHeader breakdown: ";
        x += "\n   DB access: " + astat[2];
        x += "\n   h1: " + astat[4];
        x += "\n   h2: " + astat[5];
        x += "\n   h3: " + astat[6];
        x += "\n   h4: " + astat[7];
        x += "\n   h5: " + astat[8];
        x += "\n   h6: " + astat[9];
        x += "\n   h7: " + astat[10];
        x += "\n   h8: " + astat[11];
        x += "\n   h9: " + astat[12];
        x += "\n   h10: " + astat[13];
        x += "\n   hA: " + astat[14];
        x += "\n   hB: " + astat[15];
        x += "\n   hC: " + astat[16];
        x += "\n   hD: " + astat[17];
        x += "\n   hE: " + astat[18];
        x += "\n   hF: " + astat[19];
        x += "\n   hG: " + astat[20];
        x += "\n   hH: " + astat[21];
        x += "\n   hI: " + astat[22];
        x += "\n   hJ: " + astat[23];
        x += "\n   hK: " + astat[24];
        x += "\n   hL: " + astat[25];
        x += "\n   hM: " + astat[26];
        }
        alert(x);
    }
}


function savee() {
  var xid = afx[0].catid;
  var parentrow = -1;
  var irow = -1;
  var topparent = -1;
  if (xid>0) {
    for (i=0;i<aC.length;i++) {
      if (aC[i].catid==xid) {
        irow = i;
        parentrow = aC[i].parentrow;
        if (parentrow >= 0) {
          topparent = aC[parentrow].parentrow;
        }
        break;
      }
    }
  }

  var e = ".";
  var prow = -1;
  for (i=0;i<aC.length;i++) {
    prow = aC[i].parentrow;
    switch(prow) {
    case -1:
      if (i==topparent) {
        e += aC[i].catid + ",1.";
      } else {
        e += aC[i].catid + ",0.";
      }
      break;
    case topparent:
      if (i==irow) {
        e += aC[i].catid + "," + aC[i].expflag + ".";
      } else {
        e += aC[i].catid + ",0.";
      }
      break;
    case parentrow:
      if (i==irow) {
        e += aC[i].catid + "," + aC[i].expflag + ".";
      } else {
        e += aC[i].catid + ",0.";
      }
      break;
    case irow:
      e += aC[i].xid + ",0.";
      break;
    default:
      break;
    }
  }
  afx[0].e= e;
}

function cyclestamp() {
  if (afx[0].cs) {
    var now = new Date();
    afx[0].cs.value = now.getTime();
  }
}

function submitform() {
  cyclestamp();
  newfx();        // updates form fx
  document.form1.submit();
}

function makeship() {
    // populates array aShip with shipping charges supplied by
    // instructions passed in with form - call from form's CustomLoad()
    // cheftools sample:
    // old remove 0-15.00,4.95|15.01-25.00,6.95|25.01-35.00,7.95|35.01-45.00,8.95|45.01-55.00,9.95|55.01-75.00,11.95|75.01-100.0,12.95|100.01-160.00,15.95|>160.01=10%|Express=9.95|Distance=7.50(HI,AK,PR)|
    // NEW 0-15.00,4.95|15.01-25.00,6.95|25.01-35.00,7.95|35.01-45.00,8.95|45.01-55.00,9.95|55.01-75.00,11.95|75.01-100.0,12.95|100.01-160.00,15.95|>160.01=10%|Express1=9.95|Express2=11.95|Express3=13.95|Distance=7.50(HI,AK,PR)|

    if (afx[0].ship) {
        shipdata = afx[0].ship;
        if (shipdata.length > 0) {
            ashp = shipdata.split("|");
            for (var k=0;k<ashp.length;k++) {
                aShip[k] = new shipnode();
                xshp = ashp[k];
                spot = xshp.indexOf("-");
                if (spot >= 0) {
                    // price or weight range
                    aShip[k].pricecode = 0;
                    aShip[k].low = parseFloat(xshp.substring(0,spot));
                    xshp = xshp.substring(spot+1,999);
                    spot = xshp.indexOf(",");
                    if (spot >= 0) {
                        aShip[k].high = parseFloat(xshp.substring(0,spot));
                        xshp = xshp.substring(spot+1,999);
                    }
                    if (xshp.length > 0) {
                        aShip[k].cost = parseFloat(parseFloat(xshp).toFixed(2));
                    }
                }
                if (xshp.length>0) {
                    // other variations
                    if (xshp.substring(0,1)==">") {
                        // greater than threshold
                        aShip[k].pricecode = 1;
                        xshp = xshp.substring(1,999);
                        spot = xshp.indexOf("=");
                        if (spot >= 0) {
                            aShip[k].threshold = parseFloat(xshp.substring(0,spot));
                            multiplier = xshp.substring(spot+1,999);
                            if (multiplier.indexOf("%")>0) {
                                multiplier = parseFloat(multiplier)/100;
                                multiplier = parseFloat(parseFloat(multiplier).toFixed(2));
                                aShip[k].multiplier =multiplier;
                            } else {
                                if (multiplier.indexOf(",renew")>0) {
                                    aShip[k].renew = 1;
                                    aShip[k].renewvalue = multiplier.replace(",renew","");
                                }
                            }
                        }
                    }

// new express shipping settings - start
                    if (xshp.substring(0,8)=="Express3") { 
                        // express add-on - express delivery - 3 days
                        aShip[k].pricecode = 2;
                        spot = xshp.indexOf("=");
                        if (spot >= 0) {
                            aShip[k].express3 = parseFloat(parseFloat(xshp.substring(spot+1,999)).toFixed(2));
                        }
                    }    
                    if (xshp.substring(0,8)=="Express2") { 
                        // express add-on - express delivery - 2 days
                        aShip[k].pricecode = 5;
                        spot = xshp.indexOf("=");
                        if (spot >= 0) {
                            aShip[k].express2 = parseFloat(parseFloat(xshp.substring(spot+1,999)).toFixed(2));
                        }
                    }    
                    if (xshp.substring(0,8)=="Express1") { 
                        // express add-on - express delivery - 1 day
                        aShip[k].pricecode = 6;
                        spot = xshp.indexOf("=");
                        if (spot >= 0) {
                            aShip[k].express1 = parseFloat(parseFloat(xshp.substring(spot+1,999)).toFixed(2));
                        }
                    }     
// new express shipping settings - end                                                                          
                    if (xshp.substring(0,8)=="Distance") {
                        // distance add-on
                        aShip[k].pricecode = 3;
                        spot = xshp.indexOf("=");
                        if (spot >= 0) {
                            xdist = xshp.substring(spot+1,999);
                            spot = xshp.indexOf("(");
                            if (spot >= 0) {
                                aShip[k].addon = parseFloat(parseFloat(xdist.substring(0,spot-1)).toFixed(2));
                                aShip[k].destinations = xdist.substring(0,spot+1);
                            }
                        }
                    }
                    if (xshp.substring(0,5)=="nsfree") {
                        // free shipping for non-sale items over a threshold
                        aShip[k].pricecode = 4;
                        nsthresh = xshp.substring(6,99);
                        aShip[k].nsfree = parseFloat(parseFloat(nsthresh).toFixed(2));
                    }
                }
            }
        }
    }
}

function calcship(amt,xprs,destination,isvc) {
    // first find normal range
    var ship = 0;
    var nsfree = 0;
    if (!isvc) {
        isvc=0;
    }
    // free shipping applies?
    for (var i=0;i<aShip.length;i++) {
        if (aShip[i].pricecode==4) {
            nsfree = aShip[i].nsfree;
        }
    }
    if (nsfree>0) {
        // add up nonsale items; if > threshold, shipping amt is only the sale item portion
        var si=0,nsi=0,pid=0,issale=0;
        for (var i=0;i<aCart.length;i++) {
            if (aCart[i].nsfree==-1) {
                // unknown, look it up
                issale=0;
                pid = aCart[i].prodid;
                var issa
                for (var j=0;j<aI.length;j++) {
                    if (aI[j].prodid==pid) {
                        if (aI[j].onsale>0) {
                            issale=1;
                        }
                        break;
                    }
                }
                aCart[i].nsfree = issale;
            }
            if (aCart[i].nsfree==0) {
                // normal price
                nsi += aCart[i].fpi;
            } else {
                // sale price
                si += aCart[i].fpi;
            }
        }
        // results here are subtotals for sale and nonsale items
        // if nsi > nsfree threshold, change amt to just the sale item amount
        if (nsi>nsfree) {
            amt = si;
        }
    }
    if (shipby=="weight") {
        // get total order weight
        var totwt = getweight(-1,isvc);
    }
    var totship = 0;
    for (var i=0;i<aShip.length;i++) {
        if (aShip[i].pricecode==0) {   // note - calculate shipping - from Config - regular depending on amount
            if (shipby=="weight") {
                if (totwt >= aShip[i].low && totwt <= aShip[i].high) {
                    ship = aShip[i].cost;
                }
            } else {
                if (amt >= aShip[i].low && amt <= aShip[i].high) {
                    ship = aShip[i].cost;
                }
            }
        }
        if (aShip[i].pricecode==1) {
            if (shipby=="weight") {
                if (totwt > aShip[i].threshold) {
                    totship += parseFloat(parseFloat(aShip[i].renewvalue).toFixed(2));
                    ship = 0;
                    totwt = totwt - parseFloat(parseFloat(aShip[i].threshold).toFixed(2));
                    i=-1;
                    continue;
                }
            } else {
                if (amt > aShip[i].threshold) {
                    var multip = parseFloat(parseFloat(aShip[i].multiplier).toFixed(2));
                    ship = (amt * multip);
                    ship = parseFloat(parseFloat(ship).toFixed(2));
                    break;
                }
            }
        }
    }
    ship = parseFloat(parseFloat(totship + ship).toFixed(2));
    if (xprs) {
        if (xprs>0) {
            for (var i=0;i<aShip.length;i++) { 
		  if (xprs==1 && aShip[i].pricecode==2) { // Express 3 days
                    ship += aShip[i].express3;
                    break;
                  }
		  if (xprs==2 && aShip[i].pricecode==5) { // Express 2 days
                    ship += aShip[i].express2;
                    break;
                  }
		  if (xprs==3 && aShip[i].pricecode==6) { // Express 3 days
                    ship += aShip[i].express1;
                    break;
                  }                                    
            }
        }
    }
    if (destination) {
        for (var i=0;i<aShip.length;i++) {
            if (aShip[i].pricecode==3) {
            }
            if (aShip[i].pricecode==3 && aShip[i].destinations.indexOf(destination) >= 0) {
                ship += aShip[i].addon;
                break;
            }
        }
    }
    return ship;
}

function shipnode() {
    this.pricecode = -1;
    this.low = 0;
    this.high = 0;
    this.cost = 0;
    this.threshold = 0;
    this.multiplier = 0;
    this.express1= 0;
    this.express2= 0;
    this.express3= 0;            
    this.addon = 0;
    this.destinations = 0;
    this.nsfree = 0;
    this.renew = 0;
    this.renewvalue=0;
}

function jtest(idx) {
//  if (idx < aI.length) {
        window.status = "Go to product";
//  }
}

