/**
* Global variables
*/
	dynCalendar_layers          = new Array();
	dynCalendar_mouseoverStatus = false;
	dynCalendar_mouseX          = 0;
	dynCalendar_mouseY          = 0;

    months = new Array('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月');
    days	= new Array('日', '一', '二', '三', '四', '五', '六');

    var calendars = new Array;

    function calendar(formname, formelemDay, formelemMonth, formelemYear, image) {
	    elemDay   = document.forms[formname].elements[formelemDay];
	    elemMonth = document.forms[formname].elements[formelemMonth];
	    elemYear  = document.forms[formname].elements[formelemYear];
      	calendars[calendars.length] = new dynCalendar('calendars[' + calendars.length + ']', 'setDateFromCalendar', elemDay, elemMonth, elemYear, image);
    }

/**
* 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 reference to a formelement
* @param string OPTIONAL     Optional layer name
* @param string OPTIONAL     Optional image 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.objName        = objName;
		this.formelemDay	= arguments[2];
		this.formelemMonth	= arguments[3];
		this.formelemYear	= arguments[4];
		this.monthnames     = months;
		this.daynames		= days;
		this.callbackFunc   = callbackFunc;
		this.image		    = arguments[5] ? arguments[5] : '/skins/default/images/js_calendar.gif';
		this.layerID        = arguments[6] ? arguments[6] : 'dynCalendar_layer_' + dynCalendar_layers.length;

		this.offsetX        = 5;
		this.offsetY        = 5;

		this.useMonthCombo  = true;
		this.useYearCombo   = true;
		this.yearComboStart = 2003;
		this.yearComboRange = 1;

		this.currentMonth   = this.month;
		this.currentYear    = this.year;

		/**
        * Public Methods
        */
		this.show              = dynCalendar_show;
		this.writeHTML         = dynCalendar_writeHTML;

		// Accessor methods
		this.setOffset         = dynCalendar_setOffset;

		/**
        * 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;

		this.currentMonth = month = arguments[0] != null ? arguments[0] : this.currentMonth;
		this.currentYear  = year  = arguments[1] != null ? arguments[1] : this.currentYear;

		monthnames = this.monthnames;
		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
            */
			cssClass = (i == this.date && month == this.month && year == this.year) ? 'dynCalendarToday' : 'dynCalendarDay';
			day = i;
			month2 = Number(month) + 1;
			if ((this.formelemDay != null) && (this.formelemMonth != null) && (this.formelemYear != null)) {
				linkHTML = '<a href="javascript: '+'document.forms[\''+this.formelemDay.form.name+'\'].elements[\''+this.formelemDay.name+'\'].value = \''+day+'\';'
				                                  +'document.forms[\''+this.formelemMonth.form.name+'\'].elements[\''+this.formelemMonth.name+'\'].value = \''+month2+'\';'
				                                  +'document.forms[\''+this.formelemYear.form.name+'\'].elements[\''+this.formelemYear.name+'\'].value = \''+year+'\';'
                                                  + this.objName + '._hideLayer()">' + (i++) + '</a>';
			} else {
				linkHTML = '<a href="javascript: ' + this.callbackFunc + '(' + day + ', ' + month2 + ', ' + year + '); ' + this.objName + '._hideLayer()">' + (i++) + '</a>';
			}
			ret[row][ret[row].length] = '<td align="center" class="' + cssClass + '">' + 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++;
		}

		prevImgHTML  = '&lt;&lt;';
		prevLinkHTML = '<a href="javascript: ' + this.objName + '.show(' + previousMonth + ', ' + previousYear + ')">' + prevImgHTML + '</a>';
		nextImgHTML  = '&gt;&gt;';
		nextLinkHTML = '<a href="javascript: ' + this.objName + '.show(' + nextMonth + ', ' + nextYear + ')">' + nextImgHTML + '</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="' + this.objName + '.show(this.options[this.selectedIndex].value, ' + this.objName + '.currentYear)">' + monthComboOptions + '</select>';
		} else {
			monthCombo = monthnames[thisMonth.getMonth()];
		}

		/**
        * Build year combo
        */
		if (this.useYearCombo) {
			yearComboOptions = '';
			for (i = this.yearComboStart; 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="' + this.objName + '.show(' + this.objName + '.currentMonth, this.options[this.selectedIndex].value)">' + yearComboOptions + '</select>';
		} else {
			yearCombo = thisMonth.getFullYear();
		}

		html = '<table border="0" bgcolor="#eeeeee">';
		html += '<tr><td class="dynCalendarHeader">' + prevLinkHTML + '</td><td colspan="5" align="center" class="dynCalendarHeader">' + monthCombo + ' ' + yearCombo + '</td><td align="right" class="dynCalendarHeader">' + nextLinkHTML + '</td></tr>';
		html += '<tr>';
		html += '<td class="dynCalendarDayname">' + this.daynames[0] + '</td>';
		html += '<td class="dynCalendarDayname">' + this.daynames[1] + '</td>';
		html += '<td class="dynCalendarDayname">' + this.daynames[2] + '</td>';
		html += '<td class="dynCalendarDayname">' + this.daynames[3] + '</td>';
		html += '<td class="dynCalendarDayname">' + this.daynames[4] + '</td>';
		html += '<td class="dynCalendarDayname">' + this.daynames[5] + '</td>';
		html += '<td class="dynCalendarDayname">' + this.daynames[6] + '</td></tr>';
		html += '<tr>' + ret.join('</tr>\n<tr>') + '</tr>';
		html += '</table>';

		this._setHTML(html);
		if (!arguments[0] && !arguments[1]) {
			this._showLayer();
			this._setLayerPosition();
		}
	}

	// Writes HTML to document for layer
	function dynCalendar_writeHTML()
	{
		document.write('<a href="javascript: ' + this.objName + '.show()"><img src="' + this.image + '" border="0" width="16" height="16" align="absmiddle"/></a>');
		document.write('<div class="dynCalendar" id="' + this.layerID + '" onmouseover="' + this.objName + '._mouseover(true)" onmouseout="' + this.objName + '._mouseover(false)"></div>');
	}

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

	// Returns the layer object
	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
	function dynCalendar_hideLayer()
	{
		this._getLayer().style.visibility = 'hidden';
	}

	// Shows the calendar layer
	function dynCalendar_showLayer()
	{
		this._getLayer().style.visibility = 'visible';
	}

	// Sets the layers position
	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
	function dynCalendar_setHTML(html)
	{
		this._getLayer().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;
	}

/**
* onMouseMove event handler
*/
	dynCalendar_oldOnmousemove = document.onmousemove ? document.onmousemove : new Function;

	document.onmousemove = function ()
	{
		if (arguments[0]) {
			dynCalendar_mouseX = arguments[0].pageX;
			dynCalendar_mouseY = arguments[0].pageY;
		} else {
			dynCalendar_mouseX = event.clientX + document.body.scrollLeft;
			dynCalendar_mouseY = event.clientY + document.body.scrollTop;
			arguments[0] = null;
		}

		dynCalendar_oldOnmousemove();
	}

/**
* Callbacks for document.onclick
*/
	dynCalendar_oldOnclick = document.onclick ? document.onclick : new Function;

	document.onclick = function ()
	{
		if(!dynCalendar_mouseoverStatus){
			for(i=0; i<dynCalendar_layers.length; ++i){
				dynCalendar_layers[i]._hideLayer();
			}
		}

		dynCalendar_oldOnclick(arguments[0] ? arguments[0] : null);
	}
