<!--
	// This file contains the data validation JavaScript functions
	// It is included in the HTML pages with forms that need these
	// data validation routines.


// DEFINE VARIABLES

// whitespace characters
var whitespace = " \t\n\r";



/****************************************************************/

// PURPOSE:  Check to see if the string passed in is a valid time.
//	A valid time is defined as a string which is postfixed with either
//  "PM" or "AM".  Next it checks to see if there is a colon in the
//  string.  If there is, it makes sure that at least one digit preceeds
//  it and two proceed it.

	function IsTime(strTime)
	{
		var strTestTime = new String(strTime);
		strTestTime.toUpperCase();

		var blnTime = false;

		if (strTestTime.indexOf("PM",1) != -1 || strTestTime.indexOf("AM",1))
			blnTime = true;

		if (blnTime && strTestTime.indexOf(":",0) == 0)
			blnTime = false;

		var nColonPlace = strTestTime.indexOf(":",1);
		if (blnTime && ((parseInt(nColonPlace) + 5) < (strTestTime.length - 1) || (parseInt(nColonPlace) + 4) > (strTestTime.length - 1)))
			blnTime = false;


		return blnTime;
	}

/****************************************************************/

function replaceAll (s, fromStr, toStr)
{
	var new_s = s;
	for (i = 0; i < 100 && new_s.indexOf (fromStr) != -1; i++)
	{
		new_s = new_s.replace (fromStr, toStr);
	}
	return new_s;
}

/****************************************************************/

/* PURPOSE:  Since we are using the single tick mark as the
	string delimiter to construct our SQL queries, a string with
	a tick mark in it will cause a SQL error.  Therefore we replace
	all "'" with "''", which eliminates the possibility of a SQL error.
*/

function sqlSafe (s)
{
	var new_s = s;
	new_s = replaceAll (new_s, "'", "|");
	new_s = replaceAll (new_s, "|", "''");
	new_s = replaceAll (new_s, "\"", "|");
	new_s = replaceAll (new_s, "|", "''");
	return new_s;
}

/****************************************************************/

function makeSafe (i)
{
	i.value = sqlSafe (i.value);
}

/****************************************************************/

// Check whether string s is empty.

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

/****************************************************************/

// Returns true if string s is empty or 
// whitespace characters only.

function isWhitespace (s)

{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
	// Check that current character isn't whitespace.
	var c = s.charAt(i);

	if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

function isEmail (emailStr) 
{
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	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 + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	var matchArray=emailStr.match(emailPat)
			
	if (matchArray==null) {
		alert("Incorrect Email address  (check @ and .'s)")
		return false
	}
			
	var user=matchArray[1]
	var domain=matchArray[2]
			
	if (user.match(userPat)==null) {
	    alert("Invalid username")
	    return false
	}
			
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        alert("Destination IP address is invalid!")
			return false
		    }
	    }
	    return true
	}
			
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("Invalid domain name.")
	    return false
	}
	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) { 
	   alert("The Email address must end in a three-letter domain.")
	   return false
	}
	if (len<2) {
	   var errStr="Hostname is missing!"
	   alert(errStr)
	   return false
	}
	return true;
}



/****************************************************************/
function isNumeric (s)
{
	  if (isEmpty(s))       return false;
    // is s whitespace?
    if (isWhitespace(s)) return false;
	var i = 0;

	for (i = 0; i < s.length; i++)
	{	if (s.charAt(i) < '0' || s.charAt(i) > '9')  
				return false;
	};
	return true;
    
}
function isValidIPAddress (s)
{
   if (isEmpty(s))       return false;
    // is s whitespace?
    if (isWhitespace(s)) return false;

		//first dot is not allowed
		if (s.charAt(0) ==".")  	return false; 

				
    // start looking at character position 1 
    // (i.e. second character)
    var i =1;
    var startPos = 0;
    var sLength = s.length;
    var strNumber
		var dotCount =0;
		while (dotCount <= 2) //check the contents before the last (3 rd) dot.
		{		
				// look for .
				while ((i < sLength) && (s.charAt(i) != "."))
				{		 i++ ;};
				if ((i >= sLength) || (s.charAt(i) != "."))  
				{return false;}
				else  //got the dot posn
					{
						endPos= i;
						//if the number is nonnuumeric, its invalid ip address. so return false
						strNumber=s.substring(startPos,endPos);
						if ((! isNumeric(strNumber))||(strNumber.length >3))
															return false;
						// its valid no. so, continue
						startPos =i+1;
						dotCount++;
					};
			i++;		
		}//end if while
		
		//Now, we have reached to the third dot. so check if the data after the startpos till end of the ip address is numeric.
		strNumber=s.substring(startPos,sLength);
		if ((! isNumeric(strNumber))||(strNumber.length >3))
					return false;
	return true;
}
/****************************************************************/


