﻿var theDate = new Date(); //Date object defined in JavaScript
var dateCode = 0;      // set this variable to accept the verifyDate()
                       // return value
function verifyDate(enteredDay, enteredMonth, enteredYear) {
   retVal = 0;

   theMonth = eval(enteredMonth);
   theDay = eval(enteredDay);
   theYear = eval(enteredYear);

   if(enteredDay == null && enteredYear == null)
      retVal = seperateDateString(enteredMonth);
   else if (isMonthOK() == 0)
      retVal = 1;
   else if (isDayOK() == 0)
      retVal = 2;
   else if (isYearOK() == 0)
      retVal = 3;

   return retVal;
}

function seperateDateString(dateString) {
   var retVal = 0;
   var slash1 = 0;     //character index of 1st slash
   var slash2 = 0;     //character index of 2nd slash
   var numSlashes = 0; //make sure there are two slashes

   for (slash1; slash1 < dateString.length && numSlashes == 0; slash1++) {
      if (dateString.charAt(slash1) == '/' || dateString.charAt(slash1) == '-') 
	     numSlashes++;
   }

   for (slash2 = slash1; slash2 < dateString.length && numSlashes == 1; slash2++) {
      if (dateString.charAt(slash2) == '/' || dateString.charAt(slash2) == '-')
	     numSlashes++;
   }

   if (numSlashes == 2) {
	  
	  theMonth = eval(dateString.substring(0, slash1 - 1));
	  theDay = eval(dateString.substring(slash1, slash2 - 1));
	  theYear = eval(dateString.substring(slash2, dateString.length));

      retVal = verifyDate(theMonth, theDay, theYear);
   }
   else 
     retVal = 4;

   return retVal;
}

function isMonthOK() {
   var retVal = 0;

   if(theMonth <= 12 && theMonth != 0) 
	  retVal = 1;
   else 
     retVal = 0;
   
   return retVal;
}
function isDayOK() {
   var retVal = 0;

   if(theMonth == 1 || theMonth == 3 || theMonth == 5 || theMonth == 7
       || theMonth == 8 || theMonth == 10 || theMonth == 12) {
	   if (theDay >= 1 && theDay <= 31) 
	      retVal = 1;
	   else 
         retVal = 0;
   }
   else if (theMonth == 2) {
      if (theDay >= 1 && theDay <=28) 
	     retVal = 1;
	  else if (theDay == 29 && (theYear % 4) == 0) 
	     retVal = 1;  // valid leap-year
      else if (theDay == 29 && (theYear % 4) != 0) 
		 retVal = 0;
	  else 
		 retVal = 0;
   }
   else {
      if (theDay >= 1 && theDay <= 30) 
	     retVal = 1;
	  else 
         retVal = 0;
   }
   return retVal;
}

function isYearOK() {
   var retVal = 0;
   
   if (theYear <= 50 && theYear >= 0)
      theYear += 2000;
   //else if (theYear <= 99 && theYear >= 51)
   else if (theYear <= 99 && theYear >= 21)
      theYear += 1900;

   if (theYear >= 1900 && theYear <= 2050) 
      retVal = 1;
   else 
	  retVal = 0;

   return retVal;
}
