/*-----------------------------------------------------------------------------------
  Filename  : validate.js
  Version   : 1.0
  Objective : enables to use various javascript functions for validating form fields
  ------------------------------------------------------------------------------------  
  History   : 
		22-Sep-2000		S.Gopi      Initial Creation
		27-Sep-2000		Bhami		Added already checked in functions	
		30-Oct-2000		Sudheer     Modified  chkDateAdvn function
		04-JUL-2001		Teekam	    Modified badEmail function
		05-JUL-2001		Ramana	    Modified badEmail function and 
							added chkEmailChar function
		22-Mar-2004		Mahesh		Added STrim function
  ------------------------------------------------------------------------------------  
  
  Index : 
  		1. chkempty(field)
   		2. allownumbersonly()
   		3. allowcharsonly()
   		4. chkNbr(field)
		5. chkChar(field)
  		6. AtoZonly(field)
   		7. chkEmail(fld)
  		8. validateZIP(field)
  		9. chkDate(fld)
  		10.chkDateAdvn(fld)
 		11.searchForTxtinCombo(fld,txt)
 		12.searchForValinCombo(fld,val)
 		13.rtnTxtIndexfromCombo(fld,txt)
 		14.rtnValIndexfromCombo(fld,val)
 		15.datecompare(d1,d2)
 		16.getAge(d1)
 		17.datediff(d1,d2)
 		18.yeardiff(d1,d2)
 		19.chkMoney(field)
 		20.chkAlphaNumeric(field)
 		21.chkPercent(fld)
		22.Trim(fld)
		23.STrim(fld)
  ------------------------------------------------------------------------------------
*/ 		 

/* Function to check for valid phone numbers */

function chkPhone(field)
{
	var valid = "0123456789-()"
	var ok = "yes";
	var temp;	
	for (var i=0; i<field.value.length; i++) 
	{	
		temp = "" + field.value.substring(i, i+1);		
		if (valid.indexOf(temp) == "-1") ok = "no";		
		if (ok == "no") 
		{
			alert("Invalid characters entered!");
			field.focus();
			field.select();
			return true;
		}
	}
}  

/*Following function allows numberss only in a text field
  usage:Onblur="chkNbr(this)"  */
	
  
function chkNbr(field) 
{
	var valid = "0123456789"
	var ok = "yes";
	var temp;
	for (var i=0; i<field.value.length; i++) 
	{
		temp = "" + field.value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") ok = "no";
		if (ok == "no") 
		{
			alert("Invalid entry!  Only Numbers are accepted!");
			field.focus();
			field.select();
			return true;
		}
	}
}

/*chkempty(field) function does not leave a field empty
  usage: Onblur="chkempty(this)"  */
 
function chkempty(field)
{
   var msg
   var frmVar;
   frmVar=field.name;
   //alert(frmVar);
  // alert(frmVar.length);
   //alert(frmVar.substring(0,4));
  //alert(frmVar.substring(4));
  // msg="The field '" + field.name + "' could not be empty";
    msg="The field '" + frmVar.substring(3) + "' could not be empty";
   if (field.value=="")
   {
    //   alert("This field could not be empty");
	   alert(msg);
       field.focus();
       return false;
   }

   return true;
}


/*allownumbersonly() function allows numbers only while typing in a textfield
   usage:OnKeyPress="allownumbersonly()"  */
 
function allownumbersonly()
{
if(( event.keyCode >= 97 && event.keyCode <= 122) || (event.keyCode >=65 && event.keyCode <=90))
{
event.keyCode=0;
}
}

/*allowcharsonly() function allows chars only while typing in a textfield
  usage:OnKeyPress="allowcharsonly()"  */
 
function allowcharsonly()
{
if(( event.keyCode >= 97 && event.keyCode <= 122)||(event.keyCode >=65 && event.keyCode <=90) || (event.keyCode == 32))
{}
else { event.keyCode=0;}

}

/*Following function allows characters only in a text field
  usage:Onblur="chkChar(this)"  */
	
  