// Checks to see if a required field is blank.  If it is, a warning
// message is displayed...

function ForceEntry(objField, FieldName)
{
	var strField = new String(objField.value);	
	if (isWhitespace(strField)) {
		alert(FieldName);
		objField.focus();
		objField.select();
		return false;
	}

	return true;
}
		
/****************************************************************/

// Returns true if the string passed in is a valid number
//  (no alpha characters), else it displays an error message

function ForceNumber(objField, FieldName)
{
	var strField = new String(objField.value);
	
	if (isWhitespace(strField)) return true;

	var i = 0;

	for (i = 0; i < strField.length; i++)
		if (strField.charAt(i) < '0' || strField.charAt(i) > '9') {
			alert(FieldName + " should be numeric"  );
			objField.focus();
			return false;
		}

	return true;
}

/****************************************************************/

// Returns true if the string passed in is a valid money
//  (no alpha characters except a decimal place), 
//   else it displays an error message

function ForceMoney(objField, FieldName)
{
	var strField = new String(objField.value);
	
	if (isWhitespace(strField)) return true;

	var i = 0;

	for (i = 0; i < strField.length; i++)
		if ((strField.charAt(i) < '0' || strField.charAt(i) > '9') && (strField.charAt(i) != '.')) {
			alert(FieldName + " should be numeric ");
			objField.focus();
			return false;
		}

	return true;
}


/****************************************************************/

// Right trims the string...  Useful for SQL datatypes of CHAR

function RTrim(strTrim)
{
	var str = new String(strTrim);
	var i = 0;
	var c = "";
	var endpos = 0

	for (i = str.length; i >= 0 && endpos == 0; i = i - 1) {
		c = str.charAt(i);
		if (whitespace.indexOf(c) == -1)
			endpos = i;
	}

	return str.substring(0,endpos+1);
}

/****************************************************************/

/* PURPOSE:  Returns true if the string is a valid date number.
	A method is passed in (1 = month, 2 = day).  If the string is
	nonnumeric, false is passed back.  If the day in the date string
	is greater than 31, false is returned.  If the month is greater
	than 12, an error is returned.
*/

function isDateNumber(strNum,method)
{
	
	var str = new String(strNum);
	var intNumber;
	if (isNaN(parseInt(str))) return false;
	intNumber=strNum;
	if (intNumber<1) {;return false;}
	if (method == 2)
		if (parseInt(str) > 31)
			return false;
	if (method == 1)
		if (parseInt(str) > 12)
			return false;

	for (i = 0; i < str.length; i++)
		if (str.charAt(i) < '0' || str.charAt(i) > '9')
			return false;


	return true;
}

/****************************************************************/

// Displays an alert box with the passed in string...

function PromptErrorMsg(strError,Field)
{
	//alert("You have entered an invalid date (" + strError + "). \nPlease make sure your date format is in MM/DD/YYYY format.");
	alert("Date should be valid ");
	Field.focus();
}

/****************************************************************/

/* PURPOSE: Checks to see if the string is a valid date.  A valid
	date is defined as any of the following:

		MM/DD/YY, MM/DD/YYYY, M/D/YY, M/D/YYYY,
		MM-DD-YY, MM-DD-YYYY, M-D-YY, M-D-YYYY
*/

