//Make sure that whatever is in the field is actually a number; throw an error if it isn't.
function ValidateNumeric(fieldname){
	if(document.getElementById(fieldname).value / document.getElementById(fieldname).value != 1){ 
		alert("Please enter a number."); 
		setTimeout("document.OrderForm." + fieldname + ".focus()", 0); 
		setTimeout("document.OrderForm." + fieldname + ".select()", 0); 
		return false;
	} 
	return true;
}


//Calculate total based on quantity desired and cost of selected shipping method.
//Promotional codes will only show up on the next page for now.
function Recalculate(){
	var shippingcost = 7.99;
	var unitprice = 29.99;
	var total = 0;
	
	//Sanitize quantity input
	if(document.getElementById("quantity").value > 4){ 
		alert("Sorry, but to preserve freshness and quality, we only sell up to four months' supply at a time.");
		document.getElementById("quantity").value = 4;
	}
	
	//find shipping price
	switch(document.getElementById("shipping_method").value){
		case("UPS"):	{ shippingcost=8.99; break; }
		case("UP2"):	{ shippingcost=19.99; break; }
		case("PMD"):	{ shippingcost=5.99; break; }
		default: { shippingcost=7.99; break;}
	}
	
	//recalculate the subtotal, ignoring shipping if if >50.		
	var subtotal = document.getElementById("quantity").value * unitprice;
	document.getElementById("subtotal").innerHTML= "$" + subtotal;
	
	if(subtotal>50) {
		document.getElementById("shippingcost").innerHTML = "Free!";
		document.getElementById("shippingmessage").innerHTML = "Shipping";
		document.getElementById("total").innerHTML = document.getElementById("subtotal").innerHTML;
	}
	else {
		document.getElementById("shippingcost").innerHTML = "$" + shippingcost;				
		document.getElementById("shippingmessage").innerHTML = "Shipping (Add 1 more bottle for free standard shipping!)";
		total = shippingcost + subtotal;
		document.getElementById("total").innerHTML = "$" + total.toFixed(2); 
	}			
}


//Show/Hide the ship to box.  Default is off, since most people will ship to billing address most of the time.
function ToggleShippingAddressBox(checkbox){
	if(checkbox.checked==true){ document.getElementById("ShippingAddressBox").style.display="none" }
	else{ document.getElementById("ShippingAddressBox").style.display="block"; }			
}



//No need to write another email validation function; it's already in scripts.js because the out of stock page uses it too.  
//Here it is for reference:
/*
	function ValidateEmail(elem){
		var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
		return elem.value.match(emailExp));	//will be true if it matched; false otherwise.
	}
*/

//Validate the credit card they entered.  
function ValidateCreditCard(type, ccnum) {
	var checksum = 0;

	switch(type){
		case("visa"):{
			// Visa: length 16, prefix 4, dashes optional.
			var cc_num_regex = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
			break;
		}
		case("mc"):{
			// Mastercard: length 16, prefix 51-55, dashes optional.
			var cc_num_regex = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;		
			break;
		}
		case("amex"):{		
			// American Express: length 15, prefix 34 or 37.
			var cc_num_regex = /^3[4,7]\d{13}$/;
			break;
		}
		case("discover"):{
			// Discover: length 16, prefix 6011, dashes optional.
			var cc_num_regex = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
			break;
		}
	}
	
	//if it's doesn't matched one of these regexes, it's no good; give up.  Otherwise, do the checksum tests etc.
	if(!ccnum.match(cc_num_regex)) return false;
		
	// Remove all dashes for the checksum checks to eliminate negative numbers
	ccnum = ccnum.split("-").join("");
	
	// Checksum (Mod 10) - Add even digits in even length strings or odd digits in odd length strings.
	for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) { checksum += parseInt(ccnum.charAt(i-1)); }
	
	// Analyze odd digits in even length strings or even digits in odd length strings.
	for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
		var digit = parseInt(ccnum.charAt(i-1)) * 2;
		if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
	}
	if ((checksum % 10) == 0) return true; else return false;
}





//Validate the ZIP code
function ValidateZIP(candidate){
//	var zipExp = /^\d{5}([\-]\d{4})?$/;
	var zipExp = /[0-9]{5}([-][0-9]{4})?$/;
	return candidate.match(zipExp);
}

