// Year validation
function validateYear(field) {
	var yearlength=4
	if (!(field.value.length == yearlength) && !(field.value.length==0)) {
		alert("The year must be entered in as 4 digits.");
		field.focus();
		field.select();
	}
}

// Year validation
function validatePasswordLength(field) {
	var minlength=5
	if (!(field.value.length >= minlength) && !(field.value.length==0)) {
		alert("Passwords must be at least 5 characters long.");
		field.focus();
		field.select();
	}
}

// Validation of a number range
function validateNumRange(field,minNum,maxNum,nullField) {
	if (field.value == "" && nullField == 0) {
		alert("Please enter a whole number between " + minNum + " and " + maxNum + ".");
		field.select();
		field.focus();
	}
	else if (!(field.value =="") && (isNaN(field.value) || field.value < minNum || field.value > maxNum || field.value.indexOf('.') != -1)) {
		alert("Please enter a whole number between " + minNum + " and " + maxNum + ".");
		field.select();
		field.focus();
	}
}

// Validation of a number value
function validateNum(field) {
	if (isNaN(field.value) || field.value == "" || field.value.indexOf('.') == -1) {
		alert("Please enter whole numbers only.");
		field.select();
		field.focus();
	}
}

// Validation of a currency entry
function validateCurrency(field,nullField) {
	if (field.value != "" || nullField==0) {
		num = field.value;
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num)) {
			num = "0";
			alert("You have entered an invalid amount. Please enter the value in dollars and cents.");
		}
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
		cents = "0" + cents;
		field.value = num + "." + cents;
	}
}

// Validation of a currency entry
function validateCurrency3(field,nullField) {
	if (field.value != "" || nullField==0) {
		num = field.value;
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num)) {
			num = "0";
			alert("You have entered an invalid amount. Please enter the value in dollars and cents.");
		}
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*1000+0.50000000001);
		cents = num%1000;
		num = Math.floor(num/1000).toString();
		if(cents<100) cents = "00" + cents;
		else if (cents<10) cents = "0" + cents;
		field.value = num + "." + cents;
	}
}

// Validation of a decimal entry
function validateDecimal(field) {
	num = field.value;
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) {
		num = "0";
		alert("You have entered an invalid amount. Please enter a numeric value, rounded off to 2 decimal places.");
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	field.value = num + "." + cents;
}


function validateEmail(field) {
	var emailStr = field.value;
	/* The following pattern is used to check if the entered e-mail address
	   fits the user@domain format.  It also is used to separate the username
	   from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	   characters.  We don't want to allow special characters in the address. 
	   These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a 
	   username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	   which case, there are no rules about which characters are allowed
	   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	   is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	   e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	   non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	   For example, in john.doe@somewhere.com, john and doe are words.
	   Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	   domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	/*  The following variable determines the message received by the user if the e-mail address isn't valid */
	var errorMsg = "This doesn't appear to be a valid e-mail address."
	var emailError = 0;

	/* Finally, let's start trying to figure out if the supplied address is
	   valid. */

	/* Begin with the coarse pattern to simply break up user@domain into
	   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	  /* Too many/few @'s or something; basically, this address doesn't
	     even fit the general mould of a valid e-mail address. */
		// Email address seems incorrect (check @ and .'s)
		emailError = 1;
	} else {
		var user=matchArray[1]
		var domain=matchArray[2]

		// See if "user" is valid 
		if (user.match(userPat)==null) {
		    // The username doesn't seem to be valid.
			emailError = 1;
		}

		/* if the e-mail address is at an IP address (as opposed to a symbolic
		   host name) make sure the IP address is valid. */
		var IPArray=domain.match(ipDomainPat)
		if (IPArray!=null) {
		    // this is an IP address
			  for (var i=1;i<=4;i++) {
			    if (IPArray[i]>255) {
					// Destimation IP address is invalid
					emailError = 1;
			    }
		    }
		}
	
		// Domain is symbolic name
		var domainArray=domain.match(domainPat)
		if (domainArray==null) {
			// The domain name doesn't seem to be valid
			emailError = 1;
		}
	
		/* domain name seems valid, but now make sure that it ends in a
		   three-letter word (like com, edu, gov) or a two-letter word,
		   representing country (uk, nl), and that there's a hostname preceding 
		   the domain or country. */
	
		/* Now we need to break up the domain to get a count of how many atoms
		   it consists of. */
		var atomPat=new RegExp(atom,"g")
		var domArr=domain.match(atomPat)
		var len=domArr.length
		if (domArr[domArr.length-1].length<2 || 
		    domArr[domArr.length-1].length>4) {
			// the address must end in a two to four letter word, or two letter country.
			emailError = 1;
		}
		
		// Make sure there's a host name preceding the domain.
		if (len<2) {
			// This address is missing a hostname
			emailError = 1;
		}
	}
	if (emailError==1) {
		alert(errorMsg);
		field.select();
		field.focus();
	}
	// If we've gotten this far, everything's valid!
}