function chkChar(field) {
var valid = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-*_!@#$%^&()=|?,./\<>;:~"
var ok = "yes";
var temp;
for (var i=0; i<field.value.length; i++) {
temp = "" + field.value.substring(i, i+1);
if (valid.indexOf(temp) == "-1") ok = "no";
}
if (ok == "no") {
alert("Invalid entry!  Only characters are accepted!");
field.focus();
field.select();
return true;
   }
}

/*Following function allows characters only in a text field and has been used for browser compatibility
  usage:OnSubmit="chkBSNLChar(this)"  */

function chkBSNLChar(field) {
var valid = " abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var ok = "yes";
var temp;
for (var i=0; i<field.value.length; i++) {
temp = "" + field.value.substring(i, i+1);
if (valid.indexOf(temp) == "-1") ok = "no";
}
if (ok == "no") {
alert("Invalid entry!  Only characters are accepted!");
field.focus();
field.select();
return false;
   }
else
	return true;
}


/*Following function allows characters i.e a-z or A-Z only in a text field
  usage:Onblur="AtoZonly(this)"  */
	
  
function AtoZonly(field) {
var valid = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var ok = "yes";
var temp;
for (var i=0; i<field.value.length; i++) {
temp = "" + field.value.substring(i, i+1);
if (valid.indexOf(temp) == "-1") ok = "no";
}
if (ok == "no") {
alert("Invalid entry!  Only characters a-z/A-Z are accepted!");
field.focus();
field.select();
   }
}


/*Following function checks for zipcode
  usage: Onblur= validateZIP(this)"  */

function validateZIP(field) {
var valid = "0123456789-";
var hyphencount = 0;

if (field.length!=5 && field.length!=10) {
alert("Please enter your 5 digit or 5 digit+4 zip code.");
return false;
}
for (var i=0; i < field.length; i++) {
temp = "" + field.substring(i, i+1);
if (temp == "-") hyphencount++;
if (valid.indexOf(temp) == "-1") {
alert("Invalid characters in your zip code.  Please try again.");
return false;
}
if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
return false;
   }
}
return true;
}



/*Following function checks for valid date
  usage:Onblur="chkDate(this)"  format must be mm/dd/yy */
	
function chkDate(fld){
//	window.onerror=null // for all other strange errors
	var err=0
	var psj=0;
	a=fld.value
	if (a.length != 8) err=1
	b = a.substring(0, 2)// month
	c = a.substring(2, 3)// '/'
	d = a.substring(3, 5)// day
	e = a.substring(5, 6)// '/'
	f = a.substring(6, 8)// year

	//basic error checking
	if (b<1 || b>12) err = 1
	if (c != '/') err = 1
	if (d<1 || d>31) err = 1
	if (e != '/') err = 1
	if (f<0 || f>99) err = 1
	
	//advanced error checking

	// months with 30 days
	if (b==4 || b==6 || b==9 || b==11){
		if (d==31) err=1
	}

	// february, leap year
	if (b==2){
		// feb
		var g=parseInt(f/4)
		if (isNaN(g)) {
			err=1
		}

		if (d>29) err=1
		if (d==29 && ((f/4)!=parseInt(f/4))) err=1
	}

	if (err==1){
		alert('Invalid Date!');
		fld.select();
		
	}
	

}

/*Following function checks for valid date
  usage:Onblur="chkDateAdvn(this)"  format may be mm/dd/yy, mm/dd/yyyy */

function chkDateAdvn(fld)
{
	//window.onerror=null // for all other strange errors
	if (fld.value!="")
	{
	
	var err=0
	var psj=0;
	a=fld.value
	
	if (a.length >10) err=1
	if (a.length <6) err=1
		
	if (a.indexOf("/") == "-1") err=1
	 
	var str = a.split("/");

    if (str.length !=3) err=1   // ensures date must have 2 slashes
    if (err!=1)
	{	
        b= str[0];
  		 d= str[1];
   	 	 f=str[2];
	 
		//basic error checking
		if (b<1 || b>12) err = 1
		if (d<1 || d>31) err = 1
		if ( f<0 ) err = 1
   		if (f.length >4) err=1

	
		//advanced error checking

		// months with 30 days
		if (b==4 || b==6 || b==9 || b==11){
		if (d==31) err=1
				}

		// february, leap year
		if (b==2){
			// feb
			var g=parseInt(f/4)
			if (isNaN(g)) {
			err=1
			}

			if (d>29) err=1
			if (d==29 && ((f/4)!=parseInt(f/4))) err=1
		}

 	 }
	if (err==1)
	{
		alert('Invalid Date!');
		fld.select();
	}
	else
	{
		var b=datecompare("1/1/1753",fld.value);
		var c=datecompare(fld.value,"12/31/9999");
		if( b==false || c==false)
		{
		  alert('Valid date range is: 1/1/1753 to 12/31/9999');
		  fld.select();
		}
	}
}	
}

