// ----------------------------------------------------------------------

// Javascript form validation routines.

// Author: Stephen Poley

//

// Simple routines to quickly pick up obvious typos.

// All validation routines return true if executed by an older browser:

// in this case validation must be left to the server.

//

// Update Aug 2004: have tested that IE 5.0 and IE 5.5 both support DOM model

// sufficiently well, so innerHTML option removed (redundant).

// ----------------------------------------------------------------------



var nbsp = 160;    // non-breaking space char

var node_text = 3; // DOM text node-type

emptyString = /^\s*$/



// -----------------------------------------

//                  trim

// Trim leading/trailing whitespace off string

// -----------------------------------------



function trim(str)

{

  return str.replace(/^\s+|\s+$/g, '')

};



// -----------------------------------------

//                  msg

// Display warn/error message in HTML element

// commonCheck routine must have previously been called

// -----------------------------------------



function msg(fld,     // id of element to display message in

             msgtype, // class to give element ("warn" or "error")

             message) // string to display

{

  // setting an empty string can give problems if later set to a 

  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 

  // simply use a space, but IE demands something more, like a non-breaking space.)

  var dispmessage;

  if (emptyString.test(message)) 

    dispmessage = String.fromCharCode(nbsp);    

  else  

    dispmessage = message;



  var elem = document.getElementById(fld);

  elem.firstChild.nodeValue = dispmessage;  

  

  elem.className = msgtype;

};



// -----------------------------------------

//            commonCheck

// Common code for all validation routines to:

// (a) check for older / less-equipped browsers

// (b) check if empty fields are required

// Returns true (validation passed), 

//         false (validation failed) or 

//         proceed (don't know yet)

// -----------------------------------------



var proceed = 2;

var focusEnabled=false;



function commonCheck    (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd)   // true if required

{

  if (!document.getElementById) 

    return true;  // not available on this browser - leave validation to the server

  var elem = document.getElementById(ifld);

  if (!elem.firstChild)

    return true;  // not available on this browser 

  if (elem.firstChild.nodeType != node_text)

    return true;  // ifld is wrong type of node  



  if (emptyString.test(vfld.value)) {

    if (reqd) {

      msg (ifld, "error", "Please complete");  

      if (!focusEnabled) {

        vfld.focus();  // calling this function multiple times in the same context results in JS error

        focusEnabled=true;

      }

      return false;

    }

    else {

      msg (ifld, "warn", "");   // OK

      return true;  

    }

  }

  return proceed;

}



// -----------------------------------------

//            validatePresent

// Validate if something has been entered

// Returns true if so 

// -----------------------------------------



function validatePresent(vfld,   // element to be validated

                         ifld )  // id of element to receive info/error msg

{

  var stat = commonCheck (vfld, ifld, true);

  if (stat != proceed) return stat;



  msg (ifld, "warn", "");  

  return true;

};



// -----------------------------------------

//               validateEmail

// Validate if e-mail address

// Returns true if so (and also if could not be executed because of old browser)

// -----------------------------------------



function validateEmail  (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd)   // true if required

{

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;



  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off

  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/

  if (!email.test(tfld)) {

    msg (ifld, "error", "Enter a valid e-mail address");

    vfld.focus();

    return false;

  }



  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/

  if (!email2.test(tfld)) 

    msg (ifld, "warn", "Unusual e-mail address - check if correct");

  else

    msg (ifld, "warn", "");

  return true;

};





// -----------------------------------------

//            validateTelnr

// Validate telephone number

// Returns true if so (and also if could not be executed because of old browser)

// Permits spaces, hyphens, brackets and leading +

// -----------------------------------------



function validateTelnr  (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd)   // true if required

{

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;



  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off

  //var telnr = /^\+?[0-9 ()-]+[0-9]$/;

  var telnr = /^\+?\(?(\d{3}\)?(\s|-)\d{3}(\s|-)\d{4})$/;

  if (!telnr.test(tfld)) {

    msg (ifld, "error", "ERROR: not a valid telephone number.Characters permitted are digits, space ()- and leading +.Ex:123-456-7890");

    vfld.focus();

    return false;

  }



  var numdigits = 0;

  for (var j=0; j<tfld.length; j++)

    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;



  if (numdigits<6) {

    msg (ifld, "error", "Please enter your area code and phone number (10 digits)");

    vfld.focus();

    return false;

  }



  if (numdigits>14)

    msg (ifld, "warn", numdigits + " digits - check if correct");

  else { 

    if (numdigits<10)

      msg (ifld, "warn", "Please enter your area code and phone number (10 digits)");

    else

      msg (ifld, "warn", "");

  }

  return true;

};



