// This set of function are general includes for validation
// They are designed in pairs the validation and the event function
// the event function will call the validation with the event src


function checkIsNum(strText) {
	var strValidChars, blnFlag,strChar;
    strValidChars  =  "0123456789";
    blnFlag =  true;
   
    for (var i=0; i < strText.length && blnFlag==true ; i++)
       {
        strChar  =  strText.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
				blnFlag  =  false;
				break; 
		}
       }
    
    return blnFlag;   
}



function checkIsChar(strText)  {
    var strValidChars, blnFlag,strChar;
    strValidChars  =  " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-'";
    blnFlag =  true;
   
    for (var i=0; i < strText.length && blnFlag==true ; i++)
       {
        strChar  =  strText.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
				blnFlag  =  false;
				break; 
		}
       }
    
    return blnFlag;   
    
} 


//Functions shifted by Sarika from ChangeLogin.asp to here for pwd validation

//******************************************************************
//Purpose: Checks for the numeric value entered in the field.
//Inputs : None.	
//Returns: True if validation is successful. Otherwise returns false.
//******************************************************************
function CheckNumericValue(parmValue) {
	var ValidCharacters = "1234567890" ; 
	var flag ; 
	flag = false ; 
	for(var z=0; z<parmValue.length; z++) {
		i = ValidCharacters.indexOf(parmValue.charAt(z)); 
		if (i != -1) {
			flag = true ; 
		}
	}  
	return flag ; 
} 
			
			
//Added by Sarika ON 30-03-2005 for password validation which should allow numbers + alphabets
//******************************************************************
//Purpose: Checks for the value entered in the field. for only alphabets & numbers
//Inputs : None.	
//Returns: True if validation is successful. Otherwise returns false.
//******************************************************************
function checkIsNumChar(strText)  {
    var strValidChars, blnFlag,strChar;
    strValidChars  =  "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    blnFlag =  true;
			   
    for (var i=0; i < strText.length && blnFlag==true ; i++)
       {
        strChar  =  strText.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
				blnFlag  =  false;
				break; 
		}
       }
			    
    return blnFlag;   
			    
} 

			
			
//******************************************************************
//Purpose: does a Case Sensitive string comparison .
//Inputs : both strings that need to be compared.	
//Returns: True if validation is successful. Otherwise returns false.
//******************************************************************
function CompareStrings(parmStr1, parmStr2) {
	var strLenght1; 
	var strLenght2; 
				
			
	strLenght1 = parmStr1.length ; 
	strLenght2 = parmStr2.length ; 

	if (strLenght1 != strLenght2) {
		return false ;				
	}
				
	for (var i=0;i<strLenght1;i++) {
		if (parmStr1.charCodeAt(i) != parmStr2.charCodeAt(i)) {
			return false ;
		}
	}
	return true ; 
}
//End Functions shifted


function display_name(item) {
	var strDisplay = item.getAttribute("DisplayName");
	if (strDisplay==null || strDisplay=="")
		strDisplay="Field";
	return strDisplay;
}

function trim_string() {
	var ichar, icount;
	var strValue = this;
	ichar = strValue.length - 1;
	icount = -1;
	while (strValue.charAt(ichar)==' ' && ichar > icount)
		--ichar;
	if (ichar!=(strValue.length-1))
		strValue = strValue.slice(0,ichar+1);
	ichar = 0;
	icount = strValue.length - 1;
	while (strValue.charAt(ichar)==' ' && ichar < icount)
		++ichar;
	if (ichar!=0)
		strValue = strValue.slice(ichar,strValue.length);
	return strValue;
}

function date_toSimpleForm() {
	var toSimpleForm = new String;
	toSimpleForm = this.toLocaleString();
	toSimpleForm = toSimpleForm.substring(0,toSimpleForm.indexOf(' '));
	return toSimpleForm;
}


function es_non_blank() {
	var item = event.srcElement;
	event.returnValue = vs_non_blank(item);
}