/*Following function takes combo box name & a text ,and sets the combo index to that text
  usage:searchForTxtinCombo(comboboxname,"India")   */

function searchForTxtinCombo(fld,txt)
 {   
  for(var x=0;x<fld.options.length;x++)
     { if (fld.options[x].text==txt)
        {  fld.options[x].selected=true ;
        }
       
     } 
    
 }
 
/*Following function takes combo box name & a value ,and sets the combo index to that value
  usage:searchForValinCombo(comboboxname,"Apple") */
  
 function searchForValinCombo(fld,val)
  {   
   for(var x=0;x<fld.options.length;x++)
      { if (fld.options[x].value==val )
         {  fld.options[x].selected=true ;
         }
         
    } 
  } 
  
/*Following function  returns index of the text of the combo 
    usage: var i= rtnTxtIndexfromCombo(comboboxname,"Apple") */
  
  function rtnTxtIndexfromCombo(fld,txt)
   {   
    for(var x=0;x<fld.options.length;x++)
       { if (fld.options[x].text==txt)
          {  return x ;
          }
         
       } 
      
 }
 
/*Following function  returns index of the value of the combo 
    usage: var i= rtnValIndexfromCombo(comboboxname,"Apple") */
 
 function rtnValIndexfromCombo(fld,val)
    {   
     for(var x=0;x<fld.options.length;x++)
        { if (fld.options[x].value==val)
           {  return x ;
           }
          
        } 
       
 }
 
 
 /* Following function compares 2 dates and ensures that Second Date must be greater than or eual to First date
    usage: k=datecompare(d1,d2)  */
   
 
 function datecompare(d1,d2)
 { 
 var date1 = new Date(d1);
 var date2 = new Date(d2);
 
 var x1 = date1.getTime();
 var x2 = date2.getTime();
 
 if (x2<x1)
  { return false;
  }
  else
  { return true;
  }
  
  
} 

 /*Following function  returns age
     usage: var i= getAge(d) */
  
  function getAge(d)
  {              
      var d1 = new Date(d);
      var now = new Date();
     
      var x1= d1.getTime();
      var x2= now.getTime();
      
      var y1 =d1.getYear();
      var y2 =now.getYear()
      if (y1<2000)
        { y1=y1+1900;
        }
        
      if (x1<=x2)
      { var diff = y2 - y1;
         return diff;
      }
       
      else
      { return -1;
      
      }
            
 }
 
 /*Following function  returns difference between 2 dates in days
      usage: var i= datediff(d1,d2) */
  
 function datediff(d1,d2)
 {          
      var date1 = new Date(d1);
      var date2 = new Date(d2);
      
      var x1= date1.getTime();
      var x2= date2.getTime();
      
      if (x1>x2)   
      {  var temp= date1;	// ensures that d1<d2
             date1=date2;
             date2=temp;
      }
     
 
           
      var diff = date2.getTime()- date1.getTime();
      
      var days = Math.floor(diff / (1000 * 60 * 60 * 24));
      
      return days;
}
 
 
 /*Following function  returns difference between 2 dates in years
      usage: var i= yeardiff(d1,d2) */
   
   function yeardiff(d1,d2)
   {              
       var d1 = new Date(d1);
       var d2 = new Date(d2);
      
       var x1= d1.getTime();
       var x2= d2.getTime();
       
      if (x1>x2)   
      {  var temp= d1;	// ensures that d1<d2
             d1=d2;
             d2=temp;
      }
       
       var y1 =d1.getYear();
       var y2 =d2.getYear()
      
       if (y1<2000)
         { y1=y1+1900;
         }
       if (y2<2000)
       { y2=y2+1900;
        }
         
        var diff = y2 - y1;
        return diff;
       
           
             
 }