function requiredField(field,alertMsg,ifFocus) {
	if (!(field.value)) {
		alert(alertMsg);
		if (ifFocus == 1) field.focus();
		return false;
	} else return true;
}

function trim(variable) { 
	var strText = variable + ""
    // this will get rid of leading spaces 
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    // this will get rid of trailing spaces 
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
}

// Function for click confirmation
function clickConfirm(theMessage) {
	if (confirm(theMessage)) return true;
	else return false;
}

// Validates a password entry
function validatePassword(form) {
	if (form) {
		if (form.Password && form.VerifyPass) {
			var minlength = 5;
			if (form.Password.value != form.VerifyPass.value) {
				alert("Password fields do not match.");
				form.Password.focus();
				form.Password.select();			
				return false;
			} else if (form.Password.value == "") {
				alert("You cannot have an empty password.");
				form.Password.focus();
				form.Password.select();			
				return false;
			} else if (form.Password.value.length < minlength) {
				alert("Your password must be a minimum of 5 characters in length.");
				form.Password.focus();
				form.Password.select();			
				return false;
			} else return true;
		} else return true;
	} else return true;
}

// Opens a popup menu with images
function viewImages(id, type) {
	window.open('images.php?id=' + id + '&type=' + type,'images','top=50,left=50,width=750,height=500,status=yes,resizable=yes,scrollbars=yes');
}

// Checks the e-mail address entry to see if it has changed from what it was, and alerts the user that the login will change
function validateChangedEmail(form) {
	if (form) {
		if (form.Email && form.EmailOrig) {
			if (form.Email.value == '') {
				alert('You must enter in a valid e-mail address.');
				return false;
			} else if (form.Email.value != form.EmailOrig.value) {
				if (confirm('Changing your e-mail address will change your login User ID to this site.  Be sure to make a note of this.  Do you wish to continue?')) return true;
				else return false;
			} else return true;
		} else return true;
	} else return true;
}

// Adds, removes, and changes specs on the search field
function addSearchSpec() {
	var form = document.getElementById("SearchForm");
	if (form) {
		form.e.value = 'add';
		form.submit();
	}
}
function removeSearchSpec() {
	var form = document.getElementById("SearchForm");
	if (form) {
		form.e.value = 'remove';
		form.submit();
	}
}
function changeSearchSpec() {
	var form = document.getElementById("SearchForm");
	if (form) {
		form.e.value = 'change';
		form.submit();
	}
}

// Performs a postback with the given action value
function doPost(val, form) {
	form.e.value = val;
	form.submit();
}

// Validates a quantity entered on the product detail page
function validateDetailQty(form) {
	if (form.Qty.value == '' || form.Qty.value == 0 || isNaN(form.Qty.value)) {
		alert('Please enter a valid quantity.');
		return false;
	} else return true;
}

// Validates a quantity entered/changed on the shopping card page
function validateCartQty(field,minNum,maxNum) {
	if (field.value == "" || field.value == 0) {
		alert("An empty or zero quantity value will delete the item from the cart.");
	}
	else if (!(field.value =="") && (isNaN(field.value) || field.value < minNum || field.value > maxNum || field.value.indexOf('.') != -1)) {
		alert("Please enter a whole number between " + minNum + " and " + maxNum + ".");
		field.select();
		field.focus();
	}
}

// Prompts a user for emptying the shopping cart
function emptyCart() {
	if (confirm('Are you sure you want to remove all items from your shopping cart and return to the store front?')) location.href = 'cart.php?e=delete';
}

// Sets the CSS class property of a document element
function setElementCssClass(elem_name, class_name) {
	var obj = document.getElementById(elem_name);
	if (obj) obj.className = class_name;
}

