// This fcn is called from LHP template, DivisionLocalHomePage.xml
function validateLogin(sUser, sPassword)
{	
	var oValidator = new Validator( "Please enter:\n");
	
	if (oValidator.CheckRequired(sUser, "User Name (your e-mail address)"))
	{
		oValidator.CheckEmailFormat(sUser, true, "E-mail format");
	}
	
	oValidator.CheckRequired(sPassword, "Password");
	
	if(oValidator.HasErrors())
	{
		alert(oValidator.GetErrorMessage());
		return false;
	}
	return true;	
}


//These validation functions present a single popup to the 
// user when multiple validation errors occur.


//Constructor;
function Validator(sInitErrorMessage)
{
	this.sErrorMessage = sInitErrorMessage;
	this.bSetFocus = true;
	
	//Define Methods for this object
	this.HasErrors = Validator_HasErrors;
	this.GetErrorMessage = Validator_GetErrorMessage;
	this.CheckZipFive = Validator_CheckZipFive;
	this.CheckRequired = Validator_CheckRequired;
	this.CheckLength = Validator_CheckLength;
	this.CheckPhoneEx = Validator_CheckPhoneEx;
	
	// NOTE ADDITIONS
	this.CheckEmailFormat = Validator_CheckEmailFormat;
	this.CheckCheckbox = Validator_CheckCheckbox;
	this.CheckPasswords = Validator_CheckPasswords;
	
	this.CheckPhoneDigits = Validator_CheckPhoneDigits;
	
}

function Validator_HasErrors()
{
	return !this.bSetFocus;
}

function Validator_GetErrorMessage()
{
	return this.sErrorMessage;
}


/***************************************************
	Validate required fields
	oFld:		name of required field
	sMessage:	unformatted string describing the field. e.g. "User Name".
****************************************************/
function Validator_CheckRequired(oFld,sMessage)
{
	//Debug 	alert("Called CheckRequired on " + oFld.value);

	var sValue = oFld.value;

	if (sValue == "") 
	{
		this.sErrorMessage += "- " + sMessage + "\n";	
			
		if (this.bSetFocus)
			oFld.focus();
		this.bSetFocus = false;
		return false;
	}
	return true	;
}



/***************************************************
	Require that a checkbox is checked
****************************************************/
function Validator_CheckCheckbox(oFld, sMessage)
{	
	//var CheckboxValue = oFld.checked;
	if (oFld.checked == false)	
	{		
		this.sErrorMessage += "- " + sMessage + "\n";
		if (this.bSetFocus) 
				oFld.focus();
		this.bSetFocus = false;
		return false;
	}
}

	

	/*
	@func bool | checkPasswords | Compares two values for matching and also makes certain that the correct length, and number of letters and numbers is inputed
	@parm object | oFld | Input object to validate
	@parm object | oFld2 | Input object to compare to
	@parm int | iMinNumbers | Minimum number of numeric chars
	@parm int | iMinLetters | Minimum number of alphabetic chars
	@parm int | iMinChar | Minimum number of chars over all
	@rdesc Returns true if compare works, otherwises adds error message to sValid
	*/
	
	/***************************************************
	Check 2 passwords for match, min characters, min numbers, and min letters
	****************************************************/
	function Validator_CheckPasswords(oFld,oFld2, iMinNumbers, iMinLetters, iMinChar)
	{
		//Debug alert("Called checkPasswords()");
		
		var sNum, sAlpha
		sNums = stripNumber(oFld.value);
		sAlpha = stripChars(oFld.value);
		
		//Debug		alert("Num " + sNums.length + " Alpha " + sAlpha.length);
		
		if(oFld.value != oFld2.value)
		{
			this.sErrorMessage += "- Please enter the same value in both password boxes\n";
			
			if (this.bSetFocus) 
				oFld.focus();
			this.bSetFocus = false;
			return false;
		} 
		// Max of 12 characters (hardcoded). 
		else if  (sNums.length > 12 || oFld.value.trim().length < iMinChar) 
		{	
			this.sErrorMessage += "- Please edit your password so that it contains from " + iMinChar + " to 12 characters\n";
			if (this.bSetFocus) 
				oFld.focus();
			this.bSetFocus = false;
			return false;
		}
		
		else if (iMinNumbers > 0 && sNums < iMinNumbers)
		{
			this.sErrorMessage += "- Please edit your password so that it contains at least " + iMinNumbers + " number(s)\n";
			if (this.bSetFocus)
				oFld.focus();
			this.bSetFocus = false;
			return false;
		}
		else if (iMinLetters > 0 && sAlpha < iMinLetters)
		{
			this.sErrorMessage += "- Please edit your password so that it contains at least "  + iMinLetters + " letter(s)\n";
			if (this.bSetFocus)
				oFld.focus();
			this.bSetFocus = false;
			return false;
		}
		return true;
	}
	
	
	/*
	@func string | stripChars | removes the everything but alphabetic information from a string
	@parm string | theString | String to process
	@rdesc Returns subset of theString containing only alphabetic information
	*/	
	function stripChars(theString)
	{
		var String;
		
		var re = /\d/gi;
		String = theString.replace(re,'');

		return String;
	}
	
	/*
	@func string | stripNumber | removes the everything but numeric information from a string
	@parm string | theString | String to process
	@rdesc Returns subset of theString containing only numeric information
	*/	
	function stripNumber(theNumber){
		var strNum
		
		var re = /\D/gi;
		strNum = theNumber.replace(re,'');

		return strNum;
	}
	
	/*****NEED THESE FOR TRIM FUNCTIONS******/	
	String.prototype.rightTrim = rightTrim;
	String.prototype.leftTrim = leftTrim;
	String.prototype.trim = trim;

	/*
	@func String Object | rightTrim | Trims trailing white space from string.  Uses prototype definition  "String.prototype.rightTrim = rightTrim;".
	@rdesc Returns Copy of string with trailing whitespace stripped off.
	*/
	function rightTrim() {
		return this.replace(/\s+$/gi, "");
	}

	/*
	@func String Object | leftTrim | Trims leading white space from string. Uses prototype definition  "String.prototype.leftTrim = leftTrim;".
	@rdesc Returns Copy of string with leading whitespace stripped off.
	*/
	function leftTrim() {
		return this.replace(/^\s*/gi, "");
	}

	/*
	@func String Object | trim | Trims leading and trailing white space from string. Uses prototype definition  "String.prototype.trim = trim;".
	@rdesc Returns Copy of string with leading and trailing whitespace stripped off.
	*/
	function trim() {
		return this.replace(/^\s+/,'').replace(/\s+$/,'');
	}



