// настройки
var
	shadowSpeed        = 500,   // время (мс) появления тени
	windowSpeed        = 300,   // время (мс) появления окошка
	speedPlane         = 60000, // время (мс) перемещения самолета слева направо
	speedCountryRight  = 5000,  // время (мс) смены картинки в блоке "Платиновые тарифы на авиабилеты"
	periodCountryRight = 5000;  // время (мс) автоматической смены картинки в блоке "Платиновые тарифы на авиабилеты"

// системные переменные


var
	timerCountryRight; // таймер для блока "Платиновые тарифы на авиабилеты"

(function($) {

    $(document).ready(
        function() {

            var params = {
                changedEl: ".top-currency-select select, .search-select select, .curr-select, .hotel-search-block select",
                visRows: 10,
                scrollArrows: true
            }
            cuSel(params);

            $(window).load(
                function() {
                    $("div.hotel-search-block div.cusel input").each(
                        function() {
                            $(this).attr("rel", $(this).val());
                        }
                    );
                }
            );

            //$("div.search-popular-row:odd").addClass("search-popular-row-odd");

            $("div.search-checkbox span input:checked, .chb input:checked").parent().addClass("checked");
			$(".chb").each(function(i){
				if ( ! $(this).find(":checked").length )
					$(this).addClass("chb-off");
			});

            $("div.search-checkbox, .chb").click(
                function() {
                    var curSpan = $(this).find("span");
                    curSpan.toggleClass("checked");
                    if (curSpan.hasClass("checked")) {
                        curSpan.find("input").attr("checked", "checked").change();
						$(this).removeClass("chb-off");

                        if (curSpan.parent().hasClass("search-checkbox-two")) {
                            curSpan.parents().filter("form").find("div.search-date-2").show();
                        }
                    } else {
                        curSpan.find("input").removeAttr("checked").change();
						$(this).addClass("chb-off");
                        if (curSpan.parent().hasClass("search-checkbox-two")) {
                            curSpan.parents().filter("form").find("div.search-date-2").hide();
                        }
                    }
                }
            );

            $("div.main-right-input input").focus(
                function() {
                    if ($(this).val() == "Ваш емэйл") {
                        $(this).val("").addClass("focus");
                    }
                }
            );

            $("div.main-right-input input").blur(
                function() {
                    if ($(this).val() == "") {
                        $(this).val("Ваш емэйл").removeClass("focus");
                    }
                }
            );


            $(window).load(
                function() {
                    preload([
                        '/img/datapicker-bg.png',
                        '/img/datapicker-bg-2.png',
                        '/img/datapicker-bg-3.png',
                        '/img/datapicker-bg-4.png',
                        '/img/datapicker-arrow-prev.png',
                        '/img/datapicker-arrow-prev.png',
                        '/img/datapicker-arrow-next.png'
                    ]);

                    function preload(images) {
                        var div = document.createElement("div");
                        var s = div.style;
                        s.position = "absolute";
                        s.top = s.left = 0;
                        s.visibility = "hidden";
                        document.body.appendChild(div);
                        div.innerHTML = "<img src=\"" + images.join("\" /><img src=\"") + "\" />";
                        var lastImg = div.lastChild;
                        lastImg.onload = function() {document.body.removeChild(document.body.lastChild);};
                    }
                }
            );

            $.datepicker.setDefaults( $.datepicker.regional[ "ru" ] );

            //$("div.search-date-1 input").val("");
            $("div.search-date-1 input").datepicker({
                numberOfMonths: 2,
                dateFormat: "yy-mm-dd",
                minDate: 0,
                onSelect: function(dateText, inst) {
                    $(this).parent().find("a").html("Туда " + dateText.substr(8, 2) + "." + dateText.substr(5, 2) + "." + dateText.substr(0, 4));
                    $(this).parent().find("div.search-input-tip").hide();
                    var curDateFrom = $(this).parent().parent().find("div.search-date-2 input");
                    var curDateTo   = $(this);
                    if (curDateFrom.datepicker("getDate")) {
                        if (curDateFrom.datepicker("getDate").getTime() < curDateTo.datepicker("getDate").getTime()) {
                            curDateFrom.datepicker("setDate", new Date(Number(dateText.substr(0, 4)), Number(dateText.substr(5, 2)) - 1, Number(dateText.substr(8, 2)) + 7));
                            var newDateText = curDateFrom.val();
                            curDateFrom.parent().find("a").html("Обратно " + newDateText.substr(8, 2) + "." + newDateText.substr(5, 2) + "." + newDateText.substr(0, 4));
                        }
                    }
                    curDateFrom.datepicker("option", "minDate", new Date(dateText));
                }
            });

            $("div.search-date-1 a").click(
                function() {
                    var curLink = $(this);
                    curLink.parent().find("input").datepicker("show");
                    var offsetSearch = curLink.parent().parent().offset();
                    if ($(this).parents().filter("div.search-row-3").length == 1) {
                        $("#ui-datepicker-div").addClass("ui-datepicker-3");
                        $("#ui-datepicker-div").removeClass("ui-datepicker-4");
                    } else {
                        $("#ui-datepicker-div").removeClass("ui-datepicker-2");
                    }
                    $("#ui-datepicker-div").css({"left":offsetSearch.left - 20});
                    if (curLink.parents().filter(".window").length == 1) {
                        if (curLink.parents().filter(".window").find("div.search-hotel-select-type").length == 1) {
                            $("#ui-datepicker-div").css({"position":"fixed"});
                            $("#ui-datepicker-div").css({"top":Number($("div.window").css("top").replace(/px/, "")) + 80});
                        } else {
                            $("#ui-datepicker-div").css({"position":"fixed"});
                            $("#ui-datepicker-div").css({"top":Number($("div.window").css("top").replace(/px/, "")) + 73});
                        }
                    } else {
                        $("#ui-datepicker-div").css({"position":"absolute"});
                        $("#ui-datepicker-div").css({"top":offsetSearch.top + 20});
                    }
                    return false;
                }
            );


            $("div.search-date-2 input").datepicker({
                numberOfMonths: 2,
                dateFormat: "yy-mm-dd",
                minDate: 0,
                onSelect: function(dateText, inst) {
                    $(this).parent().find("a").html("Обратно " + dateText.substr(8, 2) + "." + dateText.substr(5, 2) + "." + dateText.substr(0, 4));
                    $(this).parent().find("div.search-input-tip").hide();
                }
            });

            $("div.search-date-2 a").click(
                function() {
                    var curLink = $(this);
                    curLink.parent().find("input").datepicker("show");
                    var offsetSearch = curLink.parent().parent().offset();
                    if ($(this).parents().filter("div.search-row-3").length == 1) {
                        $("#ui-datepicker-div").addClass("ui-datepicker-4");
                        $("#ui-datepicker-div").removeClass("ui-datepicker-3");
                    } else {
                        $("#ui-datepicker-div").addClass("ui-datepicker-2");
                    }
                    $("#ui-datepicker-div").css({"left":offsetSearch.left - 20});
                    if (curLink.parents().filter(".window").length == 1) {
                        if (curLink.parents().filter(".window").find("div.search-hotel-select-type").length == 1) {
                            $("#ui-datepicker-div").css({"position":"fixed"});
                            $("#ui-datepicker-div").css({"top":Number($("div.window").css("top").replace(/px/, "")) + 80});
                        } else {
                            $("#ui-datepicker-div").css({"position":"fixed"});
                            $("#ui-datepicker-div").css({"top":Number($("div.window").css("top").replace(/px/, "")) + 73});
                        }
                    } else {
                        $("#ui-datepicker-div").css({"position":"absolute"});
                        $("#ui-datepicker-div").css({"top":offsetSearch.top + 20});
                    }
                    return false;
                }
            );
$("div.search-date-2 input").datepicker("option", "minDate",  $("div.search-date-1 input").datepicker("getDate"));
            function defaultText(id){
                    if($(id).val()== ''){
                            $(id).val($(id).attr('alt'));
                    }

                    if($(id).val() == $(id).attr('alt')){
                            $(id).removeClass("focus");
                    } else {
                            $(id).addClass("focus");
                    }

                    $(id).focus(
                        function() {
                            if($(this).val() == $(this).attr('alt') || $(this).val()== ''){
                                    $(this).addClass("focus");
                                    $(this).val('');
                            }
                        }
                    );

                    $(id).blur(
                        function() {
                            if($(this).val()== ''){
                                    $(this).val($(this).attr('alt'));
                            }

                            if($(this).val() == $(this).attr('alt')){
                                    $(this).removeClass("focus");
                            } else {
                                    $(this).addClass("focus");
                            }

                        }
                    );
            }

            defaultText(".search-input input:text");

			// маусовер на указателе на календарь низких цен

			$(".calendar-tip").hover(function(){
				$(".calendar").addClass("hover");
			}, function(){
				$(".calendar").removeClass("hover");
			});

			// переключение фильтров

			$(".filters-tabs ul li").click(function(){
				var index = $(".filters-tabs ul li").index( $(this) );
				if ( index == 5 )
					$(".filters-tabs ul li:eq(4)").click();
				else {
					$(this).siblings(".selected").removeClass("selected");
					$(this).addClass("selected");
					var index = $(this).parent().find("li").index( $(this) );
					$(".filter-visible").removeClass("filter-visible");
					$(".filter").eq(index).addClass("filter-visible");
					if ( $(this).hasClass("calendar") )
						$(".calendar-tip").addClass("calendar-tip-hidden");
				}
			});



			// открытие подробностей маршрута триггером

			$(".about-route span").click(function(){
				$(this).parentsUntil(".route-options").last().parent().next(".route-info").toggleClass("route-info-visible");
			});

			// закрытие подробностей маршрута крестиком

			$(".route-info .close").click(function(){
				$(this).parent().removeClass("route-info-visible");
			});

			// открываем окошко с поисковой формой

			$(".change").click(function(){
				showWindow( $(".s-form") );
			});

			// клик вне лайтбокса

			$(".shadow").click(function(){
				hideWindow();
			});

			// закрытие окошка крестиком

			$(".window .close").click(function(){
				hideWindow();
			});

			// окошко закрывается по ECS

			$("html").keydown(function(e){
				if ( e.keyCode == 27 )
					hideWindow();
			});

			// открытие окошек с партнерами

//			$(".price .btn-buy").click(function(){
//				showWindow( $(".partners") );
//			});

			// обработка логики чекбоксов

			$(".checkboxes").each(function(){

				var
					$chb = $(this).find(":checkbox"),
					$cchb = $(this).find(".chb span"),
					$wchb = $(this).find(".chb"),
					$reset = $(this).find(".reset"),
					$sel = $(this).find(".select-all");

				$chb.change(function(){
					var result = $(this).attr("checked");
					if ( result ) {
						$reset.removeClass("dead");
						if ( ! $chb.not(":checked").length )
							$sel.addClass("dead");
					}
					else {
						$sel.removeClass("dead");
						if ( ! $chb.filter(":checked").length )
							$reset.addClass("dead");
					}
				});

				$sel.click(function(){
					if ( ! $(this).hasClass("dead") ) {
						$chb.attr("checked", "checked");
						$cchb.addClass("checked");
						$wchb.removeClass("chb-off");
						$reset.removeClass("dead");
						$(this).addClass("dead");
					}
                                        applyFilter();
				});

				$reset.click(function(){
					if ( ! $(this).hasClass("dead") ) {
						$chb.removeAttr("checked");
						$cchb.removeClass("checked");
						$wchb.addClass("chb-off");
						$sel.removeClass("dead");
						$(this).addClass("dead");
					}
                                        applyFilter();
				});

			});

            function correctPartner() {
                var curHeightWindow = $("div.wrapper").height();
                var curHeightBlock  = $("div.topartner").height();
                $("div.topartner").css("top", (curHeightWindow - curHeightBlock) / 2);
            }

            $("div.topartner").each(
                function() {
    			    $(window).load(correctPartner);
    			    $(window).resize(correctPartner);
    			}
			);

			function animatePlane() {
			    $("div.bron-fly-line-right div").css({"left":0});
			    $("div.bron-fly-line-right div").animate({"left":785}, speedPlane, "linear",
			        function() {
        			    setTimeout(animatePlane, 0);
			        }
			    );
			}

			$("div.bron-fly-line-right div").each(
			    function() {
			        setTimeout(animatePlane, 0);
			    }
			);

//            $("div.progressBar").each(
//                function(key, item) {
//                    $(item).timeProgress(10 + Math.random() * 45);
//                }
//            );

            $("div.allproposal-menu-content ul li:odd").addClass("odd");
            $("div.country-left ul li:odd").addClass("odd");

            $("div.proposal-block").each(
                function() {
                    $(this).find("div.proposal-row:odd").addClass("proposal-row-odd");
                    $(this).find("div.proposal-row:last").addClass("proposal-row-last");
                }
            );

			$(".proposal-block-link a").click(function(){
				var curForm = $(this).parent();

				$(".s-form").find("input[name='f[From]']").val(curForm.find("input[name='special_from']").val()).addClass("focus");
				$(".s-form").find("input[name='f[FromCode]']").val(curForm.find("input[name='special_fromcode']").val());
				$(".s-form").find("input[name='f[To]']").val(curForm.find("input[name='special_to']").val()).addClass("focus");
				$(".s-form").find("input[name='f[ToCode]']").val(curForm.find("input[name='special_tocode']").val());

				showWindow($(".s-form"));

				return false;
			});

            $("#search-form form").submit(
                function() {
                    var curResult = true;

                    var curForm = $(this);

                    curForm.find("div.search-input input:text").each(
                        function() {
                            if ($(this).val() == $(this).attr("alt")) {
                                curResult = false;
                                $(this).parent().find("div.search-input-tip").show();
                            } else {
                                $(this).parent().find("div.search-input-tip").hide();
                            }
                        }
                    );

                    if (curForm.find("div.search-date-1 a").html() == curForm.find("div.search-date-1 a").attr("rel")) {
                        curResult = false;
                        curForm.find("div.search-date-1 div.search-input-tip").show();
                    } else {
                        curForm.find("div.search-date-1 div.search-input-tip").hide();
                    }

                    if (curForm.find("div.search-checkbox-two input:checked").length == 1 && (curForm.find("div.search-date-2 a").html() == curForm.find("div.search-date-2 a").attr("rel"))) {
                        curResult = false;
                        curForm.find("div.search-date-2 div.search-input-tip").show();
                    } else {
                        curForm.find("div.search-date-2 div.search-input-tip").hide();
                    }
                    if (curForm.find("div.search-checkbox-two input").attr('checked') && (curForm.find("div.search-date-2 a").html() == curForm.find("div.search-date-2 a").attr("rel"))) {
                        curResult = false;
                        curForm.find("div.search-date-2 div.search-input-tip").show();
                    } else {
                        curForm.find("div.search-date-2 div.search-input-tip").hide();
                    }

                    recalcTip();

                    return curResult;
                }
            );

            $("div.country-right").each(
                function() {
                    $(this).data("curIndex", 0);
                    $("div.country-right-photos ul li").css({"position":"absolute", "display":"none"});
                    $("div.country-right-photos ul li:first").css({"z-index":"2", "display":"block"});

                    $("div.country-right-tickets ul li:first").addClass("active");

                    timerCountryRight = setTimeout(nextCountryRight, periodCountryRight);
                }
            );

            $("div.country-right-tickets a").hover(
                function() {
                    var curPhotos  = $("div.country-right-photos ul");
                    var curTickets = $("div.country-right-tickets ul");
                    curPhotos.find("li").stop(false, true);
                    clearTimeout(timerCountryRight);

                    var curBlock = $("div.country-right");
                    var curIndex = $("div.country-right-tickets a").index($(this));
                    curBlock.data("curIndex", curIndex);

                    curPhotos.find("li").css({"z-index":"1", "display":"none"});
                    curPhotos.find("li").eq(curIndex).css({"z-index":"2", "display":"block"});
                    curTickets.find("li.active").removeClass("active");
                    curTickets.find("li").eq(curIndex).addClass("active");
                },

                function() {
                    timerCountryRight = setTimeout(nextCountryRight, periodCountryRight);
                }
            );

//            autocomplete2("where_from", {cmd: "bron_search", to_id: "from_id"});
//            autocomplete2("where_to", {cmd: "bron_search", to_id: "to_id"});
//            autocomplete2("where_from_window", {cmd: "bron_search", to_id: "from_id_window"});
//            autocomplete2("where_to_window", {cmd: "bron_search", to_id: "to_id_window"});
//            autocomplete3("hotel_search", {cmd: "bron_search"});

            $().piroBox({
                my_speed: 300, //animation speed
                bg_alpha: 0.5, //background opacity
                radius: 4, //caption rounded corner
                scrollImage : false, // true == image follows the page _|_ false == image remains in the same open position
                                     // in some cases of very large images or long description could be useful.
                slideShow : true, // true == slideshow on, false == slideshow off
                slideSpeed : 3, //slideshow
                pirobox_next : 'piro_next', // Nav buttons -> piro_next == inside piroBox , piro_next_out == outside piroBox
                pirobox_prev : 'piro_prev', // Nav buttons -> piro_prev == inside piroBox , piro_prev_out == outside piroBox
                close_all : '.piro_close' // add class .piro_overlay(with comma)if you want overlay click close piroBox
            });

            $("div.comments-param").each(
                function() {
                    var curBlock = $(this);
                    curBlock.css({"margin-left":-(curBlock.width() / 2)});

                    $(window).load(correctCommentsParam);
                    $(window).resize(correctCommentsParam);
                    $(window).scroll(correctCommentsParam);
                }
            );

            $("div.comments-param-count a").click(
                function() {
                    var curBlock = $(this).parent();
                    curBlock.toggleClass("comments-param-count-open");
                    if (curBlock.hasClass("comments-param-count-open")) {
                        $("div.comments-inner").show(0, correctCommentsParam);
                    } else {
                        $("div.comments-inner").hide(0, correctCommentsParam);
                    }
                    return false;
                }
            );

            $("div.comments-param-add a").click(
                function() {
                    shadow( 0.65, function(){
                        $("div.window-comment-form").animate({
                            top: "50%"
                        }, windowSpeed);
                    });
                    return false;
                }
            );

            $("div.window-comment-form form").submit(
                function() {
                    var result = true;
                    if ($("div.comment-form-textarea textarea").val() == "") {
                        result = false;
                        $("div.comment-form-textarea div.search-input-tip").show();
                    } else {
                        $("div.comment-form-textarea div.search-input-tip").hide();
                    }

                    if ($("div.comment-captcha-input input").val() == "") {
                        result = false;
                        $("div.comment-captcha-input div.search-input-tip").show();
                    } else {
                        $("div.comment-captcha-input div.search-input-tip").hide();
                    }

                    return result;
                }
            );

            $("a.window-comment-form-close").click(
                function() {
                    $("div.window-comment-form").animate({top: - $("div.window-comment-form").height() - 500}, windowSpeed,
                        function(){
                            shadow(0);
                        }
                    );

                    return false;
                }
            );

            $("div.search-hotel-select-type input:checked").each(
                function() {
                    $(this).parent().addClass("checked");
                }
            );

            $("div.search-hotel-select-type div").click(
                function() {
                    var curSpan = $(this).find("span");
                    $("div.search-hotel-select-type div span.checked").removeClass("checked");
                    curSpan.addClass("checked");
                    curSpan.find("input").attr("checked", "checked");

                    if($("#searchByHotel").attr('checked')){
                        $('#hotel_search_city').hide();
                        $('#hotel_search_hotel').show();
                    } else {
                        $('#hotel_search_city').show();
                        $('#hotel_search_hotel').hide();
                    }
                }
            );

            $("div.search-hotel-video a").click(
                function() {
                    showWindow( $(".s-form") );
                    return false;
                }
            );

            $("div.hotel-countries-all-link a").click(
                function() {
                    var curLink = $(this);
                    $("div.hotels-countries-all").slideToggle();
                    var curText = curLink.html();
                    curLink.html(curLink.attr("rel"));
                    curLink.attr("rel", curText);

                    return false;
                }
            );

            $("div.planetpeople-bottom-left p a").click(
                function() {
                    shadow( 0.65, function(){
                        $("div.window-comment-form").animate({
                            top: "50%"
                        }, windowSpeed);
                    });
                    return false;
                }
            );

            $("div.planetpeople-bottom").each(
                function() {
                    $(window).load(correctPlanetpeople);
                    $(window).resize(correctPlanetpeople);
                }
            );

            $("div.hotel-top-change a").click(
                function() {
                    showWindow( $(".s-form") );
                    return false;
                }
            );

            $("div.hotel-map-bottom-right a").click(
                function() {
                    $("a.viewBigMap").trigger("click");
                    return false;
                }
            );



            $("div.hotel-partners table tr:last").addClass("last");

            $("div.hotel-search-block-name a").click(
                function() {
                    var curLink = $(this);
                    var curBlock = curLink.parent().parent();
                    curBlock.toggleClass("hotel-search-block-open");
                    curBlock.find("div.hotel-search-block-content").slideToggle();

                    if (curLink.hasClass("viewBigMap")) {
                        var curText = curLink.html();
                        curLink.html(curLink.attr("rel"));
                        curLink.attr("rel", curText);
                        if (curBlock.hasClass("hotel-search-block-open")) {
                            $("div.hotel-map").slideDown(correctCommentsParam);
                            mapInit();
                        } else {
                            $("div.hotel-map").slideUp(correctCommentsParam);
                        }
                    }

                    return false;
                }
            );

            $("div.hotel-checkbox span input:checked").each(
                function() {
                    $(this).attr("rel", "checked");
                    $(this).parent().addClass("checked");
                }
            );

            $("div.hotel-radio span input:checked").each(
                function() {
                    $(this).attr("rel", "checked");
                    $(this).parent().addClass("checked");
                }
            );

            $("div.hotel-checkbox").click(
                function() {
                    var curSpan = $(this).find("span");
                    curSpan.toggleClass("checked");
                    if (curSpan.hasClass("checked")) {
                        curSpan.find("input").attr("checked", "checked");
                        if (curSpan.find("input").hasClass("checkbox-all")) {
                            var curBlock = curSpan.parents().filter("div.hotel-search-stars");
                            curBlock.find("div.hotel-checkbox span").each(
                                function() {
                                    if (!$(this).find("input").hasClass("checkbox-all")) {
                                        $(this).removeClass("checked");
                                        $(this).find("input").removeAttr("checked");
                                    }
                                }
                            );
                        } else {
                            var curBlock = curSpan.parents().filter("div.hotel-search-stars");
                            curBlock.find("div.hotel-checkbox span input.checkbox-all").each(
                                function() {
                                    $(this).parent().removeClass("checked");
                                    $(this).removeAttr("checked");
                                }
                            );
                        }
                    } else {
                        curSpan.find("input").removeAttr("checked");
                    }
                    applyFilter();
                }
            );

            $("div.hotel-radio").click(
                function() {
                    var curSpan = $(this).find("span");
                    var curName = curSpan.find("input").attr("name");
                    $("div.hotel-radio input[name='" + curName + "']").parent().removeClass("checked");
                    curSpan.addClass("checked");
                    curSpan.find("input").attr("checked", "checked");

                    if (curSpan.parents().filter("div.hotel-search-block-type").length == 1) {
                        var curBlock = curSpan.parents().filter("div.hotel-search-block-type");
                        var curIndex = curBlock.find("span").index(curSpan);
                        curBlock.parent().find("div.hotel-net-block-active").removeClass("hotel-net-block-active");
                        curBlock.parent().find("div.hotel-net-block").eq(curIndex).addClass("hotel-net-block-active");
                    }
                }
            );

            $("div.hotel-search-block-reset input").click(
                function() {
                    setTimeout(function() {
                        $("div.hotel-checkbox span input").each(
                            function() {
                                var curInput = $(this);
                                if (curInput.attr("rel")) {
                                    curInput.attr("checked", "checked");
                                    curInput.parent().addClass("checked");
                                } else {
                                    curInput.removeAttr("checked");
                                    curInput.parent().removeClass("checked");
                                }
                            }
                        );

                        $("div.hotel-radio span input").each(
                            function() {
                                var curInput = $(this);
                                if (curInput.attr("rel")) {
                                    curInput.parent().parent().trigger("click");
                                }
                            }
                        );

                        var curSlider = $("#slider-range-price-main");
                        curSlider.slider("option", "values", [curSlider.slider("option", "min"), curSlider.slider("option", "max")]);
                        $("#div_price_main_from").html('<span class="currencyWidget">' +formatCurrency( curSlider.slider("option", "min") , $("#curr-select").val() ) + '</span>');
                        $("#div_price_main_to").html('<span class="currencyWidget">' +formatCurrency( curSlider.slider("option", "max") , $("#curr-select").val() ) + '</span>');

                        $("div.hotel-search-block div.cusel input").each(
                            function() {
                                var curInput = $(this);
                                var curCusel = $(this).parents().filter("div.cusel");
                                var curDefault = curInput.attr("rel");
                                curCusel.find("span.cuselActive").removeClass("cuselActive");
                                curCusel.find("span[value='" + curDefault + "']").addClass("cuselActive");
                                curCusel.find("div.cuselText").html(curCusel.find("span.cuselActive").html());
                                curInput.val(curDefault);
                            }
                        );
                        applyFilter();

                    }, 100);
                }
            );

            $("div.hotel-search-show-link a").click(
                function() {
                    var curBlock = $(this).parents().filter("div.hotel-search-block");
                    curBlock.find("div.hotel-search-block-add").slideDown(correctCommentsParam);
                    curBlock.find("div.hotel-search-show-link").hide();
                    curBlock.find("div.hotel-search-hide-link").show();

                    return false;
                }
            );

            $("div.hotel-search-hide-link a").click(
                function() {
                    var curBlock = $(this).parents().filter("div.hotel-search-block");
                    curBlock.find("div.hotel-search-block-add").slideUp(correctCommentsParam);
                    curBlock.find("div.hotel-search-show-link").show();
                    curBlock.find("div.hotel-search-hide-link").hide();

                    return false;
                }
            );


            /* всплывающие превью изображений на hotel-inside */
            $("p.hotel-item-min-photo").each(
                function() {
                    $(this).find("a").tooltip({
                        delay: 0,
                        showURL: false,
                        bodyHandler: function() {
                            return $("<img/>").attr("src", $(this).attr("rel"));
                        }
                    });
                }
            );

            /* корректировка ссылки "Спецпредложения на авиабилеты" */
            $("span.aviacompany-header-spec").each(
                function() {
                    $(window).load(
                        function() {
                            var curBlock = $("span.aviacompany-header-spec");
                            var curWidth = curBlock.find("span.aviacompany-header-spec-left").width() + curBlock.find("span.aviacompany-header-spec-center").width() + curBlock.find("span.aviacompany-header-spec-right").width() + 1;
                            curBlock.width(curWidth);

                            var headerInnerWidth = curBlock.parent().find("strong").width();
                            var headerOuterWidth = curBlock.parent().width();

                            if ((headerOuterWidth - headerInnerWidth) < (curWidth - 31)) {
                                curBlock.css({"left":"auto", "right":0});
                            } else {
                                curBlock.css({"left":headerInnerWidth - 31, "right":"auto"});
                            }
                        }
                    );

                    $(window).resize(
                        function() {
                            var curBlock = $("span.aviacompany-header-spec");
                            var curWidth = curBlock.find("span.aviacompany-header-spec-left").width() + curBlock.find("span.aviacompany-header-spec-center").width() + curBlock.find("span.aviacompany-header-spec-right").width() + 1;
                            curBlock.width(curWidth);

                            var headerInnerWidth = curBlock.parent().find("strong").width();
                            var headerOuterWidth = curBlock.parent().width();

                            if ((headerOuterWidth - headerInnerWidth) < (curWidth - 31)) {
                                curBlock.css({"left":"auto", "right":0});
                            } else {
                                curBlock.css({"left":headerInnerWidth - 31, "right":"auto"});
                            }
                        }
                    );
                }
            );

            /* сворачивание/разворачивание списка ссылок в aviacompany */
            $("div.aviacompany-left-inner-link a").click(
                function() {
                    $(this).parent().parent().toggleClass("aviacompany-left-open");
                    return false;
                }
            );

            /* отображение окна авторизации */
            $("a.top-login").click(
                function() {
                    showWindow( $(".s-auth") );

                    return false;
                }
            );

//            /* обработка фокуса на поле e-mail в авторизации */
//            $("#LoginForm_username").focus(
//                function () {
//                    var curInput = $(this);
//                    if (curInput.val() == "Введите свою эл. почту") {
//                        curInput.val("");
//                        curInput.addClass("focus");
//                    }
//                }
//            );
//
//            $("#LoginForm_username").blur(
//                function () {
//                    var curInput = $(this);
//                    if (curInput.val() == "") {
//                        curInput.val("Введите свою эл. почту");
//                        curInput.removeClass("focus");
//                    }
//                }
//            );

            /* обработка фокуса на поле password в авторизации */
//            $("#LoginForm_password").focus(changeTextToPasswordAuth);

            /* функционал чекбокса в форме авторизации */
            $("div.rememberMe span input:checked").each(
                function() {
                    $(this).parent().addClass("checked");
                }
            );

            $("div.rememberMe").click(
                function() {
                    var curSpan = $(this).find("span");
                    curSpan.toggleClass("checked")
                    if (curSpan.hasClass("checked")) {
                        curSpan.find("input").attr("checked", "checked");
                    } else {
                        curSpan.find("input").removeAttr("checked");
                    }
                    $(this).parent().find('.search-input-tip').hide();
                }
            );

//            /* показать сообщения об ошибках */
//            $("#login-form").submit(
//                function() {
//                    var curForm = $(this);
//
//                    curForm.find("div.search-input-tip").show();
//                    recalcTip();
//
//                    return false;
//                }
//            );

            // форма подписки
            $('.main-right-input input').focus(function() {
                $('.main-right-form .search-input-tip').hide();
            });

            $('.main-right-form form').submit(function() {
                if (($('.main-right-input input').val() == '') || ($('.main-right-input input').val() == 'Ваш емэйл')) {
                    $('.main-right-form .search-input-tip').eq(0).show();
                    recalcTip();
                } else if (!(/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test($('.main-right-input input').val())) {
                    $('.main-right-form .search-input-tip').eq(1).show();
                    recalcTip();
                } else {
                    $('.subscribe-form-title span').html($('.main-right-input input').val());
                    showWindow($('.subscribe'));
                    $('.subscribe-form').show();
                    $('.subscribe-success').hide();
                    $('.subscribe-form-input input').val('Введите код').removeClass('focus');
                    $('.subscribe-form-input .search-input-tip').hide();
                }

                return false;
            });

            $('.subscribe-form-input input').focus(function() {
                if ($(this).val() == 'Введите код') {
                    $(this).val('');
                    $(this).addClass('focus');
                }
                $('.subscribe-form-input .search-input-tip').hide();
            });

            $('.subscribe-form-input input').blur(function() {
                if ($(this).val() == '') {
                    $(this).val('Введите код');
                    $(this).removeClass('focus');
                }
            });

            $('.subscribe-form form').submit(function() {
                if (($('.subscribe-form-input input').val() == '') || ($('.subscribe-form-input input').val() == 'Введите код')) {
                    $('.subscribe-form-input .search-input-tip').show();
                    recalcTip();
                } else {
                    $.ajax({
                                type: "POST",
                                dataType: "json",
                                url: $('#subscription-form').attr('action'),
                                data: {
                                        email: $('#SubscriptionForm_email').val(),
                                        verifyCode: $("#SubscriptionForm_verifyCode").val()
                                }
                        }).done(function( msg ) {
                                if(msg.status == "OK") {
                    $('.subscribe-form').hide();
                    $('.subscribe-success').show();
                    window.setTimeout(function() {
                        $('.subscribe .close').click();
                        $('.main-right-input input').val('Ваш емэйл').removeClass('focus');
                        $('.subscribe-form-input input').val('Введите код').removeClass('focus');
                    }, 4000);
                                } else {
                                        console.log(msg.error);
                                        alert(msg.error);
                }
                        });
                }
                return false;
            });

            /* отображение окна регистрации */
            $("a.top-reg").click(
                function() {
                    showWindow( $(".s-reg") );

                    return false;
                }
            );

//            $('.reg-form-input input').focus(function() {
//                if (!($(this).hasClass('focus'))) {
//                    $(this).attr('title', $(this).val());
//                    $(this).val('');
//                    $(this).addClass('focus');
//                    $(this).parent().find('em').hide();
//                    $(this).parent().find('.search-input-tip').hide();
//                }
//            });
//
//            $('.reg-form-input input').blur(function() {
//                if ($(this).val() == '') {
//                    $(this).val($(this).attr('title'));
//                    $(this).removeClass('focus');
//                    $(this).parent().find('em').show();
//                }
//            });

            $("div.search-date-3 input").val("");
            $("div.search-date-3 input").datepicker({
                numberOfMonths: 2,
                dateFormat: "yy-mm-dd",
                minDate: 0,
                maxDate: +45,
                onSelect: function(dateText, inst) {
                    $(this).parent().find("a").html("Туда " + dateText.substr(8, 2) + "." + dateText.substr(5, 2) + "." + dateText.substr(0, 4));
                    $(this).parent().find("div.search-input-tip").hide();
                }
            });

            $("div.search-date-3 a").click(
                function() {
                    var curLink = $(this);
                    curLink.parent().find("input").datepicker("show");
                    var offsetSearch = curLink.parent().parent().offset();
                    $("#ui-datepicker-div").css({"left":offsetSearch.left - 20});
                    $("#ui-datepicker-div").css({"position":"absolute"});
                    $("#ui-datepicker-div").css({"top":offsetSearch.top + 20});
                    return false;
                }
            );
                    
            var params = {
                changedEl: ".reg-form-input select"
            }
            cuSel(params);

            var params = {
                changedEl: ".statistic-period select",
                visRows: 12,
                scrollArrows: true
            }
            cuSel(params);

//            $('#user-form').submit(function() {
//                var hasErrors = false;
//
//                if (!(/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test($('#User_email').val())) {
//                    hasErrors = true;
//                    $('#User_email').parent().find('.search-input-tip').show();
//                }
//
//                if (($('#User_name').val() == '') || ($('#User_name').val() == 'Введите своё имя')) {
//                    hasErrors = true;
//                    $('#User_name').parent().find('.search-input-tip').show();
//                }
//
//                if (($('#User_pass').val() == '')) {
//                    hasErrors = true;
//                    $('#User_pass').parent().find('.search-input-tip').show();
//                }
//
//                if (($('#User_passConfirm').val() != $('#User_pass').val())) {
//                    hasErrors = true;
//                    $('#User_passConfirm').parent().find('.search-input-tip').show();
//                }
//
//                if (($('#User_verifyCode').val() == '') || ($('#User_verifyCode').val() == 'Введите код, который видите')) {
//                    hasErrors = true;
//                    $('#User_verifyCode').parent().find('.search-input-tip').show();
//                }
//
//                if ($('.s-reg .rememberMe input:checked').length != 1) {
//                    hasErrors = true;
//                    $('.s-reg .auth-links').find('.search-input-tip').show();
//                }
//
//                if (hasErrors) {
//                    recalcTip();
//
//                    return false;
//                } else {
//                    // success registration
////                    alert('Форма отправлена');
////                    return false;
//                }
//            });

            // корректировка размер карты
            //$(window).load(resizeMapInner);
            $(window).resize(resizeMapInner);

            $(window).load(
                function() {
                    preload([
                        '/img/map-mini-bg.png',
                        '/img/map-mini-arrows.png',
                        '/img/map-big-bg.png',
                        '/img/map-big-arrows.png',
                        '/img/map-error.png'
                    ]);

                    function preload(images) {
                        var div = document.createElement("div");
                        var s = div.style;
                        s.position = "absolute";
                        s.top = s.left = 0;
                        s.visibility = "hidden";
                        document.body.appendChild(div);
                        div.innerHTML = "<img src=\"" + images.join("\" /><img src=\"") + "\" />";
                        var lastImg = div.lastChild;
                        lastImg.onload = function() {document.body.removeChild(document.body.lastChild);};
                    }
                }
            );

            correctPointMini();

            correctMapError();

            $(document).click(function() {
                $('.map-error').hide();
            });

            $('.map-point-mini').click(function() {
                $('.map-point-open').removeClass('map-point-open');
                var curPoint = $(this).parent();
                curPoint.addClass('map-point-open');
                correctMapBig(curPoint.find('.map-point-big'));
                correctPointMini();
            });

            $('.map-point-big-close').click(function() {
                $(this).parent().parent().parent().removeClass('map-point-open');
                correctPointMini();
                return false;
            });

        }

    );

})(jQuery);

// корректировка размеров маленьких цен на карте
function correctPointMini() {
    $('.map-point-mini').each(function() {
        $(this).width('auto');
        var curWidth = $(this).find('.map-point-mini-center').width() + 36;
        $(this).width(curWidth);
        $(this).css('margin-left', -curWidth / 2);
    });
}

// корректировка сообщения на карте
function correctMapError() {
    var curWidth = $('.map-error-center').width() + 56;
    $('.map-error').width(curWidth);
    $('.map-error').css('margin-left', -curWidth / 2);
}

// корректировка подробной информации на карте
function correctMapBig(bigPoint) {
    var curWidth = bigPoint.find('.map-point-big-center').width() + 32;
    bigPoint.width(curWidth);
    bigPoint.css('margin-left', -curWidth / 2);
}

// корректировка размер карты
function resizeMapInner() {
    $('.page-map-content').height('auto');
    var curWindowHeight = $(window).height();
    $('.page-map-content').height(curWindowHeight - $('.page-map-header').height());
}

///* заменя текстового поля на поле ввода пароля в форме авторизации */
//function changeTextToPasswordAuth() {
//    var curInput = $(this);
//    if (curInput.val() == "Введите свой пароль") {
//        curInput.replaceWith('<input name="LoginForm[password]" id="LoginForm_password" value="" class="focus" type="password" />');
//        setTimeout(function() {$("#LoginForm_password").focus()}, 1);
//        $("#LoginForm_password").bind("blur", changePasswordToTextAuth);
//    }
//}
//
///* заменя поля ввода пароля на текстового поле в форме авторизации */
//function changePasswordToTextAuth() {
//    var curInput = $(this);
//    if (curInput.val() == "") {
//        curInput.replaceWith('<input name="LoginForm[password]" id="LoginForm_password" value="Введите свой пароль" type="text" />');
//        $("#LoginForm_password").bind("blur", changeTextToPasswordAuth);
//    }
//}


function correctPlanetpeople() {
    var curBlock = $("div.planetpeople-bottom-left");
    curBlock.css({"left":"auto"});
    var curOffsetLeft = curBlock.offset().left;
    curBlock.css({"left":-curOffsetLeft});
    var curBlockText = $("div.planetpeople-bottom-text");
    curBlockText.css({"padding-left":0, "width":"100%"});
    var curBlockTextLeft = $("div.wrapper").offset().left;
    if (curBlockTextLeft < 272) {
        curBlockText.css({"padding-left":272 - curBlockTextLeft, "width":curBlockText.width() - (272 - curBlockTextLeft)});
    } else {
        curBlockText.css({"padding-left":0, "width":"100%"});
    }
}

function correctCommentsParam() {
    var yScroll;
    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
    } else if (document.body) {
        yScroll = document.body.scrollTop;
    }

    var curWindowHeight = $(window).height();
    var curContentHeight = $("div.wrapper").height();

    if ((curContentHeight - yScroll - curWindowHeight) > 89) {
        $("div.comments-param").css({"bottom": 0});
    } else {
        $("div.comments-param").css({"bottom": 89 - (curContentHeight - yScroll - curWindowHeight)});
    }
}