//Double check whatever's left and if everything looks good, go ahead.
function ValidateOrder(){ 
	var valid = true;
	
//		if(!ValidateHowDidYouHear(document.getElementById("how"))){
//		document.getElementById("how").style.backgroundColor="#CB2525";
//		valid=false;
//	}
		
	if(!ValidateEmail(document.getElementById("email"))){
		document.getElementById("email").style.backgroundColor="#CB2525";
		valid=false;
	}
	
	if(!ValidateCreditCard(document.getElementById("cc_type").value, document.getElementById("cc_number").value)){
		document.getElementById("cc_number").style.backgroundColor="#CB2525";
		valid=false;
	}
	
	if(document.getElementById("cc_type").value==""){
		document.getElementById("cc_type").style.backgroundColor="#CB2525";
		valid=false;
	}
	
	if(document.getElementById("cc_number").value==""){
		document.getElementById("cc_number").style.backgroundColor="#CB2525";
		valid=false;
	}
		
	if(document.getElementById("cc_cvv2").value / document.getElementById("cc_cvv2").value != 1){
		document.getElementById("cc_cvv2").style.backgroundColor="#CB2525";
		valid=false;	
	}
	
	if(document.getElementById("cc_exp_month").value==""){
		document.getElementById("cc_exp_month").style.backgroundColor="#CB2525";
		valid=false;
	}
	
	if(document.getElementById("cc_exp_year").value==""){
		document.getElementById("cc_exp_year").style.backgroundColor="#CB2525";
		valid=false;
	}

	if(document.getElementById("billing_first_name").value==""){
		document.getElementById("billing_first_name").style.backgroundColor="#CB2525";
		valid=false;
	}

	if(document.getElementById("billing_last_name").value==""){
		document.getElementById("billing_last_name").style.backgroundColor="#CB2525";
		valid=false;
	}
	
	if(document.getElementById("billing_addr_1").value==""){
		document.getElementById("billing_addr_1").style.backgroundColor="#CB2525";
		valid=false;
	}

	if(document.getElementById("billing_city").value==""){
		document.getElementById("billing_city").style.backgroundColor="#CB2525";
		valid=false;
	}

	if(document.getElementById("billing_state").value==""){
		document.getElementById("billing_state").style.backgroundColor="#CB2525";
		valid=false;
	}
	
	if(!ValidateZIP(document.getElementById("billing_zip").value)){
		document.getElementById("billing_zip").style.backgroundColor="#CB2525";
		valid=false;
	}		
	
	//Same process as above, but for the rest, we'll only check them if the clone-address box is unticked.
	if((document.getElementById("clone_address").checked==false)&&(document.getElementById("shipping_first_name").value=="")){
		document.getElementById("shipping_first_name").style.backgroundColor="#CB2525";
		valid=false;
	}

	if((document.getElementById("clone_address").checked==false)&&(document.getElementById("shipping_last_name").value=="")){
		document.getElementById("shipping_last_name").style.backgroundColor="#CB2525";
		valid=false;
	}
	
	if((document.getElementById("clone_address").checked==false)&&(document.getElementById("shipping_addr_1").value=="")){
		document.getElementById("shipping_addr_1").style.backgroundColor="#CB2525";
		valid=false;
	}

	if((document.getElementById("clone_address").checked==false)&&(document.getElementById("shipping_city").value=="")){
		document.getElementById("shipping_city").style.backgroundColor="#CB2525";
		valid=false;
	}

	if((document.getElementById("clone_address").checked==false)&&(document.getElementById("shipping_state").value=="")){
		document.getElementById("shipping_state").style.backgroundColor="#CB2525";
		valid=false;
	}
	
	if((document.getElementById("clone_address").checked==false)&&(!ValidateZIP(document.getElementById("shipping_zip").value))){
		document.getElementById("shipping_zip").style.backgroundColor="#CB2525";
		valid=false;
	}
	
	//check to make sure they told us how they got here 
	if((document.getElementById("how").value=="none")){
		document.getElementById("how").style.backgroundColor="#CB2525";
		valid=false;
	}

	//check to make sure they told us whether we can email them
	if((document.OrderForm.emailme[0].checked==false) && (document.OrderForm.emailme[1].checked==false)){
		document.getElementById("emailbuttonyes").style.backgroundColor="#CB2525";
		document.getElementById("emailbuttonno").style.backgroundColor="#CB2525";
		valid=false;
	}

	if(!valid){ alert("Please correct the errors in the form before continuing."); }
	
	return valid; 
}

//Self-explanatory.
function LaunchWindow(url){window.open(url, 'open_window', 'status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0'); }