//
// Author: Steve Hanson
// Tasen Software eCommerce
//
// Copyright 2007 Tasen Software
// This code may not be reproduced or distributed without the explicit permission of Tasen Software
//
var ajaxID = "";

function checkValidationRule(validationRuleID, fieldID, maxlength, minlength) {
	var result = true;
	var delimiter = ",";
	var stringArray;
	
	//document.write("<br/>IN IT<br/>");
	
	// If there are no delimiters, then this must be a single rule.
	if(validationRuleID.indexOf(delimiter) == -1) {
		stringArray = new Array(validationRuleID);
	}
	else {
		stringArray = validationRuleID.split(delimiter);		
	}


	for(i = 0; i < stringArray.length; i++) {
		var strRuleID = parseInt(stringArray[i]);
		
		if(!(strRuleID == 0)) {
			//var vElement = new ElementValidation(validationRuleID, fieldID, maxlength, minlength);
			//vElements[vElements.length] = vElement;
			msg = msg + "<br/>processing a rule";
			
			switch(strRuleID) {
				case 0:	// This is the default validation that has no rules associated with it.
					break;		
				case 1:	// Specifically for validating max field length only.
					result = validateMaxlength(fieldID, maxlength);
					break;
				case 2:	// Specifically for validating min field length only.
					result = validateMinlength(fieldID, minlength);
					break;
				case 3:	// 

					break;
				case 4:	// Case 3 plus an IS NUMERIC check
					result = isDigits(fieldID);
					break;	
				case 5:	// Case 4 plus a price change check.
					msg = msg + "<br/>about to process price changer.";
					
					
					
					break;					
				default:
					break;
			}
		}
		if(!result) {
			break;
		}
	}
	//document.write(msg);

	return result;
}

// Returns true only if the value is any length and consists of digits between 0-9
function isDigits(fieldID)
{
	var strVal = new String(trim(document.getElementById(fieldID).value));
	var errFieldID = "err" + fieldID;		// Used to display an error instead of popping up an alert.
			
	// check for a length of 0 - if so, return false
	if(strVal.length==0) { return false; }

	// loop through each character of the string
	for(var x=0; x < strVal.length; x++) {
		// if the character is < 0 or > 9, return false (not a number)
		if(strVal.charAt(x) < '0' || strVal.charAt(x) > '9') { 
			document.getElementById(errFieldID).innerHTML  = "Field must only consist of digits 0-9.";				
			return false; 
		}
	}
	
	document.getElementById(errFieldID).innerHTML = "";	
	return true;	// It's a string of digits
}


function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

// Get a set of form elements from the fieldParams element, which is an array or a single value.
// Then we need to submit the form if there are no invalid fields. Otherwise, don't submit.
// Always return false so that the href of the link will not be execute.
function validateProductForm() {
	var validForm = true;
	var msg = '';
	
	if(document.myform.fieldParams) {
		if(document.myform.fieldParams.length) {	// If it has a length, it's an array.
			msg = "<br/>validating the form, fieldParams length: " + document.myform.fieldParams.length;		
			for (var i=0, j=document.myform.fieldParams.length; i<j; i++) {
				var attributeString = document.myform.fieldParams[i].value;	// validationRuleID,fieldID,maxlength,minlength
				var attributes = attributeString.split(",");
				// returns false if any validation fails
				var valid = checkValidationRule(attributes[0],attributes[1],attributes[2],attributes[3]);
				msg = msg + "<br/>Testing field ID: " + attributes[1] + ", valid: " + valid;
				if(valid != true) {
					validForm=false;
					msg = msg + "<br/>setting result to false: " + validForm;
				}
			}
		}
		else {
			msg = "<br/>validating the form, field value: " + document.myform.fieldParams.value;		
			var attributeString = document.myform.fieldParams.value;	// validationRuleID,fieldID,maxlength,minlength
			var attributes = attributeString.split(",");
			// returns false if any validation fails
			var valid = checkValidationRule(attributes[0],attributes[1],attributes[2],attributes[3]);
			msg = msg + "<br/>Testing field ID: " + attributes[1] + ", valid: " + valid;
			
			if(valid != true) {
				validForm=false;
				msg = msg + "<br/>setting result to false: " + validForm;
			}
		}
	}
	//document.write(msg);
	// If the form is valid, we should submit it.
	if(validForm == false) {
		alert("There were problems with the form. Please ensure all fields are valid.");
	}
	//alert("valid form: " + validForm);
	return validForm;
}

