var order = new Object(); // object to store order in
var root  = new Object();  // selection criteria
var on    = true;
var off   = false;
var cntr    = 0;           // items in object
var shpr    = 0;           	// what to charge for shipping;
var stxt    = "UPS Ground";  // shipping text
var tpos  = -1;            	// tax position selector
var tfull=0;								// full price accumulator
var	tdsc=0;									// discount price accumulator
var tdif=0;									// total price difference
var	twgt=0;  								// total weight
var oldtfull=0;							// last full price
var oldtdsc=0;							// last discount price
var oldtwgt=0;							// last total weight

var tMKF=0;									// total modules, kits
var tMKA=0;									// total modules, assembled
var tPS03=0;								// total PS03s
var tCH01KF=0;							// total CH01KFs
var tCH01KA=0;							// total CH01KAs
var	tKFcombo=0;							// total complete kits
var tKAcombo=0;							// total complete assembled

var	tA12=0;									// total A12s
var	tJ99=0;									// total J99s
var tT15=0;									// total T15s
var	tSC10=0;								// total SC10s
var	tSC25=0;								// total SC25s
var	tSC99=0;								// total SC99s
var tA12SC10Combo=0;				// total A12/SC10 combos
var tA12SC25Combo=0;				// total A12/SC25 combos
var tJ99SC99Combo=0;				// total J99/SC99 combos

var tWH01=0;								// total WH01s
var tCHKF_WHcombo=0;				// total CH01KF/WH01KA combos
var tCHKA_WHcombo=0;				// total CH01KA/WH01KA combos
var tT15KFcombo=0;					// total T15/complete kit combos

root.shp  = on;    	// shipping selection line
root.tax  = off;    // tax selection line
// place for user-specific options
root.xx_can  = ""; // place for PayPal cancel return path
root.xx_cur  = ""; // enter default currency code (or null)
root.xx_id   = ""; // PayPal ID
root.xx_img  = ""; // image URL
root.xx_lc   = ""; // 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 CalcRoot () {  // calc root stuff
  if (root.tax) tpos=0;
}


function Dollar (val) {     // force to valid dollar amount
	var str,pos,rnd=0,neg=0;
  
	if (val < 0) {
    val = -val;
		neg = 1;
  }
  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);
  if (neg == 1) str = "-" + str;
	if (str == ".00") str = "0" + str;
  return str;               // return valid string
}


function CalcTotals () { 	// calculate totals
	var i,d,q;
  q = 0.0;
  d = "";
	oldtfull=tfull;
	oldtdsc=tdsc;
	oldtwgt=twgt;
  tfull=0,tdsc=0,twgt=0;	// clear some totals
  for (i in order) { 			// calc totals we might use
    q = order[i].qty * 1.0;
    tfull = tfull + order[i].full * q;
    q = order[i].dsc * 1.0;
    tdsc = tdsc + order[i].disc * q;
	  q = order[i].qty * 1.0 + order[i].dsc * 1.0;
    twgt = twgt + order[i].wgt * q;
	}
}


function NewTotals(){ // returns true if totals have changed
	if(oldtfull != tfull) return true;
	if(oldtdsc != tdsc) return true;
	if(oldtwgt != twgt) return true;
	return false;
}