/*Following function allows money value only in a text field
  usage:Onblur="chkMoney(this)"  */
	
function chkMoney(field)
{

var valid = "0123456789."
var ok = "yes";
var temp;
for (var i=0; i<field.value.length; i++) 
{
temp = "" + field.value.substring(i, i+1);
if (valid.indexOf(temp) == "-1") ok = "no";
}
temp = "" + field.value.substring(field.value.indexOf(".") + 1,field.value.length)
if ((temp.indexOf(".") != -1) || (temp.length == 0)) ok = "no"
if (ok == "no")
{
alert("Invalid entry!  Only Monetary values are accepted!");
field.focus();
field.select();
 }
}


/*Following function allows only some specific characters in an email field .
Called from badEmail() function.*/
  
function chkEmailChar(emailVal) {

	var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_@.1234567890"
	var ok = "yes";
	var temp;
	for (var i=0; i<emailVal.length; i++) {
		temp = "" + emailVal.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") ok = "no";
	}
		if (ok == "no") {			
			return true;
   		}
}

/* Following function validates email field*/

function badEmail(theEmail)
{	
	//check for valid characters in an email field
	if (chkEmailChar(theEmail)==true)
	{return true;}
	
	var sEmail = "" + theEmail;	
	
	//check if two '@' characters exist
	var fIndex;
	var lIndex;
	fIndex = sEmail.indexOf('@');
	lIndex = sEmail.lastIndexOf('@');
	if(fIndex != lIndex)
	{
	return true;
	}	
	
	//check if the email ends with '.' character
	if ((sEmail.lastIndexOf('.') + 1) == (sEmail.length))
	{
	return true;
	}
	
	//check if '@' and '.' occur together.
	var rateIndex;
	var dotIndex;
	rateIndex = sEmail.indexOf('@');
	dotIndex = sEmail.indexOf('.');

	if(((rateIndex - dotIndex) == 1) || ((rateIndex - dotIndex) == -1))
	{
		return true;
	
	}
	
	//check for invalid position of '@' character.
	if ((sEmail.indexOf('@') == -1) || (sEmail.indexOf('@') == 0) || (sEmail.indexOf('@') == (sEmail.length -1))  ){
		return true;
	}

	//check for invalid position of '.' character.
	if ((sEmail.indexOf('.') == -1) || (sEmail.indexOf('.') == 0) || (sEmail.indexOf('.') == (sEmail.length -1))  ){
		return true;
	}
}

//this is the function which validates email field. This calls badEmail() function.
function chkEmail(fld)
{ 
  if(fld.value !="")
  {	if ( badEmail(fld.value)) 
	{ alert('Please enter a valid email address.');
	  fld.select();
	}
  }
}

function checkdate(objName) {
	var datefield = objName;
	if (chkdate(objName) == false) 
	{
	datefield.select();
	alert("That date is invalid.  Please try again.");
	datefield.focus();
	return false;
	}
	else
	{
	return true;
	}
}

function chkdate(objName) {
var strDatestyle = "US"; //United States date style
//var strDatestyle = "EU";  //European date style
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = "Jan";
strMonthArray[1] = "Feb";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Apr";
strMonthArray[4] = "May";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Aug";
strMonthArray[8] = "Sep";
strMonthArray[9] = "Oct";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dec";
strDate = datefield.value;
	if (strDate.length < 1) 
	{
	return true;
	}
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
	if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
	strDateArray = strDate.split(strSeparatorArray[intElementNr]);
		if (strDateArray.length != 3) {
		err = 1;
		return false;
		}
		else {
		strDay = strDateArray[0];
		strMonth = strDateArray[1];
		strYear = strDateArray[2];
		}
	booFound = true;
	}
	}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
   }
}
if (strYear.length == 2) {
strYear = '20' + strYear;
}
// US style
if (strDatestyle == "US") {
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
}
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
   }
}
if (isNaN(intMonth)) {
err = 3;
return false;
   }
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
}
}
else {
if (intday > 28) {
err = 10;
return false;
}
}
}
if (strDatestyle == "US") {
datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
}
else {
datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
}
return true;
}
function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;
}


