$(document).ready(function() {
    //Изменения АП вылета
    $("select[name=tours_from_id]").change(function() {
        tours_from_id_change($(this));
    });
    //Изменения АП прилёта
    $("select[name=tours_to_id]").change(function(event) {
        tours_to_id_change($(this));
    });

    var minDate = new Date();
    minDate.setDate(new Date().getDate());

    $("input[name=tours_date_from]").prop("disabled", 1);
    $("input[name=tours_date_to]").prop("disabled", 1);

    //Календарь с датами вылета
    $avalible_tours_dates_from_arr = new Array();
    $('input[name=tours_date_from]').daterangepicker({
        "autoUpdateInput": false,
        "singleDatePicker": true,
        "minDate": minDate,
        "autoApply": true,
        "linkedCalendars": true,
        "isInvalidDate": function(date) {
            $curr_date = date.format('DD.MM.YYYY');
            if ($.inArray($curr_date, $avalible_tours_dates_from_arr) == -1) {
                return "false";
            }
        }

    });
    $('input[name=tours_date_from]').on('apply.daterangepicker', function(ev, picker) {
        $(this).val(picker.startDate.format('DD.MM.YYYY'));
    });
    $('input[name=tours_date_from]').on('cancel.daterangepicker', function(ev, picker) {
        $(this).val('');
    });

    //Календарь с датами возврата
    $avalible_tours_dates_to_arr = new Array();
    $('input[name=tours_date_to]').daterangepicker({
        "autoUpdateInput": false,
        "singleDatePicker": true,
        "autoApply": true,
        "linkedCalendars": true,
        "isInvalidDate": function(date) {
            $curr_date = date.format('DD.MM.YYYY');
            if ($.inArray($curr_date, $avalible_tours_dates_to_arr) == -1) {
                return "false";
            }
        }

    });
    $('input[name=tours_date_to]').on('apply.daterangepicker', function(ev, picker) {
        $(this).val(picker.startDate.format('DD.MM.YYYY'));
    });
    $('input[name=tours_date_to]').on('cancel.daterangepicker', function(ev, picker) {
        $(this).val('');
    });

});

//Поиск туров
function tours_search() {
    $obj = $("select[name=tours_from_id]");
    tours_from_id_change($obj);
    //Загрузка фильтров
    $postdata = {
        "action" : "get_tours_left",
        "query_string" : $("input[name=query_string]").val()
    };
    $.post("/include/tours_search.php", $postdata, function(data) {
        $(".tours .left_filter").html(data);

        //Форма поиска отеля
        $(".search_hotel_field").keyup(function() {
            $value = $(this).val().toLowerCase();
            if ($value != "") {
                $(".item_hotel").hide();
                $(".item_hotel[name*='"+$value+"']").fadeIn("fast");
            } else {
                $(".item_hotel").fadeIn("fast");
            }
        });
        //Разкрытие фильтров
        $('.hotel_list .title').click(function() {
            if ($(this).next().is(":visible")) {
                $(this).next().slideUp("fast");
                $(this).find(".img").css("transform", "rotate(180deg)");
            } else {
                $(this).next().slideDown("fast");
                $(this).find(".img").css("transform", "rotate(0deg)");
            }
        });
        //Фильтр по звёздам отеля
        $(".star_item").click(function() {
            $(this).toggleClass("active");
            $str = "";
            $(".star_item").each(function() {
                if ($(this).hasClass("active")) {
                    $str += $(this).attr("value") + ",";
                }
            });
            $("input[name=stars]").val($str);

            if ($(window).width() > 768) {
                document.tours_search_form.submit();
            }
        });


        //Выбранные чекбксы помещаем в начало списка
        $("input[name^=hotel]:checked").each(function() {
            $obj = $(this).parent();
            $obj.hide();
            $obj.parent().prepend($obj);
            $obj.fadeIn("slow");
        });

        //Поиск по цене
        $("input[name=price_from], input[name=price_to]").keypress(function(e) {
            if(e.which == 13) {
                document.tours_search_form.submit();
            }
        });


        $(".reset_form").click(function() {
            document.tours_top_form.submit();
        });
        //Кастомизация select
        nice_select_ajax();

    });

    //Загрузка результатов поиска
    $postdata = {
        "action" : "get_tours_right",
        "query_string" : $("input[name=query_string]").val(),
        "town_from_name" : $("input[name=town_from_name]").val()
    };
    $(".tours .right_result").html("<div class='tours_loader'></div>");
    $.post("/include/tours_search.php", $postdata, function(data) {
        $(".tours .right_result").html(data);

        //Заявка на тур
        $(".btn_tours_order").click(function() {
            $order_data = $(this).attr("order_data");
            $agent_id = $(this).attr("agent_id");
            $lang = $(this).attr("lang");
            $site_state = $(this).attr("site_state");
            $.fancybox.open({
                src  : "/popup/order_tour.php?lang="+$lang+"&site_state="+$site_state+"&"+$order_data+"&agent_id="+$agent_id,
                type : "ajax"
            });
        });

        //Фильтры
        $(".mobile_filter .filter").click(function() {
            if ($(this).hasClass("open")) {
                $(".hotel_list .td.left_filter").hide();
                $(this).removeClass("open");
                $("#mobile_filter_submit").hide();
            } else {
                $(".hotel_list .td.left_filter").slideDown(300);
                $(this).addClass("open");
                $("#mobile_filter_submit").fadeIn("fast");
            }
        });
        //Карта
        $(".mobile_filter .map").click(function() {
            if ($(this).hasClass("open")) {
                $(".hotel_list .result_list .td.right").hide();
                $(this).removeClass("open");
            } else {
                $(".hotel_list .result_list .td.right").slideDown(300);
                $(this).addClass("open");
            }
        });

    });
}

