

// ***********************************************************
//  ecas form validation script v.08.07.02bg
// ***********************************************************
// declare global variables
var goFlag = true; // flag for proceeding
var errors = ""	// error message
var firstErrorField = ""; // records first field to focus on if error

var legacyRestrictedList = "<>\'\"\\";
var restrictedCharlist = "\'\"<>{}[]#$%^&;:/\\";
var phoneValidChars = "().-+ ";

function validateLogin(){ // **************************************
	// validates login form
	init();
	validate('username', 'Username', 1, 24, legacyRestrictedList );
	validate('password', 'Password', 4, 14, legacyRestrictedList );
	display();
	return goFlag;
}

function validateReg(){ // ****************************************
	// validates registration form for new account creation
	init();
	validate('username', 'Username', 1 , 24 , restrictedCharlist+" ");// space character appended to restricted charlist in this instance
	validate('password', 'Password', 4, 14, restrictedCharlist);
	validate('confirmpassword', "Confirm Password", 4, 14, restrictedCharlist);	
	compare('password', 'Password','confirmpassword', "Confirm Password");
	validate('firstname', 'First Name', 1, 40, "");
	validate('lastname', 'Last Name', 1, 40, "");
	validate('organization', 'Organization', 1, 255, "");
	requiredChars('email', 'E-mail');
	stateRequired('country', 'Country', 'state', 'State or Province');
	validate('street', 'Address', 1, 255, "");
	validate('city', 'City / Town', 1, 255, "");
	validate('postalcode', 'ZIP / Postal code', 1, 30, "");
	selectCheck('question', 'Identity Question');
	validate('answer', 'Answer', 1, 60, "");
	validateOptionalFields();
	display();
	return goFlag;
}

function validateEcartCreateLogin(){ // ****************************************
	// validates eCart registration form step one
	init();
	validate('username', 'Username', 1 , 24 , restrictedCharlist+" ");// space character appended to restricted charlist in this instance
	validate('password', 'Password', 4, 14, restrictedCharlist);
	validate('confirmpassword', "Confirm Password", 4, 14, restrictedCharlist);	
	compare('password', 'Password','confirmpassword', "Confirm Password");
	selectCheck('question', 'Identity Question');
	validate('answer', 'Answer', 1, 60, "");
	display();
	return goFlag;
}

function validateEcartUpdateLogin(){ // ****************************************
	// validates eCart registration form step one
	init();
	if(entry('password')){validate('password', 'Password', 4, 14, restrictedCharlist)}
	if(entry('password')){validate('confirmpassword', "Confirm Password", 4, 14, restrictedCharlist)}	
	compare('password', 'Password','confirmpassword', "Confirm Password");
	selectCheck('question', 'Identity Question');
	validate('answer', 'Answer', 1, 60, "");
	display();
	return goFlag;
}


function validateEcartCreateBilling(){ // ****************************************
	// validates eCart registration form step two
	init();
	validate('firstname', 'First Name', 1, 40, "");
	validate('lastname', 'Last Name', 1, 40, "");
	validate('organization', 'Organization', 1, 255, "");
	validate('street', 'Address', 1, 255, "");
	validate('city', 'City / Town', 1, 255, "");
	stateRequired('country', 'Country', 'state', 'State or Province');	
	validate('postalcode', 'ZIP / Postal code', 1, 30, "");	
	validate('phone', 'Phone', 1, 40, "");
	validateNums('phone', 'Phone', phoneValidChars);
	if(entry('phoneext')){validateNums('phoneext', 'Ext.', phoneValidChars);} //optional field
	requiredChars('email', 'E-mail');
	requiredChars('confirmEmail', 'Confirm E-mail');
	compare('email', 'E-mail','confirmEmail', "Confirm E-mail");
	display();
	return goFlag;
}

function validateEcartCreateShipping(){ // ****************************************
	// validates eCart registration form step three
	init();
	validate('firstnameShip', 'First Name', 1, 40, "");
	validate('lastnameShip', 'Last Name', 1, 40, "");
	validate('organizationShip', 'Organization', 1, 255, "");
	validate('streetShip', 'Address', 1, 255, "");
	validate('cityShip', 'City / Town', 1, 255, "");
	stateRequired('countryShip', 'Country', 'stateShip', 'State or Province');	
	validate('postalcodeShip', 'ZIP / Postal code', 1, 30, "");	
	validate('phoneShip', 'Phone', 1, 40, "");
	validateNums('phoneShip', 'Phone', phoneValidChars);
	if(entry('phoneextShip')){validateNums('phoneextShip', 'Ext.', phoneValidChars);} //optional field
	display();
	return goFlag;
}