// Enables/disables fields set by selections in the checkout screen
function checkEnabledCheckoutFields(form) {
	// Set enabled Billing Address fields
	if (form.BillToSelect.length) {
		if (form.BillToSelect[0].checked) {
			form.BillTo.disabled = false;
			form.BillAddress1.disabled = true;
			form.BillAddress2.disabled = true;
			form.BillCity.disabled = true;
			form.BillState.disabled = true;
			form.BillCountry.disabled = true;
			form.BillZip.disabled = true;
			setElementCssClass('BillAddressLabel', 'light');
			setElementCssClass('BillCityLabel', 'light');
			setElementCssClass('BillStateLabel', 'light');
			setElementCssClass('BillCountryLabel', 'light');
			setElementCssClass('BillZipLabel', 'light');
		} else if (form.BillToSelect[1].checked) {
			form.BillTo.disabled = true;
			form.BillAddress1.disabled = false;
			form.BillAddress2.disabled = false;
			form.BillCity.disabled = false;
			form.BillState.disabled = false;
			form.BillCountry.disabled = false;
			form.BillZip.disabled = false;
			setElementCssClass('BillAddressLabel', '');
			setElementCssClass('BillCityLabel', '');
			setElementCssClass('BillStateLabel', '');
			setElementCssClass('BillCountryLabel', '');
			setElementCssClass('BillZipLabel', '');
		}
	}
	// Set enabled shipping address fields
	var enableShipFields = false;
	// Determine if there are existing addresses
	if (form.ShipToSelect.length == 3) enableShipFields = (form.ShipToSelect[1].checked) ? true : false;
	else enableShipFields = (form.ShipToSelect[0].checked) ? true : false;
	if (!enableShipFields) {
		// DIsable shipping fields
		if (form.ShipTo) form.ShipTo.disabled = (form.ShipToSelect[0].checked) ? false : true;
		form.ShipAddress1.disabled = true;
		form.ShipAddress2.disabled = true;
		form.ShipCity.disabled = true;
		form.ShipState.disabled = true;
		form.ShipCountry.disabled = true;
		form.ShipZip.disabled = true;
		setElementCssClass('ShipAddressLabel', 'light');
		setElementCssClass('ShipCityLabel', 'light');
		setElementCssClass('ShipStateLabel', 'light');
		setElementCssClass('ShipCountryLabel', 'light');
		setElementCssClass('ShipZipLabel', 'light');
	} else {
		// Enable shipping fields
		if (form.ShipTo) form.ShipTo.disabled = true;
		form.ShipAddress1.disabled = false;
		form.ShipAddress2.disabled = false;
		form.ShipCity.disabled = false;
		form.ShipState.disabled = false;
		form.ShipCountry.disabled = false;
		form.ShipZip.disabled = false;
		setElementCssClass('ShipAddressLabel', '');
		setElementCssClass('ShipCityLabel', '');
		setElementCssClass('ShipStateLabel', '');
		setElementCssClass('ShipCountryLabel', '');
		setElementCssClass('ShipZipLabel', '');
	}
}

// Validates a selection on the order confirmation screen
function validateOrderConfirmation(form) {
	if (form.Approve[0].checked == false && form.Approve[1].checked == false) {
		alert("Please select an option before submitting your response.");
		return false;
	} else return true;
}

// Validates entries on the payment form
function validatePaymentForm(form) {
	if (form.subnum.value == 1) {
		if (confirm("Clicking on the SUBMIT ORDER button more than once may cause duplicate charges to your credit card.  Are you sure you want to submit again?")) return true;
		else return false;
	} else if (!(form.CardType.value)) {
		alert("Please select a card type.");
		return false;
	} else if (!(form.Acct.value)) {
		alert("Please enter a valid card number.");
		return false;
	} else if (!(form.ExpMonth.value) || !(form.ExpYear.value)) {
		alert("Please enter a valid expiration date.");
		return false;
	} else {
		form.Submit.value = "Please wait...";
		form.Submit.disabled = true;
		return true;
	}
}

// Prompts a user for cancelling an order
function cancelOrder() {
	if (confirm('Canceling your order will empty your shopping cart and return you to the store front.  Are you sure?')) location.href='cart.php?e=delete';
}

// Recalculates the shipping cost when the shipping method selection changes
function recalcShipping(form) {
	var waitbox = document.getElementById("lblWait");
	if (waitbox) waitbox.style.display = 'inline';
	form.submit();
}

// Prompts a user for deleting a template
function deleteTemplate(id) {
	if (confirm('Are you sure you want to delete this template?')) location.href = 'template-delete.php?id=' + id;
}

// Focuses the cursor on the first element of the form
function focusFirstFormElement() {
	var focused = false;
	var div = document.getElementById("store");
	if (div) {
		var forms = div.getElementsByTagName("form");
		// Iterate through each form
		for (var x = 0; x < forms.length; x++) {
			if (focused) break;
			var form = forms[x];
			// Iterate through each document element to find a text or drop-down field
			for (var n = 0; n < form.elements.length; n++) {
				var element = form.elements[n];
				if (element.disabled || element.readOnly) continue;
				if (element.type == 'text' || element.type == 'textarea' || element.type == 'password') {
					element.select();
					focused = true;
					break;
				} else if (element.type == 'file' || element.type == 'select-one' || element.type == 'select-multiple') {
					element.focus();
					focused = true;
					break;
				}
			}
		}
	}
}

// Returns the value of a query string parameter
function getQSValue(variable) {
	var qs = location.search.substring(1, location.search.length);
	var pairs = qs.split("&");
	for (var i = 0; i < pairs.length; i++) {
		var tmp = pairs[i].split("=");
		if (variable==tmp[0]) return tmp[1];
	}
	return null;
}

// Global loading function
function globalLoad() {
	focusFirstFormElement();
}

if (window.addEventListener) window.addEventListener("load", globalLoad, false);
else if (window.attachEvent) window.attachEvent("onload", globalLoad);

// **** CUSTOM FOR THIS STORE BUILD ****

function showCSC() {
	window.open('csc.php','images','top=50,left=50,width=450,height=300,status=yes,resizable=yes,scrollbars=yes');
}