function vs_non_blank(item) {
//	var strErrorMsg = display_name(item) + " must have a non-blank value";
	item.value=item.value.Trim();
	if (item.value.length==0) {
		item.focus();
		item.className = "Error";
//		alert(strErrorMsg);
		return false;
	}
	item.className = "TextBoxMandatory";
	return true;
}

function es_valid_number() {
	var item = event.srcElement;
	event.returnValue = vs_valid_number(item);
}

function vs_valid_number(item) {
	return check_valid_number(item, false);
}

function es_valid_decimalnumber() {
	var item = event.srcElement;
	event.returnValue = vs_valid_decimalnumber(item);
}

function vs_valid_decimalnumber(item) {
	return check_valid_number(item, true);
}

function check_valid_number(item, bDecimal) {
//	var strErrorMsg = display_name(item) + " must be a valid numeric";
//	var strDefault = default_value(item);
//	if (strDefault.length==0) {
//		//strDefault="0"; ? This line is commented as if the field is blank then 0 is assigned to that field which is logically wrong.
//	}
	document.getElementById(item).value = document.getElementById(item).value.Trim();
//	if (document.getElementById(item).value.length==0)
//		document.getElementById(item).value=strDefault;
	if (bDecimal)
		var num = ".0123456789";
	else
		var num = "0123456789";
	
	for (var intLoop = 0; intLoop < document.getElementById(item).value.length; intLoop++) {
		if (num.indexOf(document.getElementById(item).value.charAt(intLoop)) == -1) {
			document.getElementById(item).focus();
//			document.getElementById(item).className = "Error";
//			alert(strErrorMsg);
			return false;
		}
	}
	
	if (document.getElementById(item).value.indexOf(".")!=document.getElementById(item).value.lastIndexOf(".")) {
		document.getElementById(item).focus();
		document.getElementById(item).className = "Error";
//		alert(strErrorMsg);
		return false;
	}

//	document.getElementById(item).className = "TextBoxMandatory";
	return true;
}

function es_valid_hours() {
	var item = event.srcElement;
	event.returnValue = vs_valid_hours(item);
}
function vs_valid_hours(item) {
//	var strErrorMsg = display_name(item);
	if (!vs_valid_decimalnumber(item))
	{
		item.className = "Error";
		return false;
	}
	var itemValue = new Number(item.value);
	if ((itemValue < 0 || itemValue > 80)) {
		item.focus();
		item.className = "Error";
//		alert(strErrorMsg + " must have a value from 0 to 80 hours");
		return false;
	}
	itemValue *= 4;
	if ((itemValue)!=Math.ceil(itemValue)) {
		item.focus();
		item.className = "Error";
//		alert(strErrorMsg + " must be a valid quartely increment");
		return false;
	}
	item.className = "TextBoxMandatory";
	return true;
}


function es_valid_date() {
	var item = event.srcElement;
	event.returnValue = vs_valid_date(item);
}

function vs_valid_date(item) {
	var month,day,year,varDate;
	varDate = item.value;
	var DateSeparator = ReturnMeSeparator(varDate);

	day = varDate.substr(0,varDate.indexOf(DateSeparator))
	month = varDate.substring(varDate.indexOf(DateSeparator) + 1,varDate.lastIndexOf(DateSeparator))
	if (isNaN(Number(month))) {
		month = MonthNumber(month);
		if (month == '00') {
			item.focus();
			item.className = "Error";
			return false;
		}
	}
	year = varDate.substr(varDate.lastIndexOf(DateSeparator)  + 1 ,varDate.length)
	if (year.length <= 2) {
		if (parseInt(year) > 25)
			year = 1900 + parseInt(year);
		else
			year = 2000 + parseInt(year);
	}
	if ((day <= 31 && day > 0) && (month < 13 && month > 0) && (year < 2025 && year >= 1900))
	{
		if (!CheckDate(month,day,year))
		{
			item.focus();
			item.className = "Error";
			return false;
		}
	}
	else
	{
		item.focus();
		item.className = "Error";
		return false;
	}
	item.className = "TextBoxMandatory";
	item.value = LeadZero(Number(day))+ "/"+ LeadZero(Number(month))  + "/" + year.toString();
	return true;
/*
//	var strErrorMsg = display_name(item);
	if (isNaN(Date.parse(item.value))) {
		item.focus();
		item.className = "Error";
		//alert(strErrorMsg + " must be a valid Date");
		return false;
	}
	var dtItem = new Date(Date.parse(item.value));
	//item.value = dtItem.toSimpleForm(); */
}

