
function checkEmail (strng) {
var error="";
if (strng == "") {
   error = "You didn't enter an email address.\n";
}

    var emailFilter=/^.+@.+\..{2,3}$/;
    if (!(emailFilter.test(strng))) { 
       error = "Please enter a valid email address.\n";
    }
    else {
//test email for illegal characters
       var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
         if (strng.match(illegalChars)) {
          error = "The email address contains illegal characters.\n";
       }
    }
return error;    
}


// phone number - strip out delimiters and check for 10 digits

function checkPhone (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a phone number.\n";
}

var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
    if (isNaN(parseInt(stripped))) {
       error = "The phone number contains illegal characters.";
  
    }
    if (!(stripped.length == 10)) {
	error = "The phone number is the wrong length. Make sure you included an area code.\n";
    } 
return error;
}


// exactly one radio button is chosen

function checkRadio(checkvalue) {
var error = "";
   if (!(checkvalue)) {
       error = "Please check a radio button.\n";
    }
return error;
}

// valid selector from dropdown list

function checkDropdown(choice) {
var error = "";
    if (choice == 0) {
    error = "You didn't choose an option from the drop-down list.\n";
    }    
return error;
}    

function checkNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }


function checkDate(datefield, strDatestyle, upelement, doupdate) {
  //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 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;
   if (strDate.length < 1) {
    return false;
  }
  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);
    } else {
	  return false;
	}
  }
  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 (doupdate==true) {
    if (strDatestyle == "US") {
      //upelement.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
	  upelement.value = intMonth + "/" + intday + "/" + strYear;
    } else {
      //upelement.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
	  upelement.value = intday + "/" + intMonth + "/" + 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;
}

function DoFormValidation(MyForm) {

  // Final Result
  var result=true;
  //var errMessage;
  //var i, x;
  //var valrule="";
  //var rule_array, ThisRule, ThisRule_array, ThisRuleParam;
  //var fieldvalue;

  // Get all of the "input" elements on the form
  var elements = document.getElementsByTagName('input');
 
  // Loop through the elements
  for (var i = 0; i < elements.length; i++) {
	//alert('Validating Field ' + i);
	  
    // Check each element for Validation rules
    var valrule = elements.item(i).getAttribute('ValidationRule');
	var fieldname = elements.item(i).name;
    var fieldvalue = elements.item(i).value;
    //alert(fieldname + '|' + valrule);
    if (valrule==null) {
		// No Rule associated with this input field.
		;
	} else {
      // Split the validation rule array into each individual array element
      var rule_array = valrule.split('|');
      for (x = 0; x <= rule_array.length; x++) {
	    var thisrule=rule_array[x];
		if (typeof(thisrule) != "undefined") {
		  if (thisrule.length != 0) {
    	    //alert('Validating Rule ' + thisrule);
			
			if (thisrule.indexOf('=') != -1) {
			  var thisrule_array=thisrule.split('=');
			  thisrule=thisrule_array[0];
			  var thisparam=thisrule_array[1];
			}

			// Determine if the field content passes validation
			switch(thisrule) {
			  // Validation Rule OPT is an Optional field.  If it is empty, the validation will pass no matter what other
			  // rules are in place.  If it is not empty, the other rules will be applied.
			  // OPT **MUST** be the first validation rule to work reliably.
			  case 'OPT': if (typeof(fieldvalue) != "undefined") {
				            if (fieldvalue.length == 0) {
							  result=true;
							  x = rule_array.length + 1;
							}
			              } else {
						    result=true;
							x = rule_array.length + 1;
			              }
						  break;
			  // Validation rule REQ is an Required Field.  This field cannot be left empty.
			  case 'REQ': if (typeof(fieldvalue) != "undefined") {
				            if (fieldvalue.length == 0) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" cannot be left blank.');
							}
			              } else {
							elements.item(i).focus();
						    result=false;	  
							//alert('REQ Field is Undefined');
			              }
						  break;
			  // Validation Rule MAXLEN fails validation if the contents of the field are longer than the length specified by
			  // the validation rule parameter (IE, MAXLEN=5)
			  case 'MAXLEN' : if (typeof(fieldvalue) != "undefined") {
				            if (fieldvalue.length > thisparam) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be ' + thisparam + ' or fewer characters.');
							}
			              }
						  break;
			  // Validation Rule MINLEN fails validation if the contents of the field are shorter than the length specified by
			  // the validation rule parameter (IE, MINLEN=5)
			  case 'MINLEN' : if (typeof(fieldvalue) != "undefined") {
				            if (fieldvalue.length < thisparam) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be at lease ' + thisparam + ' characters.');
							}
			              }
						  break;		
			  // Validation Rule MAXVAL fails validation if the contents of the field are greater than the length specified by
			  // the validation rule parameter (IE, MAXVAL=5)
			  case 'MAXVAL' : if (typeof(fieldvalue) != "undefined") {
				            if (parseFloat(fieldvalue) > parseFloat(thisparam)) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be less than or equal to ' + thisparam + '.');
							}
			              }
						  break;
			  // Validation Rule MINVAL fails validation if the contents of the field are less than the length specified by
			  // the validation rule parameter (IE, MINVAL=5)
			  case 'MINVAL' : if (typeof(fieldvalue) != "undefined") {
				            if (parseFloat(fieldvalue) < parseFloat(thisparam)) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be at least ' + thisparam + '.');
							}
			              }
						  break;
			  // Validation Rule PHONE tests the contents of the field for a valid phone number format.  Phone number punctution
			  // is taken into account and is optional.
			  case 'PHONE' : if (typeof(fieldvalue) != "undefined") {
				            if (checkPhone(fieldvalue) != '') {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be a valid phone number.');
							}
			              }
						  break;	
			  // Validation Rule NUMERIC fails if the field does not contain a number.  Allowed characters are 0123456789.- with the
			  // negative sign (-) only allowed in the first character.
			  case 'NUMERIC' : if (typeof(fieldvalue) != "undefined") {
				            if (checkNumeric(fieldvalue) != true) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be a numeric value.');
							}
			              }
						  break;	
			  // Validation rule DATE requires either US or EU as a parameter and tests for a valid date.  Many date formats are 
			  // allowed.
			  case 'DATE' : if (typeof(fieldvalue) != "undefined") {
				            if (checkDate(fieldvalue, thisparam, null, false) != true) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be a valid date.');
							}
			              }
						  break;							  
			  // Validation rule DATEREFORMAT requires either US or EU as a parameter and tests for a valid date.  Many date formats 
			  // are allowed.  If the date passes validation, it will be reformatted to a standard MM/DD/YYYY or DD/MM/YYYY format.
			  case 'DATEREFORMAT' : if (typeof(fieldvalue) != "undefined") {
				            if (checkDate(fieldvalue, thisparam, elements.item(i), true) != true) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be a valid date.');
							}
			              }
						  break;		
			  // Validation Rule EMAIL checks the field value for a valid E-MAIL address format.
			  case 'EMAIL' : if (typeof(fieldvalue) != "undefined") {
				            if (checkEmail(fieldvalue) != '') {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be a valid e-mail address.');
							}
			              }
						  break;						  
			}
		  }

		} 
	  }
      if (result==false) { break; }	  
	}
  }

  // do it for the select elements 
  
  // Get all of the "input" elements on the form
  var elements = document.getElementsByTagName('select');
 
  // Loop through the elements
  for (var i = 0; i < elements.length; i++) {
	//alert('Validating Field ' + i);
	  
    // Check each element for Validation rules
    var valrule = elements.item(i).getAttribute('ValidationRule');
	var fieldname = elements.item(i).name;
    var fieldvalue = elements.item(i).value;
    //alert(fieldname + '|' + valrule);
    if (valrule==null) {
		// No Rule associated with this input field.
		;
	} else {
      // Split the validation rule array into each individual array element
      var rule_array = valrule.split('|');
      for (x = 0; x <= rule_array.length; x++) {
	    var thisrule=rule_array[x];
		if (typeof(thisrule) != "undefined") {
		  if (thisrule.length != 0) {
    	    //alert('Validating Rule ' + thisrule);
			
			if (thisrule.indexOf('=') != -1) {
			  var thisrule_array=thisrule.split('=');
			  thisrule=thisrule_array[0];
			  var thisparam=thisrule_array[1];
			}

			// Determine if the field content passes validation
			switch(thisrule) {
			  // Validation Rule OPT is an Optional field.  If it is empty, the validation will pass no matter what other
			  // rules are in place.  If it is not empty, the other rules will be applied.
			  // OPT **MUST** be the first validation rule to work reliably.
			  case 'OPT': if (typeof(fieldvalue) != "undefined") {
				            if (fieldvalue.length == 0) {
							  result=true;
							  x = rule_array.length + 1;
							}
			              } else {
						    result=true;
							x = rule_array.length + 1;
			              }
						  break;
			  // Validation rule REQ is an Required Field.  This field cannot be left empty.
			  case 'REQ': if (typeof(fieldvalue) != "undefined") {
				            if (fieldvalue.length == 0) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" cannot be left blank.');
							}
			              } else {
							elements.item(i).focus();
						    result=false;	  
							//alert('REQ Field is Undefined');
			              }
						  break;
			  // Validation Rule MAXLEN fails validation if the contents of the field are longer than the length specified by
			  // the validation rule parameter (IE, MAXLEN=5)
			  case 'MAXLEN' : if (typeof(fieldvalue) != "undefined") {
				            if (fieldvalue.length > thisparam) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be ' + thisparam + ' or fewer characters.');
							}
			              }
						  break;
			  // Validation Rule MINLEN fails validation if the contents of the field are shorter than the length specified by
			  // the validation rule parameter (IE, MINLEN=5)
			  case 'MINLEN' : if (typeof(fieldvalue) != "undefined") {
				            if (fieldvalue.length < thisparam) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be at lease ' + thisparam + ' characters.');
							}
			              }
						  break;		
			  // Validation Rule MAXVAL fails validation if the contents of the field are greater than the length specified by
			  // the validation rule parameter (IE, MAXVAL=5)
			  case 'MAXVAL' : if (typeof(fieldvalue) != "undefined") {
				            if (parseFloat(fieldvalue) > parseFloat(thisparam)) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be less than or equal to ' + thisparam + '.');
							}
			              }
						  break;
			  // Validation Rule MINVAL fails validation if the contents of the field are less than the length specified by
			  // the validation rule parameter (IE, MINVAL=5)
			  case 'MINVAL' : if (typeof(fieldvalue) != "undefined") {
				            if (parseFloat(fieldvalue) < parseFloat(thisparam)) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be at least ' + thisparam + '.');
							}
			              }
						  break;
			  // Validation Rule PHONE tests the contents of the field for a valid phone number format.  Phone number punctution
			  // is taken into account and is optional.
			  case 'PHONE' : if (typeof(fieldvalue) != "undefined") {
				            if (checkPhone(fieldvalue) != '') {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be a valid phone number.');
							}
			              }
						  break;	
			  // Validation Rule NUMERIC fails if the field does not contain a number.  Allowed characters are 0123456789.- with the
			  // negative sign (-) only allowed in the first character.
			  case 'NUMERIC' : if (typeof(fieldvalue) != "undefined") {
				            if (checkNumeric(fieldvalue) != true) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be a numeric value.');
							}
			              }
						  break;	
			  // Validation rule DATE requires either US or EU as a parameter and tests for a valid date.  Many date formats are 
			  // allowed.
			  case 'DATE' : if (typeof(fieldvalue) != "undefined") {
				            if (checkDate(fieldvalue, thisparam, null, false) != true) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be a valid date.');
							}
			              }
						  break;							  
			  // Validation rule DATEREFORMAT requires either US or EU as a parameter and tests for a valid date.  Many date formats 
			  // are allowed.  If the date passes validation, it will be reformatted to a standard MM/DD/YYYY or DD/MM/YYYY format.
			  case 'DATEREFORMAT' : if (typeof(fieldvalue) != "undefined") {
				            if (checkDate(fieldvalue, thisparam, elements.item(i), true) != true) {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be a valid date.');
							}
			              }
						  break;		
			  // Validation Rule EMAIL checks the field value for a valid E-MAIL address format.
			  case 'EMAIL' : if (typeof(fieldvalue) != "undefined") {
				            if (checkEmail(fieldvalue) != '') {
							  elements.item(i).focus();
							  result=false;
							  alert('The field "' + elements.item(i).getAttribute('validationname') + '" must be a valid e-mail address.');
							}
			              }
						  break;						  
			}
		  }

		} 
	  }
      if (result==false) { break; }	  
	}
  }
  
  
  // Return the result, which determines if the form has been submitted successfully.
  return result;

}
