$(document).ready(function() {

    //Для лендига показать/скрыть описание отеля
    $(".show_hotel_info_landing").click(function() {
        if ($(this).hasClass("open")) {
            $(".hotel_descr").css("height", "100px");
            $(this).html("показать полное описание отеля");
            $(this).removeClass("open");
            $("html, body").animate({ scrollTop: 600}, 600);
        } else {
            $(".hotel_descr").css("height", "auto");
            $(this).addClass("open");
            $(this).html("скрыть полное описание отеля");
        }
    });
	

//--------------------Для страницы следить за ценой---------------------------
    $(".all_chkb").click(function() {
        if ($(this).prop("checked")) {
            $(this).parent().next().hide("fast");
        } else {
            $(this).parent().next().show("fast");
        }
    });
    //Изменили страну - загрузка полей формы
    $("select[name=track_geo_id]").change(function() {
        $geo_id = $(this).val();
        $selected_city_id = 1544;
        //Загрузка городов вылета
        otpusk_get_city($geo_id, $selected_city_id);
        //Загрузка бюджета
        $postdata = {
            "action" : "track_budget",
            "geo_id" : $geo_id
        };
        $("select[name=track_budget]").css("background-image", "url('/img/ico_load.gif')");
        $.post("/autocomplete.php", $postdata, function(data) {
            $("select[name=track_budget]").css("background-image", "url('/img/wallet.svg')");
            $("select[name=track_budget]").html(data);
        });
        //Загрузка регионов
        $postdata = {
            "action" : "track_regions",
            "geo_id" : $geo_id,
            "lang" : $("input[name=lang]").val()
        };
        $.post("/autocomplete.php", $postdata, function(data) {
            $("#track_price_regions").html(data);
            update_hotels_list_track_price();
        });

    });
    //Изменили регион - загрузка отелей
    $("select[name=track_regions]").change(function() {
        update_hotels_list_track_price();
    });
    //Изменили категорию - загрузка отелей
    $("input[name=hotel_category\\[\\]").click(function() {
        update_hotels_list_track_price();
    });

    $(".all_dates").change(function() {
        $(".tr_body").hide();
        if ($(this).val() != "") {
            $("td.tour_date:contains('"+$(this).val()+"')").parent().fadeIn();
        } else {
            $(".tr_body").fadeIn();
        }
        if ($(".all_nights option:selected").val() != "") {
            $("td.tour_nights").not(":contains('"+$(".all_nights option:selected").val()+"')").parent().hide();
        }

    });
    $(".all_nights").change(function() {
        $(".tr_body").hide();
        if ($(this).val() != "") {
            $("td.tour_nights:contains('"+$(this).val()+"')").parent().fadeIn();
        } else {
            $(".tr_body").fadeIn();
        }
        if ($(".all_dates option:selected").val() != "") {
            $("td.tour_date").not(":contains('"+$(".all_dates option:selected").val()+"')").parent().hide();
        }
    });

//--------------------//Для страницы следить за ценой---------------------------


    //Выпдающие другие номера телефона
    $(".menu .tel").hover(function() {
        $("#dop_tel").fadeIn("fast");
    }, function() {
        $("#dop_tel").fadeOut("fast");
    });

    //Показать полный отзыв
    $(".show_full_comment").click(function() {
        $(this).parent().prev().css("height", "auto");
        $(this).hide();
    });

    //Переводрот блока при нажатии
    $(".block_back").click(function() {
        if (!$(this).find(".back").is(":visible")) {
            //Прячем все открытые
            $(".block_back").not(this).find(".back").hide();
            $(".block_back").not(this).find(".plashka, .descr_bottom, .title").show();
            $(".block_back").not(this).find(".wrapper").css("background-color", "rgba(0,0,0,0)");

            //Загрузка городов отправления
            if ($(this).attr("selected_city_id")) {
                $selected_city_id = $(this).attr("selected_city_id");
            } else {
                $selected_city_id = "1544";
            }
            otpusk_get_city($(this).attr("geo_id"), $selected_city_id);

            $obj = $(this);
            $obj.find(".plashka, .descr_bottom").hide();
            if ($(this).attr("hide_name") == 1) {
                $obj.find(".title").hide();
            }
            $obj.find(".back").fadeIn(900);
            $obj.find(".wrapper").css("background-color", "rgba(0,0,0,0.8)");
        }
    });


    //Календарь выбора дат для основной формы поиска
    moment.locale('ru');
    //Календарь выбора дат для форм поиска в блоках
    moment.updateLocale('ru', {
        longDateFormat : {
            L: "DD.MM.YYYY"
        }
    });
    $('.date_search_main').daterangepicker({
        "maxSpan": {
            "days": 7
        },
        "autoApply": true,
        "linkedCalendars": true
    });
    //Обычный календарь для формы СЛЕДИТЬ ЗА ЦЕНОЙ
    $('.singleDatePicker').daterangepicker({
        singleDatePicker: true,
        showDropdowns: true
    });
    //Календарь выбора дат для форм поиска в блоках
    moment.updateLocale('ru', {
        longDateFormat : {
            L: "DD.MM.YY"
        }
    });
    $('.date_search_block').daterangepicker({
        "maxSpan": {
            "days": 7
        },
        "autoApply": true,
        "linkedCalendars": true
    });

    if (!isTouchDevice()) {
        //Всплывающее окно при наведении
        $('.tip').poshytip({
            className: 'tip-twitter',
            showTimeout: 1,
            alignTo: 'target',
            alignX: 'center',
            offsetY: 5,
            keepInViewport : true,
            fade: false,
            slide: false
        });
    }
    //Окно выбора кол-ва туристов
    $(".inp_t_person").click(function() {
        $obj_input = $(this);
        $person_picker = $(".person_picker").clone();
        $obj_input.after($person_picker);
        $person_picker.show();

        //Получаем занчения из поля формы
        var childs = $obj_input.attr("childs");
        if (childs != "") {
            $childs = childs.split(","); // массив с возрастами
        } else {
            $childs = [];
        }
        $adults = $obj_input.attr("adults");

        //Устанавливаем занчения в picker
        $person_picker.find(".digit[type=adults]").attr("value", $adults);
        $person_picker.find(".digit[type=adults]").html($adults);
        if ($childs != "") {
            $person_picker.find(".digit[type=childs]").attr("value", $childs.length);
            $person_picker.find(".digit[type=childs]").html($childs.length);
        } else {
            $person_picker.find(".digit[type=childs]").attr("value", 0);
            $person_picker.find(".digit[type=childs]").html(0);
        }
        //Отображаем и зполняем поля для ввода возраста
        if ($childs != "") {
            $person_picker.find(".child_div.child"+$childs.length).fadeIn("fast");
            $.each($childs, function($key, $value) {
                $person_picker.find(".select_age_"+($key+1)).val($value);
            });
        }
        //Увеличиваем или уменьшаем туристов
        $(".sight").click(function() {
            $type = $(this).attr("type");
            $action = $(this).attr("action");
            if ($type == "adults") {
                $adults = parseInt($adults);
                if ($action == "minus") {
                    if (($adults > 1)) {
                        $adults--;
                    }
                }
                if ($action == "plus") {
                    if (($adults <= 3)) {
                        $adults++;
                    }
                }
                //Устанавливаем занчения в picker
                $person_picker.find(".digit[type=adults]").attr("value", $adults);
                $person_picker.find(".digit[type=adults]").html($adults);
                //Устанавливаем занчения в input
                $obj_input.attr("adults", $adults);
            }
            if ($type == "childs") {
                if ($action == "minus") {
                    if (($childs.length > 0)) {
                        $childs.splice(-1);
                    }
                }
                if ($action == "plus") {
                    if (($childs.length < 3)) {
                        $childs[$childs.length] = 6;
                    }
                }

                //Устанавливаем занчения в picker
                $person_picker.find(".digit[type=childs]").attr("value", $childs.length);
                $person_picker.find(".digit[type=childs]").html($childs.length);
                //Устанавливаем занчения в input
                $obj_input.attr("childs", $childs.join(","));
                //Уставливаем значение в hidden
                $("input[name=ages]").val($childs.join(","));

                //Отображаем и зполняем поля для ввода возраста
                $person_picker.find(".child_div").hide();
                $person_picker.find(".child_div.child"+$childs.length).fadeIn("fast");
                if ($childs != "") {
                    $.each($childs, function($key, $value) {
                        $person_picker.find(".select_age_"+($key+1)).val($value);
                    });
                }
            }
            make_age_str($obj_input);
        });

        //Изменяем возвраст детей
        $(".select_age").change(function() {
            $child_number = $(this).attr("child_number");
            $new_age = $(this).val();
            //Меняем данные в массиве
            $.each($childs, function($key, $value) {
                if (($key+1) == $child_number) {
                    $childs[$key] = $new_age;
                }
            });
            //Устанавливаем занчения в input
            $obj_input.attr("childs", $childs.join(","));
            //Уставливаем значение в hidden
            $("input[name=ages]").val($childs.join(","));
        });

        //Закрываем person_picker
        $(document).mouseup(function (e) { // событие клика куда либо
            if ($person_picker.has(e.target).length === 0) {
                $person_picker.remove();
            }
        });

        //Увеличиваем или уменьшаем туристов
        $(".person_picker_close").click(function() {
            $person_picker.remove();
        });

    });


    //Фиксированная шапка на главной
    $(window).scroll(function() {
        if ($("#scroll_controll").val() != "deny") {
            if (screen.width > 500) {
                $("#close_extra_fields").trigger("click");
            }
            if ($(this).scrollTop() > top_scroll) {
                $('.header').addClass("fixed");
                $('.header .search').addClass("show");
                $(".autocomplete").html("");
                $(".next_main_page").fadeOut("fast");
                //Для всех страниц кроме главной
                if (top_scroll == 180) {
                    $('.body').addClass("fixed");
                //Только для главной
                } else {
                    $(".logo").removeClass("hide");
                }
            } else {
                $('.header').removeClass("fixed");
                $('.header .search').removeClass("show");
                $('.body').removeClass("fixed");
                //Для всех страниц кроме главной
                if (top_scroll == 180) {

                //Только для главной
                } else {
                    $(".logo").addClass("hide");
                }
            }
        }
    });

    //Фильтр при выборе ночей
    $("select[name=night_from]").change(function() {
        $night_from = parseInt($("select[name=night_from]").val());
        $night_to = parseInt($("select[name=night_to]").val());
        if ($night_to < $night_from) {
            $("select[name=night_to]").val($night_from);
        }
        $("select[name=night_to] option").each(function() {
            if (parseInt($(this).val()) < $night_from) {
                $(this).prop("disabled", 1);
            } else {
                $(this).prop("disabled", 0);
            }
            if (parseInt($(this).val()) > ($night_from+7)) {
                $(this).prop("disabled", 1);
            } else {
                $(this).prop("disabled", 0);
            }
        })
    });
    $("select[name=night_to]").change(function() {
        $night_from = parseInt($("select[name=night_from]").val());
        $night_to = parseInt($("select[name=night_to]").val());
        if ($night_from > $night_to) {
            $("select[name=night_from]").val($night_to);
        }
    });



    //Боковое выдвигающееся меню
    $(".menu .menu").click(function() {
        if (!$(".slide_menu").is(":visible")) {
            $(".slide_menu").toggle("slide");
        }
    });
    $(".slide_menu").mouseleave(function() {
        if ($(".slide_menu").is(":visible")) {
            $(".slide_menu").toggle("slide");
        }
    });
    $("#slide_menu_close").click(function() {
        if ($(".slide_menu").is(":visible")) {
            $(".slide_menu").toggle("slide");
        }
    });

    //Выпадающий курс валют
    $(".menu .curr").click(function() {
        if (!$(".curr_menu").is(":visible")) {
            $(".curr_menu").slideDown("fast");
            $(".menu .curr").addClass("curr_open");
        } else {
            $(".curr_menu").slideUp("fast");
            $(".menu .curr").removeClass("curr_open");
        }
    });


    //Отображение дополнительных полей поиска. Нажали на поле поиска в шапке
    $(".inp_t_search").click(function() {
        $("#extra_fields").fadeIn("fast");
        $("#extra_fields").css("display", "table");

        //Короткая строка поиска
        $str = $("input[name=short_str]").val();
        $(".main_str").val($str);
    });

    //Закрытие дополнительных полей поиск
    $("#close_extra_fields").click(function() {
        $("#extra_fields").fadeOut("fast");

        //Полная строка со всеми параметрами поиска
        $str = $("input[name=full_str]").val();
        $(".main_str").val($str);
    });

    //Автоподсказки для поиска
    $(".main_str").keyup(function() {
        $obj = $(this);
        $str = $(this).val();
        $postdata = {
            "action" : "autocomplete",
            "str" : $str,
            "lang" : $("input[name=lang]").val()
        };
        $(this).css("background-image", "url('/img/ico_load.gif')");
        $(".autocomplete ul").hide();
        $.post("/autocomplete.php", $postdata, function(data) {
            $obj.next().html(data);
            $obj.next().find("ul").fadeIn(100);
            $obj.css("background-image", "url('/img/ico_search.png')");

            //Нажали на строку в autocomplete
            $obj.next().find("ul li").click(function() {
                $str = $(this).attr("str");
                $geo_id = $(this).attr("geo_id");
                if ($postdata.lang == "ua") {
                    $url = "/ua/results?str="+$str+"&geo_id="+$geo_id;
                } else {
                    $url = "/results?str="+$str+"&geo_id="+$geo_id;
                }
                //Дополнительноые поля поиска
                if ($("input[name=date]").val() != "") {
                    $url += "&date="+$("input[name=date]").val();
                }
                if ($("select[name=night_from]").val() != "") {
                    $url += "&night_from="+$("select[name=night_from]").val();
                }
                if ($("select[name=night_to]").val() != "") {
                    $url += "&night_to="+$("select[name=night_to]").val();
                }
                if ($("select[name=city]").val() != "") {
                    $url += "&city="+$("select[name=city]").val();
                }
                if ($("input[name=person_str]").val() != "") {
                    $url += "&person_str="+$("input[name=person_str]").val();
                }
                if ($("input[name=ages]").val() != "") {
                    $url += "&ages="+$("input[name=ages]").val();
                }
                document.location = $url;
            });

            //Закрываем autocomplete
            $(document).mouseup(function (e) { // событие клика куда либо
                if ($(".autocomplete").has(e.target).length === 0) {
                    $(".autocomplete").html("");
                }
            });

        });
    });
    //Автоподсказки для FAQ
    $(".inp_t_faq").keyup(function() {
        $obj = $(this);
        $str = $(this).val();
        $postdata = {
            "action" : "autocomplete_faq",
            "str" : $str,
            "lang" : $("input[name=lang]").val()
        };
        $(this).css("background-image", "url('/img/ico_load.gif')");
        $(".autocomplete ul").hide();
        $.post("/autocomplete.php", $postdata, function(data) {
            $obj.next().html(data);
            $obj.next().find("ul").fadeIn(100);
            $obj.css("background-image", "url('/img/ico_search.png')");

            //Нажали на строку в autocomplete
            $obj.next().find("ul li").click(function() {
                $faq_id = $(this).attr("faq_id");
                $url = "/faq?faq_id="+$faq_id;
                document.location = $url;
            });

            //Закрываем autocomplete
            $(document).mouseup(function (e) { // событие клика куда либо
                if ($(".autocomplete").has(e.target).length === 0) {
                    $(".autocomplete").html("");
                }
            });

        });
    });


    //Показать/скрыть полное описание отеля (страница горящих туров в отель)
    $(".hot_tours_descr_hotel").click(function() {
        $(this).toggleClass("up");
        if ($(this).hasClass("up")) {
            $(".hotel_descr").toggleClass("full");
            $(this).html("скрыть полное описание отеля");
        } else {
            $(".hotel_descr").toggleClass("full");
            $(this).html("показать полное описание отеля");
            $("html, body").animate({ scrollTop: 0}, 600);
        }
    });
    //Показываем отзывы в всплывающем окне (страница горящих туров в отель)
    $(".hot_tours_review_frame").fancybox({
        fitToView : true,
        autoSize: true,
        type: "iframe"
    });
    //Галлерея фото отеля(страница горящих туров в отель)
    $(".hot_tours_photo").click(function() {
        //ТАК НАДО, не удалять!
    });
    $(".hot_tours_photo_hover").click(function() {
        $(this).next().lightGallery({
            thumbnail:true,
            subHtmlSelectorRelative: true
        });
        $(this).next().find("a:first").trigger('click');
    });

    //для мобильных
    if (isTouchDevice()) {
        $(".hot_tours_photo .hot_tours_photo_hover").fadeIn("fast");
    }


    //Форма авторизации/входа
    $(".user_login").click(function() {
        $.fancybox.open({
            type        : 'ajax',
            fitToView   : true,
            width       : '300',
            height      : '300',
            autoSize    : false,
            closeClick  : false,
            href: '/login_form.php'
        });
    });

    //Добавление туристов к заявке в ЛК из истории
    $(".add_from_history").click(function() {
        $turist_id = $(this).attr("turist_id");
        $.fancybox.open({
            type        : 'ajax',
            fitToView   : true,
            width       : '300',
            height      : '200',
            autoSize    : false,
            closeClick  : false,
            href: 'turist_history.php?turist_id='+$turist_id
        });
    });

    //Изменение страны для отображения календаря минимальных цен
    $("#calendar_price_from").change(function() {
        otpusk_get_city($(this).val(), 1544);
        calendar_min_reload();
    });

    //Изменение города для отображения календаря минимальных цен
    $("#calendar_price_to").change(function() {
        calendar_min_reload();
    });

    //Раскрытие вопросов FAQ
    $(".faq_question").click(function() {
        $(".faq_question").next().hide();
        $(this).next().slideDown(100);
    });
    //Открытие вопроса FAQ по id
    if ($("#faq_active_id").val() != "" && typeof($("#faq_active_id").val()) != 'undefined' && $("#faq_active_id").val() != null) {
        $("#faq"+$("#faq_active_id").val()).next().slideDown("fast");
		$("html, body").animate({
            scrollTop: $("#faq"+$("#faq_active_id").val()).offset().top - 60
        }, 400);
    }

    //Показать все страны в футере на телефоне
    $(".mobile_state_list").click(function() {
        $(this).prev().css("height","100%");
        $(this).hide();
    });

    //Стрелка скрола страницы на главной ДАЛЕЕ
    $(".next_main_page").click(function() {
        $("html, body").animate({
            scrollTop: $(".scroll_marker").position().top - 250},
        400);
    });


});

