(function($){
	$.fn.waDatepicker = function(options){
		var options = $.extend({
			defaultDate: new Date(),
			minDate: null,
			maxDate: null,
			url: '',
			monthNames: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
			eventsNamespace: 'waDatepicker_' + Math.round(Math.random() * 100000)
		}, options || {});

		var $this = this;
		var $dropdownButton = $this.find('.face .dropdown-button');
		var $prevButton = $this.find('.controls .prev-button');
		var $nextButton = $this.find('.controls .next-button');
		var $calendar = $this.find('.calendar');
		var $monthTitle = $this.find('.controls .month-title');
		var $daysContainer = $this.find('.days');
		var calendarDisplayState = false;
		var currentDate = options.defaultDate;

		var getDoubleDigit = function(digit){
			return (digit < 10 ? '0' : '') + digit;
		}

		var setControls = function(date){
			if(currentDate.getTime() < options.maxDate.getTime()) $nextButton.show();
			else $nextButton.hide();
			if(currentDate.getTime() > options.minDate.getTime()) $prevButton.show();
			else $prevButton.hide();

			$monthTitle.text(options.monthNames[date.getMonth()] + ' ' + date.getFullYear());
		}

		var ajaxSuccess = function(data, textStatus){
			var days = data.days;
			var daysMarkup = '';

			for(var i = 0; i < data.startWeekday; ++i) daysMarkup += '<li />';

			for(var i =0; i < days.length; ++i){
				var day = days[i] || {};
				
				daysMarkup += '<li>' + (day.url ? '<a href="' + day.url + '">' + (Number(i) + 1) + '</a>' : (Number(i) + 1)) + '</li>';
			}

			$daysContainer.empty().append(daysMarkup);
			// spinner hide
		}

		var update = function(date){
			var url = options.url + date.getFullYear() + getDoubleDigit(date.getMonth() + 1) + getDoubleDigit(date.getDate()) + '/calendar.json';

			$.ajax({
				url: url,
				dataType : "json",
				beforeSend: function(){
					// spinner
				},
				success: ajaxSuccess
			});
		}

		$prevButton.click(function(e){
			if(currentDate.getTime() > options.minDate.getTime()){
				currentDate.setMonth(currentDate.getMonth() - 1);
				
				setControls(currentDate);

				update(currentDate);
			}
		});
		$nextButton.click(function(e){
			if(currentDate.getTime() < options.maxDate.getTime()){
				currentDate.setMonth(currentDate.getMonth() + 1);
				
				setControls(currentDate);

				update(currentDate);
			}
		});

		$dropdownButton.click(function(e){
			if(calendarDisplayState == false){
				$calendar.show(100);
				calendarDisplayState = true;

				$(document).bind('click.' + options.eventsNamespace, function(){
					$calendar.hide(100);
					calendarDisplayState = false;

					$(document).unbind('click.' + options.eventsNamespace);
				});

				return false;
			}
		});
		$calendar.click(function(e){e.stopImmediatePropagation();});

		setControls(currentDate);
	}
}(jQuery))