var globalField;

function setFocusTimeout(field){
 globalField = field;
 setTimeout('fieldFocus()',100);
}

function getMaxDBNumber(totalLength, decimalLength){
      maxNumber = "";
      for(i =0; i< totalLength-decimalLength; ++i){
      maxNumber += "9";
      }
      if (maxNumber ==""){
      maxNumber="0";
      }
      maxNumber += ".";
     
      for(i = 0; i <decimalLength; ++i){
      maxNumber += "9";
      }  
      return maxNumber;
}

function fieldFocus() {
     globalField.focus();
 }
 
function getElementIndex(aform,element) {
var index = -1, i = 0;
while (i < aform.length ){
if (aform[i] == element){
index = i;
break;
}
i++;
}
return index;
}

function autoTab(aform, currEle){
var nextEle;
var index = getElementIndex(aform,currEle);
if(index<-1||index >=aform.length){
index = -1;
}
nextEle = aform[index+1];
nextEle.focus();
return nextEle;
}

function validtextlength(form_element, maxlength) {
    return (form_element.value.trim().length <= maxlength)
}

function validtextfield(form_element)
{
	return (form_element.value.trim().length>0)
}
function exceedLengthLimit(form_element, maxLength){
	return form_element.value.length > maxLength;
}

/*
 * Determines whether the field specified has a length
 * that exceeds the charLimit specified. If the length does
 * exceed the limit, a notice is presented and the field is
 * truncated to that number of characters.
 *
 * field - the form field to be checked.
 * charLimit - the max number of characters allowed for the field.
 * fieldDisplayName - field name to be presented to user if 
 * warning message is displayed.
 */
function textAreaLimit(field, charLimit, fieldDisplayName) {

	if (field.value.length > charLimit) {
	
		alert("The " + fieldDisplayName + " field restricts input to a maximum of " +
				charLimit + " characters.");
	
		field.value = field.value.substring(0, charLimit);
	
	}

}

function validnumericfield(form_element)
{
	return !(isNaN(form_element.value))

}

function validzip(form_element)
{
		number=form_element.value

		number=number.replace(/\s/gi,"")
		number=number.replace(/\-/gi,"")

		valid = /^\d{5}$|^\d{9}|^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d/
		return ((number.search(valid)!=-1) && ((number.length==5) || (number.length==9) || number.length==6))
}

function validAlphaNumeric(form_element)
{   
    value=form_element.value.trim(); 
    form_element.value = value;
    valid =  new RegExp("^[a-zA-Z0-9]+$");
    return ((value.search(valid)!=-1) )
}

function validZipCode(zip1, zip2){
    if(!validnumericfield(zip1) || zip1.value.length!=5){

      return false;
    }else if(zip2.value.length>0 && !validnumericfield(zip2)){

      return false;
    }else {
      return true;
    }
}

function validphone(form_element)
{
	phno=form_element.value;
	phno=phno.replace(/\s/gi,"")
	valid = /\d{3}\-\d{3}\-\d{4}$|\d{10}|\(\d{3}\)\d{7}|\(\d{3}\)\d{3}\-\d{4}|\d{6}\-\d{4}|\d{3}\-\d{7}/;
  if(phno.search(valid)!=-1)
	{
		phno=phno.replace(/-/gi,"")
		phno=phno.replace(/\(/gi,"")
		phno=phno.replace(/\)/gi,"")
		return (phno.length<11)
	}
	return false
}

function valid2digitFY(form_element){
valid = new RegExp("^[0-9]{2}$");
formValue = form_element.value.trim();
if(formValue.search(valid)==-1)
 {
 	return false;
 }
 return true;

}