function recalcTip() {
    $("div.search-input-tip").each(
        function() {
            var curTip = $(this);
            curTip.width(curTip.find("span.sit-l").width() + curTip.find("span.sit-c").width() + curTip.find("span.sit-r").width() + 4);
        }
    );
}

function nextCountryRight()
{// смена картинки в блоке "Платиновые тарифы на авиабилеты"

    clearTimeout(timerCountryRight);

    var curBlock = $("div.country-right");
    var curIndex = Number(curBlock.data("curIndex"));

    var curPhotos  = $("div.country-right-photos ul");
    var curTickets = $("div.country-right-tickets ul");

    var newIndex = curIndex + 1;

    if (newIndex == curPhotos.find("li").length) {
        newIndex = 0;
    }

    curPhotos.find("li").eq(newIndex).show();
    curPhotos.find("li").eq(curIndex).fadeOut(speedCountryRight,
        function() {
            curPhotos.find("li").eq(curIndex).css("z-index", 1);
            curPhotos.find("li").eq(newIndex).css("z-index", 2);
            curTickets.find("li.active").removeClass("active");
            curTickets.find("li").eq(newIndex).addClass("active");
            curBlock.data("curIndex", newIndex);
            timerCountryRight = setTimeout(nextCountryRight, periodCountryRight);
        }
    );
}