function CheckDiscs () { // check for discount combos
	var i,d,q;
  
	q = 0.0;
  d = "";
	tMKF=0;									// total modules, kits
	tMKA=0;									// total modules, assembled
	tPS03=0;								// total PS03s
	tCH01KF=0;							// total CH01KFs
	tCH01KA=0;							// total CH01KAs
	tKFcombo=0;							// total complete kits
	tKAcombo=0;							// total complete assembled
	tA12=0;									// total A12s
	tJ99=0;									// total J99s
	tT15=0;									// total T15s
	tSC10=0;								// total SC10s
	tSC25=0;								// total SC25s
	tSC99=0;								// total SC99s
	tA12SC10Combo=0;				// total A12/SC10 combos
	tA12SC25Combo=0;				// total A12/SC25 combos
	tJ99SC99Combo=0;				// total J99/SC99 combos
	tWH01=0;								// total WH01s
	tCHKF_WHcombo=0;				// total CH01KF/WH01KA combos
	tCHKA_WHcombo=0;				// total CH01KA/WH01KA combos
	tT15KFcombo=0;					// total T15/complete kit combos

  for (i in order) { 			// calc totals we might use
	  q = order[i].qty * 1.0 + order[i].dsc * 1.0;
    if (q > 0) {
		  d = order[i].des;
		  if (d == "A12KA" || d == "A12KF") 
		    tA12 = tA12 + q;
		  if (d == "J99KA" || d == "J99KF") 
		    tJ99 = tJ99 + q;
		  if (d == "T15KF") 
		    tT15 = tT15 + q;
		  if (d == "SC10KA") 
		    tSC10 = tSC10 + q;
		  if (d == "SC25KA") 
		    tSC25 = tSC25 + q;
		  if (d == "SC99KA") 
		    tSC99 = tSC99 + q;
		  if (d == "A12KA" || d == "C84KA" || d == "J99KA" || d == "N72KA" || d == "T15KA") 
		    tMKA = tMKA + q;
		  if (d == "A12KF" || d == "C84KF" || d == "J99KF" || d == "N72KF" || d == "T15KF") 
		    tMKF = tMKF + q;
		  if (d == "PS03KA") 
		    tPS03 = tPS03 + q;
		  if (d == "CH01KF")
		    tCH01KF = tCH01KF + q;
		  if (d == "CH01KA")
		    tCH01KA = tCH01KA + q;
		  if (d == "WH01KA") 
		    tWH01 = tWH01 + q;
		}
	}

	sPackingCost = 0;
	if ((tCH01KA + tCH01KF) > 0){ // big box
		sShipToLength = "24";
		sShipToWidth = "12";
		sShipToHeight = "6";
		sPackingCost = sBigBox * 1.0;
	}
	else if ((tMKF + tMKA) > 2){ // medium box
		sShipToLength = "14";
		sShipToWidth = "10";
		sShipToHeight = "10";
		sPackingCost = sMedBox * 1.0;
	}
	else{
		sShipToLength = "12";
		sShipToWidth = "9";
		sShipToHeight = "6";
		sPackingCost = sSmallBox * 1.0;
	}
		
  if ((tCH01KA + tCH01KF) > 0 && tPS03 > 0 && (tMKA + tMKF) > 0 && tWH01 > 0) { // at least 1 complete kit
	 	tKAcombo = Math.min(tCH01KA, tPS03);	// find number of complete preamps
		tKAcombo = Math.min(tKAcombo, tMKA);
		tKAcombo = Math.min(tKAcombo, tWH01);
		tPS03 = tPS03 - tKAcombo;
		tMKA = tMKA - tKAcombo;
	
	 	tKFcombo = Math.min(tCH01KF, tPS03);	// find number of complete kits
		tKFcombo = Math.min(tKFcombo, (tMKA + tMKF));
		tKFcombo = Math.min(tKFcombo, tWH01);
  }
	if (tKFcombo > 0 && tT15 > 0) {	// at least 1 T15 combo
		tT15KFcombo = Math.min(tKFcombo, tT15);	// number of T15 combos
//		alert ("tKFcombo = " + tKFcombo + '\n' + "tT15 = " + tT15 + '\n' + "tT15KFcombo = " + tT15KFcombo);
	}
  if (tA12 > 0 && tSC10 > 0) { // at least 1 A12/SC10 combo
  	tA12SC10Combo = Math.min(tA12, tSC10); // number of A12 combos
  }
  if (tA12 > 0 && tSC25 > 0) { // at least 1 A12/SC25 combo
  	tA12SC25Combo = Math.min((tA12 - tA12SC10Combo), tSC25); // number of A12 combos
  }
  if (tJ99 > 0 && tSC99 > 1) { // at least 1 J99/SC99 combo
  	tJ99SC99Combo = Math.min((2*tJ99), (Math.floor(tSC99/2)*2)); // number of J99 combos
  }
  if ((tCH01KA + tCH01KF) > 0 && tWH01 > 0) { // at least 1 CH01/WH01 combo
  	tCHKA_WHcombo = Math.min(tCH01KA, tWH01); // number of CH01KA/WH01 combos
		tWH01 = tWH01 - tCHKA_WHcombo;
  	tCHKF_WHcombo = Math.min(tCH01KF, tWH01); // number of CH01KF/WH01 combos
  }
}


function ApplyDiscs (item, num) { // Apply discounts
//	alert ("Item = " + item + '\n' + "Num = " + num);
	var d,i=0,dif=0,app=0;
	while (app < num) { // apply discounts
		for (i in order) {
			if (app == num) return;
			d = order[i].des;
			if (d == item) {
				if (order[i].qty > 0) {
					order[i].qty = order[i].qty - 1.0;
					order[i].dsc = order[i].dsc + 1.0;
					dif = order[i].full * 1.0 - order[i].disc * 1.0;
				  app = app + 1.0;
					tdif = tdif + dif * 1.0;
				}
			}
		}
	}
}


