(function ($) {
	
    $.calendar = function (el, options) {
        var self = this,
			node = $(el),
			speed = $.browser.msie ? 0 : 'fast';

		node.data('calendar', this);
		

		/**
		 *	Initializing
		 */
        this.init = function () {
            this.options = $.extend({}, $.calendar.defaultOptions, options);
			
			var input = $('span input', node),
				date = input.val(),
				range = input.attr('title'),
				index = input.attr('name') || '';
			
			
			input.attr('name', null);
			
			if (input.attr('readonly')) {
				input.removeAttr('readonly');
			}
			
			$('<input type="hidden" name="day' + index + '" id="day' + index + '" />').appendTo(node);
			$('<input type="hidden" name="month' + index + '" id="month' + index + '" />').appendTo(node);
			$('<input type="hidden" name="year' + index + '" id="year' + index + '" />').appendTo(node);

			if (date != '') {
				$('> input:first', node).val(date.split('.')[0])
					.next().val(date.split('.')[1])
					.next().val(date.split('.')[2]);
			}
			
			if (range != '') {
				range = range.split('-');
				if (range[0]) this.options.minDate = range[0];
				if (range[1]) this.options.maxDate = range[1];
				input.attr('title', null);
			}

			$('span input', node).datepicker({
				dateFormat: 'dd.mm.yy',
				showOn: 'both',
				buttonImage: '/images/common/icon-calendar.gif',
				buttonImageOnly: true,
				firstDay: 1,
				prevText: '',
				nextText: '',
				defaultDate: date,
				hideIfNoPrevNext: true,
				minDate: this.options.minDate,
				maxDate: this.options.maxDate,
				showOtherMonths: true,
				duration: speed,
				onSelect: function (date, inst) {
					
					$('> input:first', node).val(date.split('.')[0])
						.next().val(date.split('.')[1])
						.next().val(date.split('.')[2]);
				},
				beforeShowDay: function (date) {
					var day = date.getDay(),
						result = [
							day && day != 6,
							day == 0 ? 'ui-datepicker-sunday' : ''
						];
					return result;
				}
			}).change(function(event) {
				var date =	input.val();
				$('> input:first', node).val(date.split('.')[0])
						.next().val(date.split('.')[1])
						.next().val(date.split('.')[2]);
			});
			$('img', node).insertAfter(node);
			var calendars = $('body > div.ui-datepicker');
			calendars.hide();
        };

        this.init();
    };

    $.calendar.defaultOptions = {
		minDate: null,
		maxDate: null
    };

    $.fn.calendar = function (options) {
        return this.each(function () {
            (new $.calendar(this, options));
        });
    };

})(jQuery);
