function makeDaysOfMonth(){
  var i = 0;
  this[i++] = 0; // dummy
  this[i++] = 31;
  this[i++] = 29;
  this[i++] = 31;
  this[i++] = 30;
  this[i++] = 31;
  this[i++] = 30;
  this[i++] = 31;
  this[i++] = 31;
  this[i++] = 30;
  this[i++] = 31;
  this[i++] = 30;
  this[i  ] = 31;
  this.length = i;
}

function calcAge(dd, mm, yy){
  var t, mon, day, year, DD, MM, YY, age;
  var MTB = new makeDaysOfMonth();
  YY   = parseInt(yy);	// year of birth (4 digits)
  MM   = parseInt(mm);	// month of birth (1-12)
  DD   = parseInt(dd);	// date of birth (1-31)
  if (MTB[MM] < DD || DD < 1) return -1;
  t    = new Date();	// get current date
  year = t.getFullYear();	// get year of current
  mon  = t.getMonth() + 1;	// get month of current
  day  = t.getDate();	// get date of current
  if (MM == 2 && DD == 29){	// check leap year
    if (!(((YY % 4 == 0) && (YY % 100 != 0)) || (YY % 400 == 0))){
      alert("The year " +YY+ " ends at 28th of "+MM+" month\nPlease check the date.");
      return -1;
    }
  }
  age = year - YY;
  if ((MM > mon) || (MM == mon && day < DD)) age --;

  return age;
}

function checkDate(strString)  
{
  var datePat = /^(\d{1,2})(\/)(\d{1,2})\2(\d{4})$/;
  var matchArray = strString.match(datePat);
  var error = "";
 
  if (matchArray == null)
  {
    error ='DOB is not in a valid.\n'
    return error;
  }
  month = matchArray[3];
  day = matchArray[1];
  year = matchArray[4];
  if (month < 1 || month > 12)
  {
    error ='Month must be between 1 and 12.\n'
    return error;
  }
  if (day < 1 || day > 31)
  {
    error ='Day must be between 1 and 31.\n'
    return error;
  }
  if ((month==4 || month==6 || month==9 || month==11) && day==31)
  {
    error = "Month " + month + " doesn't have 31 days!\n"
    return error
  }
  if (month == 2)
  {
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day>29 || (day==29 && !isleap)) 	
	{
	  error = "February " + year + " doesn't have " + day + " days!\n";
      return error;
	}
  }
  var now = new Date();
  var dateToCheck = new Date();
  now = now.getTime(); 
  dateToCheck.setYear(year);
  dateToCheck.setMonth(month-1);
  dateToCheck.setDate(day);
  var checkDate = dateToCheck.getTime();
  var futureDate = (now < checkDate);
  if (futureDate) {
  	error = "The date cannot be in the future\n"
	}	
return error;
}

function CheckDateAge(iDay,iMonth,iYear) 
{
	var sDate = iDay + "/" + iMonth + "/" + iYear;
	var error = "";
	error = checkDate(sDate);
	
	if (error == "") {
	    myDate = new Date(iYear,iMonth,iDay);
		if (calcAge(iDay,iMonth,iYear) < 18) {
			error = "You must be over 18yrs of age to use this website\n"
		}
	}
    return error;
}
