
function checkPromoForEnter (event) {
    if(event.keyCode == Event.KEY_RETURN) {
			SubmitForm($('btn_updatetotal'), 'add_promo');
        // stop processing the event
        Event.stop(event);
        return false;
    }
}

// I encountered odd bugs using prototype's Ajax.replace
// thus I gave up and wrote this javascript to directly
// create the elements

function replaceSummary(response) {
	
	if (response.search(/|/) != -1) {
		if (response.search(/ERROR/) != -1) {
			var source = document.getElementById('shippingoptionsinner');							   
			/* new page fragment */
			var fragment= document.createDocumentFragment();

			var dv1 = document.createElement("div");
			dv1.name = "shippingoptionsinner";
			dv1.id = "shippingoptionsinner";


			var d = errorMessage();
			fragment.appendChild(dv1);
			dv1.appendChild(d);

			browserSafeReplace(source, fragment);
		} 

		// subtotal|tax|shipping_service|rush_code|shipping_cost|total
		var names = { "subtotal":0, "tax": 1, "shipping_service":2, "rush_code":3, "shipping_cost":4, "total":5};							   
		var dispnames = { 0:"Subtotal:", 1:"Tax:", 2:"", 3:"", 4:"Shipping:", 5:"Total:"};
		var totals = safeSplit("|", response);

		if (doesSummaryContainRushCodeError(response)) {
			setFormResponse(totals[6]);
			scroll(0,0);
			
			return;
		}

		// ignore the last item passed back from the AJAX call
		// TODO: make this better, this sucks
		var ignorevalues = 1;

		for (i = 0;i < totals.length - ignorevalues;i++) {
			// dont print shipping service or rush_code
			if (i == 2 || i == 3) {
				continue;
			}

			var source = document.getElementById('moneysummary' + i);
			var fragment = document.createDocumentFragment();

			var tr = document.createElement("tr");
			tr.name = 'moneysummary' + i;
			tr.id = 'moneysummary' + i;

			// colspan td
			var td = document.createElement("td");
			td.colSpan = 2;
			
			// show EXEMPT for tax_exempt orders 
			if ((i == 1) && (document.getElementById('tax_exempt_order'))) {
				if (document.getElementById('tax_exempt_order').checked) {
					var dv = document.createElement("div");
					dv.style.textAlign = "right";
					dv.appendChild(document.createTextNode("EXEMPT"));
					td.appendChild(dv); 
				}
				else {
					td.appendChild(document.createTextNode("\u00A0")); // &nbsp
				} 
			
			}
			// show shipping type and rush code next to shipping cost
			else if (i == 4) {
				var dv = document.createElement("div");
				dv.style.textAlign = "right";
				dv.appendChild(document.createTextNode(totals[2] + " " + totals[3])); 
				td.appendChild(dv); 
			} else {
				td.appendChild(document.createTextNode("\u00A0")); // &nbsp
			}
			tr.appendChild(td);

			// header td
			try { // another stupid IE workaround
				td = document.createElement("<td class=\"subheader\">");
			} catch (err) {
				td = document.createElement("td");
				td.setAttribute("class", "subheader");
			}
			
			td.appendChild(document.createTextNode(dispnames[i]));
			tr.appendChild(td);

			// item data
			try { // another stupid IE workaround
				td = document.createElement("<td class=\"money\">");
			} catch (err) {
				td = document.createElement("td");
				td.setAttribute("class", "money");
			}			

			// handle error shipping amounts
			if (totals[i].search(/Unknown/) != -1) {
				td.appendChild(document.createTextNode(totals[i]));
			} else {
				td.appendChild(document.createTextNode('$' + totals[i]));
			}
			
			tr.appendChild(td);


			fragment.appendChild(tr);


			browserSafeReplace(source, fragment);
		}

	} else {
		alertAjaxError();
	}


}

function updateMoneySummary() {
	var url    = 'set_shipping_option.php';

	new Ajax.Request(
		url,
		{
			method:'get',
			onFailure: function(){ alertAjaxError(); },
			onSuccess: function(transport) {
						   var response = transport.responseText;
						   replaceSummary(response);

						}
			
		}
	);


}

