// ----------------------------------------------------------------------
// 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*$/

var dtCh= "/";
var minYear=1900;
var maxYear=2100;
var ValidationDateFormat=""; //set to DD/MM to change day & year from MM/DD (default)

function MoveFocusTo(field){
	if (typeof(field) != 'undefined'){
		if (field.type != 'hidden'){
		field.focus();
		}
	}
}

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
}


// -----------------------------------------
//                  validateOnSubmit
// Validates all fields on submit
// -----------------------------------------

  function validateOnSubmit(form, error_object) {
    var elem;
    var errs=0;
	var statement='';
	var formElements = form.elements;
	for (i=0; i<formElements.length; i++) {
		if (formElements[i].lang != undefined && formElements[i].lang != ''){
			statement='if (!validate' + formElements[i].lang + '(formElements[i],\'';
			if(error_object != null)statement += error_object; //if error_object is specified, pass this along
			else statement+= 'ValSpan_' + formElements[i].name; //otherwise ValSpan_FormName is the default error object
			statement+='\', true)) errs += 1;';
			eval(statement);
			if( error_object != null && errs > 0 ) break;
		}
	}
    if (errs>=1)  alert('Some required fields are missing or not properly formatted.');
    return (errs==0);
  };


// -----------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// -----------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};

// -----------------------------------------
//                  ValidateField
// Calls the correct validation function for this field.
// -----------------------------------------

function ValidateField(FormField,DivName)
{
	if (FormField.lang != undefined){
		validatePresent(FormField,DivName);
		//eval('validate' + FormField.lang + '(FormField,DivName);');
		
	}
};

// -----------------------------------------
//                  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;
  var test
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;
  var elem = document.getElementById(fld);
  if (elem != null){
	  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;  

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
  if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, "error", "Required");  
      MoveFocusTo(vfld);
      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;
};
// -----------------------------------------
//            validateMaxlen
// Validate if something has been entered
// Returns true if so 
// -----------------------------------------

function validateMaxlen(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;
  
  if (vfld.value.length > vfld.maxlength)
  {
	msg (ifld, "error", "too long");  
  	return false;
  }
  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", "not a valid e-mail address");
    MoveFocusTo(vfld);
    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]$/
  if (!telnr.test(tfld)) {
    msg (ifld, "error", "not a valid telephone number. Characters permitted are digits, space and ()-");
    MoveFocusTo(vfld);
    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", "" + numdigits + " digits - too short");
    MoveFocusTo(vfld);
    return false;
  }

  if (numdigits>14)
    msg (ifld, "warn", numdigits + " digits - check if correct");
  else { 
    if (numdigits<10)
      msg (ifld, "warn", "Only " + numdigits + " digits - check if correct");
    else
      msg (ifld, "warn", "");
  }
  return true;
};

// -----------------------------------------
//             validateAge
// Validate person's age
// Returns true if OK 
// -----------------------------------------

function validateAge    (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);
  var ageRE = /^[0-9]{1,3}$/
  if (!ageRE.test(tfld)) {
    msg (ifld, "error", "not a valid age");
    MoveFocusTo(vfld);
    return false;
  }

  if (tfld>=200) {
    msg (ifld, "error", "not a valid age");
    MoveFocusTo(vfld);
    return false;
  }

  if (tfld>110) msg (ifld, "warn", "Older than 110: check correct");
  else {
    if (tfld<7) msg (ifld, "warn", "This person is too young to vote");
    else        msg (ifld, "warn", "");
  }
  return true;
};

function validateDDNumber    (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);
  var numRE = /^[0-9]{1,3}$/
  if (!numRE.test(tfld)) {
    msg (ifld, "error", "not a valid number");
    MoveFocusTo(vfld);
    return false;
  }
  msg (ifld, "warn", "");
  return true;
};

function validateNumber    (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);
  var numRE = /[^0-9]/
  if (numRE.test(tfld)) {
	msg (ifld, "error", "Not a valid integer");
    MoveFocusTo(vfld);
    return false;
  }
  msg (ifld, "warn", "");
  return true;
};