function ForceDate(strDate,strField)
{
	var str
	str = new String(strDate);	
	if (isWhitespace(str)) {
		return true;
		// if the field is empty, just return true...
	}
	var i = 0, count = str.length, j = 0;
	var intMonth,intDay,strYear;
	while ((str.charAt(i) != '/' && str.charAt(i) != '-') && i < count)
		i++;

	if (i == count || i > 2) {
//		alert('1');
		PromptErrorMsg(strDate,strField);
		return false;
	}
	
	

	var addOne = false;
	if (i == 2) addOne = true;
	intMonth=str.substring(0,i);
//	if (!isDateNumber(str.substring(0,i),1)) {
//		alert('2');	
//  Error		
//		PromptErrorMsg(strDate,strField);
//		return false;
//	}
	j = i+1;
	i = 0;
	
	
	
	while ((str.charAt(i+j) != "/" && str.charAt(j+i) != "-") && i+j < count)
		i++;
			
	if (i+j == count || i > 2) {
//		alert('3');
		PromptErrorMsg(strDate,strField);
		return false;
	}
	intDay=str.substring(j,i+j);
	if (!isDateNumber(str.substring(j,i+j),2)) {
//		alert('4');
		PromptErrorMsg(strDate,strField);
		return false;
	}

	j = i+3;
	i = 0;

	if (addOne) j++;

	while (i+j < count)
		i++;
	if (i != 2 && i != 4) {
//		alert('5');
		PromptErrorMsg(strDate,strField);
		return false;
	}
	intYear=str.substring(j,i+j);
	if (!isDateNumber(str.substring(j,i+j),3)) {
//		alert('6');
		PromptErrorMsg(strDate,strField);
		return false;
	}
	if (intMonth==2){
		if (intDay>29) {
			PromptErrorMsg(strDate,strField);
			return false;
			}
		else
		   if ((intDay==29) && !IsLeapYear(intYear)) {
			PromptErrorMsg(strDate,strField);
			return false;
			}
	}
	if (intMonth==4||intMonth==6||intMonth==9||intMonth==11)
		if (intDay==31) {
			PromptErrorMsg(strDate,strField);
			return false;
			}
	if (!(isDateGreater("01/01/1753", strDate)) || isDateGreater("01/01/9999", strDate))
		{
			alert('Date out of Range'); 
			strField.focus();
			return false;
		} 	


	return true;
}

/****************************************************************/

// This function determines if the string passed in is a valid
// US zip code.  It accepts either ##### or #####-####.  If the
// string is valid, it returns true, else false.

function isZipcode(strZip)
{
	var s = new String(strZip);

	if (s.length != 5 && s.length != 10)
		// inappropriate length
		return false;


	for (var i=0; i < s.length; i++)
		if ((s.charAt(i) < '0' || s.charAt(s) > '9') && s.charAt(i) != '-')
			return false;
	return true;
}

/****************************************************************/

// This function ensures that a field is less than or equal to the
// Length passed in.  You must call this function with the element
// name in your form (for example: "ForceLength(document.forms[0].txtElement)"
// as opposed to "ForceLength(document.forms[0].txtElement.value)"
// If the field's value is too large, an error message is displayed
// and false is returned, else true is returned.

function ForceLength(objField, nLength, strWarning)
{
	var strField = new String(objField.value);

	if (strField.length > nLength) {
		alert(strWarning);
		return false;
	} else
		return true;
}
function ValidateDate(strDate,fldField,strMessage) {
    if (strDate=='') {
        alert(strMessage+' is required');
        fldField.focus();
        return false;
     }
     return (ForceDate(strDate,fldField));
}
function ValidateTime(strDate,fldField,strMessage) {
    if (strTime=='') {
        alert(strMessage+' is required');
        fldField.focus();
        return false;
     }
     
}

function IsLeapYear(strYear) 
{
		if (strYear%4 == 0)
		{
			if (strYear%100 == 0)
			{	
				if (strYear%400 == 0)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return true;
			}
		}
		else
		{
			return false;
		}
}
//Function to check whether a date is greater than other
function isDateGreater(strLowerDate,strUpperDate) {		
		
		var arrPartsLowerDate,arrPartsUpperDate;
		if ((strLowerDate=='') && (strUpperDate=='')) return false;
		arrPartsLowerDate=strLowerDate.split('/');
		arrPartsUpperDate=strUpperDate.split('/');		
		if (parseFloat(arrPartsLowerDate[2])>parseFloat(arrPartsUpperDate[2]))return false;
		if ((parseFloat(arrPartsLowerDate[2])==parseFloat(arrPartsUpperDate[2])) && (parseFloat(arrPartsLowerDate[0])> parseFloat(arrPartsUpperDate[0]))) return false;
		if ((parseFloat(arrPartsLowerDate[2])==parseFloat(arrPartsUpperDate[2])) && (parseFloat(arrPartsLowerDate[0])== parseFloat(arrPartsUpperDate[0])) && (parseFloat(arrPartsLowerDate[1])> parseFloat(arrPartsUpperDate[1]))) return false;
				
		return true;		
				
    }

