/***********************************************
 Fool-Proof Date Input Script with DHTML Calendar
 by Jason Moon - http://calendar.moonscript.com/dateinput.cfm
 ************************************************/

// Customizable variables
var startpumonth // Mike - added to keep track of the initial selected month index
var DefaultDateFormat = 'MM/DD/YYYY'; // If no date format is supplied, this will be used instead
var HideWait = 300; // Number of seconds before the calendar will disappear
var HideYear = false; // Mike - added to allow year field to be hidden (Add 'true' as a 5th argument to script call to hide year)
var Y2kPivotPoint = 76; // 2-digit years before this point will be created in the 21st century
var UnselectedMonthText = ''; // Text to display in the 1st month list item when the date isn't required
var FontSize = 11; // In pixels
var FontFamily = 'Tahoma';
var CellWidth = 25;
var CellHeight = 21;
var ImageURL = '/images/calendarDateInput/btn_calendar_inside.gif';
var NextURL = '/images/calendarDateInput/calnext.gif';
var PrevURL = '/images/calendarDateInput/calprev.gif';
var doDateChanged = false; //bill - only change do date once automatically

//Colors are now set externally by a CF-generated javascript script before including this JS script.
//var CalBGColor = 'white';
//var TopRowBGColor = '#d4d4d4';
//var DayBGColor = '#CECECE';

// Global variables
var ZCounter = 100;
var Today = new Date();
//WeekDays and MonthNames are now translated and set externally by a CF-generated javascript script before including this JS script.
//var WeekDays = new Array('S','M','T','W','T','F','S');
//var MonthNames = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var MonthDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

var showit = false;
// Write out the stylesheet definition for the calendar
// with (document) {
//    writeln('<style>');
//    writeln('td.calendarDateInput {letter-spacing:normal;line-height:normal;font-family:' + FontFamily + ',Sans-Serif;font-size:' + FontSize + '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>');
// }

// Testing Click on close, this is not ready for live use yet
// function hideDiv(e){
// var div=document.getElementById('pudate_ID');
// var target=e?e.target:event.srcElement;
// target!=div?div.style.display='none':null;
// }
// 
// document.onclick=hideDiv;



// Only allows certain keys to be used in the date field
function YearDigitsOnly(e) {
   var KeyCode = (e.keyCode) ? e.keyCode : e.which;
   return ((KeyCode == 8) // backspace
        || (KeyCode == 9) // tab
        || (KeyCode == 37) // left arrow
        || (KeyCode == 39) // right arrow
        || (KeyCode == 46) // delete
        || ((KeyCode > 47) && (KeyCode < 58)) // 0 - 9
   );
}

