/***********************************************
 Fool-Proof Date Input Script with DHTML Calendar
 by Jason Moon - webmaster@moonfam.net
 Modified 2005 by e-QualIT
 ************************************************/
// Customizable variables
var DefaultDateFormat = 'MM/DD/YYYY'; // If no date format is supplied, this will be used instead
var CalHideWait = 2; // Number of seconds before the calendar will disappear
var Y2kPivotPoint = 76; // 2-digit years before this point will be created in the 21st century
var CalFontSize = 11; // In pixels
var CalFontFamily = 'Tahoma';
var CalCellWidth = 18;
var CalCellHeight = 16;
var CalImageURL = 'images/calendar.jpg';
var CalNextURL = 'images/next.gif';
var CalPrevURL = 'images/prev.gif';
var CalBGColor = 'white';
var CalTopRowBGColor = 'buttonface';
var CalDayBGColor = 'lightgrey';
// Global variables
var CalZCounter = 100;
var CalToday = new Date();
var WeekDays = new Array('S','M','T','W','T','F','S');
var MonthDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var MonthNames = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
// Write out the stylesheet definition for the calendar
with (document) {
   writeln('<style>');
   writeln('td.calendarDateInput {padding:0px;text-align:none;letter-spacing:normal;line-height:normal;font-family:' + CalFontFamily + ',Sans-Serif;font-size:' + CalFontSize + 'px;}');
   writeln('select.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('input.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('</style>');
}
// Displays a message in the status bar when hovering over the calendar days
function DayCellHover(Cell, Over, Color, HoveredDay) {
   Cell.style.backgroundColor = (Over) ? CalDayBGColor : Color;
   if (Over) {
      if ((this.yearValue == CalToday.getFullYear()) && (this.monthIndex == CalToday.getMonth()) && (HoveredDay == CalToday.getDate())) self.status = 'Click to select today';
      else {
         var Suffix = HoveredDay.toString();
         switch (Suffix.substr(Suffix.length - 1, 1)) {
            case '1' : Suffix += (HoveredDay == 11) ? 'th' : 'st'; break;
            case '2' : Suffix += (HoveredDay == 12) ? 'th' : 'nd'; break;
            case '3' : Suffix += (HoveredDay == 13) ? 'th' : 'rd'; break;
            default : Suffix += 'th'; break;
         }
         self.status = 'Click to select ' + this.monthName + ' ' + Suffix;
      }
   }
   else self.status = '';
   return true;
}
// Sets the form elements after a day has been picked from the calendar
function PickDisplayDay(ClickedDay) {
   this.showCal();
   var MonthList = this.getMonthList();
   var DayList = this.getDayList();
	 this.setPicked(this.displayed.yearValue, this.displayed.monthIndex, ClickedDay);
	 this.getCalLinkedField().focus();
}
// Builds the HTML for the calendar days
function BuildCalendarDays() {
   var Rows = 5;
   if (((this.displayed.dayCount == 31) && (this.displayed.firstDay > 4)) || ((this.displayed.dayCount == 30) && (this.displayed.firstDay == 6))) Rows = 6;
   else if ((this.displayed.dayCount == 28) && (this.displayed.firstDay == 0)) Rows = 4;
   var HTML = '<table width="' + (CalCellWidth * 7) + '" cellspacing="0" cellpadding="1" style="cursor:default">';
   for (var j=0;j<Rows;j++) {
      HTML += '<tr>';
      for (var i=1;i<=7;i++) {
         Day = (j * 7) + (i - this.displayed.firstDay);
         if ((Day >= 1) && (Day <= this.displayed.dayCount)) {
            if ((this.displayed.yearValue == this.picked.yearValue) && (this.displayed.monthIndex == this.picked.monthIndex) && (Day == this.picked.day)) {
               TextStyle = 'color:white;font-weight:bold;'
               BackColor = CalDayBGColor;
            }
            else {
               TextStyle = 'color:black;'
               BackColor = CalBGColor;
            }
            if ((this.displayed.yearValue == CalToday.getFullYear()) && (this.displayed.monthIndex == CalToday.getMonth()) && (Day == CalToday.getDate())) TextStyle += 'border:1px solid darkred;padding:0px;';
            HTML += '<td align="center" class="calendarDateInput" style="cursor:default;height:' + CalCellHeight + ';width:' + CalCellWidth + ';' + TextStyle + ';background-color:' + BackColor + '" onClick="' + this.objName + '.pickDay(' + Day + ')" onMouseOver="return ' + this.objName + '.displayed.dayHover(this,true,\'' + BackColor + '\',' + Day + ')" onMouseOut="return ' + this.objName + '.displayed.dayHover(this,false,\'' + BackColor + '\')">' + Day + '</td>';
         }
         else HTML += '<td class="calendarDateInput" style="height:' + CalCellHeight + '">&nbsp;</td>';
      }
      HTML += '</tr>';
   }
   return HTML += '</table>';
}
// Determines which century to use (20th or 21st) when dealing with 2-digit years
function GetGoodYear(YearDigits) {
   if (YearDigits.length == 4) return YearDigits;
   else {
      var Millennium = (YearDigits < Y2kPivotPoint) ? 2000 : 1900;
      return Millennium + parseInt(YearDigits,10);
   }
}

// Returns the number of days in a month (handles leap-years)
function GetDayCount(SomeYear, SomeMonth) {
   return ((SomeMonth == 1) && ((SomeYear % 400 == 0) || ((SomeYear % 4 == 0) && (SomeYear % 100 != 0)))) ? 29 : MonthDays[SomeMonth];
}
// Highlights the buttons
function VirtualButton(Cell, ButtonDown) {
   if (ButtonDown) {
      Cell.style.borderLeft = 'buttonshadow 1px solid';
      Cell.style.borderTop = 'buttonshadow 1px solid';
      Cell.style.borderBottom = 'buttonhighlight 1px solid';
      Cell.style.borderRight = 'buttonhighlight 1px solid';
   }
   else {
      Cell.style.borderLeft = 'buttonhighlight 1px solid';
      Cell.style.borderTop = 'buttonhighlight 1px solid';
      Cell.style.borderBottom = 'buttonshadow 1px solid';
      Cell.style.borderRight = 'buttonshadow 1px solid';
   }
}
// Mouse-over for the previous/next month buttons
function NeighborHover(Cell, Over, DateObj) {
   if (Over) {
      VirtualButton(Cell, false);
      self.status = 'Click to view ' + DateObj.fullName;
   }
   else {
      Cell.style.border = 'buttonface 1px solid';
      self.status = '';
   }
   return true;
}
// Displays a message in the status bar when hovering over the calendar icon
function CalIconHover(Over) {
   var Message = (this.isViz()) ? 'hide' : 'show';
   self.status = (Over) ? 'Click to ' + Message + ' the calendar' : '';
   return true;
}
// Starts the timer over from scratch
function CalTimerReset() {
   eval('clearTimeout(' + this.CaltimerID + ')');
   eval(this.CaltimerID + '=setTimeout(\'' + this.objName + '.showCal()\',' + (CalHideWait * 1000) + ')');
}
// The timer for the calendar
function DoCalTimer(CalCancelTimer) {
   if (CalCancelTimer) eval('clearTimeout(' + this.CaltimerID + ')');
   else {
      eval(this.CaltimerID + '=null');
      this.resetTimer();
   }
}
// Show or hide the calendar
function ShowCalendar() {
   if (this.isViz()) {
      var CalStopTimer = true;
      this.getCalendar().style.zIndex = --CalZCounter;
      this.getCalendar().style.visibility = 'hidden';
   }
   else {
      var CalStopTimer = false;
      this.getCalendar().style.zIndex = ++CalZCounter;
      this.getCalendar().style.visibility = 'visible';
   }
   this.handleCalTimer(CalStopTimer);
   self.status = '';
}
// Holds characteristics about a date
function dateObject() {
   this.date = (arguments.length == 1) ? new Date(arguments[0]) : new Date(arguments[0], arguments[1], arguments[2]);
   this.yearValue = this.date.getFullYear();
   this.monthIndex = this.date.getMonth();
   this.monthName = MonthNames[this.monthIndex];
   this.fullName = this.monthName + ' ' + this.yearValue;
   this.day = this.date.getDate();
   this.dayCount = GetDayCount(this.yearValue, this.monthIndex);
   var FirstDate = new Date(this.yearValue, this.monthIndex, 1);
   this.firstDay = FirstDate.getDay();
}
// Keeps track of the date that goes into the linked field
function storedMonthObject(DateFormat, DateYear, DateMonth, DateDay) {
   dateObject.call(this, DateYear, DateMonth, DateDay);
   this.yearPad = this.yearValue.toString();
   this.monthPad = (this.monthIndex < 9) ? '0' + String(this.monthIndex + 1) : this.monthIndex + 1;
   this.dayPad = (this.day < 10) ? '0' + this.day.toString() : this.day;
   this.monthShort = this.monthName.substr(0,3).toUpperCase();
   // Formats the year value
   if (DateFormat != 'YYYYMMDD') {
      DateFormat.match(/(Y{2,4})$/);
      if (RegExp.$1.length == 2) this.yearPad = this.yearPad.substr(2);
   }
   // Formats the date
   if (/YYYYMMDD/.test(DateFormat)) this.formatted = this.yearPad + this.monthPad + this.dayPad;
   else {
      if (/MM?\/DD?\/Y{2,4}/.test(DateFormat)) var FirstPart = this.monthPad + '/' + this.dayPad + '/';
      else if (/DD?\/MM?\/Y{2,4}/.test(DateFormat)) var FirstPart = this.dayPad + '/' + this.monthPad + '/';
      else if (/DD?-((MON)|(MMM))-Y{2,4}/.test(DateFormat)) var FirstPart = this.dayPad + '-' + this.monthShort + '-';
      else if (/((MON)|(MMM))-DD?-Y{2,4}/.test(DateFormat)) var FirstPart = this.monthShort + '-' + this.dayPad + '-';
      this.formatted = FirstPart + this.yearPad;
   }
}
// Object for the current displayed month
function displayMonthObject(ParentObject, DateYear, DateMonth, DateDay) {
   dateObject.call(this, DateYear, DateMonth, DateDay);
   this.displayID = ParentObject.linkedFieldName + '_Current_ID';
   this.getDisplay = new Function('return document.getElementById(this.displayID)');
   this.dayHover = DayCellHover;
   this.goCurrent = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++CalZCounter;' + ParentObject.objName + '.setDisplayed(CalToday.getFullYear(),CalToday.getMonth());');
   if (ParentObject.formNumber >= 0) this.getDisplay().innerHTML = this.fullName;
}
// Object for the previous/next buttons
function neighborMonthObject(ParentObject, IDText, DateMS) {
   dateObject.call(this, DateMS);
   this.buttonID = ParentObject.linkedFieldName + '_' + IDText + '_ID';
   this.hover = new Function('C','O','NeighborHover(C,O,this)');
   this.getButton = new Function('return document.getElementById(this.buttonID)');
   this.go = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++CalZCounter;' + ParentObject.objName + '.setDisplayed(this.yearValue,this.monthIndex);');
   if (ParentObject.formNumber >= 0) this.getButton().title = this.monthName;
}
// Sets the currently-displayed month object
function SetDisplayedMonth(DispYear, DispMonth) {
   this.displayed = new displayMonthObject(this, DispYear, DispMonth, 1);
   // Creates the previous and next month objects
   this.previous = new neighborMonthObject(this, 'Previous', this.displayed.date.getTime() - 86400000);
   this.next = new neighborMonthObject(this, 'Next', this.displayed.date.getTime() + (86400000 * (this.displayed.dayCount + 1)));
   // Creates the HTML for the calendar
   if (this.formNumber >= 0) this.getDayTable().innerHTML = this.buildCalendar();
}
// Sets the current selected date
function SetPickedMonth(PickedYear, PickedMonth, PickedDay) {
   this.picked = new storedMonthObject(this.format, PickedYear, PickedMonth, PickedDay);
	 this.setCalLinked(this.picked.formatted);
   this.setDisplayed(PickedYear, PickedMonth);
}
// The calendar object
function calendarObject(CalLinkedField, DateFormat, DefaultDate) {
   /* Properties */
   this.linkedFieldName = CalLinkedField;
   this.monthListName = CalLinkedField + '_Month';
   this.dayListID = CalLinkedField + '_Day_ID';
   this.yearFieldID = CalLinkedField + '_Year_ID';
   this.monthDisplayID = CalLinkedField + '_Current_ID';
   this.calendarID = CalLinkedField + '_ID';
   this.dayTableID = CalLinkedField + '_DayTable_ID';
   this.calendarLinkID = this.calendarID + '_Link';
   this.CaltimerID = this.calendarID + '_Timer';
   this.objName = CalLinkedField + '_Object';
   this.format = DateFormat;
   this.formNumber = -1;
   this.picked = null;
   this.displayed = null;
   this.previous = null;
   this.next = null;
   /* Methods */
   this.setPicked = SetPickedMonth;
   this.setDisplayed = SetDisplayedMonth;
   this.resetTimer = CalTimerReset;
   this.showCal = ShowCalendar;
   this.handleCalTimer = DoCalTimer;
   this.iconCalHover = CalIconHover;
   this.buildCalendar = BuildCalendarDays;
   this.pickDay = PickDisplayDay;
   this.setCalLinked = new Function('D','if (this.formNumber >= 0) this.getCalLinkedField().value=D');
   // Returns a reference to these elements
   this.getCalLinkedField = new Function('return document.forms[this.formNumber].elements[this.linkedFieldName]');
   this.getMonthList = new Function('return document.forms[this.formNumber].elements[this.monthListName]');
   this.getDayList = new Function('return document.getElementById(this.dayListID)');
   this.getYearField = new Function('return document.getElementById(this.yearFieldID)');
   this.getCalendar = new Function('return document.getElementById(this.calendarID)');
   this.getDayTable = new Function('return document.getElementById(this.dayTableID)');
   this.getCalendarLink = new Function('return document.getElementById(this.calendarLinkID)');
   this.getMonthDisplay = new Function('return document.getElementById(this.monthDisplayID)');
   this.isViz = new Function('return !(this.getCalendar().style.visibility != \'visible\')');
   /* Constructor */
   // Functions used only by the constructor
   function getMonthIndex(MonthAbbr) { // Returns the index (0-11) of the supplied month abbreviation
      for (var MonPos=0;MonPos<MonthNames.length;MonPos++) {
         if (MonthNames[MonPos].substr(0,3).toUpperCase() == MonthAbbr.toUpperCase()) break;
      }
      return MonPos;
   }
   function SetGoodDate(CalObj, Notify) { // Notifies the user about their bad default date, and sets the current system date
      CalObj.setPicked(CalToday.getFullYear(), CalToday.getMonth(), CalToday.getDate());
      if (Notify) alert('WARNING: The supplied date is not in valid \'' + DateFormat + '\' format: ' + DefaultDate + '.\nTherefore, the current system date will be used instead: ' + CalObj.picked.formatted);
   }
   // Main part of the constructor
   if (DefaultDate == 'undefined') SetGoodDate(this, false);
   else {
      if (this.format == 'YYYYMMDD') {
         (/^\d{8}$/.test(DefaultDate)) ? this.setPicked(DefaultDate.substr(0,4), parseInt(DefaultDate.substr(4,2),10)-1, DefaultDate.substr(6,2)) : SetGoodDate(this, true);
      }
      else {
         if (/\//.test(this.format)) {
            if (/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/.test(DefaultDate)) {
               if (this.format.substr(0,1) == 'M') {
                  var MonPart = RegExp.$1;
                  var DayPart = RegExp.$2;
               }
               else {
                  var MonPart = RegExp.$2;
                  var DayPart = RegExp.$1;
               }
               this.setPicked(GetGoodYear(RegExp.$3), parseInt(MonPart,10)-1, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else if (/-/.test(this.format)) {
            var REMonths = '';
            for (var j=0;j<MonthNames.length;j++) {
               if (j > 0) REMonths += '|';
               REMonths += MonthNames[j].substr(0,3).toUpperCase();
            }
            if (this.format.substr(0,1) == 'D') {
               var DateRE = new RegExp('^(\\d{1,2})-(' + REMonths + ')-(\\d{2,4})$', 'i');
               (DateRE.test(DefaultDate)) ? this.setPicked(GetGoodYear(RegExp.$3), getMonthIndex(RegExp.$2), RegExp.$1) : SetGoodDate(this, true);
            }
            else {
               var DateRE = new RegExp('^(' + REMonths + ')-(\\d{1,2})-(\\d{2,4})$', 'i');
               (DateRE.test(DefaultDate)) ? this.setPicked(GetGoodYear(RegExp.$3), getMonthIndex(RegExp.$1), RegExp.$2) : SetGoodDate(this, true);
            }
         }
      }
   }
}
// Main function that creates the form elements
function showCal(CalLinkedField, Required, DateFormat, DefaultDate) {
   if (CalLinkedField == undefined) document.writeln('<span style="color:red;font-size:' + CalFontSize + 'px;font-family:' + CalFontFamily + ';">ERROR: Missing required parameter in call to \'DateInput\': [name of hidden date field].</span>');
   else {
      if (Required == undefined) Required = false;
      if (DateFormat == undefined) DateFormat = DefaultDateFormat;
      else if ((/^YYYYMMDD$/i.test(DateFormat)) || (/^((MM?)|(DD?))\/((MM?)|(DD?))\/Y{2,4}$/i.test(DateFormat)) || (/^((DD?)|((MON)|(MMM)))-((DD?)|((MON)|(MMM)))-Y{2,4}$/i.test(DateFormat))) DateFormat = DateFormat.toUpperCase();
      else {
         var AlertMessage = 'WARNING: The supplied date format for the \'' + CalLinkedField + '\' field is not valid: ' + DateFormat + '\nTherefore, the default date format will be used instead: ' + DefaultDateFormat;
         var CurrentDate = new storedMonthObject(DefaultDateFormat, CalToday.getFullYear(), CalToday.getMonth(), CalToday.getDate());
         if (DefaultDate != undefined) AlertMessage += '\n\nThe supplied date cannot be interpreted with the invalid format.\nTherefore, the current system date will be used instead: ' + CurrentDate.formatted;
         DateFormat = DefaultDateFormat;
         DefaultDate = CurrentDate.formatted;
         alert(AlertMessage);
      }
      // Creates the calendar object!
      eval(CalLinkedField + '_Object=new calendarObject(\'' + CalLinkedField + '\',\'' + DateFormat + '\',\'' + DefaultDate + '\')');
      if ((!Required) && (DefaultDate == undefined)) {
         var CalInitialStatus = ' style="visibility:hidden"';
         var InitialDate = '';
      }
      else {
         var CalInitialStatus = '';
         var InitialDate = eval(CalLinkedField + '_Object.picked.formatted');
      }
      if ((Required) && (DefaultDate == undefined)) DefaultDate = eval(CalLinkedField + '_Object.picked.formatted');
      // Create the form elements
      with (document) {
         // Find this form number
         for (var f=0;f<forms.length;f++) {
            for (var e=0;e<forms[f].elements.length;e++) {
               if (typeof forms[f].elements[e].type == 'string') {
                  if (forms[f].elements[e].name == CalLinkedField) {
                     eval(CalLinkedField + '_Object.formNumber='+f);
                     break;
                  }
               }
            }
         }
         write('<a' + CalInitialStatus + ' id="' + CalLinkedField + '_ID_Link" href="javascript:' + CalLinkedField + '_Object.showCal()" onMouseOver="return ' + CalLinkedField + '_Object.iconCalHover(true)" onMouseOut="return ' + CalLinkedField + '_Object.iconCalHover(false)"><img src="' + CalImageURL + '" align="baseline" title="Calendar" width="16" height="15" border="0"></a>&nbsp;');
//         write('<img src="' + CalImageURL + '" align="baseline" title="Calendar" width="16" height="15" border="0" onClick="' + CalLinkedField + '_Object.showCal()">&nbsp;');
         writeln('<span id="' + CalLinkedField + '_ID" style="position:absolute;visibility:hidden;width:' + (CalCellWidth * 7) + 'px;background-color:' + CalBGColor + ';border:1px solid dimgray;" onMouseOver="' + CalLinkedField + '_Object.handleCalTimer(true)" onMouseOut="' + CalLinkedField + '_Object.handleCalTimer(false)">');
         writeln('<table width="' + (CalCellWidth * 7) + '" cellspacing="0" cellpadding="1">' + String.fromCharCode(13) + '<tr style="background-color:' + CalTopRowBGColor + ';">');
         writeln('<td id="' + CalLinkedField + '_Previous_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CalCellHeight + '" onClick="' + CalLinkedField + '_Object.previous.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + CalLinkedField + '_Object.previous.hover(this,true)" onMouseOut="return ' + CalLinkedField + '_Object.previous.hover(this,false)" title="' + eval(CalLinkedField + '_Object.previous.monthName') + '"><img src="' + CalPrevURL + '" width="5" height="9"></td>');
         writeln('<td id="' + CalLinkedField + '_Current_ID" style="cursor:pointer" align="center" class="calendarDateInput" style="height:' + CalCellHeight + '" colspan="5" onClick="' + CalLinkedField + '_Object.displayed.goCurrent()" onMouseOver="self.status=\'Click to view ' + eval(CalLinkedField + '_Object.displayed.fullName') + '\';return true;" onMouseOut="self.status=\'\';return true;" title="Show Current Month">' + eval(CalLinkedField + '_Object.displayed.fullName') + '</td>');
         writeln('<td id="' + CalLinkedField + '_Next_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CalCellHeight + '" onClick="' + CalLinkedField + '_Object.next.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + CalLinkedField + '_Object.next.hover(this,true)" onMouseOut="return ' + CalLinkedField + '_Object.next.hover(this,false)" title="' + eval(CalLinkedField + '_Object.next.monthName') + '"><img src="' + CalNextURL + '" width="5" height="9"></td></tr>' + String.fromCharCode(13) + '<tr>');
         for (var w=0;w<7;w++) writeln('<td width="18" align="center" class="calendarDateInput" style="height:' + CalCellHeight + ';width:' + CalCellWidth + ';font-weight:bold;border-top:1px solid dimgray;border-bottom:1px solid dimgray;">' + WeekDays[w] + '</td>');
         writeln('</tr>' + String.fromCharCode(13) + '</table>' + String.fromCharCode(13) + '<span id="' + CalLinkedField + '_DayTable_ID">' + eval(CalLinkedField + '_Object.buildCalendar()') + '</span>' + String.fromCharCode(13) + '</span>');
      }
   }
}