//Фильтры для результатов поиска
function tours_search_form_submit() {
    if ($(window).width() > 768) {
        document.tours_search_form.submit();
    }
}

//Изменения АП вылета
function tours_from_id_change($obj) {
    //Так как формы поиска на главной 2 - устнавливаем во все
    $val = $obj.find("option:selected").val();
    $("select[name=tours_from_id]").val($val);

    $postdata = {
        "action" : "get_town_to",
        "tours_from_id" : $val,
        "tours_to_id" : $("input[name=tours_to_id]").val()
    };
    $.post("/include/ajax_search_form.php", $postdata, function(data) {
        $("select[name=tours_to_id]").html(data);
        $("select[name=tours_to_id]").trigger("chosen:updated");
        $obj = $("select[name=tours_to_id]");
        tours_to_id_change($obj);
    });

    //Сохраняем ID города в куку
    var expiry = 60; //дней жизки куки
    var expires = new Date();
    expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
    document.cookie = 'tours_from_id=' + $val + ';path=/' + ';expires=' + expires.toUTCString();

}
//Изменилось поле куда
function tours_to_id_change($obj) {
    //Так как формы поиска на главной 2 - устнавливаем во все
    $val = $obj.find("option:selected").val();
    $("select[name=tours_to_id]").val($val);
    $("input[name=tours_to_id]").val($val);

    //Загрузка дат туда
    $postdata = {
        "action" : "get_dates_from",
        "tours_from_id" : $("select[name=tours_from_id] option:selected").val(),
        "tours_to_id" : $obj.find("option:selected").val()
    };
    $.post("/include/ajax_search_form.php", $postdata, function(data) {
        $avalible_tours_dates_from_arr = data.from_arr.split(",");
        $avalible_tours_dates_to_arr = data.to_arr.split(",");
        $("input[name=tours_date_from]").prop("disabled", 0);
        $("input[name=tours_date_to]").prop("disabled", 0);
    }, "json");

    //Загрузка дат обратно
    $postdata = {
        "action" : "get_dates_to",
        "tours_from_id" : $("select[name=tours_from_id] option:selected").val(),
        "tours_to_id" : $("select[name=tours_to_id] option:selected").val()
    };
    $.post("/include/ajax_search_form.php", $postdata, function(data) {
        $avalible_dates_to_arr = data.split(",");
    });

}