function ClearDiscs (item) { // Clear discounts
	var d,i,qty=0;
	tdif=0;
	for (i in order) {
		d = order[i].des;
		if (d == item) {
			if (order[i].dsc > 0) {
				qty = order[i].dsc * 1.0;
				order[i].qty = order[i].qty + qty;
				order[i].dsc = 0;
			}
	  }	
	}
}


function MakeOrder (id, des, full, disc, wgt) {  // handle the 'add'
	var nr,qty,dsc;
  
	nr = id.substring (2);  // get number part of ID
  qty = document.orderf["qty" + nr].value;  // get qty
  if (isNaN (qty)) {      // test entry
    alert ("That is not a valid number!  Try again.");
    return;
  }
  
	document.orderf["prc" + nr].value = Dollar (qty * full);
  document.orderf["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 ();				// (re)create entry
  order[id].des = des;							// description
  order[id].full = Dollar (full);		// full price
  order[id].disc = Dollar (disc);		// discount price
  order[id].qty = qty;							// full price quantity
	order[id].dsc = 0;								// discount quantity
  if (wgt) order[id].wgt = wgt;
  else order[id].wgt = 0;
}


function GetOrder (id, des, full, disc, wgt) {  // get all ordered items
  MakeOrder (id, des, full, disc, wgt);
	ClearDiscs ("CH01KF");
	ClearDiscs ("CH01KA");
	ClearDiscs ("PS03KA");
	ClearDiscs ("T15KF");
	ClearDiscs ("SC10KA");
	ClearDiscs ("SC25KA");
	ClearDiscs ("SC99KA");
	ClearDiscs ("WH01KA");
	CheckDiscs ();
	ApplyDiscs ("CH01KF", tKFcombo);
	ApplyDiscs ("CH01KA", tKAcombo);
	ApplyDiscs ("PS03KA", tKFcombo);
	ApplyDiscs ("PS03KA", tKAcombo);
	ApplyDiscs ("T15KF", tT15KFcombo);
	ApplyDiscs ("SC10KA", tA12SC10Combo);
	ApplyDiscs ("SC25KA", tA12SC25Combo);
	ApplyDiscs ("SC99KA", tJ99SC99Combo);
	ApplyDiscs ("WH01KA", tCHKF_WHcombo);
	ApplyDiscs ("WH01KA", tCHKA_WHcombo);
	// document.writeln("Complete kits", tcmp);
	CalcTotals ();
	if(NewTotals()){
		ResetDropdown();
		EnableCheckout();
	  EnableA12LH();
		shpr = 0;
	}
	DispTots ();
}


function SendCart () {  // send the cart to PayPal
	var winpar = "width=800,height=600,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;
		
  for (i in order) {  															// send all valid data
    if (order[i].qty > 0) {													// add full price items
      j = j + 1;
      des = order[i].des;
      if (j == 1) {  																// put in descriptions for 1st item
        des = des + ", " + stxt;
      }
      strn = strn + "&item_name_"    + j + "=" + escape (des) +
										"&quantity_"     + j + "=" + order[i].qty +
                   	"&amount_"       + j + "=" + order[i].full;
		}
				
		if (order[i].dsc > 0) {	// add discounted items
			j = j + 1;
			des = order[i].des;
			if (j == 1) {  // put in descriptions for 1st item
			  des = des + ", " + stxt;
			}
			strn = strn + "&item_name_"    + j + "=" + escape (des) +
										"&quantity_"     + j + "=" + order[i].dsc +
	                  "&amount_"       + j + "=" + order[i].disc;
		}
  } 

	if (shpr > 0) {  // there is some shipping activity
     strn = strn + "&shipping_" + j + "=" + Dollar (shpr);
//		alert ("shpr = " + shpr + '\n' + "j = " + j);
 	}

	if (EnableCheckout()) 
		window.open (strn, "paypal", winpar);
//		alert(strn);
	else {
		alert("Can't send cart, totals are not correct!");
		return false;
	}
}


function SendUPS(){
	var sShipToWgt = document.getElementById("totwgt").value;
	var sShipToZip = document.getElementById("zipcode").value;
	
	//	validate zip
	if (isNaN(sShipToZip) || sShipToZip.length != 5){
		 alert("ZIP code must be 5 digits!");
		 return false;
	}
	//	validate wgt
	if (isNaN(sShipToWgt) || sShipToWgt < 1 || sShipToWgt > 100){
		alert("Weight must be between 1 and 100");
		return false;
	}
	//	validate country
	if (sShipToCountry != "US"){
		 alert("Cart only accepts US addresses at this time");
		 return false;
	}

	GetUPSXMLRate(sShipToWgt, sShipToZip, sShipToCountry);
	return true;
}


function DispTots () {  // display totals on the page
	var d;
  d = document.orderf;
  d.sub.value = Dollar (tfull + tdsc);
  d.wgt.value = twgt;
  d.shp.value = Dollar (shpr);
  d.dsc.value = Dollar (tdif);
  d.tot.value = Dollar (tfull + tdsc + shpr);
}


function OnRateSelect(){
	var d = document.getElementById('UPSDropdown');
	if(d) {
		var rateIndex = d.selectedIndex;
		var svcName = d.options[rateIndex].text;
		var rate = d.options[rateIndex].text;
		svcName = svcName.substring(0, svcName.indexOf("$") - 2);
		rate = rate.substring(rate.indexOf("$") + 1);
		shpr = rate * 1.0;
		stxt = svcName;
		DispTots();
		EnableCheckout();
	}
}


function EnableGetRates(){
	var d = document.orderf;
	if(d.GetRates != null){
		if(ValidZip() && (twgt > 0))
			d.GetRates.disabled=false;
		else
			d.GetRates.disabled=true;
	}
}


function EnableCheckout(){
	var d = document.orderf;
  var subtotal = tfull + tdsc;
	if(ValidZip() && (d.terms.checked == true) && (subtotal > 0) && (shpr > 0) && (twgt > 0)) {
		d.Checkout.disabled=false;
		return true;
	}
	else {
		d.Checkout.disabled=true;
		return false;
	}
}


function EnableA12LH(){
	var d = document.orderf;
	if(tA12 > 0){
		d.A12L.disabled=false;
		d.A12H.disabled=false;
 }
	else {
		d.A12L.disabled=true;
  	d.A12H.disabled=true;
 }
}


function ValidZip(){	//	validate zip
	var d = document.orderf;
	if (isNaN(d.ZipCode.value) || d.ZipCode.value.length != 5)
		return false;
	else
		return true;
}


function OnZipChange(){
	var d = document.orderf;

	if(ValidZip())
		sShipToZip = d.ZipCode.value;
	else
		sShipToZip = "";

	ResetDropdown();
	EnableCheckout();
	shpr = 0;
	DispTots();
}


function ResetDropdown(){
	var txt="<input name='GetRates' type= 'button' value= 'Get UPS Rates' onclick= 'SendUPS();' />"
	if(document.getElementById('RateDropdown')){
		document.getElementById('RateDropdown').innerHTML=txt;
		shpr = 0;
		DispTots();
		EnableCheckout();
	}
}


function Reset() { // reset objects
	var d = document.orderf;

	order = null;
	cntr = 0;
	ClearDiscs ("CH01KF");
	ClearDiscs ("CH01KA");
	ClearDiscs ("PS03KA");
	ClearDiscs ("T15KF");
	ClearDiscs ("SC10KA");
	ClearDiscs ("SC25KA");
	ClearDiscs ("SC99KA");
	ClearDiscs ("WH01KA");
	CalcTotals ();
	ResetDropdown();
	EnableCheckout();
 	EnableA12LH();
}


function wopen(url, name, w, h)
{
  // Fudge factors for window decoration space.
  w += 32;
  h += 96;
  wleft = (screen.width - w) / 2;
  wtop = (screen.height - h) / 2;
  // IE5 and other old browsers might allow a window that is
  // partially offscreen or wider than the screen. Fix that.
  // (Newer browsers fix this for us, but let's be thorough.)
  if (wleft < 0) {
    w = screen.width;
    wleft = 0;
  }
  if (wtop < 0) {
    h = screen.height;
    wtop = 0;
  }
  var win = window.open(url, name,
  'width=' + w + ', height=' + h + ', ' +
  'left=' + wleft + ', top=' + wtop + ', ' +
  'location=no, locationbar=no, personalbar=no, menubar=no, ' +
  'statusbar=no, navbar=no, toolbar=no, scrollbars=no, resizable=no');
  // Just in case width and height are ignored
  win.resizeTo(w, h);
  // Just in case left and top are ignored
  win.moveTo(wleft, wtop);
  win.focus();
}


function ShowPop(s, n) { // display popup
	var popup = null;
	
	if(n > 0) {
		if(s == 'A12') {
			wopen('A12_popup.htm', '', 500, 200);
		}
		else if(s == 'J99') {
			wopen('J99_popup.htm', '', 500, 200);
		}
		else if(s == 'Terms') {
			wopen('Terms_popup.htm', '', 700, 660);
		}
	}
}