function es_item_selected() {
	var item = event.srcElement;
	event.returnValue = vs_item_selected(item);
}
function vs_item_selected(item) {
//	var strErrorMsg = display_name(item) + " must be a valid selection";
	if (item.selectedIndex==0) {
		item.focus();
		item.className = "Error";
//		alert(strErrorMsg);
		return false;
	}
	item.className = "TextBoxMandatory";
	return true;
}

function es_valid_zip() {
	var item = event.srcElement;
	event.returnValue = vs_valid_zip(item);
}
function vs_valid_zip(item) {
//	var strErrorMsg = display_name(item) + " must be of the form 99999-9999";
	item.value=item.value.Trim();
	if (!(/^\d{5}$/.test(item.value) || /^\d{5}-\d{4}$/.test(item.value))) {
		item.focus();
		item.className = "Error";
//		alert(strErrorMsg);
		return false;
	}
	item.className = "TextBoxMandatory";
	return true;
}

function es_valid_ssnbr() {
	var item = event.srcElement;
	event.returnValue = vs_valid_ssnbr(item);
}
function vs_valid_ssnbr(item) {
//	var strErrorMsg = display_name(item) + " must be of the form 999-99-9999";
	item.value=item.value.Trim();
	if (!(/^\d{3}-\d{2}-\d{4}$/.test(item.value))) {
		item.focus();
		item.className = "Error";
//		alert(strErrorMsg);
		return false;
	}
	item.className = "TextBoxMandatory";
	return true;
}

function es_valid_email() {
	var item = event.srcElement;
	event.returnValue = vs_valid_email(item);
}
function vs_valid_email(item) {
//	var strErrorMsg = display_name(item) + " is not a valid Email";


	if (item.value == "") return true; 
	
	
	// The above line checks for Blank Email address. If so then returns true as validating a blank email 
	//address returns an error
	item.value=item.value.Trim();


	// commented because an email addr in caps was not allowed.. and it needs to be allowed. Sarika 12th Dec 2005
	/*if(! CompareStrings(item.value,item.value.toLowerCase()))
	{
		item.focus();
		return false;
	} */

	if (!(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(item.value))) { 
		item.focus();
		return false;
	}

	if (!emailCheck(item.value)) {
		return false ; 
	}

// this code is added by ADNAN to check 3 different options: 
// 1) that the email address does not start with a "._-" chars
// 2) that there are no consecutive "._-" in the email address. 
// 3) that the text after the last . in the domain name should be either 2 or 3 chars long only. 

	var str ; 
	str = item.value ; 
	
	var first, last ; 
	first = ""
	first = str.charAt(0) ; 
	last = str.charAt(str.length - 1) ; 
	if ((first == '.') || (first == '_') || (first == '-') || (last == '.') || (last == '_') || (last == '-')) {
		//alert ("You first or last character in the email address cannot be a '.', '_', or a '-'") ; 
		return false ; 
	}

	if ((str.indexOf("..") >= 0) || (str.indexOf("__") >= 0) || (str.indexOf("--") >= 0))  {
		//alert ("Cannot have 2 consecutive . or _ or -") ; 
		return false ;
	} 

	var aryEmailAddress ; 
	aryEmailAddress = str.split(".") ; 
	if((aryEmailAddress[aryEmailAddress.length - 1].length != 2) && (aryEmailAddress[aryEmailAddress.length - 1].length != 3)) {
		//alert ("domain name not correct. Length not 2 or 3") ; 
		return false ; 
	}
	

	item.className = "TextBoxMandatory";
	return true;
}