function setRushCode(rushcode, chkBoxEl, uncheckOthersList) {
	// get the check state of the element that got us here
	var chk = document.getElementById(chkBoxEl);


	// standard shipping cannot be unchecked if it was last checked
	if (rushcode == '0') {
		if (!chk.checked) {
			chk.checked = true;
			return;
		}
	} else {
		
	}


	hideDiv(document.getElementById('shippingoptionsinner')); 
	showDiv(document.getElementById('spinner')); 

	// uncheck all the other rush options
	var chklist = uncheckOthersList.split(',');
	var i = 0;
	for (i = 0; i < chklist.length;i++) {
		var itm = document.getElementById(chklist[i]);
		itm.checked = false;
	}

	// check standard if we unchecked a rush option
	if (!chk.checked) {
		var std = document.getElementById('standard');
		std.checked = true;
	}

	var url    = 'set_shipping_option.php';
	if (chk.checked) {
		var pars   = 'rushcode=' + rushcode;
	} else {
		var pars   = 'unsetrushcode=1';
	}

	pars += cacheBuster();
	
	var myAjax = new Ajax.Request(
		url,
		{
			method:'get',
			parameters:pars,
			onFailure: function(){ alertAjaxError(); },
			onSuccess: function(transport) {
				var response = transport.responseText;
				replaceSummary(response);

				if (!doesSummaryContainRushCodeError(response)) {
					// update the shipping options on a timer
					setTimeout("updateShippingOptions(true)", 1);
				} else {
					// uncheck this checkbox
					chk.checked = false;

					// restore the existing options 
					hideDiv(document.getElementById('spinner')); 
					showDiv(document.getElementById('shippingoptionsinner')); 
				}
			}
		}
	);
}

function doesSummaryContainRushCodeError(response) {
	if (response.search(/|/) != -1) {
		var totals = safeSplit("|", response);

		// if the 6th field is not empty, then we were denied setting the rushcode we requested
		if (totals[6].length > 0) {			
			return true;
		}
	}

	return false;

}


function setShippingType(shippingcode) {
	var url    = 'set_shipping_option.php';
	var pars   = 'shippingcode=' + shippingcode + cacheBuster(); 
	var myAjax = new Ajax.Request(
		url,
		{
			method:'get',
			parameters:pars,
			onFailure: function(){ alertAjaxError(); },
			onSuccess: function(transport) {
				var response = transport.responseText;
				replaceSummary(response);
			}

		}
	);
}

function setTaxExemptOrder(tax_exempt_param) {
	var url    = 'set_tax_exempt_order.php';
	var pars   = 'tax_exempt_order=' + tax_exempt_param + cacheBuster(); 
	var myAjax = new Ajax.Request(
		url,
		{
			method:'get',
			parameters:pars,
			onFailure: function(){ alertAjaxError(); },
			onSuccess: function(transport) {
				var response = transport.responseText;
				replaceSummary(response);
			}

		}
	);
}

function setShippingDestination(destcode) {
	var url    = 'calc_shipping_prices.php';
	var pars   = 'candidateNumber=' + destcode + cacheBuster(); 

	// save this new value into the hidden field so it can be passed on as needed
	document.getElementById('candidateNumber').value = destcode;
	var myAjax = new Ajax.Request(
		url,
		{
			method:'get',
			parameters:pars,
			onFailure: function(){ alertAjaxError(); },
			onSuccess: function(transport) {
				var response = transport.responseText;
				replaceShippingOptions(response);
			}

		}
	);
}


function errorMessage() {
	var d  = document.createElement("div");
	d.id = "errors";
	d.name = "errors";

	var p  = document.createElement("p");
	var warntext = "ERROR contacting UPS, please resubmit by ";
	var t = document.createTextNode(warntext);
	p.style.fontWeight = 'bold';
	p.appendChild(t);
	

	// retry link
	var a = document.createElement("a");
	a.innerHTML = 'clicking here';
	a.onclick = function() {document.getElementById('candidateNumber').value = 0; updateShippingOptions(true);}; 
	p.appendChild(a);

	d.appendChild(p);	
	
	return d;

}