function fill_turist_fields(turist_id) {
    data = $("#selected_turist_data option:selected").val();
    $arr_data = data.split(";");
    $("input[name=name\\[\\]").each(function() {
        if ($(this).attr("turist_id") == turist_id) {
            $(this).val($arr_data[0]);
        }
    });
    $("input[name=surname\\[\\]").each(function() {
        if ($(this).attr("turist_id") == turist_id) {
            $(this).val($arr_data[1]);
        }
    });
    $("input[name=birthday\\[\\]").each(function() {
        if ($(this).attr("turist_id") == turist_id) {
            $(this).val($arr_data[2]);
        }
    });
    $("input[name=passport_seria\\[\\]").each(function() {
        if ($(this).attr("turist_id") == turist_id) {
            $(this).val($arr_data[3]);
        }
    });
    $("input[name=passport_number\\[\\]").each(function() {
        if ($(this).attr("turist_id") == turist_id) {
            $(this).val($arr_data[4]);
        }
    });
    $("input[name=passport_valid_till\\[\\]").each(function() {
        if ($(this).attr("turist_id") == turist_id) {
            $(this).val($arr_data[5]);
        }
    });
    $("select[name=sex\\[\\]").each(function() {
        if ($(this).attr("turist_id") == turist_id) {
            $(this).val($arr_data[6]);
        }
    });
    //Закрываем окно fancybox
    $.fancybox.close();
}

