String.prototype.trim = function () {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};
function validate(fieldArray, theForm)
{
	/**
	*  fieldArray:
	*	each item in the array is composed of three values that are pipe delimited
	*	the first one is the actual name of the html form field
	*	the second one is the name of the field as it should appear to the user
	*	the third one is a comma delimited list showing what validation to use on the field
	*	the fourth one is optional and specifies a custom error message to use
	*
	*	example:
	*		//This is how the array should be set up in the html template
	*		<script language="javascript">
	*			var fieldArray = new Array();
	*			fieldArray[0] = "last_name|Last Name|blank";
	*			fieldArray[1] = "account_name|Company|blank|This field cannot be blank!!!";
	*			fieldArray[2] = "lead_status_id|Lead Status|DDSelected";
	*			fieldArray[3] = "phone|Phone|phone";
	*			fieldArray[4] = "phone2|International Phone|intphone";
	*			fieldArray[5] = "email|Email|blank,email";
	*			fieldArray[6] = "zip|Zip Code|zip";
	*			fieldArray[7] = "percentage|Percent|numberrange(1-100),number";
	*		</script>
	*
	*	possible values for validation:
	*		blank       - returns an error string if the field is an empty string
	*		blankNoZero - returns an error string if the field is an empty string or it is a 0
	*		DDSelected  - returns an error string if the selected value is an empty string
	*		phone       - tries to parse the field into a standard ###-###-#### format
	*		              if the value cannot be parsed an error string is returned
	*		email       - returns an error string if the value of the field is not 
	*		              empty and does not match a standard email format
	*		zip         - returns an error string if the value does not match a standard zip format
	*		number      - returns an error string if the value is not a number
	*		numberrange - returns an error string if the value is not a number or if the number is 
	*		              not within a specified range
	*
	*/

	var errors = "";
	for (i=0;i<fieldArray.length;i++)
	{
		if (fieldArray[i] == "") continue;
		data = fieldArray[i].split("|");
		field = data[0];
		fieldName = data[1];
		validateTypes = data[2].split(",");
		custErr = data[3];
		for (x=0;x<validateTypes.length;x++)
		{
			if (validateTypes[x].indexOf("(") > 0)
			{
				parameter = getParameter(validateTypes[x]);
				if (parameter.length < 1)
				{
					alert("Invalid parameter value for validation type of " + validateTypes[x] + " on " + field + " field");
				}
				theValidateType = validateTypes[x].toLowerCase().substr(0,validateTypes[x].indexOf("("));
			}else{
				theValidateType = validateTypes[x].toLowerCase();
			}
			
			switch (theValidateType)
			{	
				case "blank":
					errors += isBlank(theForm,field,fieldName,custErr,false);
				break;
				case "blanknozero":
					errors += isBlank(theForm,field,fieldName,custErr,true);
				break;
				case "ddselected":
					errors += isDDSelected(theForm,field,fieldName,custErr);
				break;
				case "multiselecthasoptions":
					errors += checkMultiSelectHasOptions(theForm,field,fieldName,custErr);
				break;
				case "phone":
					errors += checkPhoneField(theForm,field,fieldName,custErr);
				break;
				case "intphone":
					errors += checkIntPhoneField(theForm,field,fieldName,custErr);
				break;
				case "email":
					errors += isEmail(theForm,field,fieldName,custErr);
				break;
				case "zip":
					errors += isZip(theForm,field,fieldName,custErr);
				break;
				case "number":
					errors += isNumber(theForm,field,fieldName,custErr);
				break;
				case "numberrange":
					errors += isNumberRange(theForm,field,fieldName,parameter,custErr);
				break;
				case "date":
					errors += isDate(theForm, field, fieldName);
				break;
			}
		}
	}
	
	if (errors.length > 0)
	{
		alert("More Information Required:\n==============================\nPlease complete all required fields:\n\n" + errors);
		return false;
	}
	return true;
}


//////////////////////////////////////////////////////////////////////////////
//
//  isBlank()
//
//////////////////////////////////////////////////////////////////////////////
function isBlank(theForm, theField, fieldName,custErr,zeroIsBlank)
{
	//INITIALIZE VARS
	theField = eval("theForm." + theField);
	
	var errors = "";
	if(typeof(theField) == "object"){
		theField.value = theField.value.trim();
		var theValue = theField.value;
		// CHECK LENGTH OF PHONE NUMBER
		if (theValue.length < 1 || (zeroIsBlank && theValue==0)){
			if (custErr){
				errors += custErr+"\n"
			} else {
				errors += fieldName + " is a required field.\n"
			}
		}
	}
	
	return errors;
}