function validateRegPin  (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd)   // true if required

{

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;



  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off

  var pin = /^[A-Z]{4}-[0-9]{4}$/

  if (!pin.test(tfld)) {

    msg (ifld, "error", "ERROR: not a valid PIN number. Please enter your PIN as in the PIN letter.");

    vfld.focus();

    return false;

  } else {

    msg (ifld, "warn", "");

  }

 

  return true;

};



function validateUserName  (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd,minchars,maxchars)   // true if required

{

  if(minchars == null) minchars =4;

  if(maxchars == null) maxchars =14;

  

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;





  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off

  var uname = eval("/^[A-Za-z0-9]{" + minchars + "," + maxchars + "}$/");

  if (!uname.test(tfld)) {

    msg (ifld, "error", "ERROR: not a valid User Name. User Name must be "+minchars+ " - " + maxchars+ " letters or numbers");

    vfld.focus();

    return false;

  } else {

    msg (ifld, "warn", "");

  }

 

  return true;

};



function validatePassword (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd,minchars,maxchars)   // true if required

{

  if(minchars == null) minchars =4;

  if(maxchars == null) maxchars =14;

  

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;





  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off

  var pass = eval("/^[A-Za-z0-9]{" + minchars + "," + maxchars + "}$/");

  if (!pass.test(tfld)) {

    msg (ifld, "error", "ERROR: not a valid Password. Password must be "+minchars+ " - " + maxchars+ " letters or numbers");

    vfld.focus();

    return false;

  } else {

    msg (ifld, "warn", "");

  }

 

  return true;

};







// -----------------------------------------

//             validateSSN

// -----------------------------------------





function validateSSN    (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd)   // true if required

{

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;



  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off

  var ssn = /^\+?[0-9 ()-]+[0-9]$/

  if (!ssn.test(tfld)) {

    msg (ifld, "error", "ERROR:  Characters permitted are numbers only");

    vfld.focus();

    return false;

  }



  var numdigits = 0;

  for (var j=0; j<tfld.length; j++)

    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;



  if (numdigits!=4) {

    msg (ifld, "error", "Please enter only the last 4 digits of your SSN ");

    vfld.focus();

    return false;

  }else

  {

    msg (ifld, "warn", "");

  }



  return true;

};





// -----------------------------------------

//             validateZip

// -----------------------------------------







function validateZip    (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd)   // true if required

{

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;



  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off

  var zip = /^\+?[0-9 ()-]+[0-9]$/

  if (!zip.test(tfld)) {

    msg (ifld, "error", "ERROR: not a valid zip code. Characters permitted are digits, space ()- and leading +");

    vfld.focus();

    return false;

  }



  var numdigits = 0;

  for (var j=0; j<tfld.length; j++)

    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;



  if (numdigits<5) {

    msg (ifld, "error", "Please enter your zip code (5 digits)");

    vfld.focus();

    return false;

  }



  if (numdigits>14)

    msg (ifld, "warn", numdigits + " digits - check if correct");

  else { 

    if (numdigits>10)

      msg (ifld, "warn", "Please enter your zip code (5 digits)");

    else

      msg (ifld, "warn", "");

  }

  return true;

};







// -----------------------------------------

//             validateTaxYear

// -----------------------------------------







function validateTaxYear    (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd)   // true if required

{

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;



  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off



  var year = /^[0-9]{4}$/

  if (!year.test(tfld)) {

    msg (ifld, "error", "ERROR: not a valid year.");

    vfld.focus();

    return false;

  }



  var numdigits = 0;

  for (var j=0; j<tfld.length; j++)

    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;



  if (numdigits!=4) {

    msg (ifld, "error", "Please enter valid year (4 digits)");

    vfld.focus();

    return false;

  } else {

    if (tfld <1900 || tfld > 2200) {

      msg (ifld, "error", "Error: year should be between 1900 & 2200");

		vfld.focus();

      return false;

    } else {

      msg (ifld, "warn", "");

    }

  }

  return true;

};