// Gets the absolute pixel position of the supplied element
function GetTagPixels(StartTag, Direction) {
   var PixelAmt = (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   while ((StartTag.tagName != 'BODY') && (StartTag.tagName != 'HTML')) {
      StartTag = StartTag.offsetParent;
      PixelAmt += (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   }
   return PixelAmt;
}

// Is the specified select-list behind the calendar?
function BehindCal(SelectList, CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY) {
   var ListLeftX = GetTagPixels(SelectList, 'LEFT');
   var ListRightX = ListLeftX + SelectList.offsetWidth;
   var ListBottomY = ListTopY + SelectList.offsetHeight;
   return (((ListTopY < CalBottomY) && (ListBottomY > CalTopY)) && ((ListLeftX < CalRightX) && (ListRightX > CalLeftX)));
}

// For IE, hides any select-lists that are behind the calendar
function FixSelectLists(Over) {
   if (navigator.appName == 'Microsoft Internet Explorer') {
      var CalDiv = this.getCalendar();
      var CalLeftX = CalDiv.offsetLeft;
      var CalRightX = CalLeftX + CalDiv.offsetWidth;
      var CalTopY = CalDiv.offsetTop;
      var CalBottomY = CalTopY + (CellHeight * 9);
      var FoundCalInput = false;
      formLoop :
      for (var j=this.formNumber;j<document.forms.length;j++) {
      	 // set Length of elements for form being checked
      	 formElemLen = document.forms[j].elements.length;
         for (var i=0;i<formElemLen;i++) {
            FoundCalInput = false;
            if (typeof document.forms[j].elements[i].type == 'string') {
               if ((document.forms[j].elements[i].type == 'hidden') && (document.forms[j].elements[i].name == this.hiddenFieldName)) {
                  FoundCalInput = true;
                  
                  //NEED TO ADJUST ALL CAL OFFSETS!!!!
                  FoundCalRelTop = GetTagPixels(document.getElementById(this.hiddenFieldName + '_Display'), 'TOP');
                  FoundCalRelLeft = GetTagPixels(document.getElementById(this.hiddenFieldName + '_Display'), 'LEFT');

                  OffsetCalTopY = CalTopY  + FoundCalRelTop; 
                  OffsetCalBottomY = CalBottomY  + FoundCalRelTop; 
                  OffsetCalLeftX = CalLeftX  + FoundCalRelLeft; 
                  OffsetCalRightX = CalRightX  + FoundCalRelLeft; 
                  //i += 3; 3 elements between the 1st hidden field and the last year input field
               }
               if (FoundCalInput) {
               	  // loop through remaining form fields and check for overlap starting with next element
               	  for (var x = i+1;x<formElemLen;x++) {
					  if (document.forms[j].elements[x].type.substr(0,6) == 'select'||document.forms[j].elements[x].type.substr(0,4) == 'text') {
						 ListTopY = GetTagPixels(document.forms[j].elements[x], 'TOP');
						 
						 //problem here may be that calendar position is relative to display text box so
						 //we need to add position of display text box to Cal position:						 
						// alert(document.forms[j].elements[x].name + ' is ' + ListTopY + ' < ' + CalBottomY);
						 
						 if (ListTopY < (OffsetCalBottomY+FoundCalRelTop)) {
							if (BehindCal(document.forms[j].elements[x], OffsetCalLeftX, OffsetCalRightX, OffsetCalTopY, OffsetCalBottomY, ListTopY)) {
							   document.forms[j].elements[x].style.visibility = (Over) ? 'hidden' : 'visible';
							}
					     }
					
				     }
				  }
               }
            }
         }
      }
   }
}

// Displays a message in the status bar when hovering over the calendar days
// bill - removed status bar message
function DayCellHover(Cell, Over, Color, HoveredDay) {
   Cell.style.backgroundColor = (Over) ? DayBGColor : Color;
   return true;
}


//Format display date based 
function FormatDisplayDate(DisplayDateToFormat) {
	 if (CalDisplayMask == 'mmm dd yyyy') {
		FormattedDisplayDate = MonthNamesShort[DisplayDateToFormat.getMonth()] + ' ' + DisplayDateToFormat.getDate() + ', ' + DisplayDateToFormat.getFullYear();
	 }
	 else {
		// int'l format
		FormattedDisplayDate = DisplayDateToFormat.getDate() + ' ' + MonthNamesShort[DisplayDateToFormat.getMonth()] + ' ' + DisplayDateToFormat.getFullYear();
	 }

	return FormattedDisplayDate;
}


// Sets the form elements after a day has been picked from the calendar
function PickDisplayDay(ClickedDay) {
   //get old pudate for comparison with old dodate before incrementing
   var previousDate = new Date(document.getElementById(this.hiddenFieldName + '_Year_ID').value, document.getElementById(this.hiddenFieldName + '_Month_ID').value,document.getElementById(this.hiddenFieldName + '_Day_ID').value);

   this.show();
   var YearField = this.getYearField();
   
   this.setPicked(this.displayed.yearValue, this.displayed.monthIndex, ClickedDay);
   // Change the year, if necessary
   YearField.value = this.picked.yearPad;
   YearField.defaultValue = YearField.value;
   
   //build new display date
   newDisplayDate =  new Date(YearField.value,this.displayed.monthIndex,ClickedDay);
   
   document.getElementById(this.hiddenFieldName + '_Display').value = FormatDisplayDate(newDisplayDate);
   document.getElementById(this.hiddenFieldName + '_Month_ID').value = this.displayed.monthIndex;
   document.getElementById(this.hiddenFieldName + '_Day_ID').value = ClickedDay;
   document.getElementById(this.hiddenFieldName + '_Year_ID').value = YearField.value;
   
   // bill - only change do date once automatically, off for now
   // if (this.hiddenFieldName == 'dodate') {
   //		doDateChanged = true; 
   //}
   
   if (this.hiddenFieldName == 'pudate') {
		if (document.getElementById("dodate_Month_ID") && !doDateChanged && AutoDateSync) {
			
			//get original doDate
		    var previousDoDate = new Date(document.getElementById('dodate_Year_ID').value, document.getElementById('dodate_Month_ID').value,document.getElementById('dodate_Day_ID').value);
			var diff  = new Date();
			//figure out difference
			diff.setTime(Math.abs(previousDoDate.getTime() - previousDate.getTime()));
			timediff = diff.getTime();
			daysDiff = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
			// debug alert("old PU: " + previousDate + '\n\n' + "old DO: " + previousDoDate + '\n\n' + "timediff: " + timediff + '\n\n' + "daysDiff: " + daysDiff);
			newDOdate = newDisplayDate;
			newDOdate.setDate(newDOdate.getDate()+daysDiff);
			document.getElementById('dodate_Display').value = FormatDisplayDate(newDOdate);
			document.getElementById('dodate').value = newDisplayDate;
			document.getElementById('dodate_Month_ID').value = newDOdate.getMonth();
			document.getElementById('dodate_Day_ID').value = newDOdate.getDate();
			document.getElementById('dodate_Year_ID').value = newDOdate.getFullYear();
			//this updates the object for calendar
			dodate_Object.setPicked(newDOdate.getFullYear(), newDOdate.getMonth(), newDOdate.getDate());
			//bill - only change do date once automatically, off for now
			//doDateChanged = true; 
		}
	}
}

// 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="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1" style="cursor:pointer;font-size: ' + CalFontSize + '; font-family:' + CalFontFamily + ';">';
   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 = 'font-weight:bold;'
               BackColor = DayBGColor;
            }
            else {
               TextStyle = 'color:black;'
               BackColor = CalBGColor;
            }
            // this puts days in past in light grey
            if ((this.displayed.yearValue == Today.getFullYear()) && (this.displayed.monthIndex == Today.getMonth()) && (Day < Today.getDate())) TextStyle += 'color:#c3c3c3;';
            HTML += '<td align="center" class="calendarDateInput, cell'+ j + i +'" style="cursor:pointer;padding:1px;height:' + CellHeight + ';width:' + CellWidth + ';' + 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 if (Day == (this.displayed.dayCount + 1)) HTML += '<td class="calendarDateInput, celllastplusone" style="padding:1px;height:' + CellHeight + '">&nbsp;</td>';

		 else if (Day > this.displayed.dayCount) HTML += '<td class="calendarDateInput, cellsremaining" style="padding:1px;height:' + CellHeight + '">&nbsp;</td>';

         else HTML += '<td class="calendarDateInput" style="padding:1px;height:' + CellHeight + '">&nbsp;</td>';
      }
      HTML += '</tr>';
   }
   return HTML += '<tr><td colspan="7" class="cellcalendarClose" align="right" valign="middle" style="cursor:pointer;padding:1px 0px 2px 0px;margin:0;height:' + CellHeight + '" onClick="' + this.objName + '.show()"><span class="calendarClose">' + CalCloseText + '</span></td></tr></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;
}

