/*
  DatechoosereChooser 1.5
  http://beggarchooser.com/datechooser/
  05.11.2006

  Copyright (c) 2006 John Hansen

  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all copies or substantial
  portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  IN THE SOFTWARE.
*/

//Event.observe(window, 'click', DateChooser.hide);

var objPrototypes = {
    aDay: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
    aShortDay: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    aMonth: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    aShortMonth: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    aSuffix: ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st'],
    sTimezoneOffset: '',
    sEarlier: 'earlier',
    sLater: 'later',
    sToday: 'today',
    sCurrentSelection: 'current selection',
    weekOrder: [6,0,1,2,3,4,5],

    GetTimezoneOffset: function() {
	var objLocal = new Date();
	objLocal.setHours(0);
	objLocal.setMinutes(0);
	objLocal.setSeconds(0);
	objLocal.setMilliseconds(0);

	var objUTC = new Date();
	objUTC.setFullYear(objLocal.getUTCFullYear());
	objUTC.setMonth(objLocal.getUTCMonth());
	objUTC.setDate(objLocal.getUTCDate());
	objUTC.setHours(objLocal.getUTCHours());
	objUTC.setMinutes(objLocal.getUTCMinutes());
	objUTC.setSeconds(objLocal.getUTCSeconds());
	objUTC.setMilliseconds(objLocal.getUTCMilliseconds());

	this.sTimezoneOffset = ((objLocal.getTime() - objUTC.getTime()) / (1000 * 3600));
	var bNegative = (this.sTimezoneOffset < 0);
	objLocal = null;
	objUTC = null;

	this.sTimezoneOffset  = bNegative ? (this.sTimezoneOffset + '').substring(1) : this.sTimezoneOffset + '';
	this.sTimezoneOffset  = this.sTimezoneOffset.replace(/\.5/, (parseInt('$1', 10) * 60) + '');
	this.sTimezoneOffset += (this.sTimezoneOffset.substring(this.sTimezoneOffset.length - 3) != ':30') ? ':00' : '';
	this.sTimezoneOffset  = (this.sTimezoneOffset.substr(0, this.sTimezoneOffset.indexOf(':')).length == 1) ? '0' + this.sTimezoneOffset : this.sTimezoneOffset;
	this.sTimezoneOffset  = bNegative ? '-' + this.sTimezoneOffset : '+' + this.sTimezoneOffset;

	return true;
    },

    Array_push: function() {
	for (var ctr = 0; ctr < arguments.length; ctr++)
	{
	    this[this.length] = arguments[ctr];
	}

	return this.length;
    },

    Date_PHPDate: function() {
	var sFormat = (arguments.length > 0) ? arguments[0] : '';

	var nYear = this.getFullYear();
	var sYear = nYear + '';

	var nMonth = this.getMonth();
	var sMonth = (nMonth + 1) + '';
	var sPaddedMonth = (sMonth.length == 1) ? '0' + sMonth : sMonth;

	var nDate = this.getDate();
	var sDate = nDate + '';
	var sPaddedDate = (sDate.length == 1) ? '0' + sDate : sDate;

	var nDay = this.getDay();
	var sDay = nDay + '';

	sFormat = sFormat.replace(/([cDdFjlMmNnrSUwYy])/g, 'y5-cal-regexp:$1');
	sFormat = sFormat.replace(/y5-cal-regexp:c/, sYear + '-' + sPaddedMonth + '-' + sPaddedDate + 'T00:00:00' + objPrototypes.sTimezoneOffset);
	sFormat = sFormat.replace(/y5-cal-regexp:D/, objPrototypes.aShortDay[nDay]);
	sFormat = sFormat.replace(/y5-cal-regexp:d/, sPaddedDate);
	sFormat = sFormat.replace(/y5-cal-regexp:F/, objPrototypes.aMonth[nMonth]);
	sFormat = sFormat.replace(/y5-cal-regexp:j/, nDate);
	sFormat = sFormat.replace(/y5-cal-regexp:l/, objPrototypes.aDay[nDay]);
	sFormat = sFormat.replace(/y5-cal-regexp:M/, objPrototypes.aShortMonth[nMonth]);
	sFormat = sFormat.replace(/y5-cal-regexp:m/, sPaddedMonth);
	sFormat = sFormat.replace(/y5-cal-regexp:N/, (nDay == 0) ? 7 : nDay);
	sFormat = sFormat.replace(/y5-cal-regexp:n/, sMonth);
	sFormat = sFormat.replace(/y5-cal-regexp:r/, objPrototypes.aShortDay[nDay] + ', ' + sPaddedDate + ' ' + objPrototypes.aShortMonth[nMonth] + ' ' + sYear + ' 00:00:00 ' + objPrototypes.sTimezoneOffset.replace(/:/, ''));
	sFormat = sFormat.replace(/y5-cal-regexp:S/, objPrototypes.aSuffix[nDate]);
	sFormat = sFormat.replace(/y5-cal-regexp:U/, this.getTime() / 1000);
	sFormat = sFormat.replace(/y5-cal-regexp:w/, nDay);
	sFormat = sFormat.replace(/y5-cal-regexp:Y/, sYear);
	sFormat = sFormat.replace(/y5-cal-regexp:y/, sYear.substring(2));

	return sFormat;
    },

    Date_parseDate: function(uiDate) {
	uiDate = uiDate || '';
	var regexp = new RegExp('^' + objPrototypes.INPUT_DATE_FORMAT_1 + '$', 'i');
	var parts = regexp.exec(uiDate);
	if (!parts) return '';

	var tmp = {};
	var order = objPrototypes.INPUT_DATE_FORMAT_1_ORDER.split(',');
	for (var i = 0; i < order.length; i++) {
	    var n = parseInt(parts[i + 1]);
	    if (isNaN(n) || n < 0) return '';
	    tmp[order[i]] = n;
	}
	if (tmp['YEAR'] < 40) {
	    tmp['YEAR'] += 2000;
	}
	if (tmp['YEAR'] < 1900) {
	    return '';
	}
	var testDate = new Date();
	testDate.setFullYear(tmp['YEAR']);
	testDate.setMonth(tmp['MONTH'] - 1);
	testDate.setDate(tmp['DAY']);
	
	if (testDate.getFullYear()  != tmp['YEAR'] ||
	    testDate.getMonth()	    != tmp['MONTH'] - 1 ||
	    testDate.getDate()	    != tmp['DAY']) {
	    return '';
	}
	
	var zeros = '0000';
	var date =  zeros.substr(0,4 - tmp['YEAR'].length) + tmp['YEAR'] + '-' +
	zeros.substr(0,2 - tmp['MONTH'].length) + tmp['MONTH'] + '-' +
	zeros.substr(0,2 - tmp['DAY'].length) + tmp['DAY'];
	
	return date;
    }
};

