///////////////////////////////////////////////////////////////////////////
//
//	Filename:		jsfunctions.js
//
//	Description:	These are functions used for phone validation.
//					These are used in tnt_checkout_nologin.cfm and
//					   tnt_addressupdate.cfm. 
//
///////////////////////////////////////////////////////////////////////////

//Begin CQ00019751 50c
function CheckPhoneFormat(strPhone, strPattern, strFieldLabel, strFieldType){
	if (strPattern != ""){
		//Begin CQ00022381
		if (strFieldType == "phone"){
			if (strPhone.length != strPattern.length){
				alert("The length of the " + strFieldLabel + " you have entered " + strPhone + " does not match the length of the required phone format " + strPattern + ".");		
				return false;
			}
		}
		else{ //(strFieldType == "extension")
			//extension doesn't have to match the pattern length, but it can't exceed the pattern length
			if (strPhone.length > strPattern.length){
				alert("The length of the " + strFieldLabel + " you have entered " + strPhone + " exceeds the allowable length of the required extension format " + strPattern + ".");		
				return false;
			}
		}
		//End CQ00022381
		
		var strFormat = strPattern;
		var strExp = "";
		var tmpString = "";
		//begin input mask chars defined in centura
		var numMatch = /9/; //###Numeric Character
		var charMatch = /X/; //###Alpha-numeric Character
		var alphaMatch = /A/; //###Alphabet Character
		//end input mask chars defined in centura
		var spaceMatch = /\s/;
		var specialChars = /[^a-zA-Z0-9]/g;
				
		if (strFieldType == "phone"){
			//loop through the format string and build a regular expression one character at a time
			for (var i = 0; i < strFormat.length; i++){
				tmpString = strFormat.charAt(i);
				if (tmpString == "-"){
					strExp += "-";
				}
				else if (tmpString == "("){
					strExp += "\\(";
				}
				else if (tmpString == ")"){
					strExp += "\\)";
				}
				else if (spaceMatch.test(tmpString)){
					strExp += "\\s";
				}
				else if (numMatch.test(tmpString)){
					strExp += "\\d";
				}
				else if (tmpString == "."){
					strExp += "\\.";
				}
				else if (tmpString == "/"){
					strExp += "\\/";
				}
				else if (tmpString == "*"){
					strExp += "\\*";
				}
				else if (tmpString == "+"){
					strExp += "\\+";
				}
				else if (tmpString == "?"){
					strExp += "\\?";
				}
				else if (tmpString == "|"){
					strExp += "\\|";
				}
				else if (tmpString == "["){
					strExp += "\\[";
				}
				else if (tmpString == "]"){
					strExp += "\\]";
				}
				else if (tmpString == "}"){
					strExp += "\\}";
				}
				else if (tmpString == "{"){
					strExp += "\\{";
				}
				else if (charMatch.test(tmpString)){
					strExp += "[a-zA-Z0-9]";
				}
				else if (alphaMatch.test(tmpString)){
					strExp += "[a-zA-Z]";
				}
				else if (specialChars.test(tmpString)){
					strExp += tmpString;
				}			
			}
			
			var expPattern = new RegExp(strExp);
			
			if (strPhone.match(expPattern) == null){
				alert("The value for " + strFieldLabel + " is not in the proper format. \n" + strPhone + " does not match the format " + strPattern);
				return false;
			}
			else{
				return true;
			}
		}
		else{ //(strFieldType == "extension")
			//validate extension one character at a time
			var tmpPhone;
			var tmpFormat;
			var validextension = true;
			
			for (var i = 0; i < strPhone.length; i++){
				tmpPhone = strPhone.charAt(i);
				tmpFormat = strFormat.charAt(i);
				
				if (((tmpFormat == "-") || (tmpFormat == "(") || (tmpFormat == ")") || (tmpFormat == ".")) && (tmpPhone != tmpFormat)){
					//alert("1 - " + tmpFormat + " : " + tmpPhone);
					validextension = false;
				}
				else if ((spaceMatch.test(tmpFormat)) && !(spaceMatch.test(tmpPhone))){
					//alert("2 - " + tmpFormat + " : " + tmpPhone);
					validextension = false;
				}
				else if ((numMatch.test(tmpFormat)) && (tmpPhone.search(/[0-9]/) == -1)){
					//alert("3 - " + numMatch.test(tmpFormat) + " : " + tmpPhone.search(/[0-9]/));
					validextension = false;
				}
				else if ((charMatch.test(tmpFormat)) && (tmpPhone.search(/[a-zA_Z0-9]/) == -1)){
					//alert("4 - " + tmpFormat + " : " + tmpPhone);
					validextension = false;
				}
				else if ((alphaMatch.test(tmpFormat)) && (tmpPhone.search(/[a-zA-Z]/) == -1)){
					//alert("5 - " + tmpFormat + " : " + tmpPhone);
					validextension = false;
				}
				
				if (!validextension){
					alert("The value for " + strFieldLabel + " is not in the proper format. \n" + strPhone + " does not match the format " + strPattern);
					return false;
				}
			}
			
			return true;	
		}
	}
	else{
		return true;
	}
}

