/**
* Filename.......: calendar.js
* Project........: Popup Calendar
* Last Modified..: $Date: 2004/06/12 08:07:25 $
* CVS Revision...: $Revision: 1.1 $
* Copyright......: 2001, 2002 Richard Heyes
*/

/**
* Global variables
*/
	dynCalendar_layers          = new Array();
	dynCalendar_mouseoverStatus = false;
	dynCalendar_mouseX          = 0;
	dynCalendar_mouseY          = 0;

/**
* The calendar constructor
*
* @access public
* @param string objName      Name of the object that you create
* @param string callbackFunc Name of the callback function
* @param string OPTIONAL     Optional layer name
* @param string OPTIONAL     Optional images path
*/
	function dynCalendar(objName, callbackFunc)
	{
		/**
        * Properties
        */
		// Todays date
		this.today          = new Date();
		this.date           = this.today.getDate();
		this.month          = this.today.getMonth();
		this.year           = this.today.getFullYear();

		this.selDate        = this.date;
		this.selMonth       = this.month;
		this.selYear        = this.year;
		this.popup          = window.createPopup();

		this.objName        = objName;
		this.callbackFunc   = callbackFunc;
		this.imagesPath     = arguments[2] ? arguments[2] : 'images/';
		this.layerID        = 'dynCalendar_layer_' + dynCalendar_layers.length;
		this.showLink       = arguments[3] != null ? arguments[3] : true;

		this.offsetX        = 5;
		this.offsetY        = 5;

		this.useMonthCombo  = true;
		this.useYearCombo   = true;
		this.yearComboRange = 3;

		this.currentMonth   = this.month;
		this.currentYear    = this.year;

      this.calBtn = null;

		/**
        * Public Methods
        */
		this.show              = dynCalendar_show;
		this.writeHTML         = dynCalendar_writeHTML;

		// Accessor methods
		this.setOffset         = dynCalendar_setOffset;
		this.setOffsetX        = dynCalendar_setOffsetX;
		this.setOffsetY        = dynCalendar_setOffsetY;
		this.setImagesPath     = dynCalendar_setImagesPath;
		this.setMonthCombo     = dynCalendar_setMonthCombo;
		this.setYearCombo      = dynCalendar_setYearCombo;
		this.setCurrentMonth   = dynCalendar_setCurrentMonth;
		this.setCurrentYear    = dynCalendar_setCurrentYear;
		this.setSelectedDate   = dynCalendar_setSelectedDate;
		this.setYearComboRange = dynCalendar_setYearComboRange;

		/**
        * Private methods
        */
		// Layer manipulation
		this._getLayer         = dynCalendar_getLayer;
		this._hideLayer        = dynCalendar_hideLayer;
		this._showLayer        = dynCalendar_showLayer;
		this._setLayerPosition = dynCalendar_setLayerPosition;
		this._setHTML          = dynCalendar_setHTML;

		// Miscellaneous
		this._getDaysInMonth   = dynCalendar_getDaysInMonth;
		this._mouseover        = dynCalendar_mouseover;

		/**
        * Constructor type code
        */
		dynCalendar_layers[dynCalendar_layers.length] = this;
		this.writeHTML();
	}

