/*
'WO 5106 - Added function for email validation 2008-11-19 ADL
   Form Validation and Navigation Functions
   These functions provide for client-side validation of Form fields on LaWorks.net.
   Equivilant server-side validation should be provided as additional safe-guard and can be found in document "inc_ServerValidation.asp".
   These functions also provide for some basic navigation (i.e. tabing, focus) for form fields.
*/

//Gobal variables

//Use these Regular Expressions when validating for email addresses and Socail Security #s.
var emailRegExpPattern = "/^[0-9]*[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/";
var ssnRegExpPattern = "^[0-9]{3}-?[0-9]{2}-?[0-9]{4}$";


/*
   Gives focus to the specified field on the form, and if the field is an input field,
   it selects the text within the field.
   -------------------------------------------------------
   Written: 2006-10-13 KMS
   Updates:
*/
function giveFocus(fieldName)
{
	scrollTo(screen.width,screen.height);
	document.getElementById(fieldName).focus();
	if(document.getElementById(fieldName).tagName == "INPUT")
		document.getElementById(fieldName).select();
}

/*
   Submits the specified form. For use with buttons, radios, etc.
   NOTE: Submit inputs should be available in case Javascript is turned off.
   -------------------------------------------------------
   Written: 2006-10-13 KMS
   Updates:
*/
function submitForm(frmName)
{
	document.getElementById(frmName).submit();
}

/*
   Returns true if the input string contains only whitespace characters.
   -------------------------------------------------------
   Written: 2006-10-13 KMS
   Updates:
*/
function isWhitespace(str)
{
	var notWhitespace = /\S/;	//includes tabs,spaces,returns,line-feeds,empty strings

	//if no matches are found then only whitespace is present
	return (str.match(notWhitespace) == null)
}

/*
   This function calculates the number of characters entered into a field (usually a textarea)
   and updates the Count Message on the page.

   It uses a hidden input field as a backup to revert to the original text in case errors in range
   are detected.
   NOTE:  In order for this to work, you need:
			1.  Use onkey up event on input field:  onkeyup="isLengthRange(this,minRange,,maxRange);"
					where minRange is the min # of characters allowed and
					maxRange is the max # of characters allowed
			2.  Create hidden input called "field_Backup" where "field" is the name of the original input field.
					Example:   <input type="hidden" name="field_Backup" id="field_Backup">
			3.  Place following code near original field:
					Character Count: (<span id="field_LengthRemaining">Max 200, remaining 200.</span>)
					with "field" equal to the name of the original input field
   -------------------------------------------------------
   Written: 2006-12-19 DLL
   Updates:
*/
function isLengthRange(textField, textMinLength, textMaxLength)
{
	var fieldName = textField.id;
	var textBackup = document.getElementById(fieldName + "_Backup");
	var textLength = textField.value.length;
	var charactersLeft = (textMaxLength - textLength);
	var errorMessageMinCharacters = "You can't enter less than "+ textMinLength +" characters.\n";
	var errorMessageMaxCharacters = "You can't enter more than "+ textMaxLength +" characters, added character(s) ignored.\n";
	var charactersLeftCountMessage;
	var errorMessage;

	//If field length is in range, updates Character Count message
	if (isNumberInRange(textLength, textMinLength, textMaxLength))
	{
		charactersLeftCountMessage = document.getElementById(fieldName + "_LengthRemaining");
		charactersLeftCountMessage.innerHTML = "Max "+textMaxLength+", remaining "+charactersLeft+".";
	}
	else //creates error message and reverts to backup version
	{
		if (textLength < textMinLength)
		{
			errorMessage = errorMessageMinCharacters;
		}
		else errorMessage=errorMessageMaxCharacters;

		alert(errorMessage);
		textField.value = textBackup.value;
	}
	textBackup.value = textField.value;
}
/*
   Use this to match a regular expression pattern.
   NOTE:  Declared in the global area above are patterns for SSN & email addresses.
   -------------------------------------------------------
   Written: 2006-12-19 DLL
   Updates:
*/
function isRegExpMatchFound(fieldValue, pattern)
{
	/*
		If a case insensitive search is needed, add the requirement to your pattern.
		No global searches are done since only the first match is used to validate against null.
	*/

	//Return false if no match is found and true if a match is found.
	return (fieldValue.match(pattern) != null);
}

function isValidEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
 
}



/*
   Sees if value is a whole Number & is in an acceptable range.
   -------------------------------------------------------
   Written: 2006-12-19 DLL
   Updates:
*/
function isWholeNumber(fieldValue, minRange, maxRange)
{
	var isValid = true;

	if(isNaN(fieldValue))
	{
		isValid = false;
	}
	else if(!isRegExpMatchFound(fieldValue, "."))
	{
		isValid = false;
	}
	else if(!isNumberInRange(fieldValue, minRange, maxRange))
	{
		isValid = false;
	}

	return isValid;
}

/*
   After validating number elsewhere, this checks to see if it is in an acceptable range.
   Min and Max ranges are inclusive.
   -------------------------------------------------------
   Written: 2006-12-19 DLL
   Updates:
*/
function isNumberInRange(fieldValue, minRange, maxRange)
{
	return fieldValue >= minRange && fieldValue <= maxRange;
}