function showWindow( $obj )
{// crollTop;

	$("div.window div.search-input-tip").hide();
	// показываем тень
	shadow( 0.65, function(){
		$window = $obj;
		$window.animate({
			top: ( $("body").height() - $window.height() ) / 2
		}, windowSpeed);
	});
}

function hideWindow()
{// закрывает окошко

	$("div.ac_results_search").hide();

	// скрываем окошко
	$window.animate({
		top: - $window.height() - 500
	}, windowSpeed, function(){
		$window = null;
		shadow(0);
	});
}

function updateWindowPosition()
{// центрует окошко по вертикали

	if ( $window != null ) // если окошко видно

		$window.stop().animate({
			top: ( $("body").height() - $window.height() ) / 2
		}, windowSpeed);

}

function shadow( value, func )
{// плавно изменяет прозрачность тени на фоне всплывающего окошка

	func = func || function(){};

	// если вызов нелогичен, выходим из функции
	if ( value > 0 && $(".shadow").css("display") == "block" ) return 0;
	if ( !value && $(".shadow").css("display") == "none" ) return 0;

	// показываем тень
	$(".shadow").css("display", "block").animate({
		opacity: value
	}, shadowSpeed, function(){
		if ( !value )
			$(".shadow").css("display", "none");
		func();
	});

}