/*
@func bool | checkEmail | Compares the value of the object passed in to a Regular Express
@parm object | oField | Input object to validate
@rdesc Returns true if compare works, otherwises adds error message to sValid
*/
	
/***************************************************
	Check format of e-mail
****************************************************/
function Validator_CheckEmailFormat(oFld,bRequired,sMessage)
{
	var emailStr = oFld.value;
	
	//Debug alert('Called CheckEmailFormat on ' + emailStr);
	
	if (emailStr == "" && !bRequired)
	{
		return true;
	}

	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */
	var checkTLD=1;

	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	
	var emailPat=/^(.+)@(.+)$/;
	
	//	Prohibit: `~!#$%^&*()=+{}[]|\'?		Only allow alphanumerics, dash, underscore, @, and periods.
	var specialChars="\\(\\) `~!#$%^&\*\+=\|\/\}'\? ><@,;:\\\\\\\"\\.\\[\\]";
			
	var validChars="\[^\\s" + specialChars + "\]";

	/* The following pattern applies if the "user" is a quoted string (in
		which case, there are no rules about which characters are allowed
		and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
		is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")";

	/* The following pattern applies for domains that are IP addresses,
		rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
		e-mail address. NOTE: The square brackets are required. */
	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 + ")*$");

	/* The following pattern describes the structure of a normal symbolic
		domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		this.sErrorMessage += "- Please check your e-mail address for '@' and '.' characters\n";
		if (this.bSetFocus)
			oFld.focus();
		this.bSetFocus = false;
		return false;
	}

	var user=matchArray[1];
	var domain=matchArray[2];

	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			this.sErrorMessage += "- Please check your e-mail address for invalid characters\n";
			if (this.bSetFocus)
				oFld.focus();
			this.bSetFocus = false;
			return false;
		}
	}

	// Check domain
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			this.sErrorMessage += "- Please check the domain name of your e-mail address for invalid characters\n";
			if (this.bSetFocus)
				oFld.focus();
			this.bSetFocus = false;
			return false;
		}
	}

	// Check user
	if (user.match(userPat)==null) {
		this.sErrorMessage += "- Please check your e-mail user name\n";
		if (this.bSetFocus)
			oFld.focus();
		this.bSetFocus = false;
		return false;
	}

	/* If the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				this.sErrorMessage += "- Please check your e-mail destination IP address\n";
				if (this.bSetFocus)
					oFld.focus();
				this.bSetFocus = false;
				return false;
			}
		}
	return true;
	}

	// Domain is symbolic name.  Check if it's valid.
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			this.sErrorMessage += "- Please check your e-mail domain name\n";
			if (this.bSetFocus)
				oFld.focus();
			this.bSetFocus = false;
			return false;
		}
	}

	/* domain name seems valid, but now make sure that it ends in a
		known top-level domain (like com, edu, gov) or a two-letter word,
		representing country (uk, nl). Added ignoreCase March02. */
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat).ignoreCase==-1) {
		this.sErrorMessage += "The e-mail address must end in a well-known domain or two letter country\n";
		if (this.bSetFocus)
			oFld.focus();
		this.bSetFocus = false;
		return false;
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
		this.sErrorMessage += "- Please check your e-mail address for the host name\n";
		if (this.bSetFocus)
			oFld.focus();
		this.bSetFocus = false;
		return false;
	}
	return true;
}

