/* ----------------------------------------------------------
	This file contains form validation functions for elements
	that contain data of type: date, text.  As well as combo
	box data
  -------------------------------------------------------- */

function validateNoHTMLData(frm){
	with (frm){
		for (var i=0;i<elements.length;i++){
			if (elements[i].type.toLowerCase().indexOf('text') >= 0){
				elements[i].value = ReplaceBad(elements[i].value);
			}
		}
	}
}

function validateInvalidData(frm){
	with (frm){
		for (var i=0;i<elements.length;i++){
			if (elements[i].type.toLowerCase().indexOf('hidden') >= 0){
				elements[i].value = escape(elements[i].value);
			}
		}
	}
}

function validateHTMLElements(frm){
	with (frm){
		for (var i=0;i<elements.length;i++){
			if (elements[i].type.toLowerCase().indexOf('text') >= 0){
				elements[i].value = ReplaceHTMLCode(elements[i].value);
			}
		}
	}
}

function ReplaceHTMLCode(InStr){
    InStr = InStr.replace(/<body/g,"&lt;body");
	InStr = InStr.replace(/<\/body/g,"&lt;/body");
    InStr = InStr.replace(/<html/g,"&lt;html");
	InStr = InStr.replace(/<\/html/g,"&lt;/html");
    InStr = InStr.replace(/<head/g,"&lt;head");
	InStr = InStr.replace(/<\/head/g,"&lt;/head");
    InStr = InStr.replace(/<script/g,"&lt;script");
	InStr = InStr.replace(/<\/script/g,"&lt;/script");
    InStr = InStr.replace(/<link/g,"&lt;link");
	InStr = InStr.replace(/<\/link/g,"&lt;/link");
    InStr = InStr.replace(/<meta/g,"&lt;meta");
	InStr = InStr.replace(/<\/meta/g,"&lt;/meta");
    InStr = InStr.replace(/<title/g,"&lt;title");
	InStr = InStr.replace(/<\/title/g,"&lt;/title");
    return InStr;
}

