/*****************************************************************
*  File usage:  views\systemerror.tpl
*				 \accounts\add_order_account.tpl
*						\edit_account.tpl
*						\route_account.tpl
*				 \admin\add_country.tpl
					  \add_country_state.tpl
					  \case_form.tpl
*					  \edit_company.tpl
*					  \edit_company_logo.tpl
*					  \edit_country.tpl
*					  \edit_country_state.tpl
*					  \lead_form.tpl
*				 \calendar\add_activity.tpl
*						\edit_event.tpl
*						\edit_task.tpl
*				 \campaigns\edit_campaign.tpl
*				 \cases\add_case_history.tpl
*					  \edit_case.tpl
*					  \edit_case_template.tpl
*					  \edit_kb_article.tpl
*				 \contacts\contact_login.tpl
*						\edit_contact.tpl
*				 \contact_groups\edit_contact_group.tpl
*				 \deals\edit_deal.tpl
*				 \emails\edit_email.tpl
*				 \employees\edit_employee.tpl
*						 \employee_login.tpl
*				 \files\edit_file.tpl
*				 \import\dnc.tpl
*					   \lead_import.tpl
*				 \leads\add_activity.tpl
*					  \edit_lead.tpl
*					  \edit_lead_predictive.tpl
*				 \notes\edit_attachment.tpl
*					  \edit_note.tpl
*				 \orders\add_order_customer_detail.tpl
*					   \add_order_payment_details.tpl
*					   \add_order_product_details.tpl
*					   \edit_order.tpl
*				 \perms\edit_perm.tpl
*				 \promotions\edit_promotion.tpl
*				 \scripts\edit_script.tpl
*				 \triggers\deal_stage_trigger.tpl
*						\lead_status_trigger.tpl
*				 \zones\edit_zone.tpl
*------------------------------------------------------------------
*  File functions: 
*		validate():
*			 views\systemerror.tpl
*				 \accounts\add_order_account.tpl
*						\edit_account.tpl
*				 \admin\add_country.tpl
*					  \add_country_state.tpl
*					  \case_form.tpl
*					  \edit_company.tpl
*					  \edit_company_logo.tpl
*					  \edit_country.tpl
*					  \edit_country_state.tpl
*					  \lead_form.tpl
*				 \calendar\add_activity.tpl
*						\edit_event.tpl
*						\edit_task.tpl
*				 \campaigns\edit_campaign.tpl
*				 \cases\add_case_history.tpl
*					  \edit_case.tpl
*					  \edit_case_template.tpl
*					  \edit_kb_article.tpl
*				 \contacts\contact_login.tpl
*						\edit_contact.tpl
*				 \contact_groups\edit_contact_group.tpl
*				 \deals\edit_deal.tpl
*				 \emails\edit_email.tpl
*				 \employees\edit_employee.tpl
*						 \employee_login.tpl
*				 \files\edit_file.tpl
*				 \import\dnc.tpl
*					   \lead_import.tpl
*				 \leads\add_activity.tpl
*					  \edit_lead.tpl
*					  \edit_lead_predictive.tpl
*				 \notes\edit_attachment.tpl
*					  \edit_note.tpl
*				 \orders\add_order_customer_detail.tpl
*					   \add_order_payment_details.tpl
*					   \add_order_product_details.tpl
*					   \edit_order.tpl
*				 \perms\edit_perm.tpl
*				 \promotions\edit_promotion.tpl
*				 \scripts\edit_script.tpl
*				 \triggers\deal_stage_trigger.tpl
*						\lead_status_trigger.tpl
*				 \zones\edit_zone.tpl
*		isBlank():
*			js\validate.js
*		isDDSelected():
*			js\validate.js
*		checkMultiSelectHasOptions():
*			js\validate.js
*		isEmail():
*			js\validate.js
*		isZip():
*			js\validate.js
*		checkPhoneField()
*		checkIntPhoneField():
*			js\validate.js
*		isNumber():
*			js\validate.js
*		isNumberRange():
*			js\validate.js
*		getParameter():
*			js\validate.js
********************************************************************/
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
	*		IPv4        - returns an error if the value is not a valid IPv4 address format ###.###.###.###
	*/

	var errors = "";
	for (var 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 "companyemail":
					errors += isCompanyEmail(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 "ipv4":
					errors += isValidIPv4(theForm,field,fieldName,custErr);
				break;
				case "mx":
					errors += isValidDomain(theForm,field,fieldName,custErr);
				break;
				case "area_code":
					errors += isValidAreaCode(theForm,field,fieldName,custErr);
				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 = "";
	//alert(fieldName + ", " + theField + ", " + typeof(theField));
	if(typeof(theField) == "object"){
		//alert(fieldName + ", " + theField + ", " + typeof(theField));
		var theValue = theField.value;
		theValue = theValue.trim();
		//alert(theValue + " length: " + theValue.length);
		// 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, theField, fieldName,custErr)
{
	//INITIALIZE VARS
	theField = theForm[theField];

	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
	theField = eval("theForm." + theField);
	var errors = "";
	theField.value = theField.value.trim();
	var theValue = theField.value;
	
	// CHECK IF THE EMAIL IS VALID
	var re = new RegExp();
	re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
	if (!re.test(theValue) && theValue.length != 0) 
	{
		if (custErr){
			errors += custErr+"\n"
		} else {
			errors += fieldName + " is not a valid email address.\n";
		}
	}
	return errors;
}

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

	try
	{
		url = "validate_email.php?email="+theValue;
		response = AJAX_get(url, false);
		if (response == "valid")
		{
			errors.length == 0;
			return errors;
		}
	}
	catch(e){}

	if (custErr){
		errors += custErr+"\n"
	} else {
		errors += theValue + " is not a valid email address.\n";
	}
	return errors;
}

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

	try
	{
		url = "validate_areacode.php?phone_number="+theValue;
		response = AJAX_get(url, false);
		if (response == "1")
		{
			errors.length == 0;
			return errors;
		}
	}
	catch(e){}

	if (custErr){
		errors += custErr+"\n"
	} else {
		errors += theValue + " has an invalid area code.\n";
	}
	return errors;
}

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

	var atsign = theValue.substring(0,theValue.lastIndexOf('@')+1);
	var domain = theValue.substring(atsign.length,theValue.length+1);
	
	// CHECK IF THE EMAIL IS NOT A BULK ADDRESS
	if( (domain == 'gmail.com') || (domain == 'hotmail.com') || (domain == 'yahoo.com') || (domain == 'yahoo.co.in')|| (domain == 'comcast.net') || (domain == 'comcast.net') || (domain == 'aol.com') || (domain == 'msn.com') || (domain == 'earthink.net') || (domain == 'geocities.com') ){
		if (custErr){
			errors += custErr+"\n"
		} else {
			errors += theValue + " is not a valid company email address (Free addresses not accepted).\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;
	*/
	return errors;
}

//////////////////////////////////////////////////////////////////////////////
//
//  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;
}

//////////////////////////////////////////////////////////////////////////////
//
//  isValidIPv4()
//
//////////////////////////////////////////////////////////////////////////////
function isValidIPv4(theForm, theField, fieldName, custErr)
{
	errors = "";

	// CHECK TO SEE IF ITS AN ARRAY OF VALUES
	if (theField.indexOf("[]") > 0){
	  ipFields = theForm.elements[theField];
	  for (var i=0;i<ipFields.length;i++ )
	  {
		ipFields[i].value = ipFields[i].value.trim();
		// ALLOW EMPTY FIELDS
		if (ipFields[i].value != "")
		  errors += validateIP(ipFields[i].value, custErr);
		
	  }
	} else {
      ipField = eval("theForm." + theField);
	  ipField.value = ipField.value.trim();
	  // ALLOW EMPTY FIELD
	  if (ipField.value != "")
	    errors += validateIP(ipField.value, custErr);
	  
	}
	
	return errors;
}

//////////////////////////////////////////////////////////////////////////////
//
//  validateIP()
//
//////////////////////////////////////////////////////////////////////////////
function validateIP(address, custErr)
{
	sections = address.split(".");
	if (sections.length != 4)
	{
		if (custErr)
			return custErr+"\n";
		else
			return "IP Address: "+address+" is invalid.\n";
	}

	for (var i=0;i<sections.length;i++)
	{
		num = Number(sections[i]);
		if (num > 255 || num < 0 || isNaN(num))
		{
			if (custErr)
				return custErr+"\n";
			else
				return "IP Address: "+address+" is invalid.\n";
		}
	}
	return "";
}


//////////////////////////////////////////////////////////////////////////////
//
//  getParameter()
//
//////////////////////////////////////////////////////////////////////////////
function getParameter(theValue)
{
	startIndex = theValue.indexOf("(");
	endIndex   = theValue.indexOf(")");
	return theValue.substr(startIndex+1,endIndex-startIndex-1);
}