/***************************************************
	Check ZIP for 5 valid numbers
****************************************************/
function Validator_CheckZipFive(oFld,bRequired,sMessage)
{	

	var ZipValue = oFld.value;
	if (ZipValue == "" && !bRequired) 
	{
		return true;
	}
	else
	{
		var ZipPattern = new RegExp("^[0-9]{5}$");
		var ZipCheck = ZipValue.match(ZipPattern);
		if (!(ZipCheck != null))
		{
			this.sErrorMessage += "- 5-digit " + sMessage + " Code\n";	
			
			if (this.bSetFocus)
				oFld.focus();
			this.bSetFocus = false;
			return false;
		}
		else
			return true;
	}
}


/******************************************************************************************
	Check single-box phone field for exactly 10 digits after stripping non-numeric characters.
	
	@func bool | CheckPhone Digits | Strips non-numerics and validates for 10 digits.
	@parm object | oFld | Input object to validate.
	@parm bool | bRequired | Whether field is required.
	@parm string | sMessage | String describing the field.
	
******************************************************************************************/
function Validator_CheckPhoneDigits(oFld,bRequired,sMessage)
{
	var PhoneValue = oFld.value;	
	var PhoneLength = PhoneValue.length;
	var PhoneStripped = stripNumber(PhoneValue);	// Remove all non-numeric characters.
	
	// Debug alert("Stripped phone number: " + PhoneStripped + "\nLength: " + PhoneStripped.length);
	
	// Require 10 digits
	if (PhoneStripped.length < 10 || PhoneStripped.length > 10)
	{
		this.sErrorMessage += "- " + sMessage + " (10-digits in any format)\n";	
		if (this.bSetFocus)
				oFld.focus();
		this.bSetFocus = false;
		return false;
	}
	
	/* Format for email message*/
	if (PhoneStripped.length == 10)
	{
		var sPhone = new String(PhoneStripped);	
		var sArea = sPhone.substr(0,3);
		var sPrefix = sPhone.substr(3,3);
		var sBody = sPhone.substr(6,4);
		var sPhoneFormatted = sArea + "-" + sPrefix + "-" + sBody;
		//debug alert("Formatted phone number: " + sPhoneFormatted);
		
		// Plug formatted number back in.
		oFld.value = sPhoneFormatted;
	}
}
	
	
	
	function localcheckPhone(oField, sInput) {
		var oPattern = /^\d{3}-\d{3}-\d{4}$/;
		var oPatternExt = /^\d{3}-\d{3}-\d{4}x\d+$/;
		if(oField.value > "" && !(oPattern.test(oField.value) || oPatternExt.test(oField.value))) {
			return false;
		}
		return true;
	}
	
	

/***************************************************
	Require a minimum length, sLength
****************************************************/
function Validator_CheckLength(oFld, sLength, sMessage)
{
	var sInputLength = oFld.value.length;
	
	if (sInputLength < sLength) 
	{
		this.sErrorMessage += "- " + sMessage + "\n";	
			
		if (this.bSetFocus)
			oFld.focus();
		this.bSetFocus = false;
		return false;
	}
	return true	;
}


/***************************************************
	Validate a 3-box phone field
****************************************************/
function Validator_CheckPhoneEx(oAreaFld,oPrefixFld,oBodyFld,oExFld,bRequired,sMessage)
{

	var AreaValue = oAreaFld.value;
	var PrefixValue = oPrefixFld.value;
	var BodyValue = oBodyFld.value;
	var ExValue = "";
	if(oExFld)
	{
		ExValue = oExFld.value;
	}

	if (AreaValue == "" &&  PrefixValue == "" && BodyValue == ""  && ExValue == "" && !bRequired) 
	{
		return true;
	}
	else
	{
		var Pattern3 = new RegExp("^[0-9]{3}$");
		var Pattern4 = new RegExp("^[0-9]{4}$");
		var PatternEx = new RegExp("^[0-9]{0,10}$");
		
		if (!( Pattern3.test(AreaValue) && Pattern3.test(PrefixValue) && Pattern4.test(BodyValue) && PatternEx.test(ExValue))  )
		{
			this.sErrorMessage += "- " + sMessage + ": (123) 123-1234\n";	
			
			if (this.bSetFocus && !Pattern3.test(AreaValue)) {
				oAreaFld.focus();
				this.bSetFocus = false;
			}
			else if (this.bSetFocus && !Pattern3.test(PrefixValue)) {
				oPrefixFld.focus();
				this.bSetFocus = false;
			}
			else if (this.bSetFocus && !Pattern4.test(BodyValue)) {
				oBodyFld.focus();
				this.bSetFocus = false;
			}
			else if (this.bSetFocus && !PatternEx.test(ExValue)) {
				if(oExFld)
				{
					oExFld.focus();
				}
				this.bSetFocus = false;
			}
			return false;
		}
		else
		{
			var pattern555 = new RegExp("555");
			if(pattern555.test(AreaValue) || pattern555.test(PrefixValue) )
			{
				this.sErrorMessage += "- " + sMessage + ": (555) 555-xxxx is not a valid phone number\n";	
				if (this.bSetFocus && pattern555.test(AreaValue)) {
					oAreaFld.focus();
					this.bSetFocus = false;
				}
				else if (this.bSetFocus && pattern555.test(PrefixValue)) {
					oPrefixFld.focus();
					this.bSetFocus = false;
				}
				return false;
			}
			return true;
		}
	}
}