//Прорисовка календаря минимальных цен
function calendar_min_reload() {
    $geo_id = $("#calendar_price_from").val();
    var str = $("#calendar_price_from option:selected").text();
    str = str.replace(/ от.*/, '');
    $city = ($("#calendar_price_to").val()) ? $("#calendar_price_to").val() : 1544;
    $date = $("#calendar_date").val();
    $query_string = "geo_id="+$geo_id+"&str="+str+"&night_from=7&night_to=10&city="+$city+"&date="+$date+"&action=submit_search&person_str=2+взр.";
    $postdata = {
        "query_string" : $query_string,
        "lang" : $("input[name=lang]").val()
    };
    $html = "<div class='loader_top'></div>";
    $("#calendar_index_page").html($html);
    $.post("/ajax_graph.php", $postdata, function(data) {
        if (data != "") {
            $("#calendar_index_page").html(data);
            //Слайдер минимальных цен
            var price_slider = $('#price-slider').lightSlider({
                item:20,
                controls: false,
                pager:false,
                loop:false,
                slideMove:7,
                slideMargin:15,
                speed:600,
                onSliderLoad: function() {
                    $('#price-slider').removeClass('cs-hidden');
                },
                responsive : [
                    {
                        breakpoint:1000,
                        settings: {
                            item:15,
                            loop:false
                        }
                    },
                    {
                        breakpoint:600,
                        settings: {
                            item:10,
                            slideMargin:10,
                            loop:false
                        }
                    },

                    {
                        breakpoint:300,
                        settings: {
                            item:5,
                            slideMargin:5,
                            loop:false
                        }
                    }
                ]
            });
            $(".left_slide").click(function() {
                price_slider.goToPrevSlide();
            });
            $(".right_slide").click(function() {
                price_slider.goToNextSlide();
            });
            if (!isTouchDevice()) {
                //Всплывающее окно при наведении
                $('.tip').poshytip({
                    className: 'tip-twitter',
                    showTimeout: 1,
                    alignTo: 'target',
                    alignX: 'center',
                    offsetY: 5,
                    allowTipHover: false,
                    fade: false,
                    slide: false
                });
            }
        }
    });
}
function isTouchDevice() {
    return typeof window.ontouchstart !== 'undefined';
}
function make_age_str($obj_input) {
    var childs = $obj_input.attr("childs");
    $childs_str = "";
    if (childs) {
        $childs_str = childs.split(","); // массив с возрастами
    }
    $adults = $obj_input.attr("adults");
    $str = $adults+" "+$("input[name=adult_word]").val();
    if ($childs_str != "") {
        $str += "+"+$childs_str.length+" "+$("input[name=child_word]").val();
    }
    $obj_input.val($str);

}