objPrototypes.GetTimezoneOffset();
Date.prototype.getPHPDate = objPrototypes.Date_PHPDate;
if (typeof(Array.prototype.push) == 'undefined') {
    Array.prototype.push = objPrototypes.Array_push;
}

function DateDisplayer(args) {
	var objStartDate;
    var objMonthYear;
    if (args['startDate']) {
		var parts = args['startDate'].split(/[\-\ ]/);
		objStartDate = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10));
		objMonthYear = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, 1);
    }
	else {
		objStartDate = new Date();
		objMonthYear = new Date();
		objMonthYear.setDate(1);
	}
    var objEndDate;
    if (args['endDate']) {
		var parts = args['endDate'].split(/[\-\ ]/);
		objEndDate = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10));
    }
    document.getElementById(args['container']).innerHTML = Calendar.getHTML({ monthYear: objMonthYear, startDate: objStartDate, endDate: objEndDate, withLinks: false });
}

function DateChooser(args) {
    if (!document.getElementById
	|| !document.getElementsByTagName
	|| !arguments) {
	return false;
    }

    if (!DateChooser.popup) {
	DateChooser.popup = document.createElement('div');
	DateChooser.popup.style.display = 'none';
	Event.observe(DateChooser.popup, 'click', Event.stop.bindAsEventListener(this));
    }
    
    var ndDateField = document.getElementById(args['updateField'] || '');

    var nXOffset = args['xOffset'] || 0;
    var nYOffset = args['yOffset'] || 0;
    var objTimeout = null;
	var active = true;

    var objSelectedDate = new Date();
    objSelectedDate.setHours(0);
    objSelectedDate.setMinutes(0);
    objSelectedDate.setSeconds(0);
    objSelectedDate.setMilliseconds(0);
    if (args['startDate']) {
		objPrototypes.Date_parseDate(objSelectedDate, args['startDate']);
    }
    var objEndDate = new Date();
    objEndDate.setHours(0);
    objEndDate.setMinutes(0);
    objEndDate.setSeconds(0);
    objEndDate.setMilliseconds(0);
    if (args['endDate']) {
	objPrototypes.Date_parseDate(objEndDate, args['endDate']);
    }

    var objMonthYear = new Date();
    objMonthYear.setTime(objSelectedDate.getTime());
    objMonthYear.setDate(1);

    var AddClickEvents = function() {
	var aNavLinks = DateChooser.popup.getElementsByTagName('a');
	for (var nNavLink = 0; nNavLink < aNavLinks.length; ++nNavLink) {
	    Event.observe(aNavLinks[nNavLink], 'click', function(event, ndClicked) {
		Event.stop(event);
		if (ndClicked.className == 'previousyear') {
		    objMonthYear.setFullYear(objMonthYear.getFullYear() - 1);
		}
		else if (ndClicked.className == 'previousmonth') {
			if (objMonthYear.getMonth() != 0) {
				objMonthYear.setMonth(objMonthYear.getMonth() - 1);
			}
			else {
				objMonthYear.setFullYear(objMonthYear.getFullYear()-1);
				objMonthYear.setMonth(11);
			}
		}
		else if (ndClicked.className == 'currentdate') {
		    var objCurrentDate = new Date();
		    
		    objMonthYear.setFullYear(objCurrentDate.getFullYear());
		    objMonthYear.setMonth(objCurrentDate.getMonth());
		}
		else if (ndClicked.className == 'nextmonth') {
		    objMonthYear.setMonth(objMonthYear.getMonth() + 1);
		}
		else if (ndClicked.className == 'nextyear') {
		    objMonthYear.setFullYear(objMonthYear.getFullYear() + 1);
		}
		RefreshDisplay();
		AddClickEvents();
	    }.bindAsEventListener(this, aNavLinks[nNavLink]));
	}
	
	var aDateLinks = DateChooser.popup.getElementsByTagName('table')[0].getElementsByTagName('a');

    var objTempDate = new Date();
    objTempDate.setTime(objMonthYear.getTime());
    objTempDate.setDate(objTempDate.getDate() - objPrototypes.weekOrder[objTempDate.getDay()]);
 
	for (var nDateLink = 0; nDateLink < aDateLinks.length; ++nDateLink) {
		var date = objTempDate.getDate();
	    var month = objTempDate.getMonth();
	    var year = objTempDate.getFullYear();
	    Event.observe(aDateLinks[nDateLink], 'click', Event.stop);
	    Event.observe(aDateLinks[nDateLink], 'click', function(date, month, year) {
		objSelectedDate = new Date(year, month, date);

		objEndDate = new Date(year, month, date);
		
		DateChooser.hide();		
		if (objTimeout) clearTimeout(objTimeout);

		if (ndDateField) {
		    ndDateField.value = objSelectedDate.getPHPDate(objPrototypes.OUTPUT_DATE_FORMAT_3);
		}
	    }.bind(this, date, month, year));
		objTempDate.setDate(objTempDate.getDate() + 1);
	}
	return true;
    };

    var RefreshDisplay = function() {
	DateChooser.popup.innerHTML = 
	Calendar.getHTML({ monthYear: objMonthYear, startDate: objSelectedDate, withLinks: true }) +
	'<!--[if lte IE 6.5]><iframe src="/empty.html"></iframe><![endif]-->';

	return true;
    };

    this.DisplayDateChooser = function(left, top, width, height) {
	DateChooser.hide();
	
	var sqlDate = objPrototypes.Date_parseDate(ndDateField ? ndDateField.value : '');
	if (sqlDate != '') {
	    var parts = sqlDate.split(/[\-\ ]/);
	    objSelectedDate.setFullYear(parseInt(parts[0], 10));
	    objSelectedDate.setMonth(parseInt(parts[1], 10) - 1);
	    objSelectedDate.setDate(parseInt(parts[2], 10));
	}
	
	objMonthYear.setFullYear(objSelectedDate.getFullYear());
	objMonthYear.setMonth(objSelectedDate.getMonth());

	if (objTimeout) {
	    clearTimeout(objTimeout);
	}

	if (!DateChooser.popup.parentNode) document.body.appendChild(DateChooser.popup);

	DateChooser.popup.className = 'calendar popup';
	Element.setStyle(DateChooser.popup, { visibility: 'hidden',
							      display: 'block',
							     left: '0',
							     top: '0'});
	RefreshDisplay();	
	dims = { width: DateChooser.popup.offsetWidth, height: DateChooser.popup.offsetHeight };
	var vB = Position.getViewPortBounds();

	var className = 'calendar popup';
	if (top + height + dims.height < vB.top + vB.height) {
	    className += ' top';
	    DateChooser.popup.style.top = (top + height) + 'px';
	}
	else {
	    className += ' bottom';
	    DateChooser.popup.style.top = (top - dims.height) + 'px';
	}

	if (left - dims.width > vB.left) {
	    className += '-right';
	    DateChooser.popup.style.left = (left - dims.width) + 'px';
	}
	else {
	    className += '-left';
	    DateChooser.popup.style.left = left + 'px';
	}

	DateChooser.popup.className = className;
	RefreshDisplay();

	DateChooser.popup.style.visibility = '';
	DateChooser.visibleDateChooser = this;

	AddClickEvents();
	return true;
    };

	this.activate = function () {
		active = true;
	};

	this.deactivate = function () {
		active = false;
		if (DateChooser.visibleDateChooser == this) {
			DateChooser.hide();
		}
	};

    this.toggle = function(event, element) {
		Event.stop(event);

		if (!active) return;

		if (DateChooser.visibleDateChooser == this) {
			DateChooser.hide();
		}
		else {
			var pos = $(element).cumulativeOffset();
			this.DisplayDateChooser(pos[0], pos[1], element.offsetWidth, element.offsetHeight);
		}
    };
    
    if (args['trigger']) {
	Event.observe(args['trigger'], 'click', this.toggle.bindAsEventListener(this, args['trigger']));
    }    
}

