//form validation for customerModify & customerRegistration & login


function validateForm(formName, checkPass) {
	var country = formName.CountryCode.value;
	var shippingcountry = formName.shippingCountryCode.value;
	var badfields = 0;
	
	badfields += validName(formName.customerCompany, "customerCompany", "*Please enter the name of your company or business.");
	badfields += validName(formName.name, "customerName", "*Please enter the contact person's first name.");
	badfields += validName(formName.lastName, "lastName", "*Please enter the contact person's last name.");
	badfields += validPhone(formName.phone, "phone", "*Your business telephone number");
	badfields += validEmail(formName.email, formName.confirmEmail, "email");
	if (checkPass) {
		badfields += validPassword(formName.password, formName.passwordconf, "password");
	}
	badfields += validName(formName.address, "address", "*Please enter your business' billing address.");
	badfields += validName(formName.city, "city", "*Please enter your business' city.");
	badfields += validState(formName.stateCode, "state", "*Please select a state from the pull down list.");
	if (country == "USA") {badfields += validZipCode(formName.zip, "zip", "billing");}
	if (country == "Canada") {badfields += checkPostalCode(formName.zip, "zip", "");}
	badfields += validName(formName.shippingName, "shippingName", "*Please enter the recipient's first name.");
	badfields += validName(formName.shippinglastName, "shippinglastName", "*Please enter the recipient's last name.");
	badfields += validName(formName.shippingaddress, "shippingaddress", "*Please enter the shipping address.");
	badfields += validName(formName.shippingcity, "shippingcity", "*Please enter the shipping city.");
	badfields += validState(formName.shippingStateCode, "shippingStateCode", "*Please select a shipping state from the pull down list.");
	if (shippingcountry == "USA") {badfields += validZipCode(formName.shippingzip, "shippingzip", "shipping");}
	if (shippingcountry == "Canada") {badfields += checkPostalCode(formName.shippingzip, "shippingzip", "");}

	// verify that no badfields retruned a value. Alert or return true.
	if (badfields != 0){
		if (badfields == 1) {alert("You have 1 field that is not completed correctly.\nPlease correct the form and re-submit.");}
		else if (badfields > 1) {alert("You have " + badfields + " fields not completed correctly.\nPlease correct the form and re-submit.");}
		return false;
	}else{
		return true;
	}
}

/*----------------------------------------------------------
--------------billing to shipping functions--------------------------
----------------------------------------------------------*/

function billingtoshipping(checkBox, form) {
	if (checkBox.checked){
		form.shippingName.value = form.name.value; form.shippingName.readOnly = true;
		form.shippinglastName.value = form.lastName.value; form.shippinglastName.readOnly = true;
		form.shippingaddress.value = form.address.value; form.shippingaddress.readOnly = true;
		form.shippingcity.value = form.city.value; form.shippingcity.readOnly = true;
		form.shippingzip.value = form.zip.value; form.shippingzip.readOnly = true;
		form.shippingStateCode.value = form.stateCode.value; form.shippingStateCode.setAttribute("readOnly", true);
		form.shippingCountryCode.value = form.CountryCode.value; form.shippingCountryCode.setAttribute("readOnly", true);
	}else{
		form.shippingName.value = ""; form.shippingName.readOnly = false;		
		form.shippinglastName.value = ""; form.shippinglastName.readOnly = false;		
		form.shippingaddress.value = ""; form.shippingaddress.readOnly = false;		
		form.shippingcity.value = ""; form.shippingcity.readOnly = false;		
		form.shippingzip.value = ""; form.shippingzip.readOnly = false;		
		form.shippingStateCode.value = "";
		form.shippingCountryCode.value = "USA";
	}
} 

function updateShipping(checkBox, shippingField, billingField ) {
	if (checkBox.checked) {
		shippingField.value = billingField.value;
	}
}

/*----------------------------------------------------------
--------------validation functions--------------------------
----------------------------------------------------------*/

function validName(field, fieldId, errorMsg){	
		var error = 0;
		if (field.value == null || field.value.length == 0) {error=1;highlightErrors(field, fieldId, errorMsg);}
		else{
			var c = "";
			for (i = 0; i < field.value.length; i++){
				if (i == 0) {c += field.value.charAt(i).toUpperCase();}
				else if ((field.value.charAt(i-1) == " " || field.value.charAt(i-1) == "." || field.value.charAt(i-1) == "-")) {c += field.value.charAt(i).toUpperCase();}
				else {c += field.value.charAt(i).toLowerCase();}
			}
			field.value = c;
			normalDisplay(fieldId);
		}
		return error;
}

function validPhone(field, fieldId, errorMsg) {
		var error = 0;
		var stripped = field.value.replace(/[\(\)\.\-\ ]/g, ''); //strips out non-numeric
			if (field.value == null || field.value.length == 0) {error = 1; highlightErrors(field, fieldId, errorMsg + " must be provided.");}
			else if (isNaN(parseInt(stripped))){error = 1; highlightErrors(field, fieldId, errorMsg +  " contains illegal characters.");}
			else if (!(stripped.length == 10)) {error = 1; highlightErrors(field, fieldId, errorMsg +  " must be 10 digits.");}
		if (error == 0) {normalDisplay(fieldId); field.value = reformatPhone(stripped);}
		return error;
	}