function ReplaceBad(InStr){
    InStr = InStr.replace(/\</g,"&lt;"); // <
    InStr = InStr.replace(/\>/g,"&gt;"); // >
    InStr = InStr.replace(/\"/g,"'"); // "
    return InStr;
}


function validateDate(vDate) {
	var isValid = false;
	var dte = new Date(vDate);
	if (!isNaN(dte.getTime())) {
		isValid = true;
	} else {
		var arrDte = String(vDate).split('/');
		//modified 04-02-2001 to make sure there are three array elements
		//if(arrDte.length > 1){
		if(arrDte.length == 3){
			//added 04-02-2001 to check all array elements for values
			if (arrDte[0] != "" && arrDte[1] != "" && arrDte[2] != ""){
				if(arrDte[2].length == 4){
					isValid = true;
				}
			}
		}
		//}
	}
	return (isValid);
}

function validateSplitDate(fld, label, required){
	var bCheckDate = false;
	var iErrType = iErrFld = -1;	
	var arrErrLabels = new Array(" - Month", " - Day", " - Year");
	if (required){
		bCheckDate = true;
	}
	else{
		if (fld[0].value.length > 0 || fld[1].value.length > 0 || fld[2].value.length > 0){
			bCheckDate = true;
		}
	}
	if (bCheckDate){
		for (var i=0;i<3;i++){
			if (!validateText(fld[i].value)){
				iErrType = (required)? 0:9;
				iErrFld = i;
				break;
			}
			if (!validateNumber(fld[i].value)){
				iErrType = (required)? 7:11;
				iErrFld = i;
				break;
			}
		}
		if (iErrType ==-1 && !isValidMonth(fld[0].value)){
			iErrType = (required)? 3:10;
			iErrFld = 0;
		}
		if (iErrType ==-1 && !isValidYear(fld[2].value)){
			iErrType = (required)? 3:10;
			iErrFld = 2;
		}
		if (iErrType ==-1 && !isValidDay(fld[0].value, fld[1].value, fld[2].value)){
			iErrType = (required)? 3:10;
			iErrFld = 1;
		}
		if (iErrType != -1){ //error(s) occurred --> raise error
			/*
			if (iErrType > 8){ //error for non-required field
				raiseError(iErrType,label);
			}
			else{
				raiseError(iErrType,label + arrErrLabels[iErrFld]);
			}
			selectTextElement(fld[iErrFld]);
			*/
			return(iErrFld);
			
		}
	}
	return true;
}

function isValidMonth(iMonth){
	if (isNaN(iMonth)){
		return false;
	}
	switch (iMonth.length){
		case 1:
			if(iMonth == 0){
				return false;
			}
			break;
		case 2:
			if (iMonth < 1 || iMonth > 12){
				return false;
			}
			break;
		default:
			return false;
			break;
	}
	return true;
}

function isValidYear(iYear){
	if (isNaN(iYear)){
		return false;
	}
	if (iYear.length != 4){
		return false;
	}
	
	//Added for Pinkerton Validation
	var oDate = new Date();
	var maxYr = oDate.getFullYear();
	var minYr = maxYr - 100;
	
	if (iYear < minYr || iYear > maxYr){
		return(false);
	}
	return true;
}

function isValidDay(iMonth, iDay, iYear){
	var arrMonthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	var arrLeapYrMonthDays = new Array(31,29,31,30,31,30,31,31,30,31,30,31);
	if (iMonth == "" || iDay == "" || iYear == ""){
		return false;
	}
	if (iYear % 4 == 0){ //leap year
		if (iDay > arrLeapYrMonthDays[iMonth - 1] || iDay < 1){ //invalid date
			return false;
		}
	}
	else{ //regular year
		if (iDay > arrMonthDays[iMonth - 1] || iDay < 1){ //invalid date
			return false;
		}
	}
	return true;
}
	
function validateAge(dDOB){
	var dNow = new Date();
	dDOB = new Date(dDOB);
	var iYearsDiff = dNow.getFullYear() - dDOB.getFullYear() - 1;
	if ((iYearsDiff >= 18) || ((iYearsDiff == 17) && (dDOB.getMonth() < dNow.getMonth())) || ((iYearsDiff == 17) && (dDOB.getMonth() == dNow.getMonth()) && (dDOB.getDate() <= dNow.getDate()))){
		return(true);
	}
	alert("You must be 18 to participate in ShyGenius contests at this time.\nWe'll be adding the ability to offer contests to people under 18 very soon so stay tuned!");
	return(false);
}

function validateSelect(fld){
	var isValid = false;
	if (fld.selectedIndex != 0 && fld.selectedIndex != -1){
		isValid = true;
	}else if (fld.selectedIndex == 0){
		if (fld.options[fld.options.selectedIndex].value != 0 && fld.options[fld.options.selectedIndex].value != ""){
			isValid = true;
		}
	}
	return (isValid);
}

function isBlank(vVal){
	var isBlank = true;
	if(vVal != ''){
		isBlank = false;
	}
	return (isBlank);
}

function validateText(fld){
	var isValid = false;
	if (!isBlank(fld.value)){
		isValid = true;
	}
	return (isValid);
}

function validateRadio(fld){
	var isValid = true;
	var defIndx = -1;

	if (String(fld.length) != "undefined"){
		for (i=0; i<=fld.length-1; i++){
			if (fld[i].checked){
				defIndx = i;
			}
		}
	}else{
		if (fld.checked){
			defIndx = 0;
		}
	}
	if (defIndx == -1){
		isValid = false;
	}
	return (isValid);
}

function validateCheckbox(fld){
	var isValid = true;
	var defIndx = -1;

	if (String(fld.length) != "undefined"){
		for (i=0; i<=fld.length-1; i++){
			if (fld[i].checked){
				defIndx = i;
			}
		}
	}else{
		if (fld.checked){
			defIndx = 0;
		}
	}
	if (defIndx == -1){
		isValid = false;
	}
	return (isValid);
}

function validatePhone(fld){
	var phNumValid	= false;
	var areaCode	= fld[0].value;
	var prefix		= fld[1].value;
	var suffix		= fld[2].value;
	var phNum = areaCode + prefix + suffix;
	if(!isBlank(phNum)){
		if (isNaN(areaCode) || areaCode.length < 3){
			return(0);
		}		
		if (isNaN(prefix) || prefix.length < 3){
			return(1);
		}
		if (isNaN(suffix) || suffix.length < 4){
			return(2);
		}
	}else{
		return(0)
	}
	return(-1);	
}

function validateSSN(fld){
	var prt1	= fld[0].value;
	var prt2	= fld[1].value;
	var prt3	= fld[2].value;
	var SSN = prt1 + prt2 + prt3;
	if(!isBlank(SSN)){
		if (isNaN(prt1) || prt1.length != 3){
			return(0);
		}		
		if (isNaN(prt2) || prt2.length != 2){
			return(1);
		}
		if (isNaN(prt2) || prt3.length != 4){
			return(2);
		}
	}else{
		return(0)
	}
	return(-1);	
}

function validateSSN2(fld){
	var isValid = false;
	var sSSN = fld.value;
	if (sSSN != ""){
		if (!isNaN(sSSN) && sSSN.length == 9){
			isValid = true;
		}
	}else{
		isValid = true;
	}
	return(isValid);
}
	
function validateZipCode(vZip){
	var isValid = false;
	if (!isNaN(vZip) && validateLength(vZip,5)){
		isValid = true;
	}
	return (isValid);
}

function validateLength(vVal,lenCompare){
	var isValid = false;
	vVal = String(vVal);
	if(vVal.length == lenCompare){
		isValid = true;
	}
	return (isValid);
}

function validateMaxLength(vVal,lenCompare){
	vVal = String(vVal);
	if (vVal.length <= lenCompare){
		return true;
	}
	return false;
}

function validateNumber(vNum){
	var isValid = false;
	if (vNum == ""){
		isValid = false;
	}else if(!isNaN(vNum)){
		isValid = true;
	}
	return (isValid);
}

/*
function validateEmail(vEmail){
	var isValid = false;
	vEmail = String(vEmail);
	if (vEmail.indexOf('@') != -1){
		isValid = true;		
	}
	return (isValid);
}
*/

function validateMaxChars(value,operator,comparisonVal,label){
	var isValid = true;
	var showError = true;
	var sMaxCharsValidation = value.length + ' ' + operator + ' ' + comparisonVal;
	if (eval(sMaxCharsValidation)){
		isValid = false;
	}
	
	/*
	if(!isValid){
		if (showError){
			msgError = 'Please enter a value that is less than ' + comparisonVal + ' ' + 'characters' + ' ' + 'for' + ' ' + label + '.';
			alert(msgError);
		}
		return(isValid);	
	}
	*/
	
	return(isValid);
}

function validateEmail (vEmail) {
			/* 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=vEmail.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]

			// 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
			var domainArray=domain.match(domainPat)
			if (domainArray==null) {
				alert("The domain name doesn't seem to be valid.")
			    return false
			}

			/* domain name seems valid, but now make sure that it ends in a
			   three-letter word (like com, edu, gov) or a two-letter word,
			   representing country (uk, nl), and that there's a hostname preceding 
			   the domain or country. */

			/* Now we need to break up the domain to get a count of how many atoms
			   it consists of. */
			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) {
			   // the address must end in a two letter or three letter word.
			   alert("The address must end in a three-letter domain, or two letter country.")
			   return false
			}

			// Make sure there's a host name preceding the domain.
			if (len<2) {
			   var errStr="This address is missing a hostname!"
			   alert(errStr)
			   return false
			}

			// If we've gotten this far, everything's valid!
			return true;
}