// Adds/removes days from the day list, depending on the month/year
function FixDayList(DayList, NewDays) {
   var DayPick = DayList.value;
   return DayPick;
}

// Resets the year to its previous valid value when something invalid is entered
function FixYearInput(YearField) {
   var YearRE = new RegExp('\\d{' + YearField.defaultValue.length + '}');
   if (!YearRE.test(YearField.value)) YearField.value = YearField.defaultValue;
}

// Displays a message in the status bar when hovering over the calendar icon
function CalIconHover(Over) {
   var Message = (this.isShowing()) ? 'hide' : 'show';
   self.status = (Over) ? 'Click to ' + Message + ' the calendar' : '';
   return true;
}

// Starts the timer over from scratch
function CalTimerReset() {
   eval('clearTimeout(' + this.timerID + ')');
   eval(this.timerID + '=setTimeout(\'' + this.objName + '.show()\',' + (HideWait * 1000) + ')');
}

// The timer for the calendar
function DoTimer(CancelTimer) {
   if (CancelTimer) eval('clearTimeout(' + this.timerID + ')');
   else {
      eval(this.timerID + '=null');
      this.resetTimer();
   }
}

// Show or hide the calendar
function ShowCalendar() {
   if (this.isShowing()) {
      var StopTimer = true;
      this.getCalendar().style.zIndex = --ZCounter;
      this.getCalendar().style.visibility = 'hidden';
      this.fixSelects(false);
	  showit = false;
	  //bill-blur text box
	  displayBox = this.hiddenFieldName + "_Display";
	  document.getElementById(displayBox).blur();
   }
   else {
      if (showit) {
		  var StopTimer = false;
	      this.fixSelects(true);
	      this.getCalendar().style.zIndex = ++ZCounter;
	      this.getCalendar().style.visibility = 'visible';
	      this.setDisplayed(document.getElementById(this.hiddenFieldName + '_Year_ID').value,document.getElementById(this.hiddenFieldName + '_Month_ID').value);
		  showit = false;
	 }
   }
   this.handleTimer(StopTimer);
   self.status = '';
}