// build the validation object
function validation_setup() {
	this.eventNonBlank = es_non_blank;
	this.nonBlank = vs_non_blank;
	this.eventValidNumber = es_valid_number;
	this.validNumber = vs_valid_number;
	this.eventValidDecimalNumber = es_valid_decimalnumber;
	this.validDecimalNumber = vs_valid_decimalnumber;
	this.eventValidHours = es_valid_hours;
	this.validHours = vs_valid_hours;
	this.eventValidDate = es_valid_date;
	this.validDate = vs_valid_date;
	this.eventItemSelected = es_item_selected;
	this.itemSelected = vs_item_selected;
	this.eventValidZip = es_valid_zip;
	this.validZip = vs_valid_zip;
	this.eventValidSSNbr = es_valid_ssnbr;
	this.validSSNbr = vs_valid_ssnbr;
	this.eventValidEmail = es_valid_email;
	this.validEmail = vs_valid_email;
	return this;
}

// Extend the string object to include a trim function
String.prototype.Trim = trim_string;
// Extend the date object to include a simple form string conversion
Date.prototype.toSimpleForm = date_toSimpleForm;

// Construct the validation object
var validation = new Object;
validation = validation_setup();


// This set of function are for processing the key press event
// Used to restrict input on numerics and pure textual fields

function kp_integer() {
	if ((event.keyCode < 48 || event.keyCode > 57))
		event.returnValue = false;
}
function kp_numeric() {
	if ((event.keyCode != 46) && (event.keyCode < 48 || event.keyCode > 57))
		event.returnValue = false;
	if (event.keyCode == 46) {
		if (event.srcElement.value.indexOf(".") > -1)
			event.returnValue = false;
	}
}


function kp_character() {
	if ((event.keyCode < 65 || event.keyCode > 90) && (event.keyCode < 97 || event.keyCode > 122))
		event.returnValue = false;
}
function kp_convert_upper() {
	if ((event.keyCode >= 97 && event.keyCode <= 122))
		event.keyCode -= 32;
}
function kp_convert_lower() {
	if ((event.keyCode >= 65 && event.keyCode <= 90))
		event.keyCode += 32;
}


function kp_setup() {
	this.Integer = kp_integer;
	this.Numeric = kp_numeric;
	this.Character = kp_character;
	this.ConvertUpper = kp_convert_upper;
	this.ConvertLower = kp_convert_lower;
	return this;
}

var keyPressInput = new Object;
keyPressInput = kp_setup();

// the functions below are for validation of Date
function CheckLeapYr(m_year)
{
m_yr = parseInt(m_year);
//1. Divide by 4 and if the REMAINDER is 0 then it is a leap year 
m_leap = m_yr%4;
//2. Divide by 100 and if the REMAINDER is 0 then it is NOT a leap year unless, 3. 
m_leap1=m_yr%100;
//Divide by 400 and if the REMAINDER is 0 then it is a leap year.
m_leap2=m_yr%400;
if (m_leap==0 && (m_leap1 !=0 || m_leap2==0))
	{
		return true;
	}
else
	{
	return false;
	}
}

function CheckDate(c_month,c_day,c_year)
{
	c_leap_yr = CheckLeapYr(c_year);
	if (c_month==2)
	{
		if (c_leap_yr)
		{
			if (c_day > 29)
			{
//				alert("February cannot have more than 29 days in a leap year"+"\n"+"Try changing the day or the month");
				return false;
			}
		}
		else
		{
			if (c_day > 28)
			{
//				alert("February cannot have more than 28 days if not a leap year"+"\n"+"try changing the day, the month or the year");
				return false;
			}
		}
	}
	if ((c_month==9 || c_month==4 || c_month==6 || c_month==11) && c_day>30)
	{
//		alert("Day cannot be greater than 30 for month selected");
		return false;
	}
////// added by neel (to check whether date is in current Financial Year) //////

		var todayDate = new Date();
		var presentYear = todayDate.getYear();
		var presentMonth = todayDate.getMonth() + 1;
		
		if(presentMonth <= 3) // if Present Month is between 1 to 3
		{
			if(c_year < presentYear && c_month < 4)
			{
				return false;
				//alert("Date entered should be in current Financial Year " + (presentYear - 1) + "-" + presentYear);
			}
		}
		else				// if Present Month is between 4 to 12
		{
			if(c_year < presentYear)
			{
				return false;
				//alert("Date entered should be in current Financial Year " + presentYear + "-" + (presentYear + 1));
			}
			else
			{
				if(c_month < 4 && c_year == presentYear)
				{
					return false;
					//alert("Date entered should be in current Financial Year " + presentYear + "-" + (presentYear + 1));	
				}
			}
		}
//////////////////////////// added by neel /////////////////////////////////	
	return true;
}