function ApplyPhoneFormat(frmObj, strField, strPrefix, strFormat, strDelim){
	var SpecialChars = /[^a-zA-Z0-9]/g;
	//begin input mask chars defined in centura
	var NumMatch = /9/; //###Numeric Character
	var CharMatch = /X/; //###Alpha-numeric Character
	var AlphaMatch = /A/; //###Alphabet Character
	//end input mask chars defined in centura
	var SpaceMatch = /\s+$/g; //trailing space
	var tmpFrm = eval("frmObj." + strPrefix + strField);
	var frmPhone = eval("frmObj." + strField);
	var frmTmpPhone = eval("frmObj.p_" + strField);
	var frmExt = eval("frmObj.e_" + strField);
	var tmpString = tmpFrm.value;
	var newString = "";
	var aPosition = new Array();
	var strPosition = "";
	var strExtension = "";
	
	//cleanup
	if ((strPrefix == "e_") && ((frmPhone.value == "") && (frmTmpPhone.value == ""))){
		tmpFrm.value = "";
		frmPhone.value = "";
		return false;
	}
	else if ((strPrefix == "p_") && (tmpFrm.value.replace(SpecialChars,"") == "")){
		frmPhone.value = "";
		if (frmExt != null){
			frmExt.value = "";
		}
		return false;
	}
		
	//Strip the string of any non alphanumeric characters
	tmpString = tmpString.replace(SpecialChars,"");
	
	if (tmpString.length > 0){
		
		//Loop through the format and get the position and value of each format character
		for (var i = 0; i < strFormat.length; i++){
			if ((strFormat.charAt(i).search(CharMatch) == -1) && (strFormat.charAt(i).search(NumMatch) == -1) && (strFormat.charAt(i).search(AlphaMatch) == -1)){
				strPosition = i + "|" + strFormat.charAt(i);
				aPosition = aPosition.concat(strPosition);
			}
		}
				
		//Check if there is formatting to apply	
		if (aPosition.length > 0){
			//Create an array to hold the values of the characters of the formatted string
			var intLength = aPosition.length + tmpString.length;
			var newArray = new Array(intLength);
			
			//Loop through and populate the array with the format characters at the proper positions
			for (var i = 0; i < aPosition.length; i++){
				var tmpArray = aPosition[i].split("|");
				newArray[tmpArray[0]] = tmpArray[1];		
			}	
		}
		
		if (newArray != null){
			//Loop through the characters of the phone string and add them to the format array at the proper position
			for (var i = 0; i < tmpString.length; i++){
				for (var j = 0; j < newArray.length; j++){
					if (newArray[j] == null){
						newArray[j] = tmpString.charAt(i);
						break;
					}
				}
			}
			
			//Loop through the completed format array and build the new string to display
			for (var i = 0; i < newArray.length; i++){
				if (newArray[i] == null){
					newString += "";
				}
				else{
					newString += newArray[i];
				}
			}
			
		}
		else{
			newString = tmpString;

		}
		
		tmpFrm.value = newString;
		frmPhone.value = tmpFrm.value;	
	}
}
//End CQ00019751

