$(document).ready(function() {
	init_calendar();
	update_calendar();
	$("#param").click(function() {
		$("#parameters").dialog(
			{
				title:"Выберите",
				width:600,
				resizable:false,
				buttons:[
					{
						text:"Готово",
						click: function() {
							$(this).dialog("close");
						}
					}],
				open: function(event, ui) {
					$("#parameters input").blur();
				},
				close: function(event, ui) {
					update_parameters_info();
				}
			});
	});
	$(".radioset").buttonset();
	$(".radioset input").click(function() {
		if ($("input[name='routetype']:checked").val() == "ONE_WAY") {
			back_date.setTime(0);
			mouse_date.setTime(0);
		}
		update_calendar();
	});
	$('#waypoints input').autocomplete({
			source: "locations.php",
			minLength: 0,
		focus: function(event, ui) {
			return false;
		},
		select: function(event, ui) {
			$(this)
			.val(ui.item.label)
			.attr("title", ui.item.value);
			return false;
		}
		}).click(function(){
			$(this)
			.val("")
			.attr("title", "")
			.autocomplete("search");
		});
	$("#destination_point").focus();
});

var months = ["январь", "февраль", "март", "апрель", "май", "июнь", "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь"];
var months2 = ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"];
var today_date = new Date();
var first_date = new Date(today_date.getMonth(), 1, today_date.getFullYear());
var departure_date = new Date(0);
var back_date = new Date(0);
var mouse_date = new Date(0);
var day1 = 24*60*60*1000;

today_date = new Date(today_date.getFullYear(), today_date.getMonth(), today_date.getDate(), 0, 0, 0, 0);
first_date.setTime(today_date.getTime()-day1*Math.ceil((today_date.getDay()+6)%7));
//departure_date.setTime(today_date.getTime()+day1);
//back_date.setTime(today_date.getTime()+day1*18);

function roll(val) {
	first_date.setMonth(first_date.getMonth()+val);
	first_date.setDate(1);
	update_calendar();
	return false;
}

function submit_form() {
	// setup form
	$('[name="FlightSearchForm.adults"]').val($("#parameters input[name='adults']:checked").val());
	$('[name="FlightSearchForm.children"]').val($("#parameters input[name='children']:checked").val());
	$('[name="FlightSearchForm.infants"]').val($("#parameters input[name='infants']:checked").val());
	$('[name="FlightSearchForm.serviceClass"]').val($("#parameters input[name='flightclass']:checked").val());
	$('[name="FlightSearchForm.departureLocation.0"]').val($("#departure_point").val());
	$('[name="FlightSearchForm.departureLocation.0.CODE"]').val($("#departure_point").attr("title"));
	$('[name="FlightSearchForm.arrivalLocation.0"]').val($("#destination_point").val());
	$('[name="FlightSearchForm.arrivalLocation.0.CODE"]').val($("#destination_point").attr("title"));
	$('[name="FlightSearchForm.date.0"]').val(departure_date.getDate()+"."+(departure_date.getMonth()+1)+"."+departure_date.getFullYear());
	$('[name="FlightSearchForm.date.1"]').val(back_date.getDate()+"."+(back_date.getMonth()+1)+"."+back_date.getFullYear());
	$('[name="FlightSearchForm.routeType"]').val($("input[name='routetype']:checked").val());
	$("form").submit();
	return false;
}

function init_calendar() {
	$("#cells td")
		.click(function() {
			var routetype = $("input[name='routetype']:checked").val();
			var this_time = $(this).data("date");
			if (!departure_date.getTime() || (routetype=="ONE_WAY")) {
				if (this_time>=today_date.getTime()) {
					departure_date.setTime(this_time);
				}
			} else if (back_date.getTime()==this_time) {
				back_date.setTime(0);
			} else if (this_time==departure_date.getTime()) {
				if (back_date.getTime()) {
					back_date.setTime(this_time);
					mouse_date.setTime(this_time);
				} else if (this_time!=back_date.getTime) {
					departure_date.setTime(0);
					back_date.setTime(0);
					mouse_date.setTime(0);
				}
			} else if ((this_time>=today_date.getTime()) && (this_time>=departure_date.getTime())) {
				back_date.setTime(this_time);
				mouse_date.setTime(this_time);
			}
			update_calendar();
		})
		.mouseenter(function() {
			if (!back_date.getTime()) {
				mouse_date.setTime($(this).data("date"));
				update_calendar();
			}
		});
	roll(0);
}
                                
function update_cells() {
	var date = new Date(first_date.getTime());
	while (date.getDay() != 1) {
		date.setTime(date.getTime()-day1);
	}
	var type = $("input[name='routetype']:checked").val();
	$.each($("#cells td"), function(key, value) {
		var td = $(value);
		td.html(date.getDate());
		td.data("date", date.getTime());
		if ((key==0) || (date.getDate()==1) || (date.getTime() == today_date.getTime()) || (date.getTime()==departure_date.getTime()) || (date.getTime()==back_date.getTime())) {
			td.append($("<span/>").html(months2[date.getMonth()]));
		}
		td.toggleClass("month", (date.getMonth()==first_date.getMonth()));
		td.toggleClass("holiday", (date.getDay()==0) || (date.getDay()==6));
		td.toggleClass("today", date.getTime()==today_date.getTime());
		td.toggleClass("departure", date.getTime()==departure_date.getTime());
		td.toggleClass("back", date.getTime()==back_date.getTime());
		td.toggleClass("selected", (type == "ROUND_TRIP") && (departure_date.getTime()>0) && (date.getTime()>departure_date.getTime()) && (date.getTime()<=mouse_date.getTime()));
		date.setTime(date.getTime()+day1);
	});
}

function update_months() {
	var date = new Date(first_date.getTime());
	date.setMonth(date.getMonth()-2);
	$.each($("#calendar .header .month ul li"), function(key, value) {
		var child = $(value).children().get(0);
		if (child.nodeName.toLowerCase()=="a") {
			$(child).html(months[date.getMonth()]);
		} else {
			$(child).html(months[date.getMonth()]+" "+date.getFullYear());
		}

		date.setMonth(date.getMonth()+1);
	});
}

function update_parameters_info() {
	var adults = $("#parameters input[name='adults']:checked").prop("title");
	var children = $("#parameters input[name='children']:checked").prop("title");
	var infants = $("#parameters input[name='infants']:checked").prop("title");
	var flightclass = $("#parameters input[name='flightclass']:checked").prop("title");
	var items = [];
	if ((adults) && (adults != "")) { items.push(adults); }
	if ((children) && (children != "")) { items.push(children); }
	if ((infants) && (infants != "")) { items.push(infants); }
	var passengers_info = items.join(", ");
	$("#passengers_info").html(passengers_info);
	$("#class_info").html(flightclass);
}

function update_calendar() {
	update_months();
	update_cells();
	update_parameters_info();
}