function validEmail (field, confirm, fieldId) {
	var error = 0;
	var emailFilter=/^.+@.+\..{2,3}$/;
	var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
	if (field.value == null || field.value.length == 0) {error = 1; highlightErrors(field, fieldId, "*Please enter your email address.");}
	else if (!(emailFilter.test(field.value))) {error = 1; highlightErrors(field, fieldId, "*Email address is invalid.");}
	else if (field.value.match(illegalChars)) {error = 1; highlightErrors(field, fieldId, "*Email Address contains illegal characters.");}
	else{		
		for (i=0; i < field.value.length; i++){
			if (field.value.charAt(i) != confirm.value.charAt(i)){error = 1; highlightErrors(field, fieldId, "*Email addresses do not match."); break;} 
		}
	}
	if (error == 0) {normalDisplay(fieldId); field.value=field.value.toLowerCase(); confirm.value=confirm.value.toLowerCase();}
return error;
}

function validZipCode(field, fieldId, errorMsg){
		var error = 0;
		var valid = "0123456789";
		if (field.value.length != 5) {error=1; highlightErrors(field, fieldId, "*Please enter a 5 digit " +errorMsg+ " zip code.");}
		for (var i=0; i < field.value.length; i++) {
			temp = "" + field.value.substring(i, i+1);
			if (valid.indexOf(temp) == "-1") {error = 1; highlightErrors(field, fieldId, "*This is an invalid Zip Code.");}
		}			
		if (error == 0) {normalDisplay(fieldId);}
		return error;
}

function checkPostalCode(field, fieldId, errorMsg){ 
		var error = 0;
			
		if (field.value.length != 7) {error=1; highlightErrors(field,fieldId, "*Enter A 6 digit Postal Code Including A Space.");}
		
		field.value = field.value.toUpperCase();   // in case of lowercase characters
		temp = field.value;
		if(temp.length == 7) {
			//alert (temp);
			// Check for legal characters in string - note index starts at zero
			if('ABCEGHJKLMNPRSTVXY'.indexOf(temp.charAt(0))<0) {error = 1; highlightErrors(field,fieldId, "*First Postal Code Character Is Invalid.");}
			if('0123456789'.indexOf(temp.charAt(1))<0) {error = 1; highlightErrors(field,fieldId, "*Second Postal Code Character Is Invalid.");}
			if('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(temp.charAt(2))<0) {error = 1; highlightErrors(field,fieldId, "*Third Postal Code Character Is Invalid.");}
			if(" ".indexOf(temp.charAt(3)) <0) {error = 1; highlightErrors(field,fieldId, "*Forth Postal Code Character Must Be A Space.");}
			if('0123456789'.indexOf(temp.charAt(4))<0) {error = 1; highlightErrors(field,fieldId, "*Fifth Postal Code Character Is Invalid.");}
			if('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(temp.charAt(5))<0) {error = 1; highlightErrors(field,fieldId, "*Sixth Postal Code Character Is Invalid.");}
			if('0123456789'.indexOf(temp.charAt(6))<0) {error = 1; highlightErrors(field,fieldId, "*Seventh Postal Code Character Is Invalid.");}
		}
		if (error == 0) {normalDisplay(fieldId);}
		return error;
}

function validState(field, fieldId, errMsg){
	var error = 0;
		if (field.value == "default" || field.value == "" || field.value.length == 0 || field.value == null) {error = 1; highlightErrors(field, fieldId, errMsg);}
		else {normalDisplay(fieldId);}
	return error;
}

function validPassword (field, confirm, fieldId) {
	var error = 0;
	var pass = field.value
	var illegalChars = /[\W_]/;
	if (field.value.length < 5) {error = 1; highlightErrors(field, fieldId, "*Your password must be 5 characters long. Alpha-Numeric passwords are suggested for your security.");}
	else if (illegalChars.test(pass)) {error = 1; highlightErrors(field, fieldId, "*Your password contains illegal characters. Alpha-Numeric passwords are suggested for your security.");}
	else{		
		for (i=0; i < field.value.length; i++){
			if (field.value.charAt(i) != confirm.value.charAt(i)){error = 1; highlightErrors(field, fieldId, "*Your passwords do not match."); break;} 
		}
	}
	if (error == 0) {normalDisplay(fieldId);}
return error;
}


/*----------------------------------------------------------
--------Reformat Form Fileds after Validation---------------
----------------------------------------------------------*/
function reformat(s){
	var arg;
	var sPos = 0;
	var result = "";
	for (i = 1; i < reformat.arguments.length; i ++){
		arg = reformat.arguments[i];
		if (i % 2 == 1) result += arg;
		else {
			result += s.substring(sPos, sPos + arg);
			sPos += arg;
		}
	}
	return result;
}


function reformatPhone(USPhone){ return (reformat (USPhone, "(",3,") ",3, "-", 4));}

/*----------------------------------------------------------
--------------Process Errors------------------------
----------------------------------------------------------*/
function highlightErrors(field, fieldId, errorMsg){
			document.getElementById(fieldId + "ID").innerHTML = "<p class='smallred'>" + errorMsg;
		field.focus();
}
function normalDisplay(fieldId){
			document.getElementById(fieldId + "ID").innerHTML = "";
}