function validateMinlength(fieldID, minlength) {
	var value = document.getElementById(fieldID).value;
	var errFieldID = "err" + fieldID;		// Used to display an error instead of popping up an alert.
//document.write("errFieldID: " + errFieldID);
	if(value.length < minlength && minlength > 0) {
		document.getElementById(errFieldID).innerHTML  = "This length of this field must not be less than " + minlength + ".";		
		//globalValidationError = false;
		return false;
	}

	document.getElementById(errFieldID).innerHTML = "";		
	return true;
}

function validateMaxlength(fieldID, maxlength) {
	var value = document.getElementById(fieldID).value;
	var errFieldID = "err" + fieldID;		// Used to display an error instead of popping up an alert.
	//document.write("errFieldID: " + errFieldID);	
	if(value.length > maxlength && maxlength > 0) {
		document.getElementById(errFieldID).innerHTML = "This length of this field must not be greater than " + maxlength + ".";
		document.getElementById(fieldID).value = '';
		//document.write("error field should show, maxlength: " + maxlength);	
		return false;
	}	
	
	document.getElementById(errFieldID).innerHTML = "";	
	return true;
}

function checkDependentOptions(optionID) {
	//document.write("<br/>optionID: " + optionID + "<br/>");
	return true;
}


function removeItem(inventoryID, key) {
	//document.write("Removing Item.");
	document.getElementById("qty["+inventoryID+"]["+key+"]").value=0;
	document.updateform.submit();
}

function toggleShipping(on) {
	if(on) {
		document.getElementById("ecom_shippingBlock").style.visibility = "visible";
		document.getElementById("ecom_shippingBlock").style.height = "auto";
	}
	else {
		document.getElementById("ecom_shippingBlock").style.visibility = "hidden";
		document.getElementById("ecom_shippingBlock").style.height = "0px";
	}
	return
}

function stateChanged() { 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
		var response = xmlHttp.responseText;
		if(ajaxID == "login") {
			if(response == "Logged In As") {	// Valid login.
				setLoggedIn(true);			
			}
			else {								// Invalid login, display error message.
				setLoggedIn(false);			
				loginID = "";
			}
		}
		else if(ajaxID == "reg") {
			if(response == "Logged In As") {	// Valid login.
				setLoggedIn(true);			
			}
			else {								// Invalid login, display error message.
				setLoggedIn(false);			
				loginID = "";
			}		
		}
		else if(ajaxID == "logoutCheckout1") {
			if(response == "true") {	// It worked.
				setLoggedIn(false);
				//document.write( "<br/>logout successful<br/>");
			}
			else {	// It didn't work.
				//document.write( "<br/>logout unsuccessful<br/>");
			}			
			//document.write("<br/>Returned from AJAX logout<br/>");
		}		
		else if(ajaxID == "logoutCheckout2") {
			if(response == "true") {	// It worked.
				document.location.href = "http://www.coloradocookiekitchen.com/checkout1.php";	
			}
			else {	// It didn't work.
				//document.write( "<br/>logout unsuccessful<br/>");
			}			
		}
	} 
} 