/**
* Shows the calendar, or updates the layer if
* already visible.
*
* @access public
* @param integer month Optional month number (0-11)
* @param integer year  Optional year (YYYY format)
*/
	function dynCalendar_show()
	{
		// Variable declarations to prevent globalisation
		var month, year, monthnames, numdays, thisMonth, firstOfMonth;
		var ret, row, i, cssClass, linkHTML, previousMonth, previousYear;
		var nextMonth, nextYear, prevImgHTML, prevLinkHTML, nextImgHTML, nextLinkHTML;
		var monthComboOptions, monthCombo, yearComboOptions, yearCombo, html;

		header_style = 'style="font-family: Arial, Verdana, Helvetica, Sans-Serif;	font-size: 8pt;	font-weight: bold;white-space:nowrap;"';
      dayname_style = 'style="background-color: #eeeeee;	border: 1px solid #c0c0c0;	font-family: Arial, Verdana, Helvetica, Sans-Serif;	font-size: 10pt;	text-align: center;"';
      day_style = 'style="background-color: #eeeeee; cursor:hand;	color: #000000;	font-family: Arial, Verdana, Helvetica, Sans-Serif;	font-size: 10pt;"';
      link_style = 'style="background-color: #eeeeee; cursor:hand;	padding:0px 5px 0px 5px; border: 1px solid #c0c0c0; color: #000000;	font-family: Arial, Verdana, Helvetica, Sans-Serif;	font-size: 10pt;"';
      selected_style = 'style="background-color: #ffffff;	border: 1px solid #c0c0c0;	font-family: Arial, Verdana, Helvetica, Sans-Serif;	font-size: 10pt;"';
      today_style = 'style="background-color: #eeeeee;	border: 1px solid blue;	font-family: Arial, Verdana, Helvetica, Sans-Serif;	font-size: 10pt;"';
      main_style  ='style="background-color: #c0c0c0;	border: 2px outset white;	top: 1px;	left: 1px;"';


		this.currentMonth = month = arguments[0] != null ? arguments[0] : this.currentMonth;
		this.currentYear  = year  = arguments[1] != null ? arguments[1] : this.currentYear;
		this.calBtn = arguments[2] != null ? arguments[2] : this.calBtn;

		monthnames = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
		numdays    = this._getDaysInMonth(month, year);

		thisMonth    = new Date(year, month, 1);
		firstOfMonth = thisMonth.getDay();

		// First few blanks up to first day
		ret = new Array(new Array());
		for(i=0; i<firstOfMonth; i++){
			ret[0][ret[0].length] = '<td>&nbsp;</td>';
		}

		// Main body of calendar
		row = 0;
		i   = 1;
		while(i <= numdays){
			if(ret[row].length == 7){
				ret[++row] = new Array();
			}

			/**
            * Generate this cells' HTML
            */
         if ( i == this.selDate && month == this.selMonth && year == this.selYear )
            css_style = selected_style;
         else if ( i == this.date && month == this.month && year == this.year )
			   css_style = today_style;
			else
			   css_style = day_style;
			linkHTML = '<a style="cursor:hand" onclick="parent.' + this.callbackFunc + '(\''+this.objName+'\', ' + i + ', ' + (Number(month) + 1) + ', ' + year + '); parent.' + this.objName + '._hideLayer()">' + (i++) + '</a>';
			ret[row][ret[row].length] = '<td align="center" ' + css_style + '>' + linkHTML + '</td>';
		}

		// Format the HTML
		for(i=0; i<ret.length; i++){
			ret[i] = ret[i].join('\n') + '\n';
		}

		previousYear  = thisMonth.getFullYear();
		previousMonth = thisMonth.getMonth() - 1;
		if(previousMonth < 0){
			previousMonth = 11;
			previousYear--;
		}

		nextYear  = thisMonth.getFullYear();
		nextMonth = thisMonth.getMonth() + 1;
		if(nextMonth > 11){
			nextMonth = 0;
			nextYear++;
		}

      nowMonthNumDays  = this._getDaysInMonth(this.month, this.year);
      nowNextYear = this.year;
		nowNextMonth = this.month+1;
		if ( nowNextMonth > 11 ) {
		   nowNextMonth = 0;
		   nowNextYear++;
		}

		tmrDate = this.date + 1;
		tmrMonth = this.month;
		tmrYear = this.year;
		if ( tmrDate > nowMonthNumDays ) {
		   tmrDate = 1;
		   tmrMonth = nowNextMonth;
		   tmrYear = nowNextYear;
		}
		nextWkDate = this.date + 7;
		nextWkMonth = this.month;
		nextWkYear = this.year;
		if ( nextWkDate > nowMonthNumDays ) {
		   nextWkDate -= nowMonthNumDays;
		   nextWkMonth = nowNextMonth;
		   nextWkYear = nowNextYear;
		}


		prevImgHTML  = '<img style="width:10px;height:10px" src="' + this.imagesPath + '/prev.gif" alt="<<" border="0" />';
		prevLinkHTML = '<a style="cursor:hand;padding-left:5px;padding-right:5px;" onclick="parent.' + this.objName + '.show(' + previousMonth + ', ' + previousYear + ')" >' + prevImgHTML + '</a>';
		nextImgHTML  = '<img style="width:10px;height:10px" src="' + this.imagesPath + '/next.gif" alt="<<" border="0" />';
		nextLinkHTML = '<a style="cursor:hand;padding-left:5px;padding-right:5px;" onclick="parent.' + this.objName + '.show(' + nextMonth + ', ' + nextYear + ')">' + nextImgHTML + '</a>';

      todayLinkHTML = '<a '+link_style+' onclick="parent.' + this.callbackFunc + '(\''+this.objName+'\', ' + this.date + ', ' + (this.month+1) + ', ' + this.year + '); parent.' + this.objName + '._hideLayer()">Today</a>';
      tmrLinkHTML =  '<a '+link_style+' onclick="parent.' + this.callbackFunc + '(\''+this.objName+'\', ' + tmrDate + ', ' + (tmrMonth+1) + ', ' + tmrYear + '); parent.' + this.objName + '._hideLayer()">Tomorrow</a>';
      nextWkLinkHTML = '<a '+link_style+' onclick="parent.' + this.callbackFunc + '(\''+this.objName+'\', ' + nextWkDate + ', ' + (nextWkMonth+1) + ', ' + nextWkYear + '); parent.' + this.objName + '._hideLayer()">Next Week</a>';

		/**
        * Build month combo
        */
		if (this.useMonthCombo) {
			monthComboOptions = '';
			for (i=0; i<12; i++) {
				selected = (i == thisMonth.getMonth() ? 'selected="selected"' : '');
				monthComboOptions += '<option value="' + i + '" ' + selected + '>' + monthnames[i] + '</option>';
			}
			monthCombo = '<select name="months" onchange="if ( parent.' + this.objName + '.popup.isOpen) parent.' + this.objName + '.show(this.options[this.selectedIndex].value, parent.' + this.objName + '.currentYear)">' + monthComboOptions + '</select>';
		} else {
			monthCombo = monthnames[thisMonth.getMonth()];
		}

		/**
        * Build year combo
        */
		if (this.useYearCombo) {
			yearComboOptions = '';
			for (i = thisMonth.getFullYear() - this.yearComboRange; i <= (thisMonth.getFullYear() + this.yearComboRange); i++) {
				selected = (i == thisMonth.getFullYear() ? 'selected="selected"' : '');
				yearComboOptions += '<option value="' + i + '" ' + selected + '>' + i + '</option>';
			}
			yearCombo = '<select style="border: 1px groove" name="years" onchange="if ( parent.' + this.objName + '.popup.isOpen) parent.' + this.objName + '.show(parent.' + this.objName + '.currentMonth, this.options[this.selectedIndex].value)">' + yearComboOptions + '</select>';
		} else {
			yearCombo = thisMonth.getFullYear();
		}

      //html = '<link rel="stylesheet" href="templates/standard/dynCalendar.css" />';
		html += '<table border="0" '+main_style+'bgcolor="#eeeeee">';

		/*html += '<tr><td class="dynCalendar_header">' + prevLinkHTML + '</td><td colspan="5" align="center" class="dynCalendar_header">' + monthCombo + ' ' + yearCombo + '</td><td align="right" class="dynCalendar_header">' + nextLinkHTML + '</td></tr>';
		html += '<tr>';
		html += '<td class="dynCalendar_dayname">Sun</td>';
		html += '<td class="dynCalendar_dayname">Mon</td>';
		html += '<td class="dynCalendar_dayname">Tue</td>';
		html += '<td class="dynCalendar_dayname">Wed</td>';
		html += '<td class="dynCalendar_dayname">Thu</td>';
		html += '<td class="dynCalendar_dayname">Fri</td>';
		html += '<td class="dynCalendar_dayname">Sat</td></tr>';

		*/
		html = '<table border="0" bgcolor="#eeeeee">';
		html += '<tr><td '+header_style+'>' + prevLinkHTML + '</td><td colspan="5" align="center" '+header_style+'>' + monthCombo + ' ' + yearCombo + '</td><td align="right" '+header_style+'>' + nextLinkHTML + '</td></tr>';
		html += '<tr><td colspan="7" style="height:5px"></td></tr>';
		html += '<tr>';
		html += '<td '+dayname_style+'>Sun</td>';
		html += '<td '+dayname_style+'>Mon</td>';
		html += '<td '+dayname_style+'>Tue</td>';
		html += '<td '+dayname_style+'>Wed</td>';
		html += '<td '+dayname_style+'>Thu</td>';
		html += '<td '+dayname_style+'>Fri</td>';
		html += '<td '+dayname_style+'>Sat</td></tr>';
      html += '<tr><td colspan="7" style="height:5px"></td></tr>';

		html += '<tr>' + ret.join('</tr>\n<tr>') + '</tr>';

		html += '<tr><td colspan="7" style="height:12px"></td></tr>';
		html += '<tr><td colspan="7" style="text-align:center;">'+todayLinkHTML+'&nbsp;'+tmrLinkHTML+'&nbsp;'+nextWkLinkHTML+'</td></tr>';
		html += '<tr><td colspan="7" style="height:8px"></td></tr>';
		html += '</table>';
		html = '<div '+main_style+'>'+html+'</div>';
		this._setHTML( html );
   	this._showLayer();
	}