function to_h_format( mins_cnt )
{
	hors = Math.floor( mins_cnt / 60 );
	mins = mins_cnt-hors * 60;
	h1_txt = "";
	if( hors > 0 )
		h1_txt = hors + " ч.";
	if( hors > 0 && mins > 0 )
		h1_txt += " ";
	if( mins > 0 )
		h1_txt += mins + " мин.";
	if( ! h1_txt )
		h1_txt = "0 мин.";
	return h1_txt;
}

function to_hours_format( mins_cnt )
{
	hors = Math.floor( mins_cnt / 60 );
	mins = mins_cnt-hors * 60;
	ost = mins % 15;
	if (ost && mins_cnt < 1439 )
		return to_hours_format( mins_cnt - ost );
	if( hors < 10 )
		hors = "0" + hors;
	if ( mins < 10 )
		mins = "0" + mins;
	h1_txt = hors + ":" + mins;
	return h1_txt;
}


function formatCurrency(value, currency)
{
        var  templates = currencyTemplates;
        var tpl = "::value::";

        if(!currency){
                currency = "RUR";
        }

        if(templates[currency]){
                tpl = templates[currency];
        }
        //перевод в другую валюту
        var newValue = value;
        if(currencyCurs[currency] && currencyCurs[currency] > 0){
               newValue =  newValue / currencyCurs[currency];
        }

        //Форматирование суммы
        newValue = newValue.toFixed(0).toString().replace(/(\d{1,3}(?=(\d{3})+(?:\.\d|\b)))/g,"\$1"+' ');
        return tpl.replace(new RegExp('::value::','g'), newValue) + "<strong>" + value + "</strong>"
}