function validateProfile(tmpPassUp){ // ****************************************
	// validates registration form for account update
	// tmpPassUp is set to true if the user must update their temporary password
	// and false if normal update
	init();
	if(tmpPassUp){
		validate('password', 'Password', 4, 14, restrictedCharlist);
		validate('confirmpassword', "Confirm Password", 4, 14, restrictedCharlist);	
	}else{
		if(entry('password')){validate('password', 'Password', 4, 14, restrictedCharlist);}
		if(entry('confirmpassword')){validate('confirmpassword', "Confirm Password", 4, 14, restrictedCharlist);}
	}
	compare('password', 'Password','confirmpassword', "Confirm Password");
	validate('firstname', 'First Name', 1, 40, "");
	validate('lastname', 'Last Name', 1, 40, "");
	validate('organization', 'Organization', 1, 255, "");
	requiredChars('email', 'E-mail');
	validate('street', 'Address', 1, 255, "");
	validate('city', 'City / Town', 1, 255, "");
	validate('postalcode', 'ZIP / Postal code', 1, 30, "");
	stateRequired('country', 'Country', 'state', 'State or Province');
	selectCheck('question', 'Identity Question');
	validate('answer', 'Answer', 1, 60, "");
	validateOptionalFields();
	display();
	return goFlag;
}

function validateOptionalFields(){
	// optional fields... validated only if not null
	if(entry('phone')){validateNums('phone', 'Phone', phoneValidChars);}
	if(entry('phoneext')){validateNums('phoneext', 'Ext.', phoneValidChars);}
	if(entry('department')){validate('department', 'Department', 1, 255, "");}
	if(entry('title')){validate('title', 'Title', 1, 255, "");}
}

function validateLogPending(){ //**********************************
	// validates the email form field for the email nag page
	init();
	requiredChars('email', 'E-mail');
	display();
	return goFlag;
}

function validateEmail(){ //**********************************
	// validates the email form field for login pending, email nag, wait4confirm page
	init();
	requiredChars('email', 'E-mail');
	display();
	return goFlag;
}

function validateEmailNag(){ //**********************************
	// validates the email form field for login pending, email nag, wait4confirm page
	init();
	if(document.forms[0].fuseaction[1].checked){
		requiredChars('email', 'E-mail');
	}
	display();
	return goFlag;
}

function validatePasswordNag(){ //**********************************
	// validates the password form fields for the password nag page
	init();
	validate('password', 'Password', 4, 14, restrictedCharlist);
	validate('confirmpassword', "Confirm Password", 4, 14, restrictedCharlist);	
	compare('password', 'Password','confirmpassword', "Confirm Password");
	display();
	return goFlag;
}

function validateRecoverPwd1(){ //*********************************
	// validates step one of the recover password process 
	init();
	if(entry('username')){validate('username', 'Username', 1 , 24 , legacyRestrictedList);}
	validate('lastname', 'Last Name', 1, 40, "");
	requiredChars('email', 'E-mail');
	display();
	return goFlag;
}

function validateRecoverPwd2(){ //*********************************
	// validates step one of the recover password process 
	init();
	validate('answer', 'Answer', 1, 60, "");
	display();
	return goFlag;
}

function validateContact(){ // ****************************************
	// validates registration form for new account creation
	init();
	validate('firstname', 'First Name', 1, 40, "");
	validate('lastname', 'Last Name', 1, 40, "");
	requiredChars('email', 'E-mail');
	validate('contactQuestion', 'Question or Comment', 1, 2000, "");
	display();
	return goFlag;
}

function validateEmailConfirm(){
	// keeps the resend confirmation form from submitting unless email address is changed
	init();
	requiredChars('email', 'e-mail address');
	if(document.forms[0].emailCheck.value == document.forms[0].email.value){
		errors += 'Your e-mail address was not changed.  \n\nPlease check for the confirmation that was sent to ' + document.forms[0].email.value + '.';
		if(firstErrorField == ""){firstErrorField = 'email';}
		goFlag = false;
	}
	display();
	return goFlag;
}

