// This validates any date input
// 14/05/2004 LB Initial Version for Options
//  Leap Year occurs every four years, except for years ending in 00, in which case //  only if the year is divisible by 400.
 
function CheckDate(chDate,blankDate) {

var message = "This is not a valid date. Please use the dd/mm/yyyy format and ensure that the day is valid.";
var longmonth = "[01|03|05|07|08|10|12]";

// Allow blank date if the blankDate field is set
if ((blankDate != 0) && (chDate.length == 0)) {
   return true;
}

// ensure the length is correct according to the format  
  
  if ((chDate.length > 0) && (chDate.length != 10)) {
     alert(message);
     return false;
  }

// Ensure that the correct format and content has been used
  var nondigit = "[^0-9]";
  if ((chDate.substr(0,2).search(nondigit) != -1) ||
      (chDate.substr(3,2).search(nondigit) != -1) ||
      (chDate.substr(6,4).search(nondigit) != -1) ||
      (chDate.substr(2,1).search("/") == -1) ||
      (chDate.substr(5,1).search("/") == -1) ) {
      
      alert(message);
      return false;
  }


  // Ensure month length and year months are respected
  if ((chDate.substr(0,2) > 31) || (chDate.substr(0,2) < 1)) {
     alert(message + ' \n\r(Error: Day does not exist.)');
     return false;
  }

  if ((chDate.substr(3,2) > 12) || (chDate.substr(3,2) < 1) ) {
     alert(message + ' \n\r(Error: Month does not exist)');
     return false;
  }


  // Ensure that the date exists in terms of the Calendar format
  if ((chDate.substr(0,2) > 30) &&
      (chDate.substr(3,2).search(longmonth) == -1)) {
      alert(message + ' \r\n(Error: Day does not exist for this month.)');
      return false;
  }
  
// Cater for leap years
  var FebLn;
  var year = chDate.substr(6,4);
  
  if ((year % 4) != 0) {
     FebLn = "28";
  } else if ( year % 400 == 0) {
     FebLn = "29";
  } else if (year % 100 == 0) {
     FebLn = "28";
  } else { FebLn = "29"; }


  if ((chDate.substr(3,2) == "02") && 
     (chDate.substr(0,2) > FebLn) ) {
     alert(message + "\n\r(Error: February only has " + FebLn + " days in that  year.)");
      return false;
  }
  return true;

}


