/**
* This will contain validations for numeric, alpha, alphanumeric, date and other form values.
* Please put your function definition in the proper section and also add the name in the table of contents.
* This should contain utility functions only (individual functions that can be used by any page).
* Created By : Defhel
* Feb 06, 2009


  TABLE OF CONTENTS (functions available in alphabetial order)

* autoTab(input,len, e)
* checkAllCheckBox(headCheckBox, checkboxName)
* isNumeric(value)
* numericOnly(e)
* numericOnlyAndAutoTab(e,input,len) --used in keypress
* resetDate()
* setDateFieldValue(thisForm,vMonth,vDay,vYear,dateValue)
* setRequiredDateValue(vDesc)
* trim(value)
* valDateFmt(datefmt)
* validateDate(fld,fmt,rng)
* validateDefDate(thisForm,vMonth,vDay,vYear,vDesc)
* validateFromToDate(fromDesc,fmonth,fday,fyear,toDesc,tmonth,tday,tyear)
* validateNumericValue(textobj)


Note : see also validation.js you may find there the validation that you are looking for.
       if the validation that you are looking for is not in validation.js, please add your
       validation here, not in validation.js.

**/



/*********************************************************************** VALIDATIONS FOR NUMERIC BEGIN ***/

function isNumeric(value){
   return (!isNaN(value));//returns true if value is a number or value is ''.
}

function validateNumericValue(textobj){
   if (trim(textobj.value)=='') textobj.value='0';
   if (isNaN(textobj.value)) {
	 alert ("Invalid value for numeric field.\nPlease enter a numeric value.");
	textobj.select();// this will focus the field with non numeric value;
   }
   return (!isNaN(textobj.value));
}

function numericOnly(e)
{
 var keynum
 var keychar
 var numcheck

 if(window.event) // IE
	{
	keynum = e.keyCode
	}
 else if(e.which) // Netscape/Firefox/Opera
	{
	keynum = e.which
	}
 keychar = String.fromCharCode(keynum)

 if(keynum == 8 || keynum == undefined ) {
 return;
   }
 if(keynum >= 48 && keynum < 58) {
    return;
 }else{
     //alert('Invalid diagnosis code entered.');
     return false;
 }
 }

//this will blank the text box if non-numeric character was entered else it will autoTab.
function numericOnlyAndAutoTab(e,input,len) {
	text=trim(input.value);
	var x =numericOnly(e);
	if (x==null){ 
          return autoTab(input,len,e);
        }else{	  
	  return x;
	}
}



/*********************************************************************** VALIDATIONS FOR NUMERIC END ***/

/*********************************************************************** VALIDATIONS FOR ALPHA BEGIN ***/



/*********************************************************************** VALIDATIONS FOR ALPHA END ***/

/*********************************************************************** VALIDATIONS FOR ALPHANUMERIC BEGIN ***/
function trim(value){//removes leading and trailing spaces
  return value.replace(/^\s+|\s+$/g,'');
}
/*********************************************************************** VALIDATIONS FOR ALPHANUMERIC END ***/

/*********************************************************************** VALIDATIONS FOR DATE BEGIN ***/

function valDateFmt(datefmt) {myOption = -1;
for (i=0; i<datefmt.length; i++) {if (datefmt[i].checked) {myOption = i;}}
if (myOption == -1) {alert("You must select a date format");return ' ';}
return datefmt[myOption].value;}

function valDateRng(daterng) {myOption = -1;
for (i=0; i<daterng.length; i++) {if (daterng[i].checked) {myOption = i;}}
if (myOption == -1) {alert("You must select a date range");return ' ';}
return daterng[myOption].value;}

function stripBlanks(fld) {var result = "";for (i=0; i<fld.length; i++) {
if (fld.charAt(i) != " " || c > 0) {result += fld.charAt(i);
if (fld.charAt(i) != " ") c = result.length;}}return result.substr(0,c);}
var numb = '0123456789';

function isValid(parm,val) {if (parm == "") return true;
for (i=0; i<parm.length; i++) {if (val.indexOf(parm.charAt(i),0) == -1)
return false;}return true;}