function init(){ // ***********************************************
	//reset global variables
	errors = "Please correct the following: \n\n"; 
	firstErrorField=""; 
	goFlag= true; 
}

function entry(field){ // *******************************************
	// checks to see if a field is null... this is used for optional fields
	if (eval('document.forms[0].' + field + '.value != "" ')){
		return true;
	}else{
		return false;
	}
}

 function LTrim(str){ // *******************************************
	// trims off leading whitespace
	var whitespace = new String(" \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1) {
	    var j=0, i = s.length;
	    while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
	        j++;
	    s = s.substring(j, i);
	}
	return s;
}

function RTrim(str){ // *************************************
		var whitespace = new String(" \t\n\r");
        var s = new String(str);
        if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
            var i = s.length - 1;       // Get length of string
            while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                i--;
            s = s.substring(0, i+1);
        }
        return s;
}

function Trim(str){// **************************************
        return RTrim(LTrim(str));
}

function validate(fieldname, label, minChars, maxChars, restrictedChars){ // **************
	// trim entry and assign to working variable
	var tmp = eval('document.forms[0].' + fieldname);
	word = Trim(tmp.value);
	tmp.value = word;

	// check minimum value length ...  append error message if necessary
	var tmpLen = eval('document.forms[0].' + fieldname + '.value.length');
	if (tmpLen <  minChars){
		if(tmpLen == 0){
			errors += label + ' may not be blank.  \n';
		}else{
			errors += label + ' must be at least ' + minChars + ' characters \n';
		}
		// if this is the first error, flag the field for focus()
		if(firstErrorField == ""){firstErrorField = fieldname;}
		// set error flags
		goFlag = false;
	}
	
	// check maximum value length ...  append error message if necessary
	if (eval('document.forms[0].' + fieldname + '.value.length > ' + maxChars)){
		errors += label + ' may not be more than ' + maxChars + ' characters. \n';
		// if this is the first error, flag the field for focus()
		if(firstErrorField == "") {firstErrorField = fieldname;}	
		// set error flag
		goFlag = false;
	}
	
	// check for restricted characters
	if(restrictedChars != ""){
		var foundChars = "";
		for (var i = 0; i < restrictedChars.length; i++){
			// get a restricted character
			var z = restrictedChars.charAt(i);
			// search field for it...
			var tmp=eval('document.forms[0].'+fieldname+'.value');
			// if found, append foundChars var
			if(tmp.indexOf(z) != "-1"){
				if(z == " ")z = "spaces";
				foundChars += z + ' ';
			}
		}

		// if errors were found, append message and flag field for focus()
		if(foundChars.length != ""){
			errors += label + ' may not contain ' + foundChars + '  \n';
			if(firstErrorField == "") {firstErrorField = fieldname;}	
			goFlag = false;
		}
	}
}

function compare(field1, label1, field2, label2){ //***************
	var thisVar = eval('document.forms[0].' + field1 + '.value.toLowerCase()');
	var thatVar = eval('document.forms[0].' + field2 + '.value.toLowerCase()');
	// compare the two strings, append message and flag field for focus()
	if(thisVar != thatVar){
		errors += label1 + ' does not match ' + label2 + '. \n';
		if(firstErrorField == "") {firstErrorField = field1;}	
		goFlag = false;
	}
}	

function selectCheck(field, label){ //*******************************
	if (eval('document.forms[0].' + field + '.selectedIndex == 0')){
		errors += 'Please select an ' + label + '.  \n';
		// if this is the first error, flag the field for focus()
		if(firstErrorField == ""){firstErrorField = field;}
		// set error flags
		goFlag = false;
	}
}

function validateNums(field, label, exceptions){ //*********************
	// trim entry and assign to working variable
	var tmp = eval('document.forms[0].' + field);
	word = Trim(tmp.value);
	tmp.value = word;

	// set numeric and acceptable non-numeric chars to test string
	var okChars = '0123456789' + exceptions;
	// create a temp string with form field contents
	var tmp=eval('document.forms[0].'+field+'.value');
	// reset alphaChars var
	var alphaChars = "";
	//step through form field contents and extract one letter at a time
	for (var i = 0; i < tmp.length; i++){	
		var z = tmp.charAt(i);
		// look for the char in the test string. If found, append alphaChars var
		if(okChars.indexOf(z) == "-1"){
			alphaChars += z + ' ';
		}
	}
	// if errors found, append message with list of alpha chars 
	if(alphaChars.length != ""){
		errors += label +' may not contain ' + alphaChars +' \n';
		// if this is the first error, flag the field for focus()
		if(firstErrorField == ""){firstErrorField = field;}
		// set error flags
		goFlag = false;
	}
}

