// Reference: http://webreference.com/new/cfjsvalidate2.html
/*
	Usage:
	<form action="formprocessor.cfm" method="post" onSubmit="return checkForm(this)">
	
	Include:
	<script language="JavaScript1.1" src="/javascript/validate.js" type="text/javascript"></script>
	
	Note:
	Input name is case sensitive.  e.g. zip must match zip_required
*/

/*****************************************************************************/
function checkForm(thisform) {
	var returnval = true;
	var checkField = false;
	var indx;
	var field;
	var fieldname;
	var value;
	
	// Browser must be version 4 or greater
	if (parseInt(navigator.appVersion) < 4)
		return true;
	
	for(var j = 0; j < thisform.elements.length; j++) {
		indx = thisform.elements[j].name.indexOf('_required');
		if (indx != -1) {
			fieldname = thisform.elements[j].name.substring(0, indx);
			field = thisform.elements[fieldname];

			// Get value for field
			if (field.type == "select-one" || field.type == "select-multiple") {
				if (field.selectedIndex == -1)
					value = "";
				else
					value = field.options[field.selectedIndex].value;
				checkField = true;
			} else if (field.type == "text" || field.type == "textarea" || field.type == "password" || field.type == "file") {
				value = trim(field.value);
				checkField = true;
			} else if (field.type == "checkbox") { // used for checkboxes that have unique names
				if (field.checked)
					value = field.value;
				else
					value = "";
				checkField = true;
			} else if (field.type == null && field[0].type == "checkbox") { // used for checkboxes that have the same name
				var checkboxChecked = false;
				for(var i = 0; i < field.length; i++) {
					if (field[i].checked) {
						checkboxChecked = true;
						value = field[i].value;
						break;
					}
				}
				if (checkboxChecked == false)
					value = "";
				checkField = true;
			} else if (field.type == "radio") { // used for solitary radio buttons
				if (field.checked)
					value = field.value;
				else
					value = "";
				checkField = true;
			} else if (field.type == null && field[0].type == "radio") {
				var radioChecked = false;
				for(var i = 0; i < field.length; i++) {
					if (field[i].checked) {
						radioChecked = true;
						value = field[i].value;
						break;
					}
				}
				if (radioChecked == false)
					value = "";
				checkField = true;
			}

			// If this is a valid field to check, make sure length is not 0
			if (checkField) {
				if ( value.length == 0 ) {
					alert(thisform.elements[j].value);
					if (field.type != null)
						field.focus(); // move focus to required field
					returnval = false;
					break;
				}
			}
		}
		else {
			var indx;
			indx = thisform.elements[j].name.indexOf('_alphanum');
			if (indx != -1) {
				fieldname = thisform.elements[j].name.substring(0, indx);
				field = thisform.elements[fieldname];
		
				// Get value for field
				if (field.type == "text" || field.type == "textarea" || field.type == "password" || field.type == "file") {
					value = trim(field.value);
					checkField = true;
				}
				
				// If this is a valid field to check, make sure there are no invalid characters in the string
				if (checkField) {
					if ( hasInvalidChars(value) ) {
						alert(thisform.elements[j].value);
						if (field.type != null)
							field.focus(); // move focus to required field
						returnval = false;
						break;
					}
				}
			}
			else {
				var indx;
				indx = thisform.elements[j].name.indexOf('_emailfmt');
				if (indx != -1) {
					
					fieldname = thisform.elements[j].name.substring(0, indx);
					field = thisform.elements[fieldname];
		
					// Get value for field
					if (field.type == "text" || field.type == "textarea" || field.type == "password" || field.type == "file") {
						value = trim(field.value);
						checkField = true;
					}
				
					// If this is a valid field to check, make sure it is in the correct email format
					if (checkField) {
						if ( !isValidEmailFmt(value) ) {
							//alert(thisform.elements[j].value);
							if (field.type != null)
								field.focus(); // move focus to required field
							returnval = false;
							break;
						}
					}
				}
			}
		}
	}
	return returnval;
}
/*****************************************************************************/

/*****************************************************************************/
function hasInvalidChars(str) {
	
	// Check for invalid characters in the string. Return true if the string
	// contains invalid characters, otherwise return false meaning the entire
	// string contains valid characters.
	
	// Create a regular expression that checks for invalid characters.
	var regExp = new RegExp("[^ a-zA-Z0-9-&/().:=_&%#?']+");
	
	return (regExp.test(str));
}
/*****************************************************************************/

/*****************************************************************************/
function isValidEmailFmt(emailStr) {
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
		alert("Email address seems incorrect (check @ and .'s)")
		return false;
	}
	
	var user=matchArray[1]
	var domain=matchArray[2]
	if (user.match(userPat)==null) {
		alert("The username doesn't seem to be valid.")
		return false;
	}

	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Destination IP address is invalid.")
			return false;
	    }
    }
    	return true;
	}

	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("The domain name doesn't seem to be valid.")
		return false;
	}

	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>3) {
	   alert("The address must end in a three-letter domain, or two letter country.")
	   return false;
	}

	if (len<2) {
	   var errStr="This address is missing a hostname."
	   alert(errStr)
	   return false;
	}

	return true;
}
/*****************************************************************************/

/*****************************************************************************/
function ltrim (str) { return str.replace(/^\s*/, "") }
/*****************************************************************************/

/*****************************************************************************/
function rtrim (str) { return str.replace(/\s*$/, ""); }
/*****************************************************************************/

/*****************************************************************************/
function trim (str) { return rtrim(ltrim(str)); }
/*****************************************************************************/

/*****************************************************************************/
function isPositiveInteger (s, fieldName) {
	if ((parseInt (s) > 0))
		return ( (parseInt (s) > 0) );
	else {
		alert("The " + fieldName + " must be a positive number.");
		return false;
	}
}
/*****************************************************************************/

/*****************************************************************************/
// Swap out the values for the "PRD" form fields based on a checkbox's state
function swapPRDValues(field, origValue) {
	origMasterPRD = new String(document.getElementById('OrigMasterPRD').value);
	theForm = field.form;
		
	 if (field.checked) {
		if (field) {
			// This loop replaces JUST THE FIRST prd field value and 
			// sets all other "PRD" fields to the empty string
			replacedSKU = false;
			for (i = 0; i < theForm.elements.length-1; i++)  {
				if (theForm.elements[i].name == 'PRD' && (!replacedSKU) ) {
					theForm.elements[i].value = field.value;
					replacedSKU = true;
				}
				else if (theForm.elements[i].name == 'PRD')
					theForm.elements[i].value = '';
			}
		}
	}
	else if (!field.checked) {
		// Create an array from the string of original PRD values
		aryOrigMasterPRD = origMasterPRD.split(',');
		idx = 0;
		if (origMasterPRD) {
			// This loop re-instates the prd values for each PRD field
			for (i = 0; i < theForm.elements.length-1; i++) {
				if (theForm.elements[i].name == 'PRD') {
					theForm.elements[i].value = aryOrigMasterPRD[idx];
					idx++;
				}
			}
		}
	}
	return;
}
/*****************************************************************************/