// Trims the string on both sides...  
function Trim(strTrim)
{
	var str = new String(strTrim);
	var i = 0;
	var c = "";
	var endpos = 0;
	var startpos;
	//for Right Trim
	for (i = str.length; i >= 0 && endpos == 0; i = i - 1) {
		c = str.charAt(i);
		if (whitespace.indexOf(c) == -1)
			endpos = i;
	};
	str=str.substring(0,endpos+1);
	
	//for Left Trim
	startpos = str.length;
	for (i = 0; i <= str.length  && startpos == str.length ; i++ ) {
		c = str.charAt(i);
		if (whitespace.indexOf(c) == -1)
			startpos = i;
	};

	return str.substring(startpos,str.length);
}
// Right trims the string...  Useful for SQL datatypes of CHAR

function FindStr(strSearchFrom,strSearchFor)
{
	var str = new String(strSearchFrom);
	var i;
	var c = "";
	var endpos = str.length;

	for (i = 1; i <= endpos; i = i + 1 ) 
	{
		c = str.charAt(i);
		if (c==strSearchFor)
		{
			return true;
		}	
	}
	return false;
}

/****************************************************************/

// Returns false if the input value is not a valid decimal number
function isFloat(strNum,intMaxLen,intMaxLenFractional)
{
	if (Trim(strNum)=='') return false;
	var arrToken
	arrToken=strNum.split('.');
	if (arrToken.length>2) return false;
	if (arrToken.length==1)
	{
		if (!isNumeric(arrToken[0])) return false;
		if (arrToken[0].length>(intMaxLen-intMaxLenFractional)) return false;
	}
	else
	{
		if (arrToken[0]=='' && arrToken[1]=='') return false;
		if (!isNumeric(arrToken[0]) && arrToken[0]!='') return false;
		if (!isNumeric(arrToken[1]) && arrToken[1]!='') return false;
		if (arrToken[0].length>(intMaxLen-intMaxLenFractional)) return false;
		if (arrToken[0].length+arrToken[1].length>intMaxLen) return false;
	}
	return true;
}

/****************************************************************/


//Author: NARESH  -- this function validates for the text entered should be 
// numbers only
function validateText(strtxt) 
	{
		var valid = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "
		var ok = "yes";
		var temp;
		for (var i=0; i<strtxt.length; i++) 
		{
			temp = "" + strtxt.substring(i, i+1);
			if (valid.indexOf(temp) == "-1") ok = "no";
		}
		if (ok == "no") 
		{
			alert("Invalid entry, Only alphabets are accepted");
			
		return false;
		}
		return true;
	}

/*************************************************************************************/

function validateNum(strNum) 
	{
		var valid = "0123456789 "
		var ok = "yes";
		var temp;
		for (var i=0; i<strNum.length; i++) 
		{
			temp = "" + strNum.substring(i, i+1);
			if (valid.indexOf(temp) == "-1") ok = "no";
		}
		if (ok == "no") 
		{
			alert("Invalid entry, Only Numbers are accepted");
			
		return false;
		}
		return true;
	}

/*************************************************************************************/

	function validateAddr(strtxt) 
	{
		var valid = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@-./, "
		var ok = "yes";
		var temp;
		for (var i=0; i<strtxt.length; i++) 
		{
			temp = "" + strtxt.substring(i, i+1);
			if (valid.indexOf(temp) == "-1") ok = "no";
		}
		if (ok == "no") 
		{
			alert("Invalid entry, Only alphabets and numbers are accepted With( @ - . / , )");
			
		return false;
		}
		return true;
	}
	/************************************************************************************/

	function validateAlpn(strtxt) 
	{
		var valid = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
		var ok = "yes";
		var temp;
		for (var i=0; i<strtxt.length; i++) 
		{
			temp = "" + strtxt.substring(i, i+1);
			if (valid.indexOf(temp) == "-1") ok = "no";
		}
		if (ok == "no") 
		{
			alert("Invalid entry, Only alphabets and numbers are accepted");
			
		return false;
		}
		return true;
	}
// -->