function replaceShippingOptions(response) {
	

	shipArray = safeSplit(";", response);

	if (response.search(/|/) != -1) {

		var source = document.getElementById('shippingoptionsinner');
		/* new page fragment */
		var fragment= document.createDocumentFragment();

		var dv1 = document.createElement("div");
		dv1.name = "shippingoptionsinner";
		dv1.id = "shippingoptionsinner";

		if (response.search(/ERROR/) != -1) {
			var d = errorMessage();
			dv1.appendChild(d);
		}


		var ulist = document.createElement("ul");
		ulist.style.listStyleType = "none";

		// TODO: handle undefined results?
		var i=0;

		// search for a preset shipping type
		var shippingSet = false;							   
		for (i = 0;i < shipArray.length;i++) {
			var shiptype = safeSplit("|", shipArray[i]);
			if (shiptype[5] == "Y") {
				shippingSet = true;
			}
		}

		for (i = 0;i < shipArray.length;i++) {
			var shiptype = safeSplit("|", shipArray[i]);

			// only show guaranteed items
			if (shiptype[4] == "Y") {
				var li = document.createElement("li");



				// Having the space in the name messes up the javascript magic, so we get rid of it for now

				if (shiptype[0] == "Pick Up") {
					shiptype[0] = "PickUp";
				} 

				var chkname = "shipoptions";
				var chkid = "ship" + shiptype[0];

				var chk;
				try {
					var chktxt = "";
					if ((shippingSet && shiptype[5] == "Y") || (!shippingSet && shiptype[0] == "03")) {
						chktxt = "Checked"
					}
					var chkel = '<input id="' + chkid + '" name="' + chkname 
						+ '" type="radio" onclick="setShippingType(\'' 
						+ shiptype[0] + '\');" ' + chktxt + '/>';
					// This is the only way you can set the "name" attribute in IE, but it will fail in other browsers
					chk = document.createElement(chkel);
				 } catch(err) {
					 // The above will fail if not in IE, so try it the correct way here
					 chk = document.createElement('input');
					 chk.id = chkid;
					 chk.name = chkname;
					 chk.type = 'radio';
					 chk.onclick = new Function("setShippingType('" + shiptype[0] + "')");
				}



				// set the checked option for the selected shipping type or ground otherwise
				if ((shippingSet && shiptype[5] == "Y") || (!shippingSet && shiptype[0] == "03")) {
					chk.checked = true;


					// set the shipping that is stored in the cart in the case of setting the default
					if (!shippingSet && shiptype[0] == "03") {
						setTimeout("setShippingType('03')", 1);
					}
				} 

				var chktext = "$" + shiptype[2] + " - " + shiptype[1] + "; get it by " + shiptype[3];
				if (shiptype[2] <= 0.004) {
					chktext = "FREE" + " - " + shiptype[1] + "; get it by " + shiptype[3];
				}
				if (shipArray[i].search(/ERROR/) != -1) {
					chktext = shiptype[1] + " - UPS Quote Unavailable";
				}

				if (typeof(BUYIT_DEBUG) != "undefined" && BUYIT_DEBUG) {
					chktext = chktext + " (G:" + shiptype[4] + ")"; 
				}

				
				li.appendChild(chk);
				var ct = document.createTextNode(chktext);
				// bold Ground shipping
				if (shiptype[0] == "03") {
					var bold = document.createElement("b");
					bold.appendChild(ct);
					//ct.style.fontWeight = 'bold';
					li.appendChild(bold);
				} else {
					li.appendChild(ct);
				}

				 /* put paragraph in page fragment */
				ulist.appendChild(li);

			}
		}
		dv1.appendChild(ulist);
		fragment.appendChild(dv1);

		browserSafeReplace(source, fragment);							  
	} else {
		alertAjaxError();
	}


}