function validdate(form_element, dateOnly) 
{
 dateStr = (form_element.value +"").trim();
 
 if(dateOnly){
 valid =    new RegExp("^(([0]?[1-9])|([1][0-2]))" 
             + "[/]"
             + "(([0]?[1-9])|([1-2][0-9])|([3][0-1]))(["
             + "/"
              + "])([0-9]{4})$"); 
  }else  {
  valid = new RegExp("^(([0]?[1-9])|([1][0-2]))" 
             + "[/]"
             + "(([0]?[1-9])|([1-2][0-9])|([3][0-1]))"
             + "[/]"
              + "([0-9]{4})" 
              +"([ ]+)"              
              + "(([0]?[1-9])|([1][0-2]))"             
              + "[:]"
              + "(([0]?[0-9])|([1-5][0-9]))"             
              + "[:]"
              + "(([0]?[0-9])|([1-5][0-9]))"
              +"[ ]"
              +"(AM|PM)$");
  }   
  if(dateStr.search(valid)==-1)
 {
 	return false;
 }
 
 
 dateSeparator ="/";
 timeSeparator =":";    
    
 monthIndex = dateStr.indexOf(dateSeparator);
 if(monthIndex >0){
 if(dateStr.charAt(0)=='0'){
 month= parseInt(dateStr.substring(1, monthIndex));
 }else{
 month= parseInt(dateStr.substring(0, monthIndex));
 }
 month = month - 1;

 if(month<0 || month>11){
 return false;
 }
 }else{
 return false;
 }
 dateStr = dateStr.substring(monthIndex+1, dateStr.length);  
 dayIndex = dateStr.indexOf(dateSeparator); 
 if(dayIndex>0){
 if(dateStr.charAt(0)=='0'){
 day= parseInt(dateStr.substring(1, dayIndex));
 }else{
 day= parseInt(dateStr.substring(0, dayIndex));
 }

 if(day<1 || day>31){
 return false;
 } 
 }else{
 return false;
 } 
 dateStr = dateStr.substring(dayIndex+1, dateStr.length);
 
  if(!dateOnly){
 yearIndex = dateStr.indexOf(" ");
 }else{
 yearIndex = dateStr.length;
 }
 if(yearIndex >0){
 if(dateStr.charAt(0)=='0'){
 year= parseInt(dateStr.substring(1, yearIndex));
 }else{
 year= parseInt(dateStr.substring(0, yearIndex));
 }
 
 if(year< 1900 || year>9999){
 return false;
 }
 }
 else{
 return false;
 }
 
 hour = 0;
 minute = 0;
 second = 0;

 if(!dateOnly){ 
 timeStr = dateStr.substring(yearIndex + 1,dateStr.length).trim();
 hourIndex = timeStr.indexOf(timeSeparator);
 if(hourIndex >0){
 if(timeStr.charAt(0)=='0'){ 
 if(hourIndex > 1){
 hour= parseInt(timeStr.substring(1, hourIndex));
 }else{
 hour = 0;
 }
 }else{
 hour= parseInt(timeStr.substring(0, hourIndex));
 }
 if(hour<0 || hour>23){
 return false;
 }
 }else{
 return false;
 }
 
 timeStr = timeStr.substring(hourIndex+1, timeStr.length);
 minIndex = timeStr.indexOf(timeSeparator);
 if(minIndex >0){
 if(timeStr.charAt(0)=='0'){
 if(minIndex > 1){
 minute= parseInt(timeStr.substring(1, minIndex));
 }else{
 minute = 0;
 }
 }else{
 minute= parseInt(timeStr.substring(0, minIndex));
 }
 if(minute<0 || minute>59){
 return false;
 }
 }
 else{
 return false;
 } 

 
 timeStr = timeStr.substring(minIndex+1, timeStr.length);
 secIndex = timeStr.length;
 if(secIndex >0){
 if(timeStr.charAt(0)=='0'){
 if(secIndex > 1){
 second= parseInt(timeStr.substring(1, secIndex));
 }else{
 seconde = 0;
 }
 }else{
 second= parseInt(timeStr.substring(0, secIndex));
 }
 if(second<0 || second>59){
 return false;
 }
 }
 else{
 return false;
 }
 }
 
 date = new Date(year,month,day,hour,minute,second);
 if(date==null){
 return false;
 }
 formattedYear = date.getYear(); 
 //alert("date:" + (date.getMonth() + 1) +"/" + date.getDate()+"/" + formattedYear+ " " + date.getHours() +":" + date.getMinutes() + ":" + date.getSeconds() );
 if(formattedYear < 1000){
   formattedYear += 1900
  }
 
 return (formattedYear==year && date.getMonth()==month && date.getDate()==day
         && date.getHours() == hour && date.getMinutes() == minute && date.getSeconds()==second);
 }


function validext(form_element)
{
	ext=form_element.value;
	if (ext.length!=0)
	{
		invalid=/[a-zA-Z]/
		return (ext.search(invalid)==-1)
	}
	else
		return true
}

function validNumber(form_element){
if(!validtextfield(form_element)){
return false;
}
fieldValue = form_element.value.trim();
return validNumberValue(fieldValue);
}

function validNumberValue(fieldValue){
if(fieldValue=="+"||fieldValue=="-"||fieldValue=="."){
return false;
}
  
var validNumber = /^[+\-]?[0-9]*(\.[0-9]*)?$/

return validNumber.test(fieldValue);   
}


function validInteger(form_element){
if(!validtextfield(form_element)){
return false;
}
var validInteger = /^[+\-]?[0-9]+$/

return validInteger.test(form_element.value.trim());
   


}

function validDBNumber(form_element,totalLength, decimalLength){
if(!validtextfield(form_element)){
return false;
}
var intPartLength = totalLength - decimalLength;
var value = form_element.value;
return validDBValue(value,totalLength, decimalLength);
}


