$(function() {

	var _readableDateFormat = "d M, y"
	var _tripType = {
	    one: "oneway",
	    rnd: "roundtrip"
	};
	var _interval;
	
	// Выбор маршрута в один конец
	$("#route .oneway a").click(function(){
		$("#book-to-date").parents(".field").addClass("disabled")
		$("#book-to-date").attr("disabled", "disabled").val("–");
		$("#book-to-time").attr("disabled", "disabled");
		$("#route li").removeClass("current");
		$(this).parent().addClass("current");
		$("#book-type").val(_tripType.one);
		if ($(this).parents("form").find(".icon-route").length > 0) {
			$(this).parents("form").find(".icon-route").removeClass("roundtrip");
		}
		return false;
	});
	
	// Выбор маршрута в оба конца
	$("#route .roundtrip a").click(function(){
		$("#book-to-date").parents(".field").removeClass("disabled")
		offsetToDate();
		$("#book-to-time").removeAttr("disabled");
		$("#route li").removeClass("current");
		$(this).parent().addClass("current");
		$("#book-type").val(_tripType.rnd);
		if ($(this).parents("form").find(".icon-route").length > 0) {
			$(this).parents("form").find(".icon-route").addClass("roundtrip");
		}
		return false;
    });


    // Выбор СЛОЖНОГО маршрута
    $("#route .route a").click(function () {
        $("#book-to-date").parents(".field").removeClass("disabled")
        $("#book-to-date").removeAttr("disabled").datepicker("setDate", $.datepicker.parseDate(_readableDateFormat, $("#book-from-date").val()));
        $("#book-to-time").removeAttr("disabled");
        $("#route li").removeClass("current");
        $(this).parent().addClass("current");
        $("#book-type").val("route");
        if ($(this).parents("form").find(".icon-route").length > 0) {
            $(this).parents("form").find(".icon-route").addClass("roundtrip");
        }
        return false;
    });

    // Отображение/скрытие выпадающих блоков с выбором у "текстовых" полей
    $(".visual").click(function (e) {
        var box = $(this).siblings(".visual-box");
        if (box.is(":visible")) {
            box.hide();
        } else {
            box.show();
        }
        box.click(function (e) {
            e.stopPropagation();
        });
        $('html').click(function (e) {
            box.hide();
            e.stopPropagation();
        });
        return false;
    }).keydown(function () { return false }).bind('contextmenu', function () { return false });

    // Активация/дезактивация выбора аэропорта после выбора страны
    $(".country").change(function () {
        if ($(this).val() != 0) {
            $(this).parents(".visual-box").find(".airport").removeAttr("disabled");
        } else {
            $(this).parents(".visual-box").find(".airport").val(0).attr("disabled", "disabled");
        }
    });
	
	// Подстановка в поле аэропорта и страны после выбора
	$(".airport").change(function() {
		if ($(this).val() != 0) { 
				$(this).parents(".input-container").children(".input").removeClass("fade").removeClass("error").val($(this).parents(".visual-box").find('.country option:selected').html() + ", " + $(this).find('option:selected').html());
				$(this).parents(".input-container").find(":hidden").val($(this).val());
			$(this).parents(".visual-box").hide();
		}
	});

/* Russian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Andrew Stromnov (stromnov@gmail.com). */
$.datepicker.regional['ru'] = {
    closeText: 'Закрыть',
    prevText: '&#x3c;Пред',
    nextText: 'След&#x3e;',
    currentText: 'Сегодня',
    monthNames: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
		'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
    monthNamesShort: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн',
		'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'],
    dayNames: ['воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'],
    dayNamesShort: ['вск', 'пнд', 'втр', 'срд', 'чтв', 'птн', 'сбт'],
    dayNamesMin: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
    weekHeader: 'Не',
    dateFormat: 'dd.mm.yy',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: ''
};
$.datepicker.setDefaults($.datepicker.regional['ru']);
$.datepicker.setDefaults({
    changeMonth: true,
    changeYear: true,
    dateFormat: _readableDateFormat,
    altFormat: "ddmmyy",
    minDate: "0",
    maxDate: "+330"
});

// Привязка блока выбора даты к полям
$("#book-from-date").datepicker({
    altField: "#book_from_date_IATA"
}).keydown(function () { return false }).bind('contextmenu', function () { return false }).change(function () {
    if ($("#book-type").val() == _tripType.rnd) {
        offsetToDate();
    }
});
$("#book-to-date").datepicker({
    altField: "#book_to_date_IATA"
}).keydown(function () { return false }).bind('contextmenu', function () { return false });

// Отображение/скрытие блока выбора даты по клику на иконке
$("#book-from-date-icon, #book-to-date-icon").click(function () {
    var input = $(this).siblings(".input").first();
    if (!input.is(':disabled')) {
        input.datepicker("show");
    }
});

// Активация/дезактивация ценового лимита
$("#book-limit-control").change(function () {
    if ($(this).is(':checked')) {
        $(this).siblings("label, input").removeClass("disabled");
        $("#book-limit").removeAttr('disabled');
    } else {
        $(this).siblings("label, input").addClass("disabled");
        $("#book-limit").attr('disabled', "disabled");
    }
});

// Подстановка в поле краткого перечня пассажиров при выборе
$("#book-psg").siblings(".visual-box").find(".input").change(function () {
    var str = "";
    $("#book-psg").siblings(".visual-box").find(".input").each(function () {
        if ($(this).val() != 0) {
            var cat = "";
            switch ($(this).attr("id")) {
                case "book-psg-adults":
                    cat = "взр.";
                    break;
                case "book-psg-infants":
                    cat = "мла.";
                    break;
                case "book-psg-kids":
                    cat = "дет.";
                    break;
                case "book-psg-youth":
                    cat = "мол.";
                    break;
                case "book-psg-old":
                    cat = "пож.";
                    break;
            }
            str += (str.length > 0) ? " + " + $(this).val() + " " + cat : $(this).val() + " " + cat
        }
    });
    $("#book-psg").val(str);

    validatePassengers();
});

// Последовательная активация/дезактивация полей выбора перевозичков
$("#book-carriers").siblings(".visual-box").find(".input").first().change(function () {
    if ($(this).val() != 0) {
        $(this).parent(".field").next(".field").removeClass("disabled").find(".input").removeAttr("disabled");
    } else {
        $(this).parent(".field").siblings(".field").addClass("disabled").find(".input").val(0).attr("disabled", "disabled");
    }
}).parent(".field").next(".field").find(".input").change(function () {
    if ($(this).val() != 0) {
        $(this).parent(".field").next(".field").removeClass("disabled").find(".input").removeAttr("disabled");
    } else {
        $(this).parent(".field").next(".field").addClass("disabled").find(".input").val(0).attr("disabled", "disabled");
    }
});

// Подстановка в поле краткого перечня перевозчиков при выборе
$("#book-carriers").siblings(".visual-box").find(".input").change(function () {
    var str = "";
    $("#book-carriers").siblings(".visual-box").find(".input:enabled").each(function () {
        if ($(this).val() != 0) str += (str.length > 0) ? " / " + $(this).find(":selected").text() : $(this).find(":selected").text();
    });
    if (str == "") str = $("#book-carriers").siblings(".visual-box").find(".input:enabled").first().find(":selected").text();
    $("#book-carriers").val(str);
});

// Сброс формы в начальное состояние
$("#book-clear").click(function () {
    $(".form .input").removeClass("error");

    $("#direct").removeAttr("checked");

    $("#book_from").val("Город или код аэропорта").addClass("fade");
    $("#book-from-date").datepicker("setDate", "0");
    $("#book-from-time").val(0).attr("selected", "selected");

    $("#book_to").val("Город или код аэропорта").addClass("fade");
    if ($("#book-type").val() == "roundtrip") {
        $("#book-to-date").datepicker("setDate", "0");
        $("#book-to-time").val(0).attr("selected", "selected");
    }
    $("#book-psg").val("1 взр.").siblings(".visual-box").find(".input").val(0);
    $("#book-carriers").val("Любой перевозчик").siblings(".visual-box").find(".input").first().val("").parent(".field").siblings(".field").addClass("disabled").find(".input").val("").attr("disabled", "disabled");
    $("#book-psg-adults").val(1);
    $("#book-class").val(0);
    $("#book-carrier").val(0);
    //$("#book-limit-control").removeAttr("checked").siblings("label").addClass("disabled").siblings(".input").addClass("disabled").attr("disabled", "disabled").val("–");		
});

    
    
    
    // Валидация формы
	$(".form").submit(function() {
		$(this).find(".input").removeClass("error");
		var allowed = true
        
		// Проверка наличия пункта вылета
		if (!$("#book_from").val() || $("#book_from").hasClass("fade")) {
			allowed = false;
			$("#book_from").addClass("error").parents(".input-container").effect("pulsate", {times:3}, 300);
		}
        
        
		// Проверка наличия пункта прилета
		if (!$("#book_to").val() || $("#book_to").hasClass("fade")) {
			allowed = false;
			$("#book_to").addClass("error").parents(".input-container").effect("pulsate", {times:3}, 300);
		}
        
        
		// Проверка совпадения пунктов туда/обратно
		if (!$("#book_from").hasClass("fade") && ($("#book_from").val() == $("#book_to").val())) {
			allowed = false;
			$("#book_to").addClass("error").parents(".input-container").effect("pulsate", {times:3}, 300);
		}
        
       
		// Проверка дат вылета туда/обратно
		if ($("#book-type").val() == "roundtrip" && $.datepicker.parseDate(_readableDateFormat, $("#book-from-date").val()) > $.datepicker.parseDate(_readableDateFormat, $("#book-to-date").val())) {
			allowed = false;
			$("#book-to-date").addClass("error").parents(".input-container").effect("pulsate", {times:3}, 300);
		}

        
		// Проверка количества пассажиров
		if (!validatePassengers()) { 
			allowed = false;
			$("#book-psg").addClass("error").parents(".input-container").effect("pulsate", {times:3}, 300);
		}
		return allowed;
	});

    $("#message-container .cancel").click(function () {
        cancelWait();
    })


	// Валидация количества пассажиров
	function validatePassengers() {
		var correct = true
		msg = ""
		// Проверка кол-ва младенцев
		if (parseInt($("#book-psg-infants").val()) > (parseInt($("#book-psg-adults").val()) + parseInt($("#book-psg-youth").val()) + parseInt($("#book-psg-old").val()))) {
			msg += "Младенцев не должно быть меньше, чем взрослых, молодежи и пожилых в сумме. "
			correct = false;
		}
		// Проверка общего кол-ва
		var sum = 0
		$("#book-psg").siblings(".visual-box").find(".input").each(function() {
			sum += parseInt($(this).val());
		});
		if (sum > 6) {
			msg += "Всего должно быть не более 6 пассажиров. ";
			correct = false;
		}
		// Сигнализация об ошибках
		if (correct) {
			$("#book-psg").removeClass("error");
			$("#book-psg").siblings(".visual-box").find(".error").addClass("hidden");
		} else {
			$("#book-psg").addClass("error");
			$("#book-psg").siblings(".visual-box").find(".error").html(msg).removeClass("hidden");
		}
		return correct;
	}

	// Привязка даты обратного вылета
	function offsetToDate() {
	    var toDate = $.datepicker.parseDate(_readableDateFormat, $("#book-from-date").val());
	    toDate.setDate(toDate.getDate() + 7);
	    $("#book-to-date").removeAttr("disabled").datepicker("setDate", toDate);
	}
});



