// JavaScript Document
var defaultDateSeparator  = "/";        // common values would be "/" or "."
var defaultDateFormat     = "mdy";      // valid values are "mdy", "dmy", and "ymd"
var defaultUserDateFormat = "mm/dd/yyyy" //Valid format for the user to enter the date
var defaultTimeSeparator  = ":";        // common value is ":"

var dateSeparator         = defaultDateSeparator;
var dateFormat            = defaultDateFormat;
var userDateFormat        = defaultUserDateFormat;
var timeSeparator         = defaultTimeSeparator;
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
var daysInMonth = new Array(31,29,31,30,31,30,31,31,30,31,30,31);

function checkTime(theObj) {
	
  if (theObj.value == '') {
	  return;
	} 
	if (theObj.value.indexOf(timeSeparator) == -1) {
	  alert('Your entry does not have a "' + timeSeparator + '".\n It must be in 24 hour time with a "' + timeSeparator + '" separating the hours and minutes. i.e. 15' + timeSeparator + '30 = 3' + timeSeparator + '30 pm');
		theObj.value = '';
		return;
	}
	if (theObj.value.indexOf(timeSeparator) != theObj.value.lastIndexOf(timeSeparator)) {
	  alert('Your entry has too many "' + timeSeparator + '". \n It must be in 24 hour time with a "' + timeSeparator + '" separating the hours and minutes. i.e. 15' + timeSeparator + '30 = 3' + timeSeparator + '30 pm');
		theObj.value = '';
		return;
	}
  var errors = 0;
	var times = theObj.value.split(timeSeparator);
	var testVal = new String(times[0]);
	testResult = Number(testVal);
	if (isNaN(testResult)) {
    alert('The hour you have chosen (' + times[0] + ') is not a valid number.');
	  errors = 1;
	}
	if ((testResult < '0') ||
			(testResult > '23')) {
    alert('The hour you have chosen (' + times[1] + ') is not within a 24 hour range (0-23)');
	  errors = 1;
	}

	var testVal = new String(times[1]);
	testResult = Number(testVal);
	if (isNaN(testResult)) {
    alert('The minute you have chosen (' + times[1] + ') is not a valid number.');
	  errors = 1;
	}
	if ((testResult < 0) ||
			(testResult > 59)) {
    alert('The minute you have chosen (' + times[1] + ') is not within a 60 minute range (0-60)');
	  errors = 1;
	}

  if (errors != 0) {
//	  alert(errors);
		theObj.value = '';
	} 
}

/**
checks the value of a field to see if it is a valid date
*/
function isValidDate(dateField) {

  var dateString = dateField.value;
  var errorVar = '';
  var dArray;
  var d, m, y;
  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "dmy" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "ymd" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "mdy" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
			//remember that the month has been adjusted to fit the array. So the month is one less than actual - Jan = 0
			//check the year
			if (y > 0) {
			  //check the month
			  if (m >= 0) {
				  if (m < 12) {
					  //check the day of the month
						if (d > 0) {
							if (d <= daysInMonth[m]) {
							  //check for February
								if (m==1) {
								  if (d > daysInFebruary(y)) {
									  errorVar = 'There are only ' + daysInFebruary(y) + ' days in February.';
									}
								}
							} else {
							  errorVar = 'There are not that many days in ' + monthArrayLong[m] + '.';
							}
						} else {
						  errorVar = 'The Day needs to be greater than 0.';
						}
					} else {
            errorVar = 'There are only 12 months.';
					}
				} else {
			    errorVar = 'The Month needs to be greater than 0';
				}
			} else {
			  errorVar = 'The Year needs to be greater than 0';
			}
    } else {
      errorVar = 'Your Date is not in the correct format. \n Please format it like: ' + userDateFormat;
    }
  } catch(e) {
    errorVar = 'Your Date is invalid. \n Please format it like: ' + userDateFormat;
  }
 
  return errorVar;
}


/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, the length is checked.
If the array is 3 elements than an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString) {
  var dArray;
  if (dateString.indexOf(dateSeparator) >= 0) {
    dArray = dateString.split("/");
  	if (dArray.length != 3) {
      dArray = false;
	  }
  } else {
    dArray = false;
	}
  return dArray;
}

/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
  var dateVal;
  var dArray;
  var d, m, y;
 
  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "dmy" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "ymd" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "mdy" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
      dateVal = new Date(y, m, d);
    } else if (dateString) {
      dateVal = new Date(dateString);
    } else {
      dateVal = new Date();
    }
  } catch(e) {
    dateVal = new Date();
  }
 
  return dateVal; 
}

function isDateTodayOrAfter(dateField) {

  if (dateField.value == '') return;
  result = isValidDate(dateField);
	if (result != '') {
	  alert(result);
    dateField.value = "";
		return;
	}	
  var jsDate = getFieldDate(dateField.value);
	if (jsDate) {
	  var today = new Date();
    today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    if (jsDate < today) {
      // if the date is before today, alert the user and clear the field
      alert("Please enter a date that is today or later");
      dateField.value = "";
    }
	} 
}

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 );
}