function validDBValue(value,totalLength, decimalLength){

var intPartLength = totalLength - decimalLength;
if(!validNumberValue(value))
{
  return false;
}
var maxNumber=getMaxDBNumber(totalLength, decimalLength)
if(value<(-1)*maxNumber || value > parseFloat(maxNumber)){
return false;
}else{
return true;
}

}





function validtaxid(form_element)
{
	id=form_element.value	
	id=id.replace(/\s/gi,"")
	valid=/^\d{3}\-\d{2}\-\d{4}$|^\d{9}$|^\d{2}\-\d{7}$|^\d{4}-\d{4}$/
	return (id.search(valid)!=-1);
}

//function validemail(form_element)
//{
//	emailad = form_element.value
//	var exclude=/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
//	var check=/@[\w\-]+\./;
//	var checkend=/\.[a-zA-Z]{2,}$/;
//	return ((emailad.search(exclude) == -1) && (emailad.search(check) != -1) && (emailad.search(checkend) != -1))
//}

function validemail(form_element)
{
	var x = form_element.value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return (filter.test(x))
}



function validdropdown(form_element)
{
	if (form_element.selectedIndex>0) {
		return true;
	}
	
	return (form_element.options[form_element.selectedIndex].value.trim() != "");
}

function validaddressdropdown(form_element)
{
	if (form_element.selectedIndex>0) {
		return true;
	}
	
	return (form_element.options[form_element.selectedIndex].value.trim() != ""
	&& parseInt(form_element.options[form_element.selectedIndex].value.trim()) > 0
	);
}


function validcheckbox(form_element)
{
	checked = true
	for(i=0; i<form_element.length; i++)
	{
		if(form_element[i].checked)
			return (checked)
	}
	return (!checked)
}

function validPhoneNumber(phone1, phone2, phone3, required){
  if(required){
   // alert("checking required.");
    if(phone1.value.length<1 || phone2.value.length<1 || phone3.length<1){
        return false;
    }
  }
  //alert("checking numeric");
  if(!validOptionalNumeric(phone1)||!validOptionalNumeric(phone2)
    ||!validOptionalNumeric(phone3)){
     return false;
  }
  //alert("checking length");
  if(phone1.value.length + phone2.value.length + phone3.value.length > 0){
     if(phone1.value.length!=3 || phone2.value.length!=3 || phone3.value.length!=4){
         return false;
     }
  }
  return true;
}

function validOptionalNumeric(form_element)
{
	return (form_element.value.length<1 ||validnumericfield(form_element));

}

function validPhoneExt(form_element){
return validOptionalNumeric(form_element);
}


function validlink(form_element)
{
	return (form_element.value.indexOf("://") != -1)
}

function validkey(form_element) { 

    form_element.value = form_element.value.trim();
        
	valid = (form_element.value.length > 0 
	&& form_element.value.indexOf("'")== -1
	&& form_element.value.indexOf('"')== -1
	&& form_element.value.indexOf(" ")== -1
	&& form_element.value.indexOf("&") == -1	
	);	
	return valid;
}

function getIndexedField(aform, subformName, indexId, fieldName){
 return  eval("aform['" + subformName  + "[" + indexId + "]." + fieldName +"']"); 
}


function getTimeDiffMsg(timeDiff, showMilliSeconds) {
        if(timeDiff <=0){
        	return "None";
        }
		days =  Math.floor(timeDiff / (1000 * 60 * 60 * 24));
		hours =  Math.floor((timeDiff % (1000 * 60 * 60 * 24))
				/ (1000 * 60 * 60));
		minutes =  Math.floor((timeDiff % (1000 * 60 * 60))
				/ (1000 * 60));
		seconds =  Math.floor(timeDiff % (1000 * 60) / 1000);
		
		milliSeconds = timeDiff % 1000;		
		message = "";
		message += (days == 0) ? "" : days + " day ";
		message +=((hours == 0 && days == 0) ? "" : hours + " hour ");
		message +=		((minutes == 0 && days == 0 && hours == 0) ? ""
								: minutes + " minute ");
		message +=(
						(minutes == 0 && days == 0 && hours == 0
								&& seconds == 0 && showMilliSeconds) ? ""
								: seconds + " second ");
		message +=(!showMilliSeconds ? "" : milliSeconds + " millisecond ");
		
		
		return message;
}

/*
 * Validates an id to ensure it does not contain single or 
 * double quotes. If the id does contain quotes, this function
 * returns false indicating the id was invalid.
 *
 */
function validId(id) {   

	var valid = false;
	
	if (id != null && id.value != null) {
	
	    id.value = id.value.trim();
	        
		valid = (id.value.indexOf("'") == -1 && id.value.indexOf('"') == -1 );
			
	}
	
	return valid ;
	
}