//Загрузка городов отправления
function otpusk_get_city(geo_id, selected_city_id) {
    $postdata = {
        "action" : "otpusk_get_city",
        "geo_id" : geo_id,
        "selected" : selected_city_id,
        "lang" : $("input[name=lang]").val()
    };
    $("select[name=city]").css("background-image", "url('/img/ico_load.gif')");
    $.post("/autocomplete.php", $postdata, function(data) {
        $("select[name=city]").css("background-image", "url('/img/ico_map2.png')");
        $("select[name=city]").html(data);
    });
}
//Загрузка городов отправления для горящих туров
function hot_tours_get_city(state_name, selected_city_id) {
    $postdata = {
        "action" : "hot_tours_get_city",
        "state_name" : state_name,
        "selected" : selected_city_id,
        "lang" : $("input[name=lang]").val()
    };
    $("select[name=hot_tours_city]").css("background-image", "url('/img/ico_load.gif')");
    $.post("/autocomplete.php", $postdata, function(data) {
        $("select[name=hot_tours_city]").css("background-image", "url('/img/ico_map2.png')");
        $("select[name=hot_tours_city]").html(data);
    });
}

//Функция после нажатия на поиск туров
function search_results_submit() {
    //Короткая строка поиска
    $str = $("input[name=short_str]").val();
    $(".main_str").val($str);
    return true;
}

//загрузка туров на страницу
function search_results(query_string) {

//----------------------------------------Загружаем график минимальных цен---------------------------------
    $postdata = {
        "query_string" : query_string
    };
    $html = "<div class='loader_top'></div>";
    $("#search_result_container .top").html($html);
    $.post("/ajax_graph.php", $postdata, function(data) {
        if (data != "") {
            if (!data.match(/не найдено/)) {
                $("#search_result_container .top").html(data);
            } else {
                $("#search_result_container .top").hide();
            }

            //Слайдер минимальных цен
            var price_slider = $('#price-slider').lightSlider({
                item:20,
                controls: false,
                pager:false,
                loop:false,
                slideMove:7,
                slideMargin:15,
                speed:600,
                onSliderLoad: function() {
                    $('#price-slider').removeClass('cs-hidden');
                },
                responsive : [
                    {
                        breakpoint:1000,
                        settings: {
                            item:15,
                            loop:false
                        }
                    },
                    {
                        breakpoint:600,
                        settings: {
                            item:10,
                            slideMargin:10,
                            loop:false
                        }
                    },

                    {
                        breakpoint:300,
                        settings: {
                            item:5,
                            slideMargin:5,
                            loop:false
                        }
                    }
                ]
            });
            $(".left_slide").click(function() {
                price_slider.goToPrevSlide();
            });
            $(".right_slide").click(function() {
                price_slider.goToNextSlide();
            });
            if (!isTouchDevice()) {
                //Всплывающее окно при наведении
                $('.tip').poshytip({
                    className: 'tip-twitter',
                    showTimeout: 1,
                    alignTo: 'target',
                    alignX: 'center',
                    offsetY: 5,
                    allowTipHover: false,
                    fade: false,
                    slide: false
                });
            }
        }

        //Для моб устройств
        if (isTouchDevice()) {
            $("#close_extra_fields").trigger("click");
        }
    });

//----------------------------------------Загружаем доп. фильтры----------------------------------------
    $postdata = {
        "query_string" : query_string,
        "content" : "left",
        "lang" : $("input[name=lang]").val()
    };
    $html = "<div class='loader_left'></div>";
    $("#search_result_container .left").html($html);
    $.post("/ajax_search.php", $postdata, function(data) {
        $("#search_result_container .left").html(data);
        //Показать/скрыть все филтры
        $(".filter").click(function() {
            $(this).toggleClass("up");
            if ($(this).hasClass("up")) {
                $(this).prev().find("li").slideDown(100);
                $(this).html("скрыть");
            } else {
                $(this).prev().find("li:nth-child(n+6)").slideUp(100);
                $(this).html("все");
            }
        });

        //Показываем кнопку приминения филтров возле фильтров
        $(".search_results .sort_block").mouseenter(function() {
            $(".filter_apply").hide();
            $(this).find("div.filter_apply").show();
        });
        //Загрузка списка отелей
        $(".search_results .sort_block input").click(function() {
            //Загрузка списка отелей
            update_hotels_list();
        });
        $(".filter_apply").click(function() {
            //Короткая строка поиска
            $str = $("input[name=short_str]").val();
            $(".main_str").val($str);

            document.hotel_filter.submit();
        });

        //Отображение фильтров в мобильной версии
        $("#show_mobile_filters").click(function() {
            $(this).hide();
            $(".search_results .left").slideDown();
        });

        //Бюджет для фильтра результатов поиска
        $("#budget_slider").slider({
            from: 0,
            to: 300000,
            step: 500,
            smooth: true,
            round: 0,
            dimension: "&nbsp;грн",
            skin: "plastic",
            onstatechange: function(value) {
            }
        });

        //Загрузка списка отелей
        update_hotels_list();
    });

//----------------------------------------Загружаем результаты поиска----------------------------------------
    $postdata = {
        "query_string" : query_string,
        "content" : "right",
        "lang" : $("input[name=lang]").val()
    };
    $loader_text = $("#loader_text").val();
    $html = "<div class='loader_right'><div class='text'>"+$loader_text+"</div></div>";
    $("#search_result_container .right").html($html);
    $.post("/ajax_search.php", $postdata, function(data) {
        $("#search_result_container .right").html(data);
        //Отели найдены
        if (data.search(/не найдено/i) == -1) {
            //Загрузка отелей на карту google если уже загрузились филтры
            //if (document.getElementById("map_canvas")) {
                setTimeout(initialize, 2000);
            //}
        //Если нет результатов прячем фильтры
        } else {
            $("#search_result_container .right").css("width", "100%");
            $("#search_result_container .left").hide();
            //$("#search_result_container .top").hide();
        }

        //Переключение валюты
        $("div.currency span").click(function() {
            $("div.currency span").removeClass("current");
            $(this).toggleClass("current");
            $currency = $(this).attr("currency");

            //Сохраняем валюту в сессии
            $postdata = {
                "action" : "save_currency",
                "currency" : $currency
            };
            $.post("/search_results.php", $postdata, function(data) {

            });

            $(".search_resul_block .price").each(function() {
                $html = $(this).attr("price_"+$currency);
                $(this).html($html);
                if ($currency == "valuta") {
                    $(this).attr("title", $(this).attr("price_grn"));
                } else {
                    $(this).attr("title", $(this).attr("price_valuta"));
                }

            });
            if (!isTouchDevice()) {
                //Всплывающее окно при наведении
                $('.tip').poshytip({
                    className: 'tip-twitter',
                    showTimeout: 1,
                    alignTo: 'target',
                    alignX: 'center',
                    offsetY: 5,
                    allowTipHover: false,
                    fade: false,
                    slide: false
                });
            }
        });

        //Устанавливаем валюту из сессии
        $("div.currency span[currency='"+$("input[name=currency]").val()+"']").trigger("click");

        if (!isTouchDevice()) {
            //Всплывающее окно при наведении
            $('.tip').poshytip({
                className: 'tip-twitter',
                showTimeout: 1,
                alignTo: 'target',
                alignX: 'center',
                offsetY: 5,
                allowTipHover: false,
                fade: false,
                slide: false
            });
        }

        //Нажатие на кнопку следаить за ценой
        $("#follow_button").click(function() {
            if (($("#follow_contact").val() == "") || ($("#follow_name").val() == "")) {
                alert("Пожалуйста укажите Ваше имя, телефон или E-mail");
            } else {
                $postdata = {
                    "action" : "price_follow",
                    "url" : $("#follow_url").val(),
                    "name" : $("#follow_name").val(),
                    "contact" : $("#follow_contact").val(),
                    "contact_type" : $("#follow_contact_type").val(),
                    "budget" : $("#price_follow_budget_slider").val()
                };
                $.post("/search_results.php", $postdata, function(data) {
                    $("#follow_contact_container").html("<div style='font-weight: bold;color: #459add;padding-top:15px;'>Готово, мы пришлем вам лучшие предложения!</div>");
                });
            }
        });

        //Строка сделаить за ценой
        $("#follow_str").val($("input[name=full_str]").val());
        $("#follow_contact").attr("placeholder", "Телефон");
        $("#follow_contact").mask("+380999999999");
        $("#follow_contact_type").change(function() {
            if ($(this).val() == "email") {
                $("#follow_contact").attr("placeholder", "E-mail");
                $("#follow_contact").attr("maxlength", "");
                $("#follow_contact").unmask();
            } else {
                $("#follow_contact").attr("placeholder", "Телефон");
                $("#follow_contact").mask("+380999999999");
            }
        });

        //Актуазизация цены для менеджеров
        $(".price_actualize").click(function() {
            $(this).css("background-color", "#fff");
            $(this).css("background-image", "url('/img/ico_load.gif')");
            $obj = $(this);
            $postdata = {
                "action" : "price_actualize",
                "otpusk_offer_id" : $(this).attr("otpusk_offer_id"),
                "people" : $(this).attr("people")
            };
            $.post("/search_results.php", $postdata, function(data) {
                if ((data.code == 2) || (data.code == 1) || (data.code == 0)) {
                    $html = data.message;
                    $obj.parent().prev().css("background-color", "#fff951");
                    $obj.parent().prev().html($html);

                    $obj.css("background-image", "none");
                    $obj.css("background-color", "red");
                } else {
                    $html = "<b>"+Math.round(data.offer.p)+" $</b><br>";
                    $html += Math.round(data.offer.pl)+" грн";
                    $obj.parent().prev().css("background-color", "#fff951");
                    $obj.parent().prev().html($html);
                    $obj.parent().next().next().find(".manager_client_price").attr("price_usd", Math.round(data.offer.p));
                    $obj.parent().next().next().find(".manager_client_price").attr("price_uah", Math.round(data.offer.pl));

                    $obj.css("background-image", "none");
                    $obj.css("background-color", "#7fba00");
                }
            }, "json");
        });

        //Формирование прайса для менеджеров
        $(".manager_client_price").click(function() {
            if ($(this).prop("checked")) {
                $postdata = {
                    "action" : "manager_client_price",
                    "action_type" : "add",
                    "hotel_name" : $(this).attr("hotel_name"),
                    "hotel_id" : $(this).attr("hotel_id"),
                    "dates" : $(this).attr("dates"),
                    "eat_name" : $(this).attr("eat_name"),
                    "room_name" : $(this).attr("room_name"),
                    "from_city_id" : $(this).attr("from_city_id"),
                    "price_usd" : $(this).attr("price_usd"),
                    "price_uah" : $(this).attr("price_uah"),
                    "currency" : $(this).attr("currency"),
                    "person_str" : $(this).attr("person_str"),
                    "ages" : $(this).attr("ages"),
                    "otpusk_offer_id" : $(this).attr("otpusk_offer_id")

                };
                $.post("/search_results.php", $postdata, function(data) {
                    manager_price_update();
                });
            } else {
                $postdata = {
                    "action" : "manager_client_price",
                    "action_type" : "remove",
                    "otpusk_offer_id" : $(this).attr("otpusk_offer_id")
                };
                $.post("/search_results.php", $postdata, function(data) {
                    manager_price_update();
                });
            }
        });

        //Для менеджеров сохраняем прайс и выдаём ссылку
        $("#get_manager_price_url").click(function() {
            $postdata = {
                "action" : "get_manager_price_url"
            };
            $.post("/search_results.php", $postdata, function(data) {
                $url = "https://deluxe.voyage/offers/";
                $("#manager_price_url").val($url + data);
                $("#edit_manager_price_url").show();
                $("#edit_manager_price_url").attr("href", "/admin/clients_prices.php?edit_id="+data);
            });
        });

        //Бюджет для блока следить за ценой
        $("#price_follow_budget_slider").slider({
            from: 0,
            to: 150000,
            step: 500,
            smooth: true,
            round: 1,
            dimension: "&nbsp;грн",
            skin: "plastic",
            onstatechange: function(value) {
            }
        });

        //Показать все цены для менеджера
        $(".show_all.manager_price").click(function() {
            $(this).toggleClass("up");
            if ($(this).prev().is(":visible")) {
                $(this).prev().slideUp("fast");
                $(this).html("показать все цены");
            } else {
                $(this).prev().slideDown("fast");
                $(this).html("скрыть");
            }
        });

        //Скрытие/отображение бблока с выбранными ценами
        $(".show_all.manger_block_bottom").click(function() {
            $(this).toggleClass("up");
            if ($(this).hasClass("up")) {
                $(".choosen_offers").css("height", "50px");
                $(this).html("показать");
            } else {
                $(".choosen_offers").css("height", "200px");
                $(this).html("скрыть");
            }
        });

        //Код Бистрикс 24
    	/*(function(w,d,u,b){w['Bitrix24FormObject']=b;w[b] = w[b] || function(){arguments[0].ref=u;
        (w[b].forms=w[b].forms||[]).push(arguments[0])};
        if(w[b]['forms']) return;
        var s=d.createElement('script');s.async=1;s.src=u+'?'+(1*new Date());
        var h=d.getElementsByTagName('script')[0];h.parentNode.insertBefore(s,h);
        })
        (window,document,'https://bitrix.deluxe.voyage/bitrix/js/crm/form_loader.js','b24form_3');
        b24form_3({"id":"23","lang":"ru","sec":"k3rhz9","type":"inline","node": document.getElementById("bx24_form_inline_div")});*/
	
		//Код Бистрикс 24 низ
    	/*document.getElementById("w100").style.display = "block";*/

    });
}
//Функция обновления таблицы прайсов для менеджеров
function manager_price_update() {
    $postdata = {
        "action" : "manager_price_update"
    };
    $.post("/search_results.php", $postdata, function(data) {
        if (data != "") {
            $(".choosen_offers .scroll").html(data);
            if (!$(".choosen_offers").is(":visible")) {
                $(".choosen_offers").fadeIn("fast");
            }
        } else {
            $(".choosen_offers").hide("fast");
        }
    });
}
//Функция удаления тура из таблицы прайса для менеджеров
function manager_price_remove($otpusk_offer_id) {
    $postdata = {
        "action" : "manager_client_price",
        "action_type" : "remove",
        "otpusk_offer_id" : $otpusk_offer_id
    };
    $.post("/search_results.php", $postdata, function(data) {
        manager_price_update();
        $(".manager_client_price[otpusk_offer_id="+$otpusk_offer_id+"]").prop("checked", 0);
    });
}