function GetXmlHttpObject() { 
	var objXMLHttp=null
	if (window.XMLHttpRequest) {
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject) {
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	return objXMLHttp
} 

function validateCheckout1Form() {
	var field = '';
	var valid = true;
	var email1 = '';
	var email2 = '';
	field = document.getElementById("ecom_billingFirstName").value;
	if(!validateField(field,"ecom_billingFirstNameErr","Billing first name")) { valid = false; }
	field = document.getElementById("ecom_billingLastName").value;
	if(!validateField(field,"ecom_billingLastNameErr","Billing last name")) { valid = false; }
	
	field = document.getElementById("ecom_billingAddress1").value;
	if(!validateField(field,"ecom_billingAddress1Err","Billing address")) { valid = false; }	
	//field = document.getElementById("ecom_billingAddress2").value;	// Doesn't need to be checked.
	//if(!validateField(field,"ecom_billingAddress2Err","Billing address 2")) { valid = false; }
	field = document.getElementById("ecom_billingCity").value;
	if(!validateField(field,"ecom_billingCityErr","Billing city")) { valid = false; }
	field = document.getElementById("billingState").value;	// There's no ecom_ prefix on this one.
	if(!validateField(field,"ecom_billingStateErr","Billing state")) { valid = false; }
	field = document.getElementById("ecom_billingZip").value;
	if(!validateField(field,"ecom_billingZipErr","Billing zip")) { valid = false; }
	//field = document.getElementById("ecom_billingCountry").value;
	//if(!validateField(field,"ecom_billingCountryErr","Billing country")) { valid = false; }
	field = document.getElementById("ecom_billingPhone").value;
	if(!validateField(field,"ecom_billingPhoneErr","Billing phone")) { valid = false; }
	// Email check.
	email1 = document.getElementById("ecom_billingEmail").value;
	if(!validateField(email1,"ecom_billingEmailErr","Billing e-mail")) { valid = false; }
	email2 = document.getElementById("ecom_billingEmail2").value;
	if(!validateField(email2,"ecom_billingEmail2Err","Confirm billing e-mail")) { valid = false; }
	if(valid) {
		if(email1 != email2) {
			document.getElementById("ecom_billingEmail2Err").innerHTML="<font color='#FF0000'>E-mail addresses do not match<br /></font>";
			valid = false;
		}
		else {
			document.getElementById("ecom_billingEmail2Err").innerHTML="";		
		}		
	}
	// End email check.

	// Validate shipping form only if necessary.
	var shippingFieldsVisibility = document.getElementById("ecom_shippingBlock").style.visibility;
	//alert("Shipping visibility: " + shippingFieldsVisibility);
	if(shippingFieldsVisibility == "visible") {
		//alert("Checking shipping fields.");
		field = document.getElementById("ecom_shippingFirstName").value;
		if(!validateField(field,"ecom_shippingFirstNameErr","Shipping first name")) { valid = false; }
		field = document.getElementById("ecom_shippingLastName").value;
		if(!validateField(field,"ecom_shippingLastNameErr","Shipping last name")) { valid = false; }
		field = document.getElementById("ecom_shippingAddress1").value;
		if(!validateField(field,"ecom_shippingAddress1Err","Shipping address")) { valid = false; }	
		//field = document.getElementById("ecom_shippingAddress2").value;	// Doesn't need to be checked.
		//if(!validateField(field,"ecom_shippingAddress2Err","Shipping address 2")) { valid = false; }
		field = document.getElementById("ecom_shippingCity").value;
		if(!validateField(field,"ecom_shippingCityErr","Shipping city")) { valid = false; }
		field = document.getElementById("shippingState").value;	// There's no ecom_ prefix on this one.
		if(!validateField(field,"ecom_shippingStateErr","Shipping state")) { valid = false; }
		field = document.getElementById("ecom_shippingZip").value;
		if(!validateField(field,"ecom_shippingZipErr","Shipping zip")) { valid = false; }
		//field = document.getElementById("ecom_shippingCountry").value;
		//if(!validateField(field,"ecom_shippingCountryErr","Shipping country")) { valid = false; }
		field = document.getElementById("ecom_shippingPhone").value;
		if(!validateField(field,"ecom_shippingPhoneErr","Shipping phone")) { valid = false; }
		// Email check.
		email1 = document.getElementById("ecom_shippingEmail").value;
		if(!validateField(email1,"ecom_shippingEmailErr","Shipping e-mail")) { valid = false; }
		email2 = document.getElementById("ecom_shippingEmail2").value;
		if(!validateField(email2,"ecom_shippingEmail2Err","Confirm shipping e-mail")) { valid = false; }
		if(valid) {
			if(email1 != email2) {
				document.getElementById("ecom_shippingEmail2Err").innerHTML="<font color='#FF0000'>E-mail addresses do not match<br /></font>";
				valid = false;
			}
			else {
				document.getElementById("ecom_shippingEmail2Err").innerHTML="";		
			}		
		}
	}
	
	if(valid)
		document.billingForm.submit();
}

function validateCheckout2Form() {
	var field = '';
	var valid = true;
	var email1 = '';
	var email2 = '';
	field = document.getElementById("ecom_cardNumber").value;
	if(!validateField(field,"ecom_cardNumberErr","Credit card number")) { valid = false; }
	field = document.getElementById("ecom_expirationMonth").value;
	if(!validateField(field,"ecom_expirationMonthErr","Expiration month")) { valid = false; }
	field = document.getElementById("ecom_expirationYear").value;
	if(!validateField(field,"ecom_expirationYearErr","Expiration year")) { valid = false; }
	field = document.getElementById("ecom_securityCode").value;
	if(!validateField(field,"ecom_securityCodeErr","Security code")) { valid = false; }

	if(valid)
		document.ccForm.submit();
}

function prepCheckout1(username) {
		if(username.length>1) {
			loginID = username;
			setLoggedIn(true);					
		}
		else {
			setLoggedIn(false);
			loginID = "";			
		}
}

function prepCheckout2(username) {
		if(username.length>1) {
			loginID = username;			
			setLoggedIn(true);
		}
		else {
			setLoggedIn(false);
			loginID = "";			
		}
}

function trimmed(val) {
	return val.replace(/^\s+|\s+$/g, '') ;
}

function validateField(field,errField,fieldName) {
	var invalidChars = '\/\'\";:?!()[]\{\}^|';
	field = trimmed(field);
	
	if(! (field.length > 0)) {	// Field is empty.
		document.getElementById(errField).innerHTML="<font color='#FF0000'>"+fieldName+" is a required field<br /></font>";
		return false;
	}
	else {	// Field is not empty.
		for (i=0; i<invalidChars.length; i++) {
		   if (field.indexOf(invalidChars.charAt(i),0) > -1) {
			  document.getElementById(errField).innerHTML="<font color='#FF0000'>"+fieldName+" contains invalid characters<br /></font>";
			  return false;
		   }
		}
		for (i=0; i<field.length; i++) {
		   if (field.charCodeAt(i)>127) {
			  document.getElementById(errField).innerHTML="<font color='#FF0000'>"+fieldName+" contains invalid characters<br /></font>";
			  return false;
		   }
		}
		if(fieldName.toLowerCase().indexOf('zip') != "-1") {	// Zip code should be numeric.
			if(!validateZip(field,errField)) {
				return false;
			}
		}		
		if(fieldName.toLowerCase().indexOf('e-mail') != "-1") {	// E-mail address validations.
			if(!validateEmail(field,1,1,errField)) {
				return false;
			}
		}		
		if(fieldName.toLowerCase().indexOf('credit card number') != "-1") {	// CC # validations.
			if(!validateCreditCardNumber(field,errField)) {
				return false;
			}
		}		
	}
	document.getElementById(errField).innerHTML="";
	return true;
}

function validateCreditCardNumber(field,errField) {
	var length = 16;
	
	if (field.length!=16) {
		document.getElementById(errField).innerHTML="<font color='#FF0000'>Please enter a 16 digit credit card number<br /></font>";
		return false;
	}
	return true;	
}


function validateZip(field,errField) {
	var valid = "0123456789-";
	var hyphencount = 0;
	
	if (field.length!=5 && field.length!=10) {
		document.getElementById(errField).innerHTML="<font color='#FF0000'>Zip code should be either 5 or 10 characters long<br /></font>";
		return false;
	}
	for (var i=0; i < field.length; i++) {
		temp = "" + field.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1") {
			document.getElementById(errField).innerHTML="<font color='#FF0000'>Invalid characters in zip code<br /></font>";
			return false;
		}
		if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
			document.getElementById(errField).innerHTML="<font color='#FF0000'>The hyphen character should be used with a properly formatted, <br />numeric zip code 5 or 10 characters in length. ex: '12345-6789'<br /></font>";
			return false;
		}
	}
	return true;
}