function requiredChars(field, label){ //******************
	// checks for proper email syntax)
	var str=eval('document.forms[0].'+field+'.value');	
	if (window.RegExp) { // error check using regular expressions
		var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,20}|[0-9]{1,3})(\]?)$/; // valid email format
		if (!reg1.test(str) && reg2.test(str)) { // if syntax is valid

		}else{// invalid characters or non-standard format
			errors +=  label + ' \"' + str + '\" does not appear to be valid.   \n';
			if(firstErrorField == "") {firstErrorField = field;}	
			goFlag = false;
		}
	}else{// trivial error check for non-regexp supporting browsers 
		if(str.indexOf("@") == -1){ 
			errors +=  label + ' \"' + str + '\" does not appear to be valid.   \n';
			if(firstErrorField == "") {firstErrorField = field;}	
			goFlag = false;
		}
	}
}

function stateRequired(field1, label1, field2, label2){
	// check for country selected
	if(eval('document.forms[0].'+field1+'.selectedIndex == 0')){
		errors += 'Please select a '+label1+'. \n';
		// if this is the first error, flag the field for focus()
		if(firstErrorField == ""){firstErrorField = field1;}
		// set error flags
		goFlag = false;
	}
	// if country is selected...
	if(eval('document.forms[0].'+field1+'.selectedIndex != 0')){
		// if regions are available for user choice...
		if(eval('document.forms[0].'+field2+'.length > 1')){
			if(eval('document.forms[0].'+field2+'.selectedIndex == 0')){
				errors += 'Please select a '+label2+'. \n';
				// if this is the first error, flag the field for focus()
				if(firstErrorField == ""){firstErrorField = field2;}
				// set error flags
				goFlag = false;
			}
		}
	}
}

function display(){	// ********************************************
	// if errors are detected, display them and return user to the first field with errors
	if(!goFlag){
		alert(errors);
		eval('document.forms[0].' + firstErrorField + '.focus()'); 
	}
}

function popUp(url){
	helpWin = window.open(url, "helpPop", "width=700,height=500,status=no,scrollbars=yes");
	helpWin.window.focus();
}

	function updateStates(formType, country, fuze){
		if(formType == "billing")	var eState = document.registrationForm.state;
		if(formType == "shipping") var eState = document.registrationForm.stateShip;
		eState.length = 0;
		// create the default list option
		if(document.getElementById){
			eState.style.backgroundColor="#FFE4AF";
		}
		eState.options[0] = new Option("Loading Region List...","--");
		document.registrationForm.refreshed.value="true";
		document.registrationForm.fuseaction.value= fuze+".showForm";
		document.registrationForm.submit();
	}

function toggleShip(){
	var eForm = document.registrationForm;
	if(eForm.shipSame.checked){
		eForm.firstnameShip.value = eForm.firstname.value;
		eForm.lastnameShip.value = eForm.lastname.value;
		eForm.organizationShip.value = eForm.organization.value;
		eForm.streetShip.value = eForm.street.value;
		eForm.cityShip.value = eForm.city.value;
		eForm.postalcodeShip.value = eForm.postalcode.value;
		eForm.phoneShip.value = eForm.phone.value;
		eForm.phoneextShip.value = eForm.phoneext.value;
		toggleOption();
	}else{
		eForm.firstnameShip.value = "";
		eForm.lastnameShip.value = "";
		eForm.organizationShip.value = "";
		eForm.streetShip.value = "";
		eForm.cityShip.value = "";
		eForm.postalcodeShip.value = "";
		eForm.phoneShip.value = "";
		eForm.phoneextShip.value = "";
		eForm.stateShip.options.selectedIndex = "0";
	}
}

function toggleOption(){
	var eForm = document.registrationForm;
	for(var i = 0; i<eForm.stateShip.length; i++){
		if(eForm.stateShip.options[i].value == eForm.state.value){
			eForm.stateShip.selectedIndex = i;
		}
	}
}

function toggle(divName){
	if(document.getElementById){
		(document.getElementById(divName).style.display !="block")? document.getElementById(divName).style.display = "block":document.getElementById(divName).style.display = "none";
	}
}