function changeCurrency(currency)
{


        $('.currencyWidget').each(function(){
		var price = $(this).find("strong").text();
		$(this).html( formatCurrency(price, currency) );
	});
	correctPointMini();
}

function init_slider( slide_name, slide_min, slide_max, vals, type )
{ // создает слайдер

	$( "#slider-range-" + type + "-" + slide_name ).slider({
		range: true,
		min: slide_min,
		max: slide_max,
		values: vals,
		slide: function( event, ui ) {
			$( "#" + type + "_" + slide_name + "_from" ).val( ui.values[ 0 ]);
			$( "#" + type + "_" + slide_name + "_to" ).val( ui.values[ 1 ]);
			if ( type == "price" ){
				$( "#div_" + type + "_" + slide_name + "_from" ).html( '<span class="currencyWidget">' +formatCurrency( ui.values[ 0 ] , $("#curr-select").val()) + '</span>');
				$( "#div_" + type + "_" + slide_name + "_to" ).html( '<span class="currencyWidget">' +formatCurrency( ui.values[ 1 ] , $("#curr-select").val() ) + '</span>');
			}
			else if( type == "hours" ){
				$( "#div_" + type + "_" + slide_name + "_from" ).text( to_hours_format( ui.values[ 0 ] ) );
				$( "#div_" + type + "_" + slide_name + "_to" ).text( to_hours_format( ui.values[ 1 ] ) );
			}
			else{
				$( "#div_" + type + "_" + slide_name + "_from" ).text( to_h_format( ui.values[ 0 ] ) );
				$( "#div_" + type + "_" + slide_name + "_to" ).text( to_h_format( ui.values[ 1 ] ) );
			}
		},
		change: function( event, ui )
		{
			applyFilter();
		}
	});

	$( "#" + type + "_" + slide_name + "_from" ).val( $( "#slider-range-" + slide_name ).slider( "values", 0 ) );
	$( "#" + type + "_" + slide_name + "_to" ).val( $( "#slider-range-" + slide_name ).slider( "values", 1 ) );

	if ( type == "price" ){
		$( "#div_" + type + "_" + slide_name + "_from" ).html( '<span class="currencyWidget">' +formatCurrency( $( "#slider-range-" + type + "-" + slide_name ).slider( "values", 0 ), $("#curr-select").val()) + '</span>') ;
		$( "#div_" + type + "_" + slide_name + "_to" ).html( '<span class="currencyWidget">' +formatCurrency( $( "#slider-range-" + type + "-" + slide_name ).slider( "values", 1 ), $("#curr-select").val()) + '</span>' );
		//priceFormat();
	}
	else if( type == "hours" ){
		$( "#div_" + type + "_" + slide_name + "_from" ).text( to_hours_format( $( "#slider-range-" + type + "-" + slide_name ).slider( "values", 0 ) ) );
		$( "#div_" + type + "_" + slide_name + "_to" ).text( to_hours_format( $( "#slider-range-" + type + "-" + slide_name ).slider( "values", 1 ) ) );
	}
	else{
		$( "#div_" + type + "_" + slide_name + "_from" ).text( to_h_format( $( "#slider-range-" + type + "-" + slide_name ).slider( "values", 0 ) ) );
		$( "#div_" + type + "_" + slide_name + "_to" ).text( to_h_format( $( "#slider-range-" + type + "-" + slide_name ).slider( "values", 1 ) ) );
	}


	$( ".ui-slider-handle" ).each(function(){
		m_cl = $(this).next();
		if ( m_cl.html() != null && m_cl.attr( "class" ).indexOf( "ui-slider-handle", 0 ) != -1 ){
			m_cl.addClass( "ui-slider-handle-last" );
		}
	});
}