function isNum(parm) {return isValid(parm,numb);}
var mth = new Array(' ','january','february','march','april','may','june','july','august','september','october','november','december');
var day = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

function validateDate(fld,fmt,rng) {
    var dd, mm, yy;
    var today = new Date;
    var t = new Date;
    fld = stripBlanks(fld);
if (fld == '') return false;
var d1 = fld.split('\/');
if (d1.length != 3) d1 = fld.split(' ');
if (d1.length != 3) return false;
if (fmt == 'u' || fmt == 'U') {
dd = d1[1];
mm = d1[0];
yy = d1[2];}
else if (fmt == 'j' || fmt == 'J') {
dd = d1[2];
mm = d1[1];
yy = d1[0];}
else if (fmt == 'w' || fmt == 'W'){
dd = d1[0];
mm = d1[1];
yy = d1[2];}
else return false;
var n = dd.lastIndexOf('st');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf('nd');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf('rd');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf('th');
if (n > -1) dd = dd.substr(0,n);
n = dd.lastIndexOf(',');
if (n > -1) dd = dd.substr(0,n);
n = mm.lastIndexOf(',');
if (n > -1) mm = mm.substr(0,n);
if (!isNum(dd)) return false;
if (!isNum(yy)) return false;
if (!isNum(mm)) {
var nn = mm.toLowerCase();
for (var i=1; i < 13; i++) {
if (nn == mth[i] ||
nn == mth[i].substr(0,3)) {mm = i; i = 13;}
}
}
if (!isNum(mm)) return false;
dd = parseFloat(dd); mm = parseFloat(mm); yy = parseFloat(yy);
//if (yy < 100) yy += 2000;
//if (yy < 1582 || yy > 4881) return false; 
//change the validation of year coz some of the year in ctaddress are 9999
if (yy < 1800 || yy > 9999) return false;
if (mm == 2 && (yy%400 == 0 || (yy%4 == 0 && yy%100 != 0))) day[mm-1]++;
if (mm < 1 || mm > 12) return false;
if (dd < 1 || dd > day[mm-1]) return false;
t.setDate(dd); t.setMonth(mm-1); t.setFullYear(yy);
if (rng == 'p' || rng == 'P') {
    if (t > today) return false;
}else if (rng == 'f' || rng == 'F') {
    if (t < today) return false;
}else if (rng != 'a' && rng != 'A') return false;
    return true;
}

function resetDate() {
    var a = $("statusChanged");
    var b = $A(a.getElementsByTagName("INPUT"));
    b.each(function(i){i.value=""});
}

var requiredDateName="";
function setRequiredDateValue(vDesc){//called before validateDefDate
	requiredDateName=vDesc; //this will be used by validateDefDate
	//this will determine if the date to be validated in validateDefDate 
        //should have a value.
}


function setDateFieldValue(thisForm,vMonth,vDay,vYear,dateValue){ 
    //dateValue can be a Date Object or a String "mm/dd/yyyy"
    var vFieldMonth = thisForm.elements[vMonth];
    var vFieldDay = thisForm.elements[vDay];
    var vFieldYear = thisForm.elements[vYear];

    try{//if Date Object
	vFieldDay.value= dateValue.getDate();
        vFieldMonth.value=dateValue.getMonth() + 1;
	vFieldYear.value= dateValue.getFullYear();
    }catch (e){//if String 

	dateValue +="";
	dateValue = new Date(dateValue);
 	vFieldDay.value= dateValue.getDate();
	vFieldMonth.value=dateValue.getMonth() + 1;
	vFieldYear.value= dateValue.getFullYear();

	if (vFieldDay.value=='NaN'){//if invalid String then get today's date
	   dateValue = new Date();
	   vFieldDay.value= dateValue.getDate();
           vFieldMonth.value=dateValue.getMonth() + 1;
	   vFieldYear.value= dateValue.getFullYear();
	}
    }
}