function chooseDestination(response) {
	destArray = safeSplit(";", response);

	if (response.search(/|/) != -1) {

		var source = document.getElementById('shippingoptionsinner');
		/* new page fragment */
		var fragment= document.createDocumentFragment();

		var dv1 = document.createElement("div");
		dv1.name = "shippingoptionsinner";
		dv1.id = "shippingoptionsinner";

		if (response.search(/ERROR/) != -1) {
			var d = errorMessage();
			dv1.appendChild(d);
		}


		var p1 = document.createElement("p");
		p1.appendChild(document.createTextNode("Please select your shipping location from the following list:"));
		p1.style.fontWeight = 'bold';
		dv1.appendChild(p1);

		var ulist = document.createElement("ul");
		ulist.style.listStyleType = "none";

		// TODO: handle undefined results?
		var i=0;


		for (i = 0;i < destArray.length;i++) {
			var dest = safeSplit("|", destArray[i]);
			var li = document.createElement("li");


			var chkname = "shipoptions";
			var chkid = "ship" + dest[0];

			var chk;
			try {
				var chkel = '<input id="' + chkid + '" name="' + chkname 
					+ '" type="radio" onclick="setShippingDestination(\'' 
					+ dest[0] + '\');" />';
				// This is the only way you can set the "name" attribute in IE, but it will fail in other browsers
				chk = document.createElement(chkel);
			 } catch(err) {
				 // The above will fail if not in IE, so try it the correct way here
				 chk = document.createElement('input');
				 chk.id = chkid;
				 chk.name = chkname;
				 chk.type = 'radio';
				 chk.onclick = new Function("setShippingDestination('" + dest[0] + "')");
			}


			// only show one zipcode normally, unless we actually got back more than one
			var ziptext;
			if (dest[4] == dest[5]) {
				ziptext = dest[4];
			} else {
				ziptext = dest[4] + " - " + dest[5];
			}
			 			
			var chktext = dest[2] + ", " + dest[3] + " " + ziptext;

			/* new paragraph */
			//var para= document.createElement("p");
			li.appendChild(chk);
			//li.appendChild(chktext);
			li.appendChild(document.createTextNode(chktext));

			 /* put paragraph in page fragment */
			ulist.appendChild(li);
			
		}
		dv1.appendChild(ulist);
		
		fragment.appendChild(dv1);

		browserSafeReplace(source, fragment);							  
	} else {
		alertAjaxError();
	}

}

// TODO: get back a JSON object instead of rolling our own - I don't think the current installed version of prototype does this however
function updateShippingOptions(showAlert) {
	// normal parameters
	var destZip = document.getElementById('destination_zipcode').value;
	var candidateNumber = document.getElementById('candidateNumber').value

	if (destZip.length < 1 || destZip.length > 10) {
		if (showAlert) { alert("Zipcode format is incorrect"); }
		return;
	}


	hideDiv(document.getElementById('shippingoptionsinner')); 
	showDiv(document.getElementById('spinner')); 



	// debug parameters
	var debugpars = '';
	if (typeof(BUYIT_DEBUG) != "undefined" && BUYIT_DEBUG) {
		var today = document.getElementById('todays_date').value;
		var weight = document.getElementById('package_weight').value;
		var valuedollars = document.getElementById('package_value').value;

		debugpars =	"&todaysdate=" + today
					 + "&pkgweight=" + weight
					 + "&pkgvalue=" + valuedollars;
	}

	var url    = 'calc_shipping_prices.php';
	var pars   = 'zip=' + destZip + '&candidateNumber=' + candidateNumber + cacheBuster() + debugpars;

	new Ajax.Request(
		url,
		{
			method:'get',
			parameters: pars,
			onFailure: function(){ alertAjaxError(); },
			onSuccess: function(transport) {
						   var response = transport.responseText;
						   // if we got back a choose in the response, we need to show the user the possible destinations instead
						   if (response.search(/CHOOSE/) != -1) {
							   chooseDestination(response);
						   } else {
							   replaceShippingOptions(response);
						   }
						   
						   hideDiv(document.getElementById('spinner'));			   
						   showDiv(document.getElementById('shippingoptionsinner')); 
						}
			
		}
	);
}