//----------------------------------------Загрузка информации о туре----------------------------------------
function tour_info(query_string) {
    $postdata = {
        "query_string" : query_string,
        "lang" : $("input[name=lang]").val()
    };
    $html = "<div class='loader_top'></div>";
    $("#tour_info_container").html($html);
    $.post("/ajax_tour_info.php", $postdata, function(data) {
        $("#tour_info_container").html(data);
        //Переключение валюты
        $("div.currency span").click(function() {
            $("div.currency span").removeClass("current");
            $(this).toggleClass("current");
            $currency = $(this).attr("currency");

            //Сохраняем валюту в сессии
            $postdata = {
                "action" : "save_currency",
                "currency" : $currency
            };
            $.post("/search_results.php", $postdata, function(data) {

            });
            $(".book_price, .price_in_radio").each(function() {
                $html = $(this).attr("price_"+$currency);
                $(this).html($html);
                if ($currency == "valuta") {
                    $(this).attr("title", $(this).attr("price_grn"));
                } else {
                    $(this).attr("title", $(this).attr("price_valuta"));
                }

            });
            if (!isTouchDevice()) {
                //Всплывающее окно при наведении
                $('.tip').poshytip({
                    className: 'tip-twitter',
                    showTimeout: 1,
                    alignTo: 'target',
                    alignX: 'center',
                    offsetY: 5,
                    allowTipHover: false,
                    fade: false,
                    slide: false
                });
            }
        });

        //Устанавливаем валюту из сессии
        $("div.currency span[currency='"+$("input[name=currency]").val()+"']").trigger("click");
        if (!isTouchDevice()) {
            //Всплывающее окно при наведении
            $('.tip').poshytip({
                className: 'tip-twitter',
                showTimeout: 1,
                alignTo: 'target',
                alignX: 'center',
                offsetY: 5,
                allowTipHover: false,
                fade: false,
                slide: false
            });
        }

        //Загрузка карты google
        setTimeout(initialize, 1000);
        var first_load = true;
        //Нажатие на цену в таблице цен на странице тура
        $(".book_price").click(function() {
            $for = $(this).attr("for");
            //Отображение туров в зависимости от выбранной цены в таблице
            $(".offers_list li").hide();
            $(".offers_list li[for="+$for+"]").fadeIn(10);

            $("select[name=flight_from], select[name=flight_to]").show();
            $("#flight_from_err, #flight_to_err").hide();
            $("select[name=flight_from] option").hide();
            $("select[name=flight_to] option").hide();

            $(".book_price").removeClass("selected");
            $(this).addClass("selected");

            $(".total_tour_price").html("");
            $("input[name=order_price_valuta]").val("");
            $(".operator_tour_price").html("");
            $("input[name=order_price_uah]").val("");
            $(".prepayment").html("");
            $("input[name=order_prepayment_uah]").val("");

            //Заполняем поле "Выбранный тур"
            var details = $(this).attr("for");
            var all_arr = details.split('_');
            var date_arr = all_arr[0].split('-');
            $dates = date_arr[2]+"."+date_arr[1]+"."+date_arr[0]+ ", " + (all_arr[1]-1) +" ноч.";
            $("#selected_dates").html($dates);
            $("input[name=order_dates]").val($dates);
            $("#selected_room").html("");
            $("input[name=order_room_eat]").val("");
            $(".otpusk_price_actualize").hide();
            $("#selected_price").html("");
            $("#actualize_info").hide();

            if (isTouchDevice()) {
                if (!first_load) {
                    $("html, body").animate({scrollTop: $(".choose_price").position().top-150 }, 600);
                } else {
                    first_load = false;
                }
            }

        });
        var first_load2 = true;
        //Выбор номера и питания на странице тура
        $("input[name=offer_id]").click(function() {
            $offer_id = $(this).val();
            $tour_currency = $("#tour_currency").val();
            $("#order_btn").fadeOut("fast");
            //Вывод перелётов для Desktop
            $("select[name=flight_from] option").hide();
            $("select[name=flight_to] option").hide();
            if ($("select[name=flight_from] option[offer_id='"+$offer_id+"']").length > 0) {
                $("select[name=flight_from]").show();
                $("#flight_from_err").hide();
                $("select[name=flight_from] option[offer_id='"+$offer_id+"']").show();
                $("select[name=flight_from] option[offer_id='"+$offer_id+"']").prop("selected", true);
            } else {
                $("select[name=flight_from]").hide();
                $("#flight_from_err").show();
            }
            if ($("select[name=flight_to] option[offer_id='"+$offer_id+"']").length > 0) {
                $("select[name=flight_to]").show();
                $("#flight_to_err").hide();
                $("select[name=flight_to] option[offer_id='"+$offer_id+"']").show();
                $("select[name=flight_to] option[offer_id='"+$offer_id+"']").prop("selected", true);
            } else {
                $("select[name=flight_to]").hide();
                $("#flight_to_err").show();
            }
            //Вывод перелётов для Mobile
            $("input[name=flight_from]").parent().parent().hide();
            $("input[name=flight_to]").parent().parent().hide();
            if ($("input[offer_id_from='"+$offer_id+"']").length > 0) {
                $("#flight_from_err_mobile").hide();
                $("input[offer_id_from='"+$offer_id+"']").parent().parent().show();
            } else {
                $("input[name=flight_from]").parent().parent().hide();
                $("#flight_from_err_mobile").show();
            }
            if ($("input[offer_id_to='"+$offer_id+"']").length > 0) {
                $("#flight_to_err_mobile").hide();
                $("input[offer_id_to='"+$offer_id+"']").parent().parent().show();
            } else {
                $("input[name=flight_to]").parent().parent().hide();
                $("#flight_to_err_mobile").show();
            }

            $(".total_tour_price").html($(this).attr("price_valuta")+" <span>"+$tour_currency+"</span>");
            $("input[name=order_price_valuta]").val($(this).attr("price_valuta"));
            $price_grn = parseInt($(this).attr("price_grn"));
            $(".operator_tour_price").html($price_grn+" <span>грн</span>");
            $("input[name=order_price_uah]").val($price_grn);
            $("input[name=order_operator_id]").val($(this).attr("operator_id"));
            //Предоплата
            $prepayment = Math.round($price_grn*20/100);
            if ($prepayment < 5000) {
                $prepayment = 5000;
            }
            $(".prepayment").html($prepayment+" <span>грн</span>");
            $("input[name=order_prepayment_uah]").val($prepayment);

            //Заполняем поле "Выбранный тур"
            $("#selected_room").html($(this).attr("str"));
            $("input[name=order_room_eat]").val($(this).attr("str"));
            $(".otpusk_price_actualize").fadeIn("fast");
            $(".otpusk_price_actualize").attr("otpusk_offer_id", $offer_id);
            $("input[name=order_otpusk_offer_id]").val($offer_id);
			
			//if ($(".email_auto").val().length != 0){$(".email_auto").val($offer_id+'@deluxe.voyage');}
			
            $("#selected_price").html($(this).attr("price_valuta")+" <span>"+$tour_currency+"</span>"+ " ("+$price_grn+" <span>грн</span>"+")");
            $("#actualize_info").hide();

            if (isTouchDevice()) {
                if (!first_load2) {
                    $("html, body").animate({scrollTop: $("#selected_room").position().top-400 }, 600);
                } else {
                    first_load2 = false;
                }
            }
        });

        //Нажатие на галочке "Забронировать без паспортных данных"
        $("#bron_without_turists").click(function() {
            if ($(this).prop("checked")) {
                $(".turists_list_div").fadeOut("fast");
            } else {
                $(".turists_list_div").fadeIn("fast");
            }
        });

        //Показать/скрыть полное описание отеля
        $(".descr_hotel").click(function() {
            $(this).toggleClass("up");
            if ($(this).hasClass("up")) {
                $(".hotel_descr").toggleClass("full");
                $(this).html("скрыть полное описание отеля");
            } else {
                $(".hotel_descr").toggleClass("full");
                $(this).html("показать полное описание отеля");
                $("html, body").animate({ scrollTop: $(".descr_hotel").position().top-150}, 600);
            }
        });

        //Строка сделаить за ценой
        $("#follow_str").val($("input[name=full_str]").val());

        //При пезвой загрузке выбор минимальной цены (дата и ночи)
        $(".book_price.selected").trigger("click");

        //При резвой загрузке выбор минимальной цены (тип комнаты и номер)
        $("input[name=offer_id]").each(function() {
            $obj = $(this);
            if ($(this).attr("is_min_price") == "yes") {
                $obj.trigger("click");
            }
        });
		
		//Код Битрикс 24
		(function(w,d,u,b){w['Bitrix24FormObject']=b;w[b] = w[b] || function(){arguments[0].ref=u;
        (w[b].forms=w[b].forms||[]).push(arguments[0])};
        if(w[b]['forms']) return;
        var s=d.createElement('script');s.async=1;s.src=u+'?'+(1*new Date());
        var h=d.getElementsByTagName('script')[0];h.parentNode.insertBefore(s,h);
        })
        (window,document,'https://bitrix.deluxe.voyage/bitrix/js/crm/form_loader.js','b24form');
        b24form({"id":"26","lang":"ru","sec":"tb2bzc","type":"inline","node": document.getElementById("b_24_f")});

        //Проверка актуальности тура
        $(".otpusk_price_actualize").click(function() {
            $obj = $(this);
            $postdata = {
                "action" : "price_actualize",
                "otpusk_offer_id" : $(this).attr("otpusk_offer_id"),
                "people" : $(this).attr("people")
            };
            $(".otpusk_price_actualize").hide();
            $obj.parent().css("background-image", "url('/img/ico_load.gif')");
            $.post("/search_results.php", $postdata, function(data) {
                if ((data.code == 2) || (data.code == 1) || (data.code == 0)) {
                    $html = "<div class='price_actualize_err'>"+data.message+"</div>";
                } else {
                    $html = "<div class='price_actualize_ok'>Тур актуален</div>";
                    $price_valuta = "<b>"+Math.round(data.offer.p)+" "+data.offer.u+"</b>";
                    $price_grn = Math.round(data.offer.pl)+" грн";
                    $html += "<div>Стоимость тура "+$price_valuta+" ("+$price_grn+")</div>";
                    $("#order_btn").fadeIn("fast");
                }
                $obj.parent().css("background-image", "none");
                $("#actualize_info").html($html);
                $("#actualize_info").fadeIn("fast");
            }, "json");
        });

        //Показываем отзывы в всплывающем окне
        $(".review_frame").fancybox({
            fitToView : true,
            autoSize: true,
            type: "iframe"
        });

        //Галлерея фото отеля
        $(".photo").click(function() {
            //ТАК НАДО, не удалять!
        });
        $(".photo_hover").click(function() {
            $(this).next().lightGallery({
                thumbnail:true,
                subHtmlSelectorRelative: true
            });
            $(this).next().find("a:first").trigger('click');
        });

        //$(".tel_format").mask('+38 (000) 000 00 00');
		$(".tel_format").inputmask({"mask": "380999999999"});

        //для мобильных
        if (isTouchDevice()) {
            $(".photo .photo_hover").fadeIn("fast");
        }

        //Проверка промокода
        $("input[name=promo_code]").keyup(function() {
            $postdata = {
                "action" : "check_promo_code",
                "promo_code" : $(this).val(),
                "otpusk_offer_id" : $("input[name=order_otpusk_offer_id]").val()
            };
            $(".promo_code_discount").hide();
            $.post("/search_results.php", $postdata, function(data) {
                if (data != "") {
                    $html = '<td>Скидка по Промо коду</td><td style="text-align: left;color: #e1b435;font-size: 20px">'+data+'%</td>';
                    $(".promo_code_discount").html($html);
                    $(".promo_code_discount").fadeIn("fast");
                }
            });
        });

        //Строка в поле поиска при поиске по offer_id
        if ($("input[name=temp_catalog_geo_id]").val()) {
            $("input[name=geo_id]").val($("input[name=temp_catalog_geo_id]").val());
            $(".main_str").val($("input[name=temp_catalog_str]").val());
            $("input[name=short_str]").val($("input[name=temp_catalog_str]").val());
            $("input[name=full_str]").val($("input[name=temp_catalog_str]").val());
            $("input[name=date]").val($("input[name=temp_catalog_date]").val());
            $("select[name=night_from]").val($("input[name=temp_catalog_night]").val());
            $("select[name=night_to]").val($("input[name=temp_catalog_night]").val());
        }

    });
}