function validateEmail(addr,man,db,errField) {

	if (addr.length==0 && man) {
	   if (db) document.getElementById(errField).innerHTML="<font color='#FF0000'>E-mail address is required<br /></font>";
	   return false;
	}
	var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
	for (i=0; i<invalidChars.length; i++) {
	   if (addr.indexOf(invalidChars.charAt(i),0) > -1) {
		  if (db) document.getElementById(errField).innerHTML="<font color='#FF0000'>E-mail address contains invalid characters<br /></font>";
		  return false;
	   }
	}
	for (i=0; i<addr.length; i++) {
	   if (addr.charCodeAt(i)>127) {
		  if (db) document.getElementById(errField).innerHTML="<font color='#FF0000'>E-mail address contains invalid characters<br /></font>";
		  return false;
	   }
	}
	
	var atPos = addr.indexOf('@',0);
	if (atPos == -1) {
	   if (db) document.getElementById(errField).innerHTML="<font color='#FF0000'>E-mail address must contain @<br /></font>";   
	   return false;
	}
	if (atPos == 0) {
	   if (db) document.getElementById(errField).innerHTML="<font color='#FF0000'>E-mail address must not start with @<br /></font>";      
	   return false;
	}
	if (addr.indexOf('@', atPos + 1) > - 1) {
	   if (db) document.getElementById(errField).innerHTML="<font color='#FF0000'>E-mail address must contain only one @<br /></font>";      
	   return false;
	}
	if (addr.indexOf('.', atPos) == -1) {
	   if (db) document.getElementById(errField).innerHTML="<font color='#FF0000'>E-mail address must contain a period<br /></font>";      
	   return false;
	}
	if (addr.indexOf('@.',0) != -1) {
	   if (db) document.getElementById(errField).innerHTML="<font color='#FF0000'>Period must not immediately follow @<br /></font>";      
	   return false;
	}
	if (addr.indexOf('.@',0) != -1){
	   if (db) document.getElementById(errField).innerHTML="<font color='#FF0000'>Period must not immediately precede @<br /></font>";      
	   return false;
	}
	if (addr.indexOf('..',0) != -1) {
	   if (db) document.getElementById(errField).innerHTML="<font color='#FF0000'>Two periods must not be adjacent<br /></font>";         
	   return false;
	}
		
	if (db) document.getElementById(errField).innerHTML="";         
	return true;
}