// Hides the input elements when the "blank" month is selected
function SetElementStatus(Hide) {
   this.getDayList().style.visibility = (Hide) ? 'hidden' : 'visible';
   this.getYearField().style.visibility = (Hide) ? 'hidden' : 'visible';
   this.getCalendarLink().style.visibility = (Hide) ? 'hidden' : 'visible';
}


// Sets the date, based on the day selected
function CheckDayChange(DayList) {
   if (this.isShowing()) this.show();
   this.setPicked(this.picked.yearValue, this.picked.monthIndex, DayList.selectedIndex+1);
   
}

// Changes the date when a valid year has been entered
function CheckYearInput(YearField) {
   //if ((YearField.value.length == YearField.defaultValue.length) && (YearField.defaultValue != YearField.value)) {
      if (this.isShowing()) {
         this.resetTimer(); // Gives the user more time to view the calendar with the newly-entered year
         this.getCalendar().style.zIndex = ++ZCounter; // Make sure this calendar is on top of any other calendars
      }
      var NewYear = GetGoodYear(YearField.value);
      var MonthList = this.getMonthList();
      var NewDay = FixDayList(this.getDayList(), GetDayCount(NewYear, this.picked.monthIndex));
      this.setPicked(NewYear, this.picked.monthIndex, NewDay);
      YearField.defaultValue = YearField.value;
   //}
}

// Holds characteristics about a date
function dateObject() {
   if (Function.call) { // Used when 'call' method of the Function object is supported
      var ParentObject = this;
      var ArgumentStart = 0;
   }
   else { // Used with 'call' method of the Function object is NOT supported
      var ParentObject = arguments[0];
      var ArgumentStart = 1;
   }
   ParentObject.date = (arguments.length == (ArgumentStart+1)) ? new Date(arguments[ArgumentStart+0]) : new Date(arguments[ArgumentStart+0], arguments[ArgumentStart+1], arguments[ArgumentStart+2]);
   ParentObject.yearValue = ParentObject.date.getFullYear();
   ParentObject.monthIndex = ParentObject.date.getMonth();
   ParentObject.monthName = MonthNames[ParentObject.monthIndex];
   ParentObject.fullName = ParentObject.monthName + ' ' + ParentObject.yearValue;
   ParentObject.day = ParentObject.date.getDate();
   ParentObject.dayCount = GetDayCount(ParentObject.yearValue, ParentObject.monthIndex);
   var FirstDate = new Date(ParentObject.yearValue, ParentObject.monthIndex, 1);
   ParentObject.firstDay = FirstDate.getDay();
}

