/**
 * jQuery custom selectcalendars
 * 
 * Copyright (c) 2008 Krzysztof Suszyński (suszynski.org)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * Modified by Ilya Shindyapin to convert to select calendar
 * utilizing the DHTML Calendar (jsCalendar)
 *
 * @version 0.0.1
 * @category visual
 * @package jquery
 * @subpakage ui.selectcalendar
 * @author Ilya Shindyapin
**/
var GLOBAL_JQUERY_SELECTCALENDAR = new Array();
var GLOBAL_JQUERY_SELECTCALENDAR_RESTRICTION = '';
jQuery.fn.selectcalendar = function(options){
	var today = new Date();
	var thisYear = today.getFullYear();
	
	function isDisabled(date) {
		var MINUTE = 60 * 1000;
		var HOUR = 60 * MINUTE;
		var DAY = 24 * HOUR;
		var WEEK = 7 * DAY;
		var today = new Date();
		return ((date.getTime() - today.getTime()) / DAY) < -1;
	}
	
	/* Default settings */
	var settings = {
		className: 'jquery-selectcalendar',
		animationSpeed: "normal",
		dateFormat: '%m-%d-%Y',
		startYear: (thisYear-5),
		disabledFunction: isDisabled,
		disabledOverrideFunction: null,
		endYear: (thisYear+10),
		replaceInvisible: false
	};

	var commonClass = 'jquery-custom-selectcalendars-replaced';
	var listOpen = false;
	var showList = function(listObj) {
		var selectcalendar = listObj.parents('.' + settings.className + '');
		
		listObj.slideDown(settings.animationSpeed, function(){
			listOpen = true;
		});

		//listObj[0].scrollTop=0;
		selectcalendar.addClass('selecthover');
		jQuery(document).bind('keydown', onSelectCalendarKeyDown);
		jQuery(document).bind('click', onBlurList);
		//listObj.focus();
		return listObj;
	}
	var hideList = function(listObj) {
		var selectcalendar = listObj.parents('.' + settings.className + '');
		jQuery(document).unbind('keydown', onSelectCalendarKeyDown);
		listObj.slideUp(settings.animationSpeed, function(){
			listOpen = false;
			jQuery(this).parents('.' + settings.className + '').removeClass('selecthover');
		});
		jQuery(document).unbind('click', onBlurList);
		return listObj;
	}
	var onBlurList = function(e) {
		var trgt = e.target;
		var currentListElements = jQuery('.' + settings.className + '-list:visible').parent().find('*').andSelf();
		if(jQuery.inArray(trgt, currentListElements)<0 && listOpen) {
			hideList( jQuery('.' + commonClass + '-list') );
		}
		return false;
	}
	var onSelectCalendarClick = function () {
		var thisMoreButton = jQuery(this).parent().find('.' + settings.className + '-moreButton');
		var otherLists = jQuery('.' + settings.className + '-list')
			.not(thisMoreButton.siblings('.' + settings.className + '-list'));
		hideList( otherLists );
		var thisList = thisMoreButton.siblings('.' + settings.className + '-list');
		if(thisList.filter(":visible").length > 0) {
			hideList( thisList );
		}else{
			showList( thisList );
		}
	}
	var onSelectCalendarKeyDown = function (e) {}
		
	/* Processing settings */
	settings = jQuery.extend(settings, options || {});
	/* Wrapping all passed elements */
	return this.each(function(i) {
		var _this = jQuery(this);
		if(_this.filter(':visible').length == 0 && !settings.replaceInvisible)
			return;
		
		// Setup the replacement divs and add the onclick events
		var replacement = jQuery(
			'<div class="' + settings.className + ' ' + commonClass + '">' +
				'<div class="' + settings.className + '-moreButton" />' +
				'<div class="' + settings.className + '-list ' + commonClass + '-list" />' +
				'<a href="#" onclick="return false;" class="' + settings.className + '-currentItem" />' +
			'</div>')
			.find('.' + settings.className + '-currentItem')
				.attr('tabindex', _this.attr('tabindex') || '')
				.click(onSelectCalendarClick)
				.end();

		// This adds the calendar to the div that is dropped down
		//var parent = null;
		var parent = jQuery('div.' + settings.className + '-list', replacement)[0];

		// This sets the text inside the input converted
		jQuery('a.'+settings.className + '-currentItem', replacement).text( this.value );
		
		// This controls the div that is displayed underneath (popup)
		// Also adds the mouseenter and mouseleave events to the arrow
		replacement.find('div.' + settings.className + '-moreButton')
			.click(onSelectCalendarClick)
			.bind('mouseenter',function(){
				jQuery(this).addClass('morebuttonhover');
			}).bind('mouseleave',function(){
				jQuery(this).removeClass('morebuttonhover');
			});
			
		_this.hide().replaceWith(replacement).appendTo(replacement);
		
		var thisListCalendar = replacement.find('.' + settings.className + '-list');
		var thisListCalendarWidth = Math.round(_this.width() + 5);
		if(jQuery.browser.safari)
			thisListCalendarWidth = thisListCalendarWidth * 0.99; //originally 0.94, but caused Safari width problems.
		replacement.css('width', thisListCalendarWidth + 'px');
		thisListCalendar.css({
			width: Math.round(thisListCalendarWidth) + 'px'
		});
		
		if( !this.id ){
			this.id = settings.className + '-calendarDate_'+i;
		}
		var input = this.id;
		// construct a calendar giving only the "selected" handler.
		var cal = new Calendar(0, _this.attr('value'), function(cal, date) {
			if(cal.dateClicked){
				jQuery('a.'+settings.className + '-currentItem', replacement).text( date );
				jQuery('#'+input).attr( 'value', date );
				onSelectCalendarClick();
			}
		});

		cal.weekNumbers = false;
		cal.showHeaderInfo = false;
		cal.setDisabledHandler( ( ( typeof settings.disabledOverrideFunction == 'function' ) ? settings.disabledOverrideFunction : settings.disabledFunction ) );
		cal.setDateFormat( settings.dateFormat );
		cal.setRange( settings.startYear, settings.endYear ); // min/max year allowed.
		
		if( this.className.match(/disabled_/) ){
			disabledDaysPresent = false;
			thisClasses = this.className.split(' ');
			for( i=0; i<thisClasses.length; i++ ){
				if( thisClasses[i].match(/disabled_/) ){
					disabledArray = thisClasses[i].split( '_' );
					disabledDaysArray = disabledArray[1].split( '-' );
					if( disabledArray[2] ){
						GLOBAL_JQUERY_SELECTCALENDAR_RESTRICTION = disabledArray[2];
					}
					disabledDaysPresent = true;
					cal.setDisabledDaysOfWeek( disabledDaysArray );
					break;
				}
			}
		
		}
		cal.create( parent );
		cal.show();
		GLOBAL_JQUERY_SELECTCALENDAR[input] = cal;
		
	});
}
jQuery.fn.unselectcalendar = function(){
	var commonClass = 'jquery-custom-selectcalendares-replaced';
	return this.each(function() {
		var selectToRemove = jQuery(this).filter('.' + commonClass);
		selectToRemove.replaceWith(selectToRemove.find('select').show());		
	});
}