function validateDate    (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);
    var daysInMonth = DaysArray(12);
	var pos1= tfld.indexOf(dtCh);
	var pos2=tfld.indexOf(dtCh,pos1+1);
	var strMonth=tfld.substring(0,pos1);
	var strDay=tfld.substring(pos1+1,pos2);
	if (ValidationDateFormat=="DD/MM"){
		strDay=tfld.substring(0,pos1);
		strMonth=tfld.substring(pos1+1,pos2);
	}
	var strYear=tfld.substring(pos2+1);
	strYr=strYear;
	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)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, "error",  "error", "field required");  
      MoveFocusTo(vfld);
      return false;
    }
	}
	if ((pos1==-1 || pos2==-1) && tfld != '' ){
		 msg (ifld, "error", "Date format: m/d/yy");

		 //MoveFocusTo(vfld);
		return false
	}
	if ((strMonth.length<1 || month<1 || month>12)  && tfld != '' ){
		 msg (ifld, "error", "Please enter a valid month");
		 //MoveFocusTo(vfld);
		return false
	}
	if ((strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])  && tfld != '' ){
		msg (ifld, "error", "Please enter a valid day");
		//MoveFocusTo(vfld);
		return false
	}
	if ((strYear.length != 4 || year==0 || year<minYear || year>maxYear)  && tfld != '' ){
		msg (ifld, "error", "Please enter a valid 4 digit year between "+minYear+" and "+maxYear+"");
		//MoveFocusTo(vfld);
		return false
	}
	if ((tfld.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(tfld, dtCh))==false)  && tfld != '' ){
		msg (ifld, "error", "Please enter a valid date");
		 // MoveFocusTo(vfld);
		return false
	}
	var isDate = new Date(vfld.value);
    if (isDate == "NaN") {
		msg (ifld, "error", "Please enter a valid date");
		return false
	}else{
		var CurDate = new Date()
		if (isDate > CurDate){
			test=confirm("You've entered a date in the future. Is this correct?")
			if (!test){
				msg (ifld, "error", "Your date is in the future");
				return false
			}
			//msg (ifld, "warn", "Your date is in the future!");
		}
		var OldDate=new Date(95,01,01)
		if (isDate < OldDate){
			test=confirm("You've entered a date older then 10 years. Is this correct?")
			if (!test){
				msg (ifld, "error", "Your date is over 10 years old");
				return false
			}
		}
	}
	//alert(isDate(vfld.value));
    //if (!isDate(vfld.value)) {
	//	msg (ifld, "error", "Please enter a valid date.");
	//	return false
    //}
  return true;
};

function validateIsDate    (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);
    var daysInMonth = DaysArray(12)
	var pos1= tfld.indexOf(dtCh)
	var pos2=tfld.indexOf(dtCh,pos1+1)
	var strMonth=tfld.substring(0,pos1)
	var strDay=tfld.substring(pos1+1,pos2)
	if (ValidationDateFormat=="DD/MM"){
		strDay=tfld.substring(0,pos1);
		strMonth=tfld.substring(pos1+1,pos2);
	}
	var strYear=tfld.substring(pos2+1)
	strYr=strYear
	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)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, "error",  "error", "field required");  
      MoveFocusTo(vfld);
      return false;
    }
	}
	if ((pos1==-1 || pos2==-1) && tfld != '' ){
		 msg (ifld, "error", "Date format: m/d/yy");

		 //MoveFocusTo(vfld);
		return false
	}
	if (year > 2078){
		 msg (ifld, "error", "Please enter a valid year");
		 //MoveFocusTo(vfld);
		return false
	}
	if ((strMonth.length<1 || month<1 || month>12)  && tfld != '' ){
		 msg (ifld, "error", "Please enter a valid month");
		 //MoveFocusTo(vfld);
		return false
	}
	if ((strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])  && tfld != '' ){
		msg (ifld, "error", "Please enter a valid day");
		//MoveFocusTo(vfld);
		return false
	}
	if (strYear.length != 4 && strYear.length != 2){
		msg (ifld, "error", "Please enter a valid 4 or 2 digit year");
		//MoveFocusTo(vfld);
		return false
	}
	
	if ((tfld.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(tfld, dtCh))==false)  && tfld != '' ){
		msg (ifld, "error", "Please enter a valid date");
		 // MoveFocusTo(vfld);
		return false
	}
	var isDate = new Date(vfld.value);
    if (isDate == "NaN") {
		msg (ifld, "error", "Please enter a valid date");
		return false
	}
  msg (ifld, "warn", "");   // OK
  return true;
};

function validateIsDateNotRequired    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
	return validateIsDate(vfld,ifld,false);
};

function validateNumberNotRequired    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
	return validateNumber(vfld,ifld,false);
};