function LeadZero(nNum) {
    return (parseInt(nNum)<10 ? "0" : "" ) + parseInt(nNum).toString();
}

function ReturnMeSeparator(DateString) {
	DateString += '';
	if (DateString.indexOf("/") != -1)
	{
		if (DateString.indexOf("-") == -1)
			return '/';
		else
			return '';
	}
	if (DateString.indexOf("-") != -1)
	{
			if (DateString.indexOf("/") == -1)
					return "-";
		else
			return '';
	}
	if (DateString.indexOf(".") != -1)
	{
			if (DateString.indexOf("/") == -1)
					return ".";
		else
			return '';
	}
	return '';
}

function MonthNumber(parmMonthName) {
	parmMonthName = parmMonthName.toLowerCase();
	switch (parmMonthName) {
		case 'jan' :
			return '01';
		case 'feb' :
			return '02';
		case 'mar' :
			return '03';
		case 'apr' :
			return '04';
		case 'may' :
			return '05';
		case 'jun' :
			return '06';
		case 'jul' :
			return '07';
		case 'aug' :
			return '08';
		case 'sep' :
			return '09';
		case 'oct' :
			return '10';
		case 'nov' :
			return '11';
		case 'dec' :
			return '12';
		default  :
			return '00';
	}
}



function Trim(Text) {
	while (Text.indexOf(" ") == 0)
	{
		Text = Text.substr(1, Text.length)
	}
	if (Text.length > 0)
	{
		while (Text.lastIndexOf(" ") == (Text.length - 1))
		{
			Text = Text.substr(0, Text.length - 1)
		}
	}
	return Text;
}

function frmLogin_onsubmit()
{
	if(!validateString(document.frmLogin.txtLogin,"Please enter your Username!"))
		return false;

	if(!validateString(document.frmLogin.txtPassword,"Please enter your Password!"))
		return false;

	frmLogin.submit()
}

function validateString(passedObject, passedString)
{
	if (passedObject.value=='')
	{
		alert(passedString)
		passedObject.focus();
		return false;
	}
	return true;
}

function vbUnescape(parm){
	return unescape(parm);
}
function vbescape(parm){
	return escape(parm);
}


/***********************************************************************************/
//added by Adnan on 9th Mar 2004 to validate email addresses

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)$/;
 var knownDomsPat="";
 
 /* 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("Please enter your valid Email address.");
 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("The username of your Email address contains invalid characters.");
   return false;
    }
 }
 for (i=0; i<domain.length; i++) 
 {
  if (domain.charCodeAt(i)>127) 
  {
//   alert("Ths domain name of your Email address contains invalid characters.");
   return false;
     }
 }

 // See if "user" is valid 

 if (user.match(userPat)==null) 
 {

 // user is not valid

//  alert("Please enter your valid Email address.");
  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("Please enter your valid Email address.");
   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("Please enter your valid Email address.");
   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("Please enter your valid Email address.");
  return false;
 }

 // Make sure there's a host name preceding the domain.

 if (len<2)
 {
//  alert("Please enter your valid Email address.");
  return false;
 }

// If we've gotten this far, everything's valid!
return true;
}

/***********************************************************************************/


//******************************************************************
//Purpose: does a Case Sensitive string comparison .
//Inputs : both strings that need to be compared.	
//Returns: True if validation is successful. Otherwise returns false.
//******************************************************************

function CompareStrings(parmStr1, parmStr2) {
	var strLenght1; 
			
	strLenght1 = parmStr1.length ; 

	for (var i=0;i<strLenght1;i++) {
		if (parmStr1.charCodeAt(i) != parmStr2.charCodeAt(i)) {
			return false ;
		}
	}
	return true ; 
}