//Begin CQ00022381
function CheckPhoneFields(frmObj, mode){
	var PhoneFormatString = frmObj.phone_format.value;
	var ExtensionFormatString = frmObj.ext_format.value;
	var ExtensionDelimiter = frmObj.ext_delim.value;
	var validnumber = true;
	var spaceMatch = /\s/gi;
	
	// D00017358 - Do not validate the phone ( return true ) if the country is non USA
	//if (frmObj.AddrCountry.value != "USA")
	//{   
		//alert( "Country is " + frmObj.AddrCountry.value );
	//	return true;
//	}

	if (frmObj.phone_format.value != ""){ //if there is a format defined then validate
		for (var i=0; i < frmObj.length; i++){ //loop through all of the form elements and find the phone fields
			var tempObj = frmObj.elements[i];
			
			if ((tempObj.type == "text") && (tempObj.name.substring(0,2) == "p_") && (tempObj.value.replace(spaceMatch,"") != "")){
				var basename = tempObj.name.substring(2);
				var baseObj = eval("frmObj." + basename);
				var phoneObj = tempObj;
				var extensionObj = eval("frmObj." + "e_" + basename);
				var phonetypeObj = eval("frmObj." + basename + "_type");
				
				if (mode == "update"){
					//if we are in the address update page then apply the phone format before validating
					//apply format to phone
					ApplyPhoneFormat(frmObj,basename,'p_',PhoneFormatString,ExtensionDelimiter);
					
					//apply format to extension
					if (extensionObj != null){
						ApplyPhoneFormat(frmObj,basename,'e_',ExtensionFormatString,ExtensionDelimiter);
					}
				}	

				//validate phone number
				if (!CheckPhoneFormat(phoneObj.value, PhoneFormatString, phonetypeObj.value, "phone")){
					validnumber = false;
					break;
				}
				
				//validate extension if there is one
				if ((extensionObj != null) && (extensionObj.value.replace(spaceMatch,"") != "")){
					if (!CheckPhoneFormat(extensionObj.value, ExtensionFormatString, phonetypeObj.value + " Extension", "extension")){
						validnumber = false;
						break;
					}
				}
				
				//populate the hidden with the fully formatted phone number, delimiter, and extension if there is one
				if ((ExtensionDelimiter != "") && (extensionObj != null) && (extensionObj.value.replace(spaceMatch,"") != "")){
					baseObj.value = phoneObj.value + ExtensionDelimiter + extensionObj.value;
				}
				else{ //There is no extension
					baseObj.value = phoneObj.value;
				}				
			}
		}
		
		if (!validnumber){
			return false;
		}
		else{
			return true;
		}
	}
	else{ //there is no format to validate against so return true
		return true;
	}
}
//End CQ00022381

//Begin CQ00022521
function changecase2(frmObj) {
	// Begin: Modified By Abhishek Garg on 07/10/2003 for CQ00026669
	var index;
	var tmpStr;
	var tmpChar;
	var preString;
	var postString;
	var strlen;
	tmpStr = frmObj.value.toLowerCase();
	strLen = tmpStr.length;
	if (strLen > 0)  
	{
		for (index = 0; index < strLen; index++)  
		{
			if (index == 0)  
			{
				tmpChar = tmpStr.substring(0,1).toUpperCase();
				postString = tmpStr.substring(1,strLen);
				tmpStr = tmpChar + postString;
			} 
			else 
			{
				tmpChar = tmpStr.substring(index, index+1);
				if (tmpChar == " " && index < (strLen-1))  
				{
					tmpChar = tmpStr.substring(index+1, index+2).toUpperCase();
					preString = tmpStr.substring(0, index+1);
					postString = tmpStr.substring(index+2,strLen);
					tmpStr = preString + tmpChar + postString;
				}
			}
		}
	}
	frmObj.value = tmpStr;
	// End: Modified By Abhishek Garg on 07/10/2003 for CQ00026669
}
//End CQ00022521

