Search.Datepicker = function()
{
	this.mouthArrayEng = Array('January','February','March','April','May','June','July','August','September','October','November','December' );
	this.mouthArrayRus = Array('Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь' );
	this.cell_date_from = null;
	this.cell_date_to = null;
	this.todayDate = new Date();
	this.current_year = this.todayDate.getFullYear(); // текущий год
	this.current_month = this.todayDate.getMonth()+1; // текущий месяц
	this.is_calendar_update = false; // 
}
Search.Datepicker.prototype = {
	init: function() {
		var self = this;
		$("div.day-norm").click(function() {
			if ($(this).hasClass("day1") || $(this).hasClass("day2"))
			{
				self.removeSelectDate($(this));
			} else {
				self.addSelectDate($(this));
			}
		});
		$("div.cal-left").click(function() {
			self.leftMonth();
		});
		$("div.cal-right").click(function() {
			self.rightMonth();
		});
	},
	getCellDate: function(date_string) {
		if (date_string == null || date_string == "") return null;
		var date = new Date();
		date.parseDate(date_string);
		return date;
	},
	leftYear: function() {
		this.current_year-=1;
	},
	rightYear: function() {
		this.current_year+=1;
	},
	leftMonth: function() {
		this.is_calendar_update = true;
		this.current_month-=1;
		if (this.current_month <= 0) {
			this.current_month = 12;
			this.leftYear();
		}
		this.redrawCalendar();
	},
	rightMonth: function() {
		this.is_calendar_update = true;
		this.current_month+=1;
		if (this.current_month > 12) {
			this.current_month = 1;
			this.rightYear();
		}
		this.redrawCalendar();
	},
	createSelectPeriod: function() {
		//alert(Search.Params.date_from + "/" + Search.Params.date_to);
		for(var i=0; i<35;i++) {
			var cell = $("div#cell_" + i);
			var date = this.getCellDate(cell.attr("title"));
			cell.removeClass("between");
			if (Search.Params.date_from != null && Search.Params.date_to != null && date > Search.Params.date_from && date < Search.Params.date_to) {
				cell.addClass("between");
			}
		}	
	},
	//создать ячейку в календаре
	createCell: function(id, date) {
		var currentDate = new Date();
		var cell = $("div#cell_" + id);
		cell.removeClass();
		if (currentDate.format("yyyymmdd") == date.format("yyyymmdd")) cell.addClass("day-norm day-curr");
		else if (date.format("m") == this.current_month) cell.addClass("day-norm");
		else cell.addClass("day-norm other-month");
		cell.empty();
		cell.html(date.format("dd"));
		cell.attr('title', date.format("dd.mm.yyyy"));
		if (Search.Params.date_from != null && date.format("yyyymmdd") == Search.Params.date_from.format("yyyymmdd")) {
			this.createDirection(cell, date, "day1");
		}
		if (Search.Params.date_to != null && date.format("yyyymmdd") == Search.Params.date_to.format("yyyymmdd")) {
			this.createDirection(cell, date, "day2");
		}
	},
	//перерисовать календарь
	redrawCalendar: function() {
		// при перерсовки календаря необходимо обнулить выбранные ячейки так как в новом месяце ячейки уже будут иметь новые даты
		this.cell_date_from = null; // обнуляем выбранные ячейки
		this.cell_date_to = null; // обнуляем выбранные ячейки
		//
		if (this.is_calendar_update) { // если изменили календарь
			var day = 1;
			var date = new Date(this.mouthArrayEng[this.current_month-1]+", "+day+", "+this.current_year);
		} else {
			var date = new Date();
			date.parseDate(this.todayDate.format("dd.mm.yyyy"));
		}
		// корректируем дату
		var dayOfWeekCorrect = date.getDay();
		if (dayOfWeekCorrect == 0) dayOfWeekCorrect = 7;
		date.removeDay(dayOfWeekCorrect-1);
		$("td.cal-tc").html(this.mouthArrayRus[this.current_month-1] + " " + this.current_year);		
		
		for(var i=0; i<35;i++)
		{
			this.createCell(i, date)
			date.addDay(1);
		}
		this.createSelectPeriod(); // добавить выделение
	},
	// Выделить ячейку добавив направление
	createDirection: function(cell, date, style) {
		if (style == "day1" && Search.Params.date_to != null)
		{
			if (date.getTime() > Search.Params.date_to.getTime()) {
				if (this.cell_date_to != null) this.removeSelectDate(this.cell_date_to); // удаляем выделение ячейки
			}
		} else if (style == "day2" && Search.Params.date_from != null) {
			if (Search.Params.date_from.getTime() > date.getTime()) {
				if (this.cell_date_from != null) this.removeSelectDate(this.cell_date_from); // удаляем выделение ячейки
				style = "day1";
			}
		}
		// если необходимо удалить уже выбранную ячейку
		if (style == "day1" && Search.Params.date_from != null) {
			if (Search.Params.date_from.getTime() != date.getTime() && this.cell_date_from != null) this.removeSelectDate(this.cell_date_from);
		}
		if (style == "day2" && Search.Params.date_to != null) {
			if (Search.Params.date_to.getTime() != date.getTime() && this.cell_date_to != null) this.removeSelectDate(this.cell_date_to);
		}
		var number = cell.html();
		cell.empty();
		cell.removeClass();
		cell.addClass(style);
		var date_direction = $('<div/>').attr('class','date-direction');
		date_direction.html(number);
		date_direction.appendTo(cell);
		// сохраняем значения
		if (style == "day1") {
			if (Search.Params.city_from != null && Search.Params.city_to != null) $('<div class="directions"><span>' + Search.Params.city_from + '</span><span class="arr">→</span><span>' + Search.Params.city_to + '</span></div>').appendTo(cell);
			if (Search.Params.date_from == null) Search.Params.date_from = new Date();
			Search.Params.date_from.setTime(date.getTime());
			this.cell_date_from = cell;
		} else {
			if (Search.Params.city_from != null && Search.Params.city_to != null) $('<div class="directions"><span>' + Search.Params.city_to + '</span><span class="arr">→</span><span>' + Search.Params.city_from + '</span></div>').appendTo(cell);
			if (Search.Params.date_to == null) Search.Params.date_to = new Date();
			Search.Params.date_to.setTime(date.getTime());
			this.cell_date_to = cell;
		}	
	},
	// Убираем выделение ячейки
	removeSelectDate: function(cell) {
		var number = cell.find(".date-direction").html();
		var title = cell.attr("title");
		var date = this.getCellDate(title);
		//
		if (Search.Params.date_from != null && date.getTime() == Search.Params.date_from.getTime()) Search.Params.date_from = null;
		if (Search.Params.date_to != null && date.getTime() == Search.Params.date_to.getTime()) Search.Params.date_to = null;
		//
		cell.removeClass();
		if (this.todayDate.format("yyyymmdd") == date.format("yyyymmdd")) {
			cell.addClass("day-norm day-curr");
		} else if (date.format("m") == this.current_month) {
			cell.addClass("day-norm");
		} else {
			cell.addClass("day-norm other-month");
		}
		cell.empty();
		cell.html(number);
		this.createSelectPeriod(); // добавить выделение
	},
	removeSelectDateFrom: function() {
		if (this.cell_date_from != null) this.removeSelectDate(this.cell_date_from);
	},
	removeSelectDateTo: function() {
		if (this.cell_date_to != null) this.removeSelectDate(this.cell_date_to);
	},
	// добавляем выделение ячейки
	addSelectDate: function(cell) {
		var title = cell.attr("title");
		var date = this.getCellDate(title);
		var date_restriction = new Date();
		date_restriction.parseDate(this.todayDate.format("dd.mm.yyyy"));
		date_restriction.addDay(2); // добавляем дни так как бронирование не может быть менее чем за 2-ое суток
		if (date_restriction.format("yyyymmdd") > date.format("yyyymmdd")) return; // нельзя установить дату в календаре меньше текущей
		if (!Search.Params.is_flight_back) {
			this.createDirection(cell, date, "day1");	
		} else {
			if (Search.Params.date_from == null) {
				this.createDirection(cell, date, "day1");
			} else {
				this.createDirection(cell, date, "day2");
			}
		}
		this.createSelectPeriod(); // добавить выделение
	}
}