// -----------------------------------------

//             validateWholeSSN

// -----------------------------------------





function validateWholeSSN    (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd)   // true if required

{

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;



  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off

  var wholessn = /^\+?[0-9 ()-]+[0-9]$/

  if (!wholessn.test(tfld)) {

    msg (ifld, "error", "ERROR:  Please enter your Social Security Number without dashes or spaces (Example:123456789)");

    vfld.focus();

    return false;

  }



  var numdigits = 0;

  for (var j=0; j<tfld.length; j++)

    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;



  if (numdigits<9) {

    msg (ifld, "error", "Please enter your Social Security Number without dashes or spaces (Example:123456789)");

    vfld.focus();

    return false;

  }



  if (numdigits!=9){

    msg (ifld, "warn", numdigits + " digits - check if correct");

    return false;

  } else {

    msg (ifld, "warn", "");

  }



  return true;

};



// -----------------------------------------

//             validateDOB

// -----------------------------------------





function validateDOB    (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd)   // true if required

{

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;



  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off

  var res = isDate(tfld,"mmddyyyy");

    if (!res) {

       msg (ifld, "warn", " Date of Birth enterd is either incorrect or in incorrect format");

    } else { 

       msg (ifld, "warn", "");

    }  

  return res;  

};



// -----------------------------------------

//             validateFederalID

// -----------------------------------------







function validateFederalID    (vfld,   // element to be validated

                         ifld,   // id of element to receive info/error msg

                         reqd)   // true if required

{

  var stat = commonCheck (vfld, ifld, reqd);

  if (stat != proceed) return stat;



  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off

  var federalId = /^\+?[0-9 ()-]+[0-9]$/

  if (!federalId.test(tfld)) {

    msg (ifld, "error", "ERROR: not a valid Federal ID. Characters permitted are digits, space ()-");

    vfld.focus();

    return false;

  }



  var numdigits = 0;

  for (var j=0; j<tfld.length; j++)

    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;



  if (numdigits != 7) {

    msg (ifld, "error", "Please enter Federal ID(7 digits)");

    vfld.focus();

    return false;

  }else {

      msg (ifld, "warn", "");

  }

  return true;

};



//

// DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)

//

// Declaring valid date character, minimum year and maximum year

var dtCh= "-";

var minYear=1800;

var maxYear=2500;



function isInteger(s){

	var i;

    for (i = 0; i < s.length; i++){   

        // Check that current character is number.

        var c = s.charAt(i);

        if (((c < "0") || (c > "9"))) return false;

    }

    // All characters are numbers.

    return true;

}



function stripCharsInBag(s, bag){

	var i;

    var returnString = "";

    // Search through string's characters one by one.

    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++){   

        var c = s.charAt(i);

        if (bag.indexOf(c) == -1) returnString += c;

    }

    return returnString;

}



function daysInFebruary (year){

	// February has 29 days in any year evenly divisible by four,

    // EXCEPT for centurial years which are not also divisible by 400.

    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );

}

function DaysArray(n) {

	for (var i = 1; i <= n; i++) {

		this[i] = 31

		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}

		if (i==2) {this[i] = 29}

   } 

   return this

}



// syntax: isDate("1900-02-23","yyyy-mm-dd");