function CheckPostalCodeFormat(frmObj, fldObj, CountryCodeFieldName, CountryName )
{
	var tmpZip;
	var tmpCountryCode;
	var digitExp  = /^\d{1}$/;
	var objUSZipExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
	//var objCANZipExp =  /^\D{1}\d{1}\D{1} \d{1}\D{1}\d{1}$/;
	var objCANZipExp =  /^[ABCEGHJKLMNPRSTVXY]\d{1}[ABCDEFGHJKLMNPQRSTUVWXYZ] \d{1}[ABCDEFGHJKLMNPQRSTUVWXYZ]\d{1}$/;
	//http://www.infinitegravity.ca/postalcodeformat.htm
 
	tmpZip = fldObj.value;
	if (tmpZip == "" )
	{
		return true;
	}
	if (CountryName == "" )
	{
		if ( digitExp.test( fldObj.name.substring( fldObj.name.length - 1)) == true )
		{
			tmpCountryCode = eval("frmObj." + CountryCodeFieldName + fldObj.name.substring( fldObj.name.length - 1) + ".value" );
		}
		else
		{
			tmpCountryCode = eval("frmObj." + CountryCodeFieldName + ".value" );	
		}
	}
	else
	{
		tmpCountryCode = CountryName;
	}
	
    if ( tmpCountryCode == "USA" || tmpCountryCode == "" )
	{
		if ( tmpZip.length == 6 && tmpZip.substring( tmpZip.length-1) == "-"  )
		{
			tmpZip =   tmpZip.substring( 0, tmpZip.length-1);
			fldObj.value = tmpZip;
		}
		else if ( tmpZip.length == 9 )
		{
			tmpZip =   tmpZip.substring( 0, 5) + "-" + tmpZip.substring( 5, 9) ;
			fldObj.value = tmpZip;
		}
		else if ( tmpZip.length == 10 && tmpZip.substring( 5,6 ) == " " )
		{
			tmpZip =   tmpZip.substring( 0, 5) + "-" + tmpZip.substring( 6, 10) ;
			fldObj.value = tmpZip;
		}		
		if ( objUSZipExp.test( tmpZip )  == false )
		{   
			alert( "Invalid US Zip Code format \n Correct format is 99999 OR 99999-9999  " );
			fldObj.focus();
			return false;
		}
	}
	else if ( tmpCountryCode == "CAN" )
	{
		tmpZip = tmpZip.toUpperCase();
		if ( tmpZip.length == 6 )
		{
			tmpZip =   tmpZip.substring( 0, 3) + " " + tmpZip.substring( 3, 6) ;
			fldObj.value = tmpZip;
		}

		if ( objCANZipExp.test( tmpZip )  == false )
		{   
			alert( "Invalid Canadian Zip Code format \n Correct format is A9A 9A9  " );
			fldObj.focus();
			return false;
		}
		fldObj.value = tmpZip;
	}
}



function emailCheck (emailStr) 
{

	/* 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;
	
	/* The following is the list of known TLDs that an e-mail address must end with. */
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	
	/* The following pattern is used to check if the entered e-mail address fits the user@domain format.  It also is used to separate the username from the domain. */
	var emailPat=/^(.+)@(.+)$/;
	
	/* The following string represents the pattern for matching all special characters.  We don't want to allow special characters in the address. These characters include ( ) < > @ , ; : \ " . [ ] */
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	
	/* The following string represents the range of characters allowed in a username or domainname.  It really states which chars aren't allowed.*/
	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})\]$/;
	
	/* The following string represents an atom (basically a series of non-special characters.) */
	var atom=validChars + '+';
	
	/* The following string represents one word in the typical username. For example, in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")";
	
	// The following pattern describes the structure of the user
	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 +")*$");
	
	/* Finally, let's start trying to figure out if the supplied address is valid. */
	/* Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat);
	
	if (matchArray==null) 
	{
		/* Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address. */
		alert("Email address seems incorrect (check @ and .'s)");
		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) 
		{
			alert("Ths username contains invalid characters.");
			return false;
		}
	}

	for (i=0; i<domain.length; i++) 
	{
		if (domain.charCodeAt(i)>127) 
		{
			alert("Ths domain name contains invalid characters.");
			return false;
		}
	}
	
	// See if "user" is valid 
	if (user.match(userPat)==null) 
	{
		// user is not valid
		alert("The username doesn't seem to be valid.");
		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) 
	{
		// this is an IP address
		for (var i=1;i<=4;i++) 
		{
			if (IPArray[i]>255) 
			{
				alert("Destination IP address is invalid!");
				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) 
		{
			alert("The domain name does not seem to be valid.");
			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), and that there's a hostname preceding the domain or country. */
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) 
	{
		alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) 
	{
		alert("This address is missing a hostname!");
		return false;
	}
	// If we've gotten this far, everything's valid!
	return true;
}