//----------------------------------------Блок горящите туры----------------------------------------

//Раскрытие всех туров
$(".price.button").click(function() {
    if ($(this).hasClass("open")) {
        $(this).parent().next().hide();
        $(this).html($("input[name=show_tours_word]").val());
        $(this).css("background", "#E1B435");
        $(this).removeClass("open");
    } else {
        $(this).parent().next().slideDown();
        $(this).html($("input[name=hide_tours_word]").val());
        $(this).css("background", "#a5a5a5");
        $(this).addClass("open");

        $position = $(this).position();
        $("html, body").animate({ scrollTop: $position.top}, 600);
    }
});
//Окно заказа тура
$(".order_hot_tours").click(function() {
    $tour_details = $(this).attr("tour_details");
    $operator_id = $(this).attr("operator_id");
    $price = $(this).attr("price");
    $.fancybox({
        height : '300',
        fitToView   : true,
        autoSize: false,
        href: "/ajax_order_hot_tour.php?tour_details="+$tour_details+"&operator_id="+$operator_id+"&price="+$price,
        type: "ajax"
    });
});


function hot_tours(query_string) {
    $postdata = {
        "query_string" : query_string,
        "lang" : $("input[name=lang]").val()
    };
    $html = "<div class='loader_top'></div>";
    $("#hot_tours_container").html($html);
    $.post("/ajax_hot_tours.php", $postdata, function(data) {
        $("#hot_tours_container").html(data);

        //Раскрытие всех туров
        $(".price.button").click(function() {
            if ($(this).hasClass("open")) {
                $(this).parent().next().hide();
                $(this).html($("input[name=show_tours_word]").val());
                $(this).css("background", "#E1B435");
                $(this).removeClass("open");
            } else {
                $(this).parent().next().slideDown();
                $(this).html($("input[name=hide_tours_word]").val());
                $(this).css("background", "#a5a5a5");
                $(this).addClass("open");

                $position = $(this).position();
                $("html, body").animate({ scrollTop: $position.top - 170}, 600);
            }
        });

        //Окно заказа тура
        $(".order_hot_tours").click(function() {
            $tour_details = $(this).attr("tour_details");
            $operator_id = $(this).attr("operator_id");
            $price = $(this).attr("price");
            $.fancybox({
                height : '300',
                fitToView   : true,
                autoSize: false,
                href: "/ajax_order_hot_tour.php?tour_details="+$tour_details+"&operator_id="+$operator_id+"&price="+$price,
                type: "ajax"
            });
        });



    });
}
function get_check_box(name) {
    $res = "";
    $('input[name='+name+'\\[\\]').each(function() {
        if ($(this).prop("checked")) {
            $res += "&stars[]="+$(this).val();
        }
    });
    return $res;
}