/**
* Writes HTML to document for layer
*
* @access public
*/
	function dynCalendar_writeHTML()
	{
		if ( this.showLink ) {
 			document.write('<a id="'+this.objName+'_calbtn" href="javascript: ' + this.objName + '.show()"><img src="' + this.imagesPath + 'dynCalendar.gif" border="0" width="16" height="16" /></a>');
      }
	}

/**
* Sets the offset to the mouse position
* that the calendar appears at.
*
* @access public
* @param integer Xoffset Number of pixels for vertical
*                        offset from mouse position
* @param integer Yoffset Number of pixels for horizontal
*                        offset from mouse position
*/
	function dynCalendar_setOffset(Xoffset, Yoffset)
	{
		this.setOffsetX(Xoffset);
		this.setOffsetY(Yoffset);
	}

/**
* Sets the X offset to the mouse position
* that the calendar appears at.
*
* @access public
* @param integer Xoffset Number of pixels for horizontal
*                        offset from mouse position
*/
	function dynCalendar_setOffsetX(Xoffset)
	{
		this.offsetX = Xoffset;
	}

/**
* Sets the Y offset to the mouse position
* that the calendar appears at.
*
* @access public
* @param integer Yoffset Number of pixels for vertical
*                        offset from mouse position
*/
	function dynCalendar_setOffsetY(Yoffset)
	{
		this.offsetY = Yoffset;
	}