DateChooser.hide = function() {
    if (DateChooser.popup) {
	DateChooser.popup.style.display = 'none';
	DateChooser.visibleDateChooser = null;
    }
};

var Calendar = {};
Calendar.getHTML =  function(args) {
    var objMonthYear = args['monthYear'];
    var objSelectedDate = args['startDate'];
    var objEndDate = args['endDate'] || args['startDate'];
    var withLinks = args['withLinks'];

    var objToday = new Date();
    objToday.setHours(0);
    objToday.setMinutes(0);
    objToday.setSeconds(0);
    objToday.setMilliseconds(0);
    
    var aTable = '';
    aTable += '<div class="header">';
    if (withLinks) aTable += '<a class="currentdate" href="#" title="Current Date">';
    aTable += objMonthYear.getPHPDate("F Y");
    if (withLinks) aTable += '</a>';
    aTable += '</div>';
    aTable += '<div class="content"><table cellpadding="0" cellspacing="2">';
    aTable += '<thead><tr>';
    for (var i = 0; i < objPrototypes.aShortDay.length; ++i)  {
	aTable += '<td>' + objPrototypes.aShortDay[i] + '</td>';
    }
    aTable += '</tr></thead>';
    aTable += '<tbody>';
    
    var objTempDate = new Date();
    objTempDate.setTime(objMonthYear.getTime());
    objTempDate.setDate(objTempDate.getDate() - objPrototypes.weekOrder[objTempDate.getDay()]);
    var inSelectionRange = false;
    var startTime   = objSelectedDate.getTime();
    var endTime	    = objEndDate.getTime();
    for (var weekOfMonth = 0; weekOfMonth < 6; weekOfMonth++) {
	aTable += '<tr>';
	for (var dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
	    if (objTempDate.getTime() == startTime) inSelectionRange = true;
	    var classNames = [];
	    if (inSelectionRange) {
		classNames.push('selectedday');
	    }
	    else {
		classNames.push((weekOfMonth % 2 == 0) ? 'even' : 'odd');		    
		if (objTempDate.getTime() == objToday.getTime()) classNames.push('today');
	    }
	    if (objTempDate.getMonth() != objMonthYear.getMonth()) {
		classNames.push('next-month');
	    }
	    var sClass = (classNames.length != 0) ? ' class="' + classNames.join(' ') + '"' : '';
	    aTable += '<td' + sClass + '>';
	    if (withLinks) aTable += '<a href="#" style="display:block; width:32px;">';
	    else aTable += '<div style="display:block; width:32px;">';
	    aTable += objTempDate.getDate();
	    if (withLinks) aTable += '</a>';
	    else aTable += '</div>';
	    aTable += '</td>';
	    if (objTempDate.getTime() == endTime) inSelectionRange = false;
	    objTempDate.setDate(objTempDate.getDate() + 1);
	}
	aTable += '</tr>';
    }
    aTable += '</tbody></table></div>';
    aTable += '<div class="footer">';
    if (withLinks) aTable += '<a class="previousmonth" href="#" title="Previous Month">&laquo; ' + objPrototypes.sEarlier + '</a>';
    aTable += '<div class="description">';
    aTable += ' <img src="/app/img/screen/icn_today.gif" alt="today" class="icon"> ' + objPrototypes.sToday;
    aTable += ' <img src="/app/img/screen/icn_current_selection.gif" alt="selection" class="icon"> ' + objPrototypes.sCurrentSelection;
    aTable += '</div>';
    if (withLinks) aTable += '<a class="nextmonth" href="#" title="Next Month">' + objPrototypes.sLater + ' &raquo;</a>';
    aTable += '</div>';
    
    return aTable;
};