/*Following function allows Alpha Numeric characters i.e a-z or A-Z or 0-9 only in a text field
  usage:Onblur="chkAlphaNumeric(this)"  */
	
  
function chkAlphaNumeric(field) {
var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var ok = "yes";
var temp;
for (var i=0; i<field.value.length; i++) {
temp = "" + field.value.substring(i, i+1);
if (valid.indexOf(temp) == "-1") ok = "no";
}
if (ok == "no") {
alert("Invalid entry!  Only Alpha Numeric Charecters are accepted!");
field.focus();
field.select();
   }
}

/*Following function checks for percentage values 
  usage:Onblur="chkPercent(this)"  */

function chkPercent(fld)
{ 
 if (fld.value!="")
   { 
     if (isNaN(fld.value))
     { alert("Enter Numeric values only");
       fld.select();
     }
     
     if ( fld.value < 0 || fld.value > 100)
     { alert("Percentage Range should be 0 - 100");
       fld.select();
     }
  }

}
/* Trim function used in email*/
function Trim(fld)
{
 var str = fld.value;
 var tempstr
 tempstr = ""
 for(i=0;i<str.length;i++){
  if(str.substr(i,1)!=' '){
   tempstr = tempstr + str.substr(i,1)
  }
 }
fld.value=tempstr;
}

function strim(fld){
	//Left Trim
	str = fld.value;
	tempstr="";
	for(i=0;i< str.length;i++){
		if(str.substr(i,1)!=' '){
		tempstr = str.substr(i);
		break;
		}
	}
	//Right Trim
	str = tempstr;
	tempstr = "";
	for(i=str.length-1;i>=0;i--){
		if(str.substr(i,1)!=' '){
			tempstr=str.substr(0,i+1)
			break;
		}
	}
	fld.value=tempstr;
}
//newly added
/*
         var count=0;
		var imgCount=0;
		function loadImage()
		{
		    //document.Form1.hdnImage.value="ADbanner2.gif"+"$"+"ADbanner1.gif"+"$"+"AD_CellOne_old.gif";
		   var img=document.getElementById("bsnlmenu_hdnVar");
		    alert(img);
		    if (img!=null)
		    {
		      alert(document.getElementById("bsnlmenu_hdnVar").value);
		    }
			//var hdnImageVar="ADbanner1.gif"+"$"+"AD_CellOne_old.gif";
			var hdnImageVar=document.getElementById("bsnlmenu_hdnVar").value;
			array=hdnImageVar.split('$');
			//alert(array);
			if (imgCount==array.length)
			{
				imgCount=0;
			}
				var banner=document.getElementById("adbanner");
				//alert(banner);
				if (banner!=null)
				{
				//alert(document.Form1.adbanner);
				    banner.src="../images/"+array[imgCount];
				   // alert(banner.src);
				}
			    imgCount=imgCount+1;
			
		}
		window.setInterval('loadImage()',5000);
		*/
		
		var count=0;
		var imgCount=0;
		
		function loadImage()
		{
		    
			var sqrarray;
			var hdnImageVar=document.getElementById("bsnlmenu_hdnVar").value;
			var hdnSqrImageVar=document.getElementById("rightmenu_hdnSqrVar").value;
			sqrarray=hdnSqrImageVar.split('$');
			
			array=hdnImageVar.split('$');
			
			//alert(array);
			//alert(sqrarray);
			if (count==sqrarray.length)
			{
			   count=0;
			}
			if (imgCount==array.length)
			{
				imgCount=0;
			}
				var banner=document.getElementById("adbanner");
				//alert(banner);
				if (banner!=null)
				{
				//alert(document.Form1.adbanner);
				    banner.src="../images/"+array[imgCount];
				   // alert(banner.src);
				}
				imgCount=imgCount+1;
				var sqrbanner=document.getElementById("rightadbanner");
				if (sqrbanner!=null)
				{
				  sqrbanner.src="../images/"+sqrarray[count];
				}
			    count=count+1;
			
		}
		window.setInterval('loadImage()',9000);