//----------------------------------------Блок индивидуальные туры----------------------------------------
function ind_tours(query_string) {
    $postdata = {
        "query_string" : query_string,
        "lang" : $("input[name=lang]").val()
    };
    $html = "<div class='loader_top'></div>";
    $("#ind_tours_container").html($html);
    $.post("/ajax_ind_tours.php", $postdata, function(data) {
        $("#ind_tours_container").html(data);
    });
}






//Проверка всех полей формы при бронировании тура
function check_form_fields() {
    $submit = true;
    
    $(".fill_request").each(function() {
        if (($(this).val() == "") && $(this).is(":visible")) {
            $submit = false;
            $(this).css("background-color", "#fff9c1");
        } else {
            $(this).css("background-color", "#FFFFFF");
        }
    });
    /*if (!isEmail($("input[name=email]").val())) {
        alert("Проверьте правильность ввода E-mail");
        return false;
    }*/
    $(".fill_request_chk").each(function() {
        if (!$(this).prop("checked") && $(this).is(":visible")) {
            $submit = false;
            alert("Вы должны принять условия");
            return false;
        }
    });
    
    if ($submit) {
        return true;
    } else {
        alert("Не все обязательные поля заполнены");
        return false;
    }
}
function isEmail(email) {
    var regex = /\@/;
    return regex.test(email);
}

//Отправка события GA и FB при бронировании
function send_ga_ev_order() {
	gtag('event', 'Формы', {
	'event_category' : 'Подбор тура - бронировка на сайте',
	});
	fbq('trackCustom', 'FormSend');
}

//Перевод карты гугл в полноэкранный режим
function google_map_full_screen() {
    var elem = document.getElementById("map_canvas");
    if (elem.requestFullscreen) {
        elem.requestFullscreen();
    } else if (elem.mozRequestFullScreen) {
        elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
        elem.webkitRequestFullscreen();
    } else if (elem.msRequestFullscreen) {
        elem.msRequestFullscreen();
    }
}

//Очистка всех  фильтров
function filter_form_reset() {
    $(".search_results .sort_block input[type=checkbox]").attr("checked", false);
    $(".search_results .sort_block input[name=hotel_rate][value='']").prop("checked", true);
    $("input[name=selected_hotels]").val("");
    //Загрузка списка отелей
    update_hotels_list();
}

//Обновление списка отелей в фильтре
function update_hotels_list() {
    $country_id = "";
    //Поиск по региону
    if ($("input[name=region_id]").val() != "") {
        $region_id = $("input[name=region_id]").val();
        $country_id = $("input[name=country_id]").val();
    //Поиск по стране.Собираем выбранные регионы
    } else if ($("input[name=country_id]").val() != "") {
        $region_id = "";
        $("input[name=regions\\[\\]").each(function() {
            if ($(this).prop("checked")) {
                $region_id += $(this).val()+",";
            }
        });
        $country_id = $("input[name=country_id]").val();
    }
    //Собираем категории отелей
    $hotel_category = "";
    $("input[name=hotel_category\\[\\]").each(function() {
        if ($(this).prop("checked")) {
            $hotel_category += $(this).val()+",";
        }
    });
    //Собираем услуги в отелях
    $services = "";
    $("input[name=services\\[\\]").each(function() {
        if ($(this).prop("checked")) {
            $services += $(this).val()+",";
        }
    });
    if ($country_id != "") {
        $postdata = {
            "country_id" : $country_id,
            "region_id" : $region_id,
            "hotel_category" : $hotel_category,
            "only_recomend" : $("input[name=only_recomend]").val(),
            "services" : $services,
            "selected_hotels" : $("input[name=selected_hotels]").val(),
            "lang" : $("input[name=lang]").val()
        };
        $("#hotels_filter_list").html('<div class="title">Отели</div><div class="sort_block" id="hotels_list" style="height: 391px;"></div>');
        $("#hotels_filter_list").css("background-image", "url('/img/ico_load.gif')");
        $("#totel_hotels_found").html("");
        $.post("/ajax_get_hotels.php", $postdata, function(data) {
            $("#hotels_filter_list").html(data);
            //Всего найдено отелей
            $totel_hotels_found = data.split("checkbox").length-2;
            if ($postdata.lang == "ua") {
                $("#totel_hotels_found").html("Всього знайдено готелів: "+$totel_hotels_found);
            } else {
                $("#totel_hotels_found").html("Всего найдено отелей: "+$totel_hotels_found);
            }
            $("#hotels_filter_list").css("background-image", "none");

            //Поиск по первым буквам отеля
            $("#hotel_name_search").keyup(function() {
                $("#hotels_filter_list li").hide();
                search = $(this).val();
                var split = search.split(' ');
                for (var i = 0, len = split.length; i < len; i++) {
                    split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
                }
                search = split.join(' ');
                if ($("#only_recomend").prop("checked")) {
                    $("#hotels_filter_list li.top_recomend label:contains('"+search+"')").parent().show();
                } else {
                    $("#hotels_filter_list li label:contains('"+search+"')").parent().show();
                }
            });
            //Показывать только рекомендованые отели
            $("#only_recomend").click(function() {
                search = $("#hotel_name_search").val();
                if (search != "") {
                    var split = search.split(' ');
                    for (var i = 0, len = split.length; i < len; i++) {
                        split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
                    }
                    search = split.join(' ');
                }
                if ($("#only_recomend").prop("checked")) {
                    $("#hotels_filter_list li").hide();
                    if (search != "") {
                        $("#hotels_filter_list li.top_recomend label:contains('"+search+"')").parent().show();
                        $("#hotels_filter_list li.top_recomend label:contains('"+search+"')").prev().prop("checked", 1);
                    } else {
                        $("#hotels_filter_list li.top_recomend").show();
                        $("#hotels_filter_list li.top_recomend input").before().prop("checked", 1);
                    }
                } else {
                    if (search != "") {
                        $("#hotels_filter_list li label:contains('"+search+"')").parent().show();
                        $("#hotels_filter_list li label:contains('"+search+"')").prev().prop("checked", 0);
                    } else {
                        $("#hotels_filter_list li").show();
                        $("#hotels_filter_list li input").before().prop("checked", 0);
                    }
                }
            });
            if ($postdata.only_recomend == 1) {
                //$("#only_recomend").trigger("click");
            }

        });
    }
}

//Обновление списка отелей в грабере цен
function update_hotels_list_track_price() {
    $track_regions = $("select[name=track_regions]").val();
    $country_id = $("select[name=track_geo_id]").val();

    //Собираем категории отелей
    $hotel_category = "";
    $("input[name=hotel_category\\[\\]").each(function() {
        if ($(this).prop("checked")) {
            $hotel_category += $(this).val()+",";
        }
    });
    if ($country_id != "") {
        $postdata = {
            "country_id" : $country_id,
            "track_regions" : $track_regions,
            "hotel_category" : $hotel_category,
            "only_recomend" : $("input[name=only_recomend]:checked").val(),
            "selected_hotels" : $("select[name=selected_hotels]").val()
        };
		console.log ($postdata);
        $("#hotels_filter_list").html('<div class="title">Отели</div><div class="sort_block" id="hotels_list" style="height: 391px;"></div>');
        $("#hotels_filter_list").css("background-image", "url('/img/ico_load.gif')");
        $("#totel_hotels_found").html("");
        $.post("/ajax_get_hotels.php", $postdata, function(data) {
            $("#hotels_filter_list").html(data);
            //Всего найдено отелей
            $totel_hotels_found = data.split("checkbox").length-2;
            $("#totel_hotels_found").html("Всего найдено отелей: "+$totel_hotels_found);
            $("#hotels_filter_list").css("background-image", "none");

            //Поиск по первым буквам отеля
            $("#hotel_name_search").keyup(function() {
                $("#hotels_filter_list li").hide();
                search = $(this).val();
                var split = search.split(' ');
                for (var i = 0, len = split.length; i < len; i++) {
                    split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
                }
                search = split.join(' ');
                if ($("#only_recomend").prop("checked")) {
                    $("#hotels_filter_list li.top_recomend label:contains('"+search+"')").parent().show();
                } else {
                    $("#hotels_filter_list li label:contains('"+search+"')").parent().show();
                }
            });
            //Показывать только рекомендованые отели
            $("#only_recomend").click(function() {
                search = $("#hotel_name_search").val();
                if (search != "") {
                    var split = search.split(' ');
                    for (var i = 0, len = split.length; i < len; i++) {
                        split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
                    }
                    search = split.join(' ');
                }
                if ($("#only_recomend").prop("checked")) {
                    $("#hotels_filter_list li").hide();
                    if (search != "") {
                        $("#hotels_filter_list li.top_recomend label:contains('"+search+"')").parent().show();
                        $("#hotels_filter_list li.top_recomend label:contains('"+search+"')").prev().prop("checked", 1);
                    } else {
                        $("#hotels_filter_list li.top_recomend").show();
                        $("#hotels_filter_list li.top_recomend input").before().prop("checked", 1);
                    }
                } else {
                    if (search != "") {
                        $("#hotels_filter_list li label:contains('"+search+"')").parent().show();
                        $("#hotels_filter_list li label:contains('"+search+"')").prev().prop("checked", 0);
                    } else {
                        $("#hotels_filter_list li").show();
                        $("#hotels_filter_list li input").before().prop("checked", 0);
                    }
                }
            });
            if ($postdata.only_recomend == 1) {
                //$("#only_recomend").trigger("click");
            }

        });
    }
}