function show_filtered_count(filtered_count)
{
	var ending_id = filtered_count % 10;
	var tens = filtered_count % 100;
	if (ending_id == 0 || (tens > 10 && tens < 20))
	{
		ending = 'й';
	}
	else if (ending_id == 1)
	{
		ending = 'е';
	}
	else if (ending_id <= 4)
	{
		ending = 'я';
	}
	else
	{
		ending = 'й';
	}

	$('.result-count').text('Найдено ' + filtered_count + ' предложени' + ending);
}

function showFormError(field, message)
{
        $('.error-'+field).show();
        $('.error-'+field+' .sit-c').html(message);
}

function declOfNum(number, titles)
{
        cases = [2, 0, 1, 1, 1, 2];
        return titles[ (number%100>4 && number%100<20)? 2 : cases[(number%10<5)?number%10:5] ];
}

function notification(text){
        $(function() {
                $('#notification-text').html(text);
                showWindow($('.notification'));
                window.setTimeout ("hideWindow();", 5000);
        });
}

function showHotelSearchForm(type, search)
{
        if(type == "city") {
                $('#searchByCity').click();
                if(search) {
                        $('#hotel_search_city').val(search);
                        
                }
                $('#hotel_search_city').addClass('focus');
        }
        
        if(type == "hotel") {
                $('#searchByHotel').click();
                if(search) {
                        $('#hotel_search_hotel').val(search);
                        
                }
                
                $('#hotel_search_hotel').addClass('focus');
                
        }
        
        showWindow($(".s-form"));
}