/**
* Sets the images path
*
* @access public
* @param string path Path to use for images
*/
	function dynCalendar_setImagesPath(path)
	{
		this.imagesPath = path;
	}

/**
* Turns on/off the month dropdown
*
* @access public
* @param boolean useMonthCombo Whether to use month dropdown or not
*/
	function dynCalendar_setMonthCombo(useMonthCombo)
	{
		this.useMonthCombo = useMonthCombo;
	}

/**
* Turns on/off the year dropdown
*
* @access public
* @param boolean useYearCombo Whether to use year dropdown or not
*/
	function dynCalendar_setYearCombo(useYearCombo)
	{
		this.useYearCombo = useYearCombo;
	}

/**
* Sets the current month being displayed
*
* @access public
* @param boolean month The month to set the current month to
*/
	function dynCalendar_setCurrentMonth(month)
	{
		this.currentMonth = month;
	}

/**
* Sets the current month being displayed
*
* @access public
* @param boolean year The year to set the current year to
*/
	function dynCalendar_setCurrentYear(year)
	{
		this.currentYear = year;
	}

   function dynCalendar_setSelectedDate( day, month, year ) {
      day = Number(day);
      month = Number(month)-1;
      year = Number(year);
      this.selDate = day;
      this.selMonth = month;
      if ( year < 30 )
         this.selYear = year + 2000;
      else
         this.selYear = year + 1900;
      this.currentMonth = month;
      this.currentYear = this.selYear;

   }

/**
* Sets the range of the year combo. Displays this number of
* years either side of the year being displayed.
*
* @access public
* @param integer range The range to set
*/
	function dynCalendar_setYearComboRange(range)
	{
		this.yearComboRange = range;
	}

/**
* Returns the layer object
*
* @access private
*/
	function dynCalendar_getLayer()
	{
		var layerID = this.layerID;

		if (document.getElementById(layerID)) {

			return document.getElementById(layerID);

		} else if (document.all(layerID)) {
			return document.all(layerID);
		}
	}

/**
* Hides the calendar layer
*
* @access private
*/
	function dynCalendar_hideLayer()
	{
		this.popup.hide();
	}

/**
* Shows the calendar layer
*
* @access private
*/
	function dynCalendar_showLayer()
	{
	   this.popup.show(0, 0, 0, 0);
      var real_height = this.popup.document.body.scrollHeight;
      var real_width = this.popup.document.body.scrollWidth;
      var calbtn = this.calBtn != null ? this.calBtn : document.getElementById( this.objName+'_calbtn' );
	   this.popup.show(this.offsetX, this.offsetY, real_width, real_height + 4, calbtn);
	}

/**
* Sets the layers position
*
* @access private
*/
	function dynCalendar_setLayerPosition()
	{
		//this._getLayer().style.top  = (dynCalendar_mouseY + this.offsetY) + 'px';
		//this._getLayer().style.left = (dynCalendar_mouseX + this.offsetX) + 'px';
	}

/**
* Sets the innerHTML attribute of the layer
*
* @access private
*/
	function dynCalendar_setHTML(html)
	{
		this.popup.document.body.innerHTML = html;
	}

/**
* Returns number of days in the supplied month
*
* @access private
* @param integer month The month to get number of days in
* @param integer year  The year of the month in question
*/
	function dynCalendar_getDaysInMonth(month, year)
	{
		monthdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
		if (month != 1) {
			return monthdays[month];
		} else {
			return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ? 29 : 28);
		}
	}

/**
* onMouse(Over|Out) event handler
*
* @access private
* @param boolean status Whether the mouse is over the
*                       calendar or not
*/
	function dynCalendar_mouseover(status)
	{
		dynCalendar_mouseoverStatus = status;
		return true;
	}