function selectTextElement(fld){		
	fld.select();
	fld.focus();
}

function selectComboElement(fld){
	fld.options[0].selected = true;
	fld.focus();
}





function raiseError(elType,label, iOptNum){
	//NR = not required
	var errMsg = '';
	var errMsg_Blank			= 'Please enter a value';
	var errMsg_Select			= 'Please select an option';
	var errMsg_DteInvalid		= 'Please enter a valid date value (mm/dd/yyyy)';
	var errMsg_RadInvalid		= 'Please select a radio button value';
	var errMsg_PhInvalid		= 'Please enter a valid phone number value';
	var errMsg_ZipInvalid		= 'Please enter a valid zip code';
	var errMsg_NumInvalid		= 'Please enter a valid number';
	var errMsg_EmailInvalid		= 'Please enter a valid email address';
	var errMsg_NRDtePartBlank	= 'Please enter a value or clear all data';
	var errMsg_NRDtePartInvalid	= 'Please enter a valid date value (mm/dd/yyyy) or clear all data';
	var errMsg_NRDteNumInvalid	= 'Please enter a valid number or clear all data';
	var errMsg_MaxLenInvalid	= 'You surpassed the maximum allowable character limit of ';
	var errMsg_CheckInvalid		= 'Please select a check box value';
	
	switch(elType){
		case 0 : 
			errMsg = errMsg_Blank; break;
		case 1 : 
			errMsg = errMsg_Select; break;
		case 3 : 
			errMsg = errMsg_DteInvalid; break;
		case 4 : 
			errMsg = errMsg_RadInvalid; break;
		case 5 : 
			errMsg = errMsg_PhInvalid; break;
		case 6 : 
			errMsg = errMsg_ZipInvalid; break;
		case 7 : 
			errMsg = errMsg_NumInvalid; break;
		case 8: 
			errMsg = errMsg_EmailInvalid; break;
		case 9:
			errMsg = errMsg_NRDtePartBlank; break;
		case 10:
			errMsg = errMsg_NRDtePartInvalid; break;
		case 11:
			errMsg = errMsg_NRDteNumInvalid; break;
		case 12:
			errMsg = errMsg_MaxLenInvalid + iOptNum; break;
		case 13:
			errMsg = errMsg_CheckInvalid; break;
		default : 
			errMsg = 'Unknown Error';
	}
	
	if (label != ''){
		errMsg += ' for ' + label;
	}
	errMsg += '.';
	
	alert(errMsg);
}