/*
   Takes date and attempts to add "/" as best as possible.
   -------------------------------------------------------
   Written: 2006-12-19 DLL
   Updates:
*/
function addSlash(str)
{
	//format: m/d/yy | m/dd/yy | mm/d/yy | mm/dd/yy
	var DateRegExp = "\^([1-9]|1[012])/([1-9]|[12][0-9]|3[01])/([0-9]{2})\$";

	if(str.match(DateRegExp) != null)
	{
		newstr = str.substr(0,str.lastIndexOf("/") + 1) + "20" + str.substr(str.lastIndexOf("/") + 1,2);
		return newstr;
	}

	//format: mm/dd/yyyy | mm/d/yyyy | m/dd/yyyy | m/d/yyyy
	var DateRegExp = "\^([1-9]|1[012])/([1-9]|[12][0-9]|3[01])/(19[0-9]{2}|20[0-9]{2})\$";

	if(str.match(DateRegExp) != null)
	{
		return str;
	}

	//dates entered without dashes
	newstr = str.replace("/","");

	if(newstr.length == 8)
	{
		//format: mmddyyyy
		newstr = newstr.substr(0,2) + "/" + newstr.substr(2,2) + "/" + newstr.substr(4,newstr.length - 1);
		return newstr;
	}
	else if(newstr.length == 6)
	{
		//format: mmddyy
		var DateRegExp = "\^(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])([0-9]{2})\$";

		if(newstr.match(DateRegExp) != null)
		{
			newstr = newstr.substr(0,2) + "/" + newstr.substr(2,2) + "/20" + newstr.substr(4,newstr.length - 1);				
		}
		else
		{
			//format: mdyyyy
			var DateRegExp = "\^([1-9])([1-9])(19[0-9]{2}|20[0-9]{2})\$";

			if(newstr.match(DateRegExp) != null)
			{
				newstr = newstr.substr(0,1) + "/" + newstr.substr(1,1) + "/" + newstr.substr(2,newstr.length - 1);
			}
		}
		return newstr;
	}
	else if(newstr.length == 4)
	{
		//format: mdyy
		newstr = newstr.substr(0,1) + "/" + newstr.substr(1,1) + "/20" + newstr.substr(2,newstr.length - 1);
		return newstr;
	}
	else return str;
}

/*
   Checks to see if string is a vaild date.
   NOTE:  Be sure to run addSlash() as needed before calling
   -------------------------------------------------------
   Written: 2006-12-19 DLL
   Updates:
*/
function isDate(fieldValue)
{
	var newDate = new Date(fieldValue);
	var isValid = true;

	try
	{
		if(newDate == "Invalid Date")
		{
			throw "error";
		}
		else if ((newDate.getMonth()+1) + "/" + (newDate.getDate()) + "/" + (newDate.getFullYear()) != RemoveLeadingZerosFromDate(fieldValue))
		{
			throw "error";
		}
	}
	catch(er)
	{
		if(er == "error")
		{
			isValid = false;
		}
	}
	finally
	{
		return isValid;
	}
}

/*
   Removes leading zeros from the month and day from date string to use
   for comparsion with Date object.  When converting Date object to string
   leading zeros are not present, but they may be in the original string
   NOTE:  This is primarily used for isDate function.  However, use as needed.
   -------------------------------------------------------
   Written: 2006-12-19 DLL
   Updates:
*/
function RemoveLeadingZerosFromDate(fieldValue)
{
	var month = fieldValue.split("/")[0];
	var day = fieldValue.split("/")[1];
	var year = fieldValue.split("/")[2];

	if(month.length == 2 && month.substr(0,1) == "0")
	{
		month = month.substr(1,1);
	}

	if(day.length == 2 && day.substr(0,1) == "0")
	{
		day = day.substr(1,1);
	}

	return month +"/"+ day +"/"+ year;
}

/*
   Encodes problem characters to their HTML Entity code for inputing into
   SQL database. Previous methods had replaced characters with spaces; this
   method preserves the original meaning the the text while safe-guarding the database.

   Characters include: <> (less/greater-than) prevents insertion of server side scripting
			& (ampersand) When displaying as part of HTML, should be converted to HTML entitiy
			% (percent) prevents insertion of server side scripting
			" (quotation) When displaying as part of HTML, should be converted to HTML entitiy
			' (apostrophe) in SQL single apostrophes denote strings, double apostrophes allow apostrophes to be considered part of the string itself
   -------------------------------------------------------
   Written: 2006-10-13 KMS
   Updates:
*/
function encodeHTMLSymbolsForSQL(str)
{
	//replace ampersand symbol
	str = str.replace(/&/g,"&amp;");

	//replace Less-Than symbol
	str = str.replace(/\</g,"&lt;");
	
	//replace Greater-Than symbol
	str = str.replace(/\>/g,"&gt;");

	//replace percent symbol
	str = str.replace(/%/g,"&#37;");
	
	//replace quotation marks
	str = str.replace(/\"/g,"&quot;");

	//replace apostrophes with double apostrophes
	str = str.replace(/\'/g,"\'\'");
	return str;
}

/*
   Removes any HTML tags and their attributes from the input string.
   -------------------------------------------------------
   Written: 2006-10-13 KMS
   Updates:
*/
function RemoveHTML(strHTML)
{
	var noHTML, indxStartTag, indxEndTag
	noHTML = strHTML

	//Find the first occurrance of the < that denotes the begining of a HTML tag
	indxStartTag = strHTML.indexOf("<");

	//Loop until < is no longer present
	while(indxStartTag != -1)
	{
		var removeSub	//Tag to remove

		//Retrieve the start of the tag to remove
		removeSub = noHTML.substr((indxStartTag - 1),noHTML.length);

		//Find index where the HTML tag is ended
		indxEndTag = removeSub.indexOf(">");

		//If no > (partial tag only), then remove til end of string
		if(indxEndTag == -1)
		{
			indxEndTag = removeSub.length;
		}

		//Retrieve the end of the tag to remove
		removeSub = removeSub.substr(0, indxEndTag + 1);

		//Remove the HTML
		noHTML = noHTML.replace(removeSub,"");

		//Find start of next tag to remove
		indxStartTag = noHTML.indexOf("<");
	}
	return noHTML
}