$(document).ready(function() {

// Подсвечиваем переключалки-дублёры
$(".switch-double-hover .switch").hover(
	function() {
		$(this).parents(".switch-double-hover").addClass("hover");
	},
	function() {
		$(this).parents(".switch-double-hover").removeClass("hover");
	}
);

// Подсвечиваем ссылки-дублёры вместе
$("a").hover(
    function(){
        $("a[href=" + $(this).attr("href") + "]").addClass("pseudo-hover");
    },
    function(){
        $("a").removeClass("pseudo-hover");
    }
);

// Показываем большой попап с телефоном и адресами
$(".small-phone .switch").click(function(event) {
    event.stopPropagation();
    var small_phone = $(".small-phone .switch");
    var phone_flying = $(".phone-flying");
    var big_phone = $(".b-where-to-go .phone");
    phone_flying.css({"left": small_phone.offset().left, "top": small_phone.offset().top, "display": "block"});
    phone_flying.animate({"left":  big_phone.offset().left, "top":  big_phone.offset().top, "fontSize": "7em", "lineHeight": "1.1em"}, 200, function(){
    });
    setTimeout(function(){
        var speed = 200;
            if ($.browser.msie) {
                speed = 0;
            }
        $(".f-phone-popup")
                .css({"display": "none", "visibility": "visible"})
                .fadeIn(speed, function(){ phone_flying.hide(); })
                .addClass("f-phone-popup_opened z-index-top");
        $(".z-index-top").not(".f-phone-popup").removeClass("z-index-top");
        //
    },250);
    $(".small-phone").css({"visibility": "hidden"});
});

// Прячем большой попап с телефоном и адресами
$(".f-phone-popup .close").click(function closePopup() {
    var small_phone = $(".small-phone .switch");
    var phone_flying = $(".phone-flying");
    var big_phone = $(".b-where-to-go .phone");
    phone_flying.css({"left": big_phone.offset().left, "top": big_phone.offset().top, "display": "block"});
    phone_flying.animate({"left":  small_phone.offset().left, "top":  small_phone.offset().top, "fontSize": "1.5em", "lineHeight": ".9em"}, 200, function(){
    });
    setTimeout(function(){
        $(".small-phone").css({"visibility": "visible"});
        phone_flying.hide();
    },200);
    $(".f-phone-popup")
            .css({"visibility": "hidden"})
            .removeClass("f-phone-popup_opened");
});

$(".f-phone-popup").bind("click", function(event) {
    event.stopPropagation();
});

$(document).bind("click", function() {
    if ($(".f-phone-popup").hasClass("f-phone-popup_opened")) {
    var small_phone = $(".small-phone .switch");
    var phone_flying = $(".phone-flying");
    var big_phone = $(".b-where-to-go .phone");
    phone_flying.css({"left": big_phone.offset().left, "top": big_phone.offset().top, "display": "block"});
    phone_flying.animate({"left":  small_phone.offset().left, "top":  small_phone.offset().top, "fontSize": "1.5em", "lineHeight": ".9em"}, 200, function(){
    });
    setTimeout(function(){
        $(".small-phone").css({"visibility": "visible"});
        phone_flying.hide();
    },200);
    $(".f-phone-popup")
            .css({"visibility": "hidden"})
            .removeClass("f-phone-popup_opened");
    }
});


// Подсвечиваем заголовок в попапе с телефоном, при наведении на соответсвующую точку на карте
    $(".b-where-to-go .map .point").hover(
        function() {
            $(this).parents(".b-where-to-go").find(".places h3").eq($(this).prevAll().size()).addClass("pseudo-hover");
        },
        function() {
            $(this).parents(".b-where-to-go").find(".places h3").removeClass("pseudo-hover");
        }
    );

    $(".b-where-to-go .places h3 strong").hover(
        function() {
            $(this).parents(".b-where-to-go").find(".map .point").eq($(this).parents("td").prevAll().size()).addClass("pseudo-hover");
        },
        function() {
            $(this).parents(".b-where-to-go").find(".map .point").removeClass("pseudo-hover");
        }
    );


// Модельный ряд
function modelRange() {
        var modelsShaft = $(".f-model-range .models-shaft");
        if (modelsShaft.width()) {
            var modelSelected = $(".model_selected", modelsShaft);
            modelsShaft
                .css({"left": ($("body").width() / 2) - modelSelected.position().left - (($(".model_selected img", modelsShaft).width() - 50) / 2)  + "px"})
                .addClass("models-shaft_ready");


        modelsShaft.find(".model").not(".model_selected").find("a").one("click", function changeModel(event){
            var destination = $(this).attr("href");
            var newModelSelected = $(this).parents(".model");
            event.preventDefault();
            $("a", modelsShaft).unbind("click", changeModel);
            modelsShaft.find(".model").not(".model_selected").find("a").bind("click", function(event){
                event.preventDefault();
            });
            $(".unselected", modelSelected).show();
            $(".selected", modelSelected).hide();
            $(".model-sprite", modelSelected).css({"background-position": "-50px -50px", "margin-left": "0", "width": $(".model-sprite", modelSelected).width() - 50 + "px"});
            $(".heading", modelSelected)
                .fadeOut(100, function(){
                    $(".model-name", this).text($(".model-name", newModelSelected).text());
                    $(".variants", this).remove();
                    $(this)
                        .appendTo(newModelSelected)
                        .fadeIn(100);
            });
            modelSelected
                .css({"color": "#555"});
            $(this).css({"color": "#fff", "cursor": "default"});
            $(".model-sprite", this).css({"background-position": "0 -100px", "margin-left": "-50px", "width": $(".model-sprite", this).width() + 50 + "px"});
            modelSelected.removeClass("model_selected");
            newModelSelected.addClass("model_selected");
            modelsShaft.animate({"left": ($("body").width() / 2) - newModelSelected.position().left - (($(".model_selected img", modelsShaft).width() - 50) / 2)  + "px"}, 1000, "easeInOutExpo", function(){
                location.href = destination;
            });
        });
        }

}


modelRange();  //Сразу и на ресайзе


//Растяжка «левее, правее»
function ClassAdverstingShield()
    {
        var jItems = $("#adversing-shield-content .block");
        var iItemNumber = 0;
        var aItems = [];

        jItems.each(function()
        {
        	aItems[iItemNumber] = $(this).html();
        	iItemNumber++;
        });

        var iMaxScreen = Math.ceil(iItemNumber/3) - 1;
        var iMax = iMaxScreen;
        var iMin = 0;

        var iMaxItem = iItemNumber - 1;
        var iStartItem = 0;

        var iMinHeight = 150; // Минимальная высота, ниже которой не становится щит
        var iBaseAnimationSpeed = 300; // Базовая скорость анимации
        if ($.browser.msie && $.browser.version == 6) iBaseAnimationSpeed = 0;
        var oThis = this;
        var bIsShieldMoving = false;
        var iCount = 0;
        var i = 1;
        var iBordersHeight = $('.f-adversting-shield .content').parent().height() - $('.f-adversting-shield .content').height();
        $('.f-adversting-shield .adversting-shaft').animate({height: iMinHeight + 'px'}, iBaseAnimationSpeed);
        $("#adv-previous").addClass('disabled-left-arrow');
        $("#adv-next").click( function()
        {
            if (bIsShieldMoving || iCount >= iMax) return false;
            $("#adv-previous").removeClass('disabled-left-arrow');
            bIsShieldMoving = true;
            var iWidth = $('.f-adversting-shield .content').width();
            var jOldShit = $('.f-adversting-shield .content');
            var jNewShield = $('.f-adversting-shield .content').clone();
            // Заполняем новым содержимым
            if ((iCount + 2)*3 <= iMaxItem)
            {
            	iStartItem = (iCount + 1)*3;
            }
            else
            {
            	iStartItem = iMaxItem - 2;
            }
            i = 0;
            $('.column', jNewShield).each(function()
                {
                    $(this).html(aItems[iStartItem + i]);
                    i++;
                });
            jNewShield.css({'position': 'absolute', 'top': '0', 'left': iWidth + 'px', 'width': iWidth + 'px'});
            $('.f-adversting-shield .content').animate({left: -iWidth + 'px'}, iBaseAnimationSpeed, 'swing');
            $('.f-adversting-shield .adversting-shaft').append(jNewShield);

            var iHeight = jNewShield.height() + iBordersHeight;
            if (iHeight < iMinHeight) iHeight = iMinHeight;
            $('.f-adversting-shield .adversting-shaft').animate({height: iHeight + 'px'}, iBaseAnimationSpeed);
            jNewShield.animate({left: 0 + 'px'}, iBaseAnimationSpeed, 'swing', function() {
                jOldShit.remove();
                jNewShield.css({'position': 'relative', 'top': '0', 'left': 0, 'width': 'auto'});
                bIsShieldMoving = false;
                iCount++;
                if (iCount >= iMax) $("#adv-next").addClass('disabled-right-arrow');
            });
        });
        $("#adv-previous").click( function()
        {
            if (bIsShieldMoving || iCount <= iMin) return false;
            $("#adv-next").removeClass('disabled-right-arrow');
            bIsShieldMoving = true;
            var iWidth = $('.f-adversting-shield .content').width();
            var jOldShit = $('.f-adversting-shield .content');
            var jNewShield = $('.f-adversting-shield .content').clone();

            // Заполняем новым содержимым
           	iStartItem = (iCount-1)*3;
            i = 0;
            $('.column', jNewShield).each(function()
                {
                    $(this).html(aItems[iStartItem + i]);
                    i++;
                });

            jNewShield.css({'position': 'absolute', 'top': '0', 'left': -iWidth + 'px', 'width': iWidth + 'px'});
            $('.f-adversting-shield .content').animate({left: iWidth + 'px'}, 300, 'swing');
            $('.f-adversting-shield .adversting-shaft').append(jNewShield);


            var iHeight = jNewShield.height() + iBordersHeight;
            if (iHeight < iMinHeight) iHeight = iMinHeight;
            $('.f-adversting-shield .adversting-shaft').animate({height: iHeight + 'px'}, iBaseAnimationSpeed);
            jNewShield.animate({left: 0 + 'px'}, 300, 'swing', function() {
                jOldShit.remove();
                jNewShield.css({'position': 'relative', 'top': '0', 'left': 0, 'width': 'auto'});
                bIsShieldMoving = false;
                iCount--;
                if (iCount <= iMin) $("#adv-previous").addClass('disabled-left-arrow');
            });
        });
        this.disableArrows = function ()
        {
            $("#adv-next").addClass('no-right-arrow');
            $("#adv-previous").addClass('no-left-arrow');
        }

        //this.disableArrows();

    }

var SHIELD = new ClassAdverstingShield();

// Следим за футером
function footer() {
    var footer_car = $(".f-footer .car");
    footer_cars_width = 0;
    for (i=0; i<footer_car.size(); i++) {
        footer_cars_width += footer_car.eq(i).width();
    }
}

function footer_align() {
    if ($("body").width() > footer_cars_width) {
        $(".f-footer .cars").addClass("cars_align-center");
    } else {
        $(".f-footer .cars").removeClass("cars_align-center");
    }
}


footer();
footer_align();


// Прибиваем картинки к подписи у инлайн-блоков, ровняем высоту блоков, стоящих в одном ряду
// В «шахматном» шоуруме ровняем все блоки ещё и по ширине, для красивых переносов.
function showroom(resize) {
    var showroom = $(".f-showroom");
    if (showroom.width()) {
        for (q=0; q<showroom.size(); q++) {
            var car = $(".f-showroom").eq(q).find(".car").not(".car_not-in-line");
            var car_chess = $(".f-showroom_chess").eq(q).find(".car");
            car.removeClass("car_first-in-line_odd");
            if (car.width()) {
                var start_i = 0;
                var start_top = car.eq(0).position().top;
                var max_height_in_row = 0;
                var max_width = 0;
                var odd = 1;
                var image = car.find(".image");
                var label = car.find(".label");
                for (i=0; i<car.size(); i++) {
                    if (resize == 0) {
                        if ( image.eq(i).width() > max_width ) {
                                max_width = image.eq(i).width();
                            }
                        image.css("width", max_width + "px");
                    }
                    if (resize == 1) {
                        image.eq(i).css("height", image.eq(i).find("img").height());
                    }
                    var image_height = image.eq(i).height();
                    if ( image_height > max_height_in_row ) {
                        max_height_in_row = image_height;
                    }
                    if ( (i + 1 == car.size()) || (car.eq(i+1).position().top > start_top) ) {
                        //alert(max_height_in_row);
                        if ( (i + 1 == car.size()) || (car.eq(i+1).position().top > start_top) ) {
                            if (i + 1 != car.size()) {
                                image.slice(start_i, i+1).css("height", max_height_in_row + "px");
                                if (odd % 2 && car_chess.width()) {
                                    car.eq(i+1).addClass("car_first-in-line_odd");
                                }
                                start_i = i+1;
                                start_top = car.eq(i+1).position().top;
                                max_height_in_row = 0;
                                odd++;
                            } else {
                                image.slice(start_i)
                                    .css("height", max_height_in_row + "px");
                                if (odd % 2 && car.eq(i).position().top > start_top  && car_chess.width()) {
                                    car.eq(i).addClass("car_first-in-line_odd");
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

showroom(0);

function facts(resize) {
    var fact = $(".f-model-features .fact");
    if (fact.width()) {
        var start_i = 0;
        var start_top = fact.eq(0).position().top;
        var max_height_in_row = 0;
        var image = fact.children("div").children(".image");
        for (i=0; i<fact.size(); i++) {
            if (resize == 1) {
                image.eq(i).css("height", image.eq(i).find("img").height());
            }
            var image_height = image.eq(i).height();
            if ( image_height > max_height_in_row ) {
                max_height_in_row = image_height;
            }
            if ( (i + 1 == fact.size()) || (fact.eq(i+1).position().top > start_top) ) {
                if (i + 1 != fact.size()) {
                    image.slice(start_i, i+1).css("height", max_height_in_row + "px");
                    start_i = i+1;
                    start_top = fact.eq(i+1).position().top;
                    max_height_in_row = 0;
                } else {
                    image.slice(start_i).css("height", max_height_in_row + "px");
                }
            }
        }
    }
}

facts(0);

// Пересчитываем всё, что нужно пересчитать при ресайзе
$(window).resize(function(){
    showroom(1);
    facts(1);
    footer_align();
    modelRange();
});


});
