
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits = "1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i)) == -1) { return false; }
		}
	return true;
	}

function _getInt(str,i,minlength,maxlength) {
	for (x=maxlength; x>=minlength; x--) {
		var token = str.substring(i,i+x);
		if (token.length < minlength) {
			return null;
			}
		if (_isInteger(token)) { 
			return token;
			}
		}
	return null;
	}

// ------------------------------------------------------------------
// isDate ( date_string, format_string )
//
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
//
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val,format) {
	var date = getDateFromFormat(val,format);
	if (date == 0) { return false; }
	return true;
	}


// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// 
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | y or yy (2 or 4 digits)
// Month        | MMM (name or abbr.)| M or MM (1 or 2 digits)
// Day of Month | DD (2 digits)      | D or DD (1 or 2 digits)
//
// Examples:
//  "MMM D, Y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/D/YY"   matches: 01/20/00
//                      9/2/00
//  "MMM DD, YYYY" matches: "January 01, 2000"
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val = val+"";
	format = format+"";
	var i_val = 0;
	var i_format = 0;
	var c = "";
	var token = "";
	var token2= "";
	var x,y;
	var now   = new Date();
	var year  = now.getFullYear();
	var month = now.getMonth()+1;
	var date  = now.getDate();
	
	while (i_format < format.length) {
		// Get next token from format string
		c = format.charAt(i_format);
		token = "";
		while ((format.charAt(i_format) == c) && (i_format < format.length)) {
			token += format.charAt(i_format);
			i_format++;
			}
		// Extract contents of value based on format token
		if (token=="YYYY" || token=="YY" || token=="Y") {
			if (token=="YYYY") { x=2;y=4; }// 2-or-4-digit year
			if (token=="YY")   { x=2;y=4; }// 2-or-4-digit year
			if (token=="Y")    { x=2;y=4; }// 2-or-4-digit year
			year = _getInt(val,i_val,x,y);
			if (year == null) { return 0; }
			// 1 or 3 digit years and years > 9999 are invalid (Note: SQL does not support dates < 1752)
			if ((year.length == 1) || (year.length == 3) || (year.length > 4)) { return 0; }
			i_val += year.length;
			if (year.length == 2) {
				if (year > 70) {
					year = 1900+(year-0);
					}
				else {
					year = 2000+(year-0);
					}
				}
			}
		else if (token=="MMM"){// Month name
			month = 0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name = MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase() == month_name.toLowerCase()) {
					month = i+1;
					if (month>12) { month -= 12; }
					i_val += month_name.length;
					break;
					}
				}
			if (month == 0) { return 0; }
			if ((month < 1) || (month>12)) { return 0; }
			// TODO: Process Month Name
			}
		else if (token=="MM" || token=="M") {
			x=1; y=2;	// 1-or-2-digit month
			month = _getInt(val,i_val,x,y);
			if (month == null) { return 0; }
			if ((month < 1) || (month > 12)) { return 0; }
			i_val += month.length;
			}
		else if (token=="DD" || token=="D") {
			x=1; y=2;	// 1-or-2-digit day
			date = _getInt(val,i_val,x,y);
			if (date == null) { return 0; }
			if ((date < 1) || (date>31)) { return 0; }
			i_val += date.length;
			}
		else {
			if (val.substring(i_val,i_val+token.length) != token) {
				return 0;
				}
			else {
				i_val += token.length;
				}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) {
		return 0;
		}
	// Is date valid for month?
	if (month == 2) {
		// Check for leap year
		if ( ( (year%4 == 0)&&(year%100 != 0) ) || (year%400 == 0) ) { // leap year
			if (date > 29){ return false; }
			}
		else {
			if (date > 28) { return false; }
			}
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return false; }
		}
	var newdate = new Date(year,month-1,date);
	return newdate;
	}


// formatDate (date_object, format)
//
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
function formatDate(date,format) {
	return formatYearMonthDate(	date.getFullYear(),
								date.getMonth()+1,
								date.getDate(),
								format);
	}

// formatYearMonthDate (year, month, date, format)
//
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
//
// NOTE: This function is the SAME as formatDate in date.js, only the arguments have changed
//
function formatYearMonthDate(year,month,date,format) {
	format = format+"";
	var result = "";
	var i_format = 0;
	var c = "";
	var token = "";
	var y = year+"";
	var m = month;
	var d = date;
	var yyyy,yy,mmm,mm,dd;
	// Convert real date parts into formatted versions
	// Year
	if (y.length < 4) {
		y = y-0+1900;
		}
	y = ""+y;
	yyyy = y;
	yy = y.substring(2,4);
	// Month
	if (m < 10) { mm = "0"+m; }
		else { mm = m; }
	mmm = MONTH_NAMES[m-1];
	// Date
	if (d < 10) { dd = "0"+d; }
		else { dd = d; }
	// Now put them all into an object!
	var value = new Object();
	value["YYYY"] = yyyy;
	value["YY"] = yy;
	value["Y"] = y;
	value["MMM"] = mmm;
	value["MM"] = mm;
	value["M"] = m;
	value["DD"] = dd;
	value["D"] = d;
	while (i_format < format.length) {
		// Get next token from format string
		c = format.charAt(i_format);
		token = "";
		while ((format.charAt(i_format) == c) && (i_format < format.length)) {
			token += format.charAt(i_format);
			i_format++;
			}
		if (value[token] != null) {
			result = result + value[token];
			}
		else {
			result = result + token;
			}
		}
	return result;
	}

// trims preceeding and trailing whitespaces
function dateTrim(strText) 
{	
    // this will get rid of leading spaces 
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    // this will get rid of trailing spaces 
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

    return strText;
	}

function extractDateFromDateField(fieldName,dateForm,format,dateIsRequired,displayAlert) {
	// defaults for optional args
	if (arguments.length<=3) {
		dateIsRequired = false;
		displayAlert = true;
		}
	// Form must follow these naming conventions:
	//   Common name for form = <dateForm>
	//   Date text field = <dateForm> + "DateField"
	//   Year value = <dateForm> + "Year"
	//   Month value = <dateForm> + "Month"
	//   Date value = <dateForm> + "Date"
	var dateText = eval('document.' + dateForm + 'DateField.value');
	if(dateIsRequired || dateTrim(dateText).length>0) {
		if (isDate(dateText,format)) {
			var theDate = getDateFromFormat(dateText,format);
			var yearForm = eval('document.' + dateForm + 'Year');
			var monthForm = eval('document.' + dateForm + 'Month');
			var dateForm = eval('document.' + dateForm + 'Date');
			yearForm.value  = theDate.getFullYear();
			monthForm.value = theDate.getMonth();
			dateForm.value  = theDate.getDate();
			return theDate;
			}
		else if (displayAlert) {
			alert(fieldName + ' is invalid: Please enter a valid date in ' + format + ' format\nor select the date from a calendar by clicking the Calendar button.');
			return false;
			}
		}
	// date field is required and date field is empty, then display error message
	else if (dateIsRequired && displayAlert) {
		alert(fieldName + ' is required: Please enter a valid date in ' + format + ' format\nor select the date from a calendar by clicking the Calendar button.');
			return false;
		}
	// date is not required and date field is empty, so return true
	else {
		return true;
		}
	}