// Keeps track of the date that goes into the hidden field
function storedMonthObject(DateFormat, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(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;
//   alert(this.monthName);
   this.monthShort = this.monthName.substr(0,3); //removed this because possible encoding issues .toUpperCase();
   // Formats the year with 2 digits instead of 4
   if (DateFormat.indexOf('YYYY') == -1) this.yearPad = this.yearPad.substr(2);
   // Define the date-part delimiter
   if (DateFormat.indexOf('/') >= 0) var Delimiter = '/';
   else if (DateFormat.indexOf('-') >= 0) var Delimiter = '-';
   else var Delimiter = '';
   // Determine the order of the months and days
   if (/DD?.?((MON)|(MM?M?))/.test(DateFormat)) {
      this.formatted = this.dayPad + Delimiter;
      this.formatted += (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
   }
   else if (/((MON)|(MM?M?))?.?DD?/.test(DateFormat)) {
      this.formatted = (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
      this.formatted += Delimiter + this.dayPad;
   }
   // Either prepend or append the year to the formatted date
   this.formatted = (DateFormat.substr(0,2) == 'YY') ? this.yearPad + Delimiter + this.formatted : this.formatted + Delimiter + this.yearPad;
}

// Object for the current displayed month
function displayMonthObject(ParentObject, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.displayID = ParentObject.hiddenFieldName + '_Current_ID';
   this.getDisplay = new Function('return document.getElementById(this.displayID)');
   this.dayHover = DayCellHover;
   this.goCurrent = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(Today.getFullYear(),Today.getMonth());');
   if (ParentObject.formNumber >= 0) this.getDisplay().innerHTML = this.fullName;
}

// Object for the previous/next buttons
function neighborMonthObject(ParentObject, IDText, DateMS) {
   (Function.call) ? dateObject.call(this, DateMS) : dateObject(this, DateMS);
   this.buttonID = ParentObject.hiddenFieldName + '_' + IDText + '_ID';
   //bill - removed status bar hovers
   //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=++ZCounter;' + 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.setHidden(this.picked.formatted);
   this.setDisplayed(PickedYear, PickedMonth);
}

// The calendar object
function calendarObject(DateName, DateFormat, DefaultDate) {

   /* Properties */
   this.hiddenFieldName = DateName;
   this.monthListID = DateName + '_Month_ID';
   this.dayListID = DateName + '_Day_ID';
   this.yearFieldID = DateName + '_Year_ID';
   this.monthDisplayID = DateName + '_Current_ID';
   this.calendarID = DateName + '_ID';
   this.dayTableID = DateName + '_DayTable_ID';
   this.calendarLinkID = this.calendarID + '_Link';
   this.timerID = this.calendarID + '_Timer';
   this.objName = DateName + '_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.checkYear = CheckYearInput;
   this.fixYear = FixYearInput;
//   this.changeMonth = CheckMonthChange;
   this.changeDay = CheckDayChange;
   this.resetTimer = CalTimerReset;
   this.hideElements = SetElementStatus;
   this.show = ShowCalendar;
   this.handleTimer = DoTimer;
   this.iconHover = CalIconHover;
   this.buildCalendar = BuildCalendarDays;
   this.pickDay = PickDisplayDay;
   this.fixSelects = FixSelectLists;
   this.setHidden = new Function('D','if (this.formNumber >= 0) this.getHiddenField().value=D');
   // Returns a reference to these elements
   this.getHiddenField = new Function('return document.forms[this.formNumber].elements[this.hiddenFieldName]');
   this.getMonthList = new Function('return document.getElementById(this.monthListID)');
   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.isShowing = 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(Today.getFullYear(), Today.getMonth(), Today.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 != '') {
      if ((this.format == 'YYYYMMDD') && (/^(\d{4})(\d{2})(\d{2})$/.test(DefaultDate))) this.setPicked(RegExp.$1, parseInt(RegExp.$2,10)-1, RegExp.$3);
      else {
         // Get the year
         if ((this.format.substr(0,2) == 'YY') && (/^(\d{2,4})(-|\/)/.test(DefaultDate))) { // Year is at the beginning
            var YearPart = GetGoodYear(RegExp.$1);
            // Determine the order of the months and days
            if (/(-|\/)(\w{1,3})(-|\/)(\w{1,3})$/.test(DefaultDate)) {
               var MidPart = RegExp.$2;
               var EndPart = RegExp.$4;
               if (/D$/.test(this.format)) { // Ends with days
                  var DayPart = EndPart;
                  var MonthPart = MidPart;
               }
               else {
                  var DayPart = MidPart;
                  var MonthPart = EndPart;
               }
               MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
               this.setPicked(YearPart, MonthPart, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else if (/(-|\/)(\d{2,4})$/.test(DefaultDate)) { // Year is at the end
            var YearPart = GetGoodYear(RegExp.$2);
            // Determine the order of the months and days
            if (/^(\w{1,3})(-|\/)(\w{1,3})(-|\/)/.test(DefaultDate)) {
               if (this.format.substr(0,1) == 'D') { // Starts with days
                  var DayPart = RegExp.$1;
                  var MonthPart = RegExp.$3;
               }
               else { // Starts with months
                  var MonthPart = RegExp.$1;
                  var DayPart = RegExp.$3;
               }
               MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
               this.setPicked(YearPart, MonthPart, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else SetGoodDate(this, true);
      }
   }
}


// Main function that creates the form elements
function DateInput(DateName, Required, DateFormat, DefaultDate, HideYear) {
   if (arguments.length == 0) document.writeln('<span style="color:red;font-size:' + FontSize + 'px;font-family:' + FontFamily + ';">ERROR: Missing required parameter in call to \'DateInput\': [name of hidden date field].</span>');
   else {
      // Handle DateFormat
      if (arguments.length < 3) { // The format wasn't passed in, so use default
         DateFormat = DefaultDateFormat;
         if (arguments.length < 2) Required = false;
      }
      else if (/^(Y{2,4}(-|\/)?)?((MON)|(MM?M?)|(DD?))(-|\/)?((MON)|(MM?M?)|(DD?))((-|\/)Y{2,4})?$/i.test(DateFormat)) DateFormat = DateFormat.toUpperCase();
      else { // Passed-in DateFormat was invalid, use default format instead
         var AlertMessage = 'WARNING: The supplied date format for the \'' + DateName + '\' field is not valid: ' + DateFormat + '\nTherefore, the default date format will be used instead: ' + DefaultDateFormat;
         DateFormat = DefaultDateFormat;
         if (arguments.length == 4) { // DefaultDate was passed in with an invalid date format
            var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
            AlertMessage += '\n\nThe supplied date (' + DefaultDate + ') cannot be interpreted with the invalid format.\nTherefore, the current system date will be used instead: ' + CurrentDate.formatted;
            DefaultDate = CurrentDate.formatted;
         }
         alert(AlertMessage);
      }
	
      // Define the current date if it wasn't set already
      if (!CurrentDate) var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
      // Handle DefaultDate
      if (arguments.length < 4) { // The date wasn't passed in
         DefaultDate = (Required) ? CurrentDate.formatted : ''; // If required, use today's date
      }
      // Creates the calendar object!
      eval(DateName + '_Object=new calendarObject(\'' + DateName + '\',\'' + DateFormat + '\',\'' + DefaultDate + '\')');
      // Determine initial viewable state of day, year, and calendar icon
      if ((Required) || (arguments.length == 4)) {
         var InitialStatus = '';
         var InitialDate = eval(DateName + '_Object.picked.formatted');
      }
      else {
         var InitialStatus = ' style="visibility:hidden"';
         var InitialDate = '';
         eval(DateName + '_Object.setPicked(' + Today.getFullYear() + ',' + Today.getMonth() + ',' + Today.getDate() + ')');
      }
      // Create the form elements
      with (document) {
         writeln('<input type="hidden" style="visibility:hidden; display:none;" id="'+ DateName + '" name="' + DateName + '" value="' + InitialDate + '">');
         // 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].type == 'hidden') && (forms[f].elements[e].name == DateName)) {
                     eval(DateName + '_Object.formNumber='+f);
                     break;
                  }
               }
            }
         }
         
         
   
		 //get display date formatted properly
		 Date_Display = new Date(InitialDate);
		 InitialDate_Display = FormatDisplayDate(Date_Display);

		 // onBlur="javascript:FixDisplay(' + DateName + ');"
         writeln('<input type="text" class="calendarDateInputText" onFocus="javascript:showit=true;' + DateName + '_Object.show();" name="' + DateName + '_Display" id="' + DateName + '_Display" value="' + InitialDate_Display + '" size="20" readonly="readonly" >');

         writeln('<input type="hidden" name="' + DateName + '_Month_ID" id="' + DateName + '_Month_ID" value="' + Date_Display.getMonth() + '">');
         writeln('<input type="hidden" name="' + DateName + '_Day_ID" id="' + DateName + '_Day_ID" value="' + Date_Display.getDate() + '">');
         writeln('<input type="hidden" name="' + DateName + '_Year_ID" id="' + DateName + '_Year_ID" value="' + Date_Display.getFullYear() + '">');

       //  write('<a' + InitialStatus + ' id="' + DateName + '_ID_Link" href="javascript:' + DateName + '_Object.show()" onMouseOver="return ' + DateName + '_Object.iconHover(true)" onMouseOut="return ' + DateName + '_Object.iconHover(false)" onclick="showit=true;"><img src="' + ImageURL + '" align="top" title="Calendar" border="0"></a>&nbsp;');
         write('&nbsp;');
         writeln('<span  class="calendartable" id="' + DateName + '_ID" style="position:absolute;top:25px;left:0;visibility:hidden;width:' + (CellWidth * 7) + 'px;background-color:' + CalBGColor + ';border:1px solid #9e9e9e;" onMouseOver="' + DateName + '_Object.handleTimer(true)" onMouseOut="' + DateName + '_Object.handleTimer(false)">');
         writeln('<table style="font-size: ' + CalFontSize + '; font-family:' + CalFontFamily + ';" width="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1">' + String.fromCharCode(13) + '<tr style="background-color:' + TopRowBGColor + ';">');
// old line with hovers         writeln('<td id="' + DateName + '_Previous_ID" style="padding:1px; cursor:pointer" align="center" class="calendarDateInput" style="height:' + CellHeight + '" onClick="' + DateName + '_Object.previous.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + DateName + '_Object.previous.hover(this,true)" onMouseOut="return ' + DateName + '_Object.previous.hover(this,false)" title="' + eval(DateName + '_Object.previous.monthName') + '"><img src="' + PrevURL + '"></td>');
         writeln('<td class="calendartopleft" id="' + DateName + '_Previous_ID" style="padding:1px; cursor:pointer" align="center" class="calendarDateInput" style="height:' + CellHeight + '" onClick="' + DateName + '_Object.previous.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" title="' + eval(DateName + '_Object.previous.monthName') + '"><img src="' + PrevURL + '" class="calendarImg"></td>');
         writeln('<td id="' + DateName + '_Current_ID" align="center" class="calendarDateInput" style="cursor:pointer; padding:1px; height:' + CellHeight + '" colspan="5" onClick="' + DateName + '_Object.displayed.goCurrent()" onMouseOver="self.status=\'Click to view ' + CurrentDate.fullName + '\';return true;" onMouseOut="self.status=\'\';return true;">' + eval(DateName + '_Object.displayed.fullName') + '</td>');
// old line with hovers         writeln('<td id="' + DateName + '_Next_ID" style="cursor:pointer" align="center" class="calendarDateInput" style="padding:1px; height:' + CellHeight + '" onClick="' + DateName + '_Object.next.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + DateName + '_Object.next.hover(this,true)" onMouseOut="return ' + DateName + '_Object.next.hover(this,false)" title="' + eval(DateName + '_Object.next.monthName') + '"><img src="' + NextURL + '"></td></tr>' + String.fromCharCode(13) + '<tr>');
         writeln('<td class="calendartopright" id="' + DateName + '_Next_ID" style="cursor:pointer" align="center" class="calendarDateInput" style="padding:1px; height:' + CellHeight + '" onClick="' + DateName + '_Object.next.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" title="' + eval(DateName + '_Object.next.monthName') + '"><img src="' + NextURL + '" class="calendarImg"></td></tr>' + String.fromCharCode(13) + '<tr>');
         for (var w=0;w<7;w++) writeln('<td width="' + CellWidth + '" align="center" class="calendarDateInput" style="padding:1px; height:' + CellHeight + ';width:' + CellWidth + ';font-weight:bold;background-color: #ededed; border-top:0px solid dimgray;border-bottom:0px solid dimgray;">' + WeekDays[w] + '</td>');
         writeln('</tr>' + String.fromCharCode(13) + '</table>' + String.fromCharCode(13) + '<span id="' + DateName + '_DayTable_ID">' + eval(DateName + '_Object.buildCalendar()') + '</span>' + String.fromCharCode(13) + '</span>');
      }
   }  
      
   // MIKE - Firefox tends to forget which day to select when a page is refreshed. This ensures the correct day is selected.
   daymenuid = DateName + '_Day_ID';
   useday = eval(DateName + '_Object.picked.day') -1;
   document.getElementById(daymenuid).selectedIndex = useday;
   // alert(daymenuid + ',' + useday);
   
   
   document.onclick = function(e){
	e =e || window.event;
	var element = e.target || e.srcElement;
	if (element.className.match(/^[Cc]alendar/) == null && element.className != 'calendarDateInputText') {
		eval(DateName + '_Object.show()');
		pudate_Object.show();
	}
	if(element.id == 'pudate_Display'  && DateName == 'dodate'){eval(DateName + '_Object.show()');}
}
   
}