//////////////////////////////////////////////////////////////////////////////
//
//  isDDSelected()
//
//////////////////////////////////////////////////////////////////////////////
function isDDSelected(theForm, theFieldName, fieldName,custErr)
{
	//INITIALIZE VARS
	if (theFieldName.indexOf("[]") > 0){
		isprod = true;
		theField = document.getElementById(theFieldName);
	} else {
		theField = eval("theForm." + theFieldName);
	}
	var errors = "";
	var theValue = "";

	if (theField.options.length > 0 && theField.selectedIndex >= 0){
		theValue = theField.options[theField.selectedIndex].value;
	} else {
		if (custErr){
			errors += custErr+"\n"
		} else {
			errors += "You must select an option from " + fieldName + ".\n"
		}
		return errors;
	}

	// CHECK IF THE VALUE IS SOMETHING OTHER THAN BLANK
	if (theValue.length < 1){
		if (custErr){
			errors += custErr+"\n"
		} else {
			errors += "You must select an option from " + fieldName + ".\n"
		}
	}
	return errors;
}


//////////////////////////////////////////////////////////////////////////////
//
//  checkMultiSelectHasOptions()
//
//////////////////////////////////////////////////////////////////////////////
function checkMultiSelectHasOptions(theForm, theField, fieldName,custErr)
{
	//INITIALIZE VARS
	theField = document.getElementById(theField);
	var errors = "";
	var theValue = "";
	// CHECK THAT THE SELECT FIELD HAS OPTIONS
	if (theField.options.length < 1)
	{
		if (custErr){
			errors += custErr+"\n"
		} else {
			errors += fieldName + " cannot be blank.\n"
		}
	}
	return errors;
}

//////////////////////////////////////////////////////////////////////////////
//
//  isEmail()
//
//////////////////////////////////////////////////////////////////////////////
function isEmail(theForm, theField, fieldName,custErr)
{
	//INITIALIZE VARS
	var theField = eval("theForm." + theField);
	theField.value = theField.value.trim();
	var errors = '';
	var str = theField.value;
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);//first @ index
	var lstr=str.length;//string length
	var ldot=str.indexOf(dot);//first . index
	var valid = true;
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) valid = false;//@ is missing or is first character
	else if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) valid = false;//dot is missing or is first/last character
	else if (str.indexOf(at,(lat+1))!=-1) valid = false;//there's more than one @
	else if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) valid = false;//there's a dot right before or right after the @
	else if (str.indexOf(dot,(lat+2))==-1) valid = false;//there's no dot after the @
	else if (str.indexOf(" ")!=-1) valid = false;//there are spaces in the address
	
	if (!valid) 
	{
		errors += fieldName + " is not a valid email address.\n";
	}
	return errors;
}


//////////////////////////////////////////////////////////////////////////////
//
//  isZip()
//
//////////////////////////////////////////////////////////////////////////////
function isZip(theForm, theField, fieldName,custErr)
{
	
	//INITIALIZE VARS
	theField = eval("theForm." + theField);
	var errors = "";
	var theValue = theField.value;

	// CHECK IF THE ZIPCODE IS VALID
	var re = new RegExp();
	re = /^[0-9]{5}$/;
	if (theValue.length > 5)
	{
		theValue = theValue.substr(0,5);
	}
	if (!re.test(theValue) && theValue.length != 0) 
	{
		errors += fieldName + " is not a valid zip code.\n";
	}
	theField.value = theValue;
	return errors;

	
	errors.length == 0;
	return errors;
}


//////////////////////////////////////////////////////////////////////////////
//
//  checkPhoneField()
//
//////////////////////////////////////////////////////////////////////////////
function checkPhoneField(theForm, phoneField, fieldName,custErr)
{
	//INITIALIZE VARS
	
	phoneField = eval("theForm." + phoneField);
	var firstThree = "";
	var middleThree = "";
	var lastNumbers = "";
	var errors = "";
	var phone=phoneField.value;
	

	// CLEAR ALL NON NUMBER CHARACTERS
	phone = phone.replace(/[\(\)\- ,\.]/g,"");

	// CLEAR LEADING 1
	if (phone.length > 10){
		phone = (phone.charAt(0)=="1"?phone.substr(1,phone.length):phone);
	}
	
	// CHECK LENGTH OF PHONE NUMBER
	if (phone.length < 10 && phone.length > 0){
		errors += fieldName + " is an invalid phone format:  Not enough numbers.\n"
	}

	// CHECK IF INPUT IS A NUMBER
	if (isNaN(phone)){
		errors += fieldName + " is an invalid phone format:  Invalid characters.\n"
	}

	// SHOW ERRORS
	if (errors.length > 0){
		//errors += "\nMust use following format:  ###-###-####";
		return errors;
	}

	// GET FIRST THREE
	if (phone.length > 2){
		firstThree = "(" + phone.substr(0,3) + ") ";
		// GET SECOND THREE
		if (phone.length > 5){
			middleThree = phone.substr(3,3) + "-";
			// GET REST OF NUMBER
			if (phone.length > 5){
				lastNumbers = phone.substr(6,phone.length);
			}
		}else{
			lastNumbers = phone.substr(3,phone.length);
		}
	}else{
		lastNumbers = phone;
	}
	
	// PUT NUMBERS TOGETHER
	newPhone = firstThree + middleThree + lastNumbers;

	
	// RETURN VALUE
	phoneField.value = newPhone;
	return errors;

	errors.length == 0;
	return errors;
	phoneField.value = phoneField;	
}