function isDate(dtStr,format){

	var daysInMonth = DaysArray(12);

	var pos1,pos2,strYear="",strMonth="",strDay="",debug,regex,regexRes;

	

	var debug=false; // set to 'true' if needed debug information

	

	dtCh = "/";

	var delimCheck = true;

	//var re = /^\d{4}-\d{2}-\d{2}$/;

	//var res = str1.match(re);

	

	

	if(format){

	  format=format.toLowerCase();

	} else {

	   if(debug) {

	     alert(" No value for 'format' in function call ");

	   }	   

	   return false;	   

	}

	

	if( (format=="yyyy-mm-dd") || (format=="yyyy/mm/dd") ) {

	

	  regex = /^\d{4}\/\d{2}\/\d{2}$/;

	  if(format=="yyyy-mm-dd") {

	    dtCh = "-";

	    regex = /^\d{4}-\d{2}-\d{2}$/;

	  }

	  pos1=dtStr.indexOf(dtCh);

	  pos2=dtStr.indexOf(dtCh,pos1+1);

	  strYear=dtStr.substring(0,pos1);

	  strMonth=dtStr.substring(pos1+1,pos2); 

	  strDay=dtStr.substring(pos2+1); 	 

	 

	} else if( (format=="mm-dd-yyyy") || (format=="mm/dd/yyyy") ) {

       regex = /^\d{2}\/\d{2}\/\d{4}$/;

       if(format=="mm-dd-yyyy") {

	       dtCh = "-";

	       regex = /^\d{2}-\d{2}-\d{4}$/;

	    }

	    pos1=dtStr.indexOf(dtCh);

	    pos2=dtStr.indexOf(dtCh,pos1+1);

	    

	    strMonth=dtStr.substring(0,pos1);

	    strDay=dtStr.substring(pos1+1,pos2); 

	    strYear=dtStr.substring(pos2+1); 	 	   

	    

	} else if( (format=="dd-mm-yyyy") || (format=="dd/mm/yyyy") ) {

       regex = /^\d{2}\/\d{2}\/\d{4}$/;

       if(format=="dd-mm-yyyy") {

	       dtCh = "-";

	       regex = /^\d{2}-\d{2}-\d{4}$/;

	    }

	    pos1=dtStr.indexOf(dtCh);

	    pos2=dtStr.indexOf(dtCh,pos1+1);

	    

	    strDay=dtStr.substring(0,pos1);

	    strMonth=dtStr.substring(pos1+1,pos2); 

	    strYear=dtStr.substring(pos2+1); 	 	   



	} else if(format=="yyyymmdd") {

	   regex = /^\d{8}$/;

	   delimCheck = false;

	   strYear=dtStr.substring(0,4);

		strMonth=dtStr.substring(4,6);	

	   strDay=dtStr.substring(6,8);



	} else if(format=="mmddyyyy") {

	   regex = /^\d{8}$/;

	   delimCheck = false;

	   strMonth=dtStr.substring(0,2);

		strDay=dtStr.substring(2,4);	

	   strYear=dtStr.substring(4,8);

	

	} else if(format=="ddmmyyyy") {

	   regex = /^\d{8}$/;

	   delimCheck = false;

	   strDay=dtStr.substring(0,2);

		strMonth=dtStr.substring(2,4);	

		strYear=dtStr.substring(4,8);

		

	} else {

	  return false;

	   

	}

	

	

	if(debug) {

	  alert("delimiter: "+dtCh+"  delimCheck:"+delimCheck);

	  alert(" Date String: "+dtStr +" format:"+format+" Day: "+strDay+" month:"+strMonth+" Year:"+strYear);

	}

	regexRes = dtStr.match(regex);

	if( !regexRes) {

	   

	   if(debug) {

	     alert(dtStr +" failed to match reg ex:"+regex);

	   }

	   return false;

	}

	//return;

	

	strYr=strYear;

	// Dont strip the leading 0

	//if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);

	//if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);

	

	for (var i = 1; i <= 3; i++) {

		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);

	}

	//syn: parseInt(NUMBER,base);

	month=parseInt(strMonth,10);	

	day=parseInt(strDay,10);

	year=parseInt(strYr,10);

	// Check only if the format includes delimiters

	if(delimCheck) {

	  if (pos1==-1 || pos2==-1){

		if(debug) {

		  alert("The date format should be : mm/dd/yyyy")

		}

		return false;

	  }

	}

	if (strMonth.length!=2 || month<1 || month>12){

		if(debug) {

		  alert("Please enter a valid month. length:"+strMonth.length+" month:"+month);

		}

		return false;

	}

	if (strDay.length!=2 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){

		if(debug) {

		  alert("Please enter a valid day");

		}

		return false;

	}

	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){

		if(debug) {

		  alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);

		}

		return false;

	}

	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){

		if(debug) {

		  alert("Please enter a valid date");

		}

		return false;

	}



   if(debug) {

     alert(dtStr+ " is a valid Date");

   }

return true;

}