function validateDefDate(thisForm,vMonth,vDay,vYear,vDesc){
    var vFieldMonth = thisForm.elements[vMonth];
    var vFieldDay = thisForm.elements[vDay];
    var vFieldYear = thisForm.elements[vYear];

    if (requiredDateName==vDesc){
	if (trim(vFieldMonth.value).length==0 ||
	    trim(vFieldDay.value).length==0 ||
	    trim(vFieldYear.value).length==0 ){
	   alert ('The ' + vDesc + ' date is blank. Please return to the page and enter a valid ' + vDesc + ' date.');
	   vFieldMonth.select();
	   return false;
	}
    }

    if (((vFieldMonth.value.length > 0) &&
         ((vFieldDay.value.length == 0) ||
          (vFieldYear.value.length == 0)))||
        ((vFieldDay.value.length > 0) &&
          ((vFieldMonth.value.length == 0) ||
           (vFieldYear.value.length == 0))) ||
        ((vFieldYear.value.length > 0) &&
         ((vFieldDay.value.length == 0) ||
          (vFieldMonth.value.length == 0)))){
        alert('Invalid ' + vDesc + ' Date');
        //resetDate();
        return false;
    }

    datefieldval=vFieldMonth.value+'/'+vFieldDay.value+'/'+vFieldYear.value;
    //alert(datefieldval);
    if(!validateDate(datefieldval,'U','A')){
        alert('Invalid ' + vDesc + ' Date (mm/dd/yyyy)');
          if (vDesc == 'Disenrollment'){
          	$("re-enrollmentbtn").disabled=0;
          }

        //resetDate();                        
        return false;
    }
    return true;
}

function validateFromToDate(fromDesc,fmonth,fday,fyear,toDesc,tmonth,tday,tyear){
	var fromDate=new Date(parseInt(fyear),parseInt(fmonth)-1,parseInt(fday)) //Month is 0-11 in JavaScript
	var toDate=new Date(parseInt(tyear),parseInt(tmonth)-1,parseInt(tday)) //Month is 0-11 in JavaScript
	if(fromDate>toDate){
		alert(toDesc+" Date must be later than "+fromDesc+" Date.");
		return false;
	}else{
		return true;
	}
}


/*********************************************************************** VALIDATIONS FOR DATE END ***/

/*********************************************************************** VALIDATIONS FOR OTHERS BEGIN ***/
function checkAllCheckBox(headCheckBox, checkboxName){
   //select/unselect toggle all checkbox.
   //Checkbox headCheckBox - The checkbox to click to toggle select/unselect all
   //String checkboxName - The name of the array of checkbox.
   var FormObj= headCheckBox.form;
	
   if (headCheckBox.checked) {
        if (FormObj.elements[checkboxName].length) {	
          for (i=0;i<FormObj.elements[checkboxName].length;++ i) {
            FormObj.elements[checkboxName][i].checked=true;
          }
	} else {
	  FormObj.elements[checkboxName].checked=true;
	}	
   } else {
	if (FormObj.elements[checkboxName].length) {			
          for (i=0;i<FormObj.elements[checkboxName].length;++ i) {
            FormObj.elements[checkboxName][i].checked=false;
          }
        } else {
	  FormObj.elements[checkboxName].checked=false;
	}	
   }
}//checkAllCheckBox End


var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) {//autotab start
    var keyCode = (isNN) ? e.which : e.keyCode;
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
    if (input.value.length >= len && !containsElement(filter,keyCode)) {
        input.value = input.value.slice(0, len);
	try{
	   input.form[(getIndex(input)+1)].focus();
	} catch(err) {
	   //alert('catch');
	   input.form[(getIndex(input)+1)].focus();
	}
    }

    function containsElement(arr, ele) {
        var found = false, index = 0;
        while (!found && index < arr.length)
        if (arr[index] == ele)
            found = true;
        else
            index++;
        return found;
    }

    function getIndex(input) {
        var index = -1, i = 0, found = false;
        while (i < input.form.length && index == -1)
        if (input.form[i] == input)index = i;
        else i++;
        return index;
    }

    return true;
}//autotab end


/*********************************************************************** VALIDATIONS FOR OTHERS END ***/