//////////////////////////////////////////////////////////////////////////////
//
//  checkIntPhoneField()
//
//////////////////////////////////////////////////////////////////////////////
function checkIntPhoneField(theForm, phoneField, fieldName,custErr)
{
	//INITIALIZE VARS
	
	phoneField = eval("theForm." + phoneField);
	var firstThree = "";
	var middleThree = "";
	var lastNumbers = "";
	var errors = "";
	var phone=phoneField.value;
	
	// CLEAR LEADING 1
	if (phone.length == 11){
		phone = (phone.charAt(0)=="1"?phone.substr(1,phone.length):phone);
	}

	// IF LENGTH OF PHONE IS EQUAL TO 10 CLEAR ALL NON NUMBER CHARACTERS
	if (phone.replace(/[\(\)\- ,\.]/g,"").length == 10){
		phone = phone.replace(/[\(\)\- ,\.]/g,"");
	}else{
		return errors;
	}

	// GET FIRST THREE
	firstThree = "(" + phone.substr(0,3) + ") ";

	// GET SECOND THREE
	middleThree = phone.substr(3,3) + "-";
	
	// GET REST OF NUMBER
	lastNumbers = phone.substr(6,phone.length);
	
	// PUT NUMBERS TOGETHER
	newPhone = firstThree + middleThree + lastNumbers;
	
	// RETURN VALUE
	phoneField.value = newPhone;
	return errors;
}

//////////////////////////////////////////////////////////////////////////////
//
//  isNumber()
//
//////////////////////////////////////////////////////////////////////////////
function isNumber(theForm, theField, fieldName,custErr)
{
	//INITIALIZE VARS
	var theFormField = eval("theForm." + theField);
	var errors = "";
	var theFieldValue = theFormField.value;
	
	// CHECK IF THE VALUE IS A NUMBER OR NOT
	if (isNaN(theFieldValue)){
		if (custErr){
			errors += custErr+"\n"
		} else {
			errors += fieldName + " is not a valid number.\n"
		}
	}
	return errors;
}

//////////////////////////////////////////////////////////////////////////////
//
//  isNumberRange(range)
//
//////////////////////////////////////////////////////////////////////////////
function isNumberRange(theForm, theField, fieldName, range,custErr)
{
	//INITIALIZE VARS
	var theFormField = eval("theForm." + theField);
	var errors = "";
	var theFieldValue = theFormField.value;
	
	// CHECK IF THE VALUE IS A NUMBER OR NOT
	errors += isNumber(theForm, theField, fieldName, custErr);
	
	// CHECK IF THE VALUE WITHIN THE SPECIFIED RANGE
	rangeVals = range.split("-");
	if (parseInt(theFieldValue) < parseInt(rangeVals[0]) || parseInt(theFieldValue) > parseInt(rangeVals[1])){
		if (custErr){
			errors += custErr+"\n"
		} else {
			errors += fieldName + " is not within the specified range of " + rangeVals[0] + " - " + rangeVals[1] + ".\n"
		}
	}
	return errors;
}
function isDate(theForm, theField, fieldName){
	//INITIALIZE VARS
	theField = eval("theForm." + theField);
	
	var errors = "";
	if(typeof(theField) == "object"){
		//ajax.js is required for this to work
		theField.value = AJAX_get("/do=parse_date?date="+theField.value, false);
		var theValue = theField.value;
		// CHECK LENGTH OF PHONE NUMBER
		if (theValue.length < 1){
			errors += fieldName + " is a required field.\n"
		}
	}
	
	return errors;
}
//////////////////////////////////////////////////////////////////////////////
//
//  getParameter()
//
//////////////////////////////////////////////////////////////////////////////
function getParameter(theValue)
{
	startIndex = theValue.indexOf("(");
	endIndex   = theValue.indexOf(")");
	return theValue.substr(startIndex+1,endIndex-startIndex-1);
}