//*******************************************************************************************/
// $.event.special.hover Plugin - rev 5
// Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
// Created: 2008-06-02 | Updated: 2008-07-30
//*******************************************************************************************/

(function(c){c.fn._hover=c.fn.hover;c.fn.hover=function(f,e,d){if(d){this.bind("hoverstart",f)
}if(e){this.bind("hoverend",d?d:e)}return !f?this.trigger("hover"):this.bind("hover",d?e:f)
};var b=c.event.special.hover={delay:100,speed:100,setup:function(d){d=c.extend({speed:b.speed,delay:b.delay,hovered:0},d||{});
c.event.add(this,"mouseenter mouseleave",a,d)},teardown:function(){c.event.remove(this,"mouseenter mouseleave",a)
}};function a(d){var f=d.data||d;switch(d.type){case"mouseenter":f.dist2=0;f.event=d;
d.type="hoverstart";if(c.event.handle.call(this,d)!==false){f.elem=this;c.event.add(this,"mousemove",a,f);
f.timer=setTimeout(e,f.delay)}break;case"mousemove":f.dist2+=Math.pow(d.pageX-f.event.pageX,2)+Math.pow(d.pageY-f.event.pageY,2);
f.event=d;break;case"mouseleave":clearTimeout(f.timer);if(f.hovered){d.type="hoverend";
c.event.handle.call(this,d);f.hovered--}else{c.event.remove(f.elem,"mousemove",a)
}break;default:if(f.dist2<=Math.pow(f.speed*(f.delay/1000),2)){c.event.remove(f.elem,"mousemove",a);
f.event.type="hover";if(c.event.handle.call(f.elem,f.event)!==false){f.hovered++}}else{f.timer=setTimeout(e,f.delay)
}f.dist2=0;break}function e(){a(f)}}})(jQuery);

/*******************************************************************************************/

$(document).ready(function ()
{
    //---------------------------------------------------------------------
    //  About System Block
    //---------------------------------------------------------------------
    if ($('#priceua_about-system').length)
    {
        setAboutSystemPosition();
    }

    //---------------------------------------------------------------------
    //  Search field helper phrase
    //---------------------------------------------------------------------
    $('#q').focus(function () {
        if ($(this).attr('value') == 'Что Вы хотите купить?') {
            $('#priceua_search-box .search-box_content').removeClass('disabled').addClass('active');
            $(this).removeClass('disabled').addClass('active');
            $(this).attr('value','');
        }
        $("#checkbox-menu").removeClass("opened");
        if ($('#checkbox-menu').css('display') == 'none')
        {
            $('#checkbox-menu').show();
            $('.search-box_wrapper').addClass('with_menu');
        }
    });
    $('#q').blur(function (){
        if ($(this).attr('value') == '') {
            $("#priceua_search-box .search-box_content").removeClass('active').addClass('disabled');
            $(this).removeClass('active').addClass('disabled');
            $(this).attr('value','Что Вы хотите купить?');
        }
        $('#priceua_header #love-day-share-link').removeClass('vs-autosuggest');
    });
    $("#imageField").click(function () {
        return checkSubmitForm();

        if ($('#checkbox-menu:visible').length)
        {
            $("#checkbox-menu").removeClass("opened");
            if ($("#q").attr('value') == 'Что Вы хотите купить?' || $("#q").attr('value') == '') {
                $("#checkbox-menu").hide();
                $('.search-box_wrapper').removeClass('with_menu');
            }
        }
    });
    $("#q").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            return checkSubmitForm();
            return false;
        } else {
            return true;
        }
    });

    //---------------------------------------------------------------------
    //  Show|hide categories on main (new header as split 105)
    //---------------------------------------------------------------------
    $('#show-category a').click(function() {
        $(this).toggleClass('active');
        $('#priceua_search').toggleClass('show-categories');
        $('#priceua_new-categories').toggle();

        if ($(this).hasClass('active') && $('#category-tab_history .main_category_link').hasClass('current')) {
            pageTracker._trackEvent('user_panel', 'history', 'show');
        }

        if (!$(this).hasClass('active') && $.browser.msie && $.browser.version == 8)
       {
            var h = $(".top_popular-content").height();
            $(".top_popular-content").height(h);
            $(".top_popular-content").css('padding-bottom','40px');
       }
        return false;
    });

    //---------------------------------------------------------------------
    //  Show|hide user link (for loggined user)
    //---------------------------------------------------------------------
    $('#priceua_header .regmenow li.user-nick a').click(function() {
        if ($("#geo-regions").hasClass("opened_from_header"))
        {
            closeRegionFromHeader();
        }
        else if ($("#geo-regions").hasClass("opened_from_content"))
        {
            animateRegionToHeader();
        }

        $('#user-links').show();
        $(this).css('visibility','hidden');
        $('#priceua_search').addClass('user-links-show');
        return false;
    });
    $('#priceua_header #user-links .user-nick a').click(function() {
        $('#user-links').hide();
        $('#priceua_header .regmenow li.user-nick a').css('visibility','visible');
        $('#priceua_search').removeClass('user-links-show');
        return false;
    });

    $('#show_all_categories').click(function() {
        $("a[id^='activator_']").each(function() {
                var activator_id = $(this).attr('id');
                $(this).fadeOut();
                $("#t_" + activator_id).fadeIn(function() {
                    if ($.browser.msie) this.style.removeAttribute('filter');
                });
                $("#t_" + activator_id + "_2").fadeIn(function() {
                   if ($.browser.msie) this.style.removeAttribute('filter');
                });
            });
     });

    //---------------------------------------------------------------------
    //  SEO Description text for catalog
    //---------------------------------------------------------------------
    $('#block_best-feedbacks .hide_link').click(function() {
        $(this).hide().next().show('fast');
        return false;
    });
    $('#block_section-description p:gt(1)').hide();
    $('#block_section-description p:eq(1)').append(
        ' <a href="javascript:void(0);" onclick="$(this).hide(); $(\'#block_section-description p:gt(1)\').show(\'normal\');" class="common" title="Открыть текст">...</a>'
    );

    //---------------------------------------------------------------------
    //  Comparison scripts
    //---------------------------------------------------------------------
    $("a[id^='activator_']").click(function() {
        var activator_id = $(this).attr('id');
        $(this).fadeOut();
        $("#t_" + activator_id).fadeIn();
        if ($("#t_" + activator_id).prev(".ellipsis").length) $("#t_" + activator_id).prev(".ellipsis").fadeOut();
    });

    //---------------------------------------------------------------------
    //  AJAX link for "categories" menu for all pages except index
    //---------------------------------------------------------------------
    var link_menu_opened = false;
    var categories_link_menu_timeout = null;
    $('#ajax-link_menu-categories-new').click(function() {
        if ($("#geo-regions").hasClass("opened_from_header"))
        {
            closeRegionFromHeader();
        }
        else if ($("#geo-regions").hasClass("opened_from_content"))
        {
            animateRegionToHeader();
        }

        if ($('#checkbox-menu:visible').length)
        {
            $("#checkbox-menu").removeClass("opened");
            if ($("#q").attr('value') == 'Что Вы хотите купить?' || $("#q").attr('value') == '') {
                $("#checkbox-menu").hide();
                $('.search-box_wrapper').removeClass('with_menu');
            }
        }
        if ($('#priceua_categories').css('display') == 'block' && !$('#priceua_categories').hasClass('default-view'))
        {
            $('#priceua_categories').fadeOut(100, function () {
                link_menu_opened = false;
                $('#priceua_search').removeClass('show-categories');
                $('#show-category a').removeClass('active');
                $('#show-category a span').css('background', 'url(/images/site_0/skin_1/backgrounds/new-ny-split.png) no-repeat -880px -338px');
            });
        }
        else
        {
            clearTimeout(categories_link_menu_timeout);
            if ( $('#priceua_categories_wrapper').length && ! $('#priceua_categories_wrapper').hasClass('loaded')) {
                $.ajax({
                    type: 'POST',
                    url: '/index.php?action=main_catalog',
                    data : { gaTrackerPageType : typeof(window.gaTrackerPageType) !== 'undefined' ? window.gaTrackerPageType : '' },
                    beforeSend: function () {
                        $('#ajax-loading_menu-categories').addClass('loading');
                        $('#show-category a span').css('background', 'url(/images/site_0/skin_1/animations/spin_dotted-blue.gif) no-repeat 3px 2px');
                    },
                    success: function(data) {
                        $('#priceua_categories_wrapper').html(data);
                        $('#priceua_categories_wrapper').addClass('loaded');
                        $('#ajax-loading_menu-categories').removeClass('loading');
                        if ($('#category-tab_history .main_category_link').hasClass('current')) {
                            pageTracker._trackEvent('user_panel', 'history', 'show');
                        }
                        $('#show-category a span').css('background', 'url(/images/site_0/skin_1/backgrounds/new-ny-split.png) no-repeat -880px -322px');
                        $('#panes_history .history-models').addClass('size_' + $('#panes_history .history-models div.model-item').length);
                    }
                });
            }
            $('#priceua_categories').fadeIn(100, function () {
                link_menu_opened = true;
                $('#priceua_search').addClass('show-categories');
                $('#show-category a').addClass('active');
                $('#show-category a span').css('background', 'url(/images/site_0/skin_1/backgrounds/new-ny-split.png) no-repeat -880px -322px');
            });
        }
        return false;
    });

    //---------------------------------------------------------------------
    //  Popup for Discount
    //---------------------------------------------------------------------
    $('.discount-popup-link').mouseover(function(){
        offset = $(this).offset();
        popup_h = $('#discount-popup').height();
        showHelpPopup('discount-popup', offset);
        $('#discount-popup').show();
    }).mouseout(function(){
        $('#discount-popup').hide();
    });

    //---------------------------------------------------------------------
    //  Popup for Top5
    //---------------------------------------------------------------------
    $('.top5-popup-link').mouseover(function(){
        offset = $(this).offset();
        popup_h = $('#top5-popup').height();
        showHelpPopup('top5-popup', offset);
        $('#top5-popup').show();
    }).mouseout(function(){
        if (!$('#top5-popup').hasClass('hovered')) $('#top5-popup').hide();
    });

    //---------------------------------------------------------------------
    //  Popup for Sell This Model (model page)
    //---------------------------------------------------------------------
    $('#sell-this-model').mouseover(function(e){
        offset = $(this).offset();
        popup_h = $('#sell-this-model-popup').height();
        showHelpPopup('sell-this-model-popup', offset, 700, e.pageX);
        $('#sell-this-model-popup').show();
    }).mouseout(function(){
        $('#sell-this-model-popup').hide();
    });

    //---------------------------------------------------------------------
    //  Hover for IE6
    //---------------------------------------------------------------------
    $('.price-line').mouseover(function(){
        $(this).addClass('hovered');
    }).mouseout(function(){
        $(this).addClass('hovered');
    });

    //---------------------------------------------------------------------
    //  Geo-targeting
    //---------------------------------------------------------------------
    if ($('#region_not_identified').length)
    {
        var site_left = $('#priceua_header').offset().left;
        var reg_not_ident_left = $('#select-region .icon').offset().left - site_left - 45;
        if (site_left < 45)
        {
            reg_not_ident_left = 690;
            var top_arrow_left = $("body").width() - site_left - $('#select-region .icon').offset().left - 60;
            $('#region_not_identified .top-arrow').css({'left':'auto','right':top_arrow_left});
        }
        $('#region_not_identified').css('left', reg_not_ident_left);
        $('#region_not_identified').fadeIn('fast');
    }
    $('#region_not_identified.show, #region_not_identified .select-city').click(function() {
        openRegionFromHeader();
        $(this).fadeOut('fast');
    });
    $("#select-region").click(function() {
        if (!$("#geo-regions").hasClass("opened_from_header"))
        {
            openRegionFromHeader();
            $('#region_not_identified').fadeOut('fast');
        }
        else
        {
            closeRegionFromHeader();
        }
    });
    $(".change-region-from-cont").click(function() {
        var geo_top = ($("body").height() - 358) / 2 + $(document).scrollTop();
        $("#geo-regions").css({top:geo_top, height:358, width:475, left:262, opacity: 1});
        $("#geo-regions").addClass("opened_from_content");
        $("#geo-regions").show(function() {
            if ($.browser.msie) this.style.removeAttribute('filter');
        });
        if ($(this).hasClass('edit_link')) pageTracker._trackEvent('region', 'show_dialog_from_changelink');
            else pageTracker._trackEvent('region', 'show_dialog_from_name');
    });
    $("#geo-close").click(function() {
        animateRegionToHeader();
    });
    $('#form-regions input[name="GeoRegion"]').change(function() {
        if ($("#geo-regions").hasClass("opened_from_header"))
        {
            closeRegionFromHeader();
        }
        else if ($("#geo-regions").hasClass("opened_from_content"))
        {
            if ($.browser.opera)
            {
                $("#geo-regions").fadeOut('slow');
                $("#geo-regions").removeClass("opened_from_content");
            }
            else
            {
                animateRegionToHeader();
            }
        }
        iRegionId = $(this).attr('id');
        $('#form-regions').attr('action', 'http://' + mainDomain + fullUrl.replace(/t[0-9]+/, 't' + $("#"+iRegionId).val()));
        sRegionNameTo = $(this).next('label[for="'+iRegionId+'"]').text();
        if (typeof(fromiRegionId) == 'undefined') fromiRegionId = 'Вся Украина';
        pageTracker._trackEvent('region', 'changed', fromiRegionId + '_TO_' + sRegionNameTo);
        $('#form-regions').submit();
    });
    $('#form-regions input[name="GeoRegion"]').mouseover(function() {
        $(this).next('#geo-regions label').addClass('hover');
    }).mouseout(function(){
        $(this).next('#geo-regions label').removeClass('hover');
    });

    $('body').click(function(event) {
        if (event.target.id != 'priceua_new-categories' && $(event.target).parents().filter('#priceua_new-categories:visible').length != 1 && event.target.id != 'priceua_categories_wrapper' && $(event.target).parents().filter('#priceua_categories_wrapper:visible').length != 1 && !$('#priceua_search').hasClass('is_main')) {
            $('#priceua_new-categories').hide();
            $('#priceua_search').removeClass('show-categories');
            $('#show-category a').removeClass('active');
        }

        // user menu in header
        if (event.target.id != 'user-links' && $(event.target).parents().filter('#user-links:visible').length != 1) {
            $('#user-links').hide();
            $('#priceua_header .regmenow li.user-nick a').css('visibility','visible');
            $('#priceua_search').removeClass('user-links-show');
        }

        if (event.target.id != 'checkbox-menu' && $(event.target).parents().filter('#checkbox-menu:visible').length != 1 && event.target.id != 'q' && event.target.id != 'category-span') {
            $("#checkbox-menu").removeClass("opened");
            if ($("#q").attr('value') == 'Что Вы хотите купить?' || $("#q").attr('value') == '') {
                $("#checkbox-menu").hide();
                $('.search-box_wrapper').removeClass('with_menu');
            }
        }

        // show all categories
        if (event.target.id != 'priceua_categories' && $(event.target).parents().filter('#priceua_categories:visible').length != 1 && !$('#priceua_search').hasClass('is_main') && !$('#priceua_categories').hasClass('default-view'))
        {
            $('#priceua_categories').fadeOut(100, function () {
                link_menu_opened = false;
                $('#show-category a').removeClass('active');
                $('#show-category a span').css('background', 'url(/images/site_0/skin_1/backgrounds/new-ny-split.png) no-repeat -880px -338px');
            });
        }

        // Geo-targeting
        if (event.target.id != 'geo-regions' && $(event.target).parents().filter('#geo-regions:visible').length != 1 && event.target.id != 'select-region' && $(event.target).parents().filter('#select-region:visible').length != 1 && event.target.id != 'region_not_identified' && $(event.target).parents().filter('#region_not_identified:visible').length != 1) {
            if ($("#geo-regions").hasClass("opened_from_header"))
            {
                closeRegionFromHeader();
            }
            else if ($("#geo-regions").hasClass("opened_from_content") && !$(event.target).hasClass("change-region-from-cont") && $(event.target).parents().filter('.change-region-from-cont').length != 1)
            {
                animateRegionToHeader();
            }
            if (!$("#geo-regions").hasClass("opened_from_content")) {
                $("#geo-regions").fadeOut('fast');
            }
        }

        // User Toolbar
        if (event.target.id != 'history-popup' && $(event.target).parents().filter('#history-popup:visible').length != 1 && event.target.id != 'history' && $(event.target).parents().filter('#history:visible').length != 1 && $('#history-popup:visible').length > 0)
        {
            closeUserToolbarPopup('history', false);
        }
        if (event.target.id != 'compare-popup' && $(event.target).parents().filter('#compare-popup:visible').length != 1 && event.target.id != 'compare' && $(event.target).parents().filter('#compare:visible').length != 1 && $('#compare-popup:visible').length > 0)
        {
            closeUserToolbarPopup('compare', false);
        }
        if (event.target.id != 'poll-popup' && $(event.target).parents().filter('#poll-popup:visible').length != 1 && event.target.id != 'poll' && $(event.target).parents().filter('#poll:visible').length != 1 && $('#poll-popup:visible').length > 0)
        {
            closeUserToolbarPopup('poll', false);
        }
        if (event.target.id != 'what-this' && $(event.target).parents().filter('#what-this:visible').length != 1 && event.target.id != 'what-this-popup' && $(event.target).parents().filter('#what-this-popup:visible').length != 1)
        {
            if ($('#what-this-popup:visible').length > 0)
            {
                $('#what-this-popup').hide();
                $('#what-this-popup').removeClass('show');
                $('#what-this-popup .del-model').addClass('hidden');
            }
        }
    });

    //---------------------------------------------------------------------
    //  Banner 160x600 on Bazar
    //---------------------------------------------------------------------
    if ( $('.bazar-banner').length ) {
        showRightBazarBanner();
        if ( $(document).scrollTop() > 0 ) slideRightBazarBanner();
    }
    $(window).resize(function () {
        showRightBazarBanner();
        if ($('#priceua_about-system').length) setAboutSystemPosition();
    });
    $(window).scroll(function () {
        slideRightBazarBanner();
    });

    //---------------------------------------------------------------------
    //  User Toolbar (#881 - split 3)
    //---------------------------------------------------------------------
    $('#user-toolbar #history').click(function() {
        if (!$(this).hasClass('active')) {
            $.ajax({
                type: "POST",
                url: "/module/history/get-history",
                dataType: "json",
                beforeSend: function () {
                    $('#user-toolbar #history').addClass('loading');
                },
                success: function(data) {
                    if (typeof data.r.models != 'undefined'){
                        // очищаем и скрываем все, относящееся к показу истории моделей/категорий
                        $('#del-history-models').addClass('hidden');
                        $('#head-history-empty').addClass('hidden');
                        $('#head-history-list-models').addClass('hidden');
                        $('#head-history-categories').addClass('hidden');
                        $('#history-categories').html('');
                        $('#history-list-models').html('');
                        $('#count-history-models').text('0');
                        if (data.r.models.length != 0 || data.r.other.length != 0) {
                            $('#del-history-models').removeClass('hidden');
                            if (data.r.models.length != 0) {
                                $('#head-history-list-models').removeClass('hidden');
                                $('#history-list-models').html(data.r.models);
                                $('#count-history-models').text($('#history-list-models .list-models-item').length); // обновляем кол-во моделей в тулбаре
                                $('#head-history-categories').removeClass('no_models');
                            } else {
                                $('#head-history-categories').addClass('no_models');
                            }
                            if (data.r.other.length != 0) {
                                $('#head-history-categories').removeClass('hidden');
                                $('#history-categories').html(data.r.other);
                            }
                            $('table.top_propos tr td span.nopause').each(function() {
                                $(this).replaceWith('<a href="' + $(this).attr('href') + '" class="' + $(this).attr('class') + '" id="' + $(this).attr('id') + '" title="' + $(this).attr('title') + '" target="_blank" rel="nofollow">' + $(this).html() + '</a>');
                            });
                            $('table.top_propos tr td span.pause').each(function() {
                                $(this).replaceWith('<a href="' + $(this).attr('href') + '" class="' + $(this).attr('class') + '" id="' + $(this).attr('id') + '" title="' + $(this).attr('title') + '">' + $(this).html() + '</a>');
                            });
                        } else {
                            $('#head-history-empty').removeClass('hidden');
                            $('#history-categories').html('<p>Здесь сохраняется информация о недавно просмотренных товарах или категориях.<br/>Вы пока не просматривали ни одной категории и не выбирали еще ни одной модели.</p>');
                        }
                        $('#user-toolbar #history').removeClass('loading');
                    }
                    showUserToolbarPopup('history');
                    pageTracker._trackEvent('user_panel', 'bar_history', 'show');
                }
            });
        } else {
            closeUserToolbarPopup('', true);
            $('#history-list-models').html('');
            $('#history-categories').html('');
        }
    });

    $('#user-toolbar #compare').click(function() {
        if (!$(this).hasClass('active')) {
            $.ajax({
                type: "POST",
                url: "/module/history_compare/get-info",
                dataType: "json",
                beforeSend: function () {
                    $('#user-toolbar #compare').addClass('loading');
                },
                success: function(data) {
                    if (typeof data.r != 'undefined'){
                        // очищаем и скрываем все, относящееся к показу моделей добавленных к сравнению
                        $('#go-compare').addClass('hidden');
                        $('#del-compare-models').addClass('hidden');
                        $('#compare-popup .divider-horisontal').addClass('hidden');
                        $('#compare-list-models').html('');
                        $('#count-compare-models').text('0');
                        if (data.r.length != 0){
                            $('#go-compare').removeClass('hidden');
                            $('#del-compare-models').removeClass('hidden');
                            $('#head-compare-list-models').removeClass('hidden');
                            $('#compare-popup .divider-horisontal').removeClass('hidden');
                            $('#compare-list-models').html(data.r);
                            $('#count-compare-models').text($('#compare-list-models .list-models-item').length);
                        } else {
                            $('#compare-list-models').html('<p>Вы пока не выбирали ни одной модели. Выберите минимум две для сравнения.</p>');
                        }
                        $('#user-toolbar #compare').removeClass('loading');
                    }
                    showUserToolbarPopup('compare');
                    pageTracker._trackEvent('user_panel', 'compare', 'show');
                }
            });
        } else {
            closeUserToolbarPopup('', true);
            $('#compare-list-models').html('');
        }
    });

    $('#user-toolbar #poll').click(function() {
        if (!$(this).hasClass('active')) {
            showUserToolbarPopup('poll');
            pageTracker._trackEvent('user_panel', 'poll', 'show');
        } else {
            closeUserToolbarPopup('', true);
        }
    });

    $('#poll_form input[name="radio_vote"]').mouseover(function() {
        $(this).next('label').addClass('hover');
    }).mouseout(function(){
        $(this).next('label').removeClass('hover');
    });
    //---------------------------------------------------------------------
    //  Hide User Toolbar (#881 - split 3)
    //---------------------------------------------------------------------
    $('#hide-toolbar').click(function() {
        $('#user-toolbar').animate({
            width: 0,
            right: 0,
            opacity: 0
        }, function() {
            if ($.browser.msie) this.style.removeAttribute('filter');
        });
        $('#user-toolbar-hided').show();
        $.cookie("hide_toolbar", 1, {expires: 1, path: '/'});
    });
    //---------------------------------------------------------------------
    //  Show Toolbar (#881 - split 3)
    //---------------------------------------------------------------------
    $('#show-toolbar').click(function() {
        $('#user-toolbar-hided').hide();
        $('#user-toolbar').animate({
            width: '100%',
            opacity: 1
        }, function() {
            if ($.browser.msie) this.style.removeAttribute('filter');
        });
        $.cookie("hide_toolbar", 0, {expires: 1, path: '/'});
    });

    $('.show-category-popup').click(function() {
        $.ajax({
            type: "POST",
            url: "/module/history_compare/compare",
            dataType: "json",
            success: function(data) {
                if (typeof data.r != 'undefined') {
                    if (data.r.redirect) {
                        window.location = data.r.redirect;
                    } else if(data.r.categories) {
                        $('#select-category-popup').html(data.r.categories);
                        $('#select-category-popup').show();
                        $('.show-category-popup').fadeTo('fast', 0.2);
                    }
                }
            }
        });
    });

    //---------------------------------------------------------------------
    //  What this (User toolbar help popup)
    //---------------------------------------------------------------------
    $('#what-this').mouseover(function(e) {
        if ($('#user-toolbar').css('opacity') == 1)
        {
            var bottom_arrow_left = e.pageX;
            showWhatThisPopup(bottom_arrow_left);
        }
    }).mouseout(function(){
        $('#what-this-popup').hide();
        $('#what-this-popup .del-model').addClass('hidden');
    });

    $('.simple-close').click(function() {
        $(this).parent().hide();
        if ($(this).parent().attr('id') == 'what-this-popup')
        {
            $('#what-this-popup .del-model').addClass('hidden');
        }
    });

    /*  added link to h1 - model page  */
    $('#page_model #breadcrumbs-simple-new.prices_tab h1').html('<a href="#price-lines">' + $('#page_model #breadcrumbs-simple-new.prices_tab h1').text() + '</a>');

    /*  Show/Hide user_feedback-link on model page  */
    $('#page_model div.model-info div.description tr.post_comment').mouseover(function(e) {
        $('#page_model div.model-info div.description a.common.user_feedback').css('display', 'inline');
    }).mouseout(function(){
        $('#page_model div.model-info div.description a.common.user_feedback').css('display', 'none');
    });

    //---------------------------------------------------------------------
    //  Total User reg/auth Popup
    //---------------------------------------------------------------------
    if ($.browser.opera || $.browser.msie) {
        $('div.username-wrapper').each(function() {
            $(this).addClass('opera');
        });
    }
    $(document).delegate("a.window-popup-link", "click", function() {
        var window_left = 0;
        if ($('body').width() > 1040) window_left = ($('body').width() - 1040) / 2;
        window.open($(this).attr('href'),'user_agreement','width=1040,height=' + ($(document).height() - 160) + ',left=' + window_left + ',top=110,scrollbars=yes');
        return false;
    });
    $('#total-reg-auth-overlay').click(function() {
        $('.total-reg-popup').each(function() {
            $(this).hide('fast');
        });
        $(this).hide('fast');
    });

    //---------------------------------------------------------------------
    //  Bazar Subcribe
    //---------------------------------------------------------------------
    $('div#total-bazar-popup div.checkbox-wrapper input.input-checkbox').mouseover(function(e) {
        $(this).next().addClass('hovered');
    }).mouseout(function(){
        $(this).next().removeClass('hovered');
    });
    $('div#total-bazar-popup div.checkbox-wrapper input.input-checkbox').change(function() {
        $(this).next().toggleClass('checked');
    });
    $('input#category_all').change(function() {
        if ($(this).is(":checked"))
        {
            $('form#bazar_subscribe input.input-checkbox').each(function() {
                $(this).attr('checked', 'checked');
                $(this).next().addClass('checked');
            });
        }
    });
    
    //---------------------------------------------------------------------
    //  SEO for top-proposition links
    //---------------------------------------------------------------------
    $('table.top_propos tr td span.nopause').each(function() {
        $(this).replaceWith('<a href="' + $(this).attr('href') + '" class="' + $(this).attr('class') + '" id="' + $(this).attr('id') + '" title="' + $(this).attr('title') + '" target="_blank" rel="nofollow">' + $(this).html() + '</a>');
    });
    $(document).delegate("table.top_propos a.nopause", "mousedown", function() {
        var aid = $(this).attr('id');
        if (aid != '') pageTracker._trackPageview('"' + aid + '"');
    });
    $('table.top_propos tr td span.pause').each(function() {
        $(this).replaceWith('<a href="' + $(this).attr('href') + '" class="' + $(this).attr('class') + '" id="' + $(this).attr('id') + '" title="' + $(this).attr('title') + '">' + $(this).html() + '</a>');
    });
    $(document).delegate("table.top_propos a.pause", "click", function() {
        if ($('#history').hasClass('active')) closeUserToolbarPopup('history', false);
        getPriceInfo($(this).attr('id'));
    });
    
    //---------------------------------------------------------------------
    //  SEO for links in price-lines
    //---------------------------------------------------------------------
    $('div.price-line.catalog div.row-wrapper div.row div.product span.nopause').each(function() {
        $(this).replaceWith('<a href="' + $(this).attr('href') + '" class="' + $(this).attr('class') + '" id="' + $(this).attr('id') + '" target="_blank" rel="nofollow">' + $(this).html() + '</a>');
    });
    $(document).delegate("div.price-line.catalog div.row-wrapper div.row div.product a.nopause", "mousedown", function() {
        var aid = $(this).attr('id');
        if (aid != '') pageTracker._trackPageview('"' + aid + '"');
    });
    $('div.price-line.catalog div.row-wrapper div.row div.product span.pause').each(function() {
        $(this).replaceWith('<a href="' + $(this).attr('href') + '" class="' + $(this).attr('class') + '" id="' + $(this).attr('id') + '">' + $(this).html() + '</a>');
    });
    $(document).delegate("div.price-line.catalog div.row-wrapper div.row div.product a.pause", "click", function() {
        getPriceInfo($(this).attr('id'));
    });
    
    //---------------------------------------------------------------------
    //  SEO for links in recomended-goods
    //---------------------------------------------------------------------
    $('div.price-line_recomended-goods span.total_offers').each(function() {
        $(this).replaceWith('<a href="' + $(this).attr('rel') + '" class="' + $(this).attr('class') + '" id="' + $(this).attr('id') + '" rel="nofollow">' + $(this).html() + '</a>');
    });
    $(document).delegate("div.price-line_recomended-goods a.total_offers", "mousedown", function() {
        var aid = $(this).attr('id');
        $.cookie('last_action_id', aid, { expires: 0.01, path: '/'}); 
        pageTracker._trackPageview('/priceua_blocks/banners_split_click_by_' + aid);
    });
    
    //---------------------------------------------------------------------
    //  Discount Subscribe field helper phrase
    //---------------------------------------------------------------------
    $('#discount-subscribe_email').focus(function () {
        if ($(this).val() == 'Ваш E-mail') {
            $(this).val('');
             $(this).addClass('active');
        }
    });
    $('#discount-subscribe_email').blur(function (){
        if ($(this).val() == '') {
            $(this).val('Ваш E-mail');
            $(this).removeClass('active');
        }
    });
    
    //---------------------------------------------------------------------
    //  Context Ads (Height)
    //---------------------------------------------------------------------
    if (($('div.context-wrapper div.context-ads.big-img').length || $('div.context-wrapper div.context-ads.middle-img').length) && !$('div.context-wrapper').hasClass('dinamics'))
    {
        var aContextHeight = []
        $('div.context-wrapper div.context-ads div.ad-item').each(function(index) {
            aContextHeight[index] = $(this).children('a').height()
        })
        $('div.context-wrapper div.context-ads div.ad-item a').height(Math.max.apply(null, aContextHeight))
    }
    
    /*  Browser type & version  */
    var browser_data;
    if ($.browser.webkit) browser_data = 'webkit';
    else if ($.browser.opera) browser_data = 'opera';
    else if ($.browser.msie) browser_data = 'msie';
    else if ($.browser.mozilla) browser_data = 'mozilla';
    browser_data += ' v' + parseInt($.browser.version);
    $('html').addClass(browser_data);
    
    //---------------------------------------------------------------------
    //  Credit field helper phrase
    //---------------------------------------------------------------------
    $(document).delegate("#credit-form-phone", "focus", function() {
        if ($(this).val() == 'Например: 0447589955') {
            $(this).val('');
            $(this).removeClass('unactive');
        }
    });
    $(document).delegate("#credit-form-phone", "blur", function() {
        if ($(this).val() == '') {
            $(this).val('Например: 0447589955');
            $(this).addClass('unactive');
        }
    });
    
    $(document).delegate("#user-popup-overlay", "click", function() {
        hideRegAuthPopup();
    });
    $(document).delegate("#user-popup-container a.close-popup", "click", function() {
        hideRegAuthPopup();
    });
    
    //---------------------------------------------------------------------
    //  SEO for links in price-lines (Grid Mode)
    //---------------------------------------------------------------------
    $('div.grid-item div[id^="grid-item-priceline_"]').each(function() {
        $(this).replaceWith('<a href="' + $(this).attr('class') + '" id="' + $(this).attr('id') + '" title="' + $(this).attr('title') + '" class="' + $(this).attr('rel') + '" target="_blank" rel="nofollow">' + $(this).html() + '</a>');
    });
    $(document).delegate('div.grid-item a[id^="grid-item-priceline_"]', 'mousedown', function() {
        var aid = $(this).attr('class');
        if (aid != '' && typeof aid != 'undefined') pageTracker._trackPageview('"' + aid + '"');
        $.priceClickTrack('catalog');
    });
});

function delModel(mid, all, module, controller)
{
    if (!mid && !all) return false;
    $.ajax({
        type: "POST",
        url: "/module/" + controller + "/d-items",
        data: {"mid" : mid, "all" : all},
        dataType: "json",
        success: function(data) {
            if (typeof data.r != 'undefined') {
                if (data.r.mid != 0) {
                    $('.' + module + '_model_' + data.r.mid).each(function(){
                        $(this).remove();
                    });
                    if (module == 'compare') {
                        UnCheck(data.r.mid);
                        if ($('#compare_models li').length == 0 || $('#compare_models li').length == 'undefined') {
                            $('#compare_bodels_block').hide();
                            $('ul.other-pages').css('margin-bottom','1em');
                        }
                    }
                    plusMinuseOne(module, '-');
                } else if (data.r.all != 0) {
                    $('#' + module + '-list-models').html('');
                    $('#count-' + module + '-models').text(0);
                    clearToolbarBlock(module, true);
                    if ($('#page_comparison').length) {
                        $('#page_comparison div.price-line.comparison label input[type=checkbox]').each(function() {
                            $(this).attr('checked', false);
                        });
                    }
                }
            }
        }
    });
}

function countHistoryModels(count)
{
    $('#count-compare-models').text(count);
}

function plusMinuseOne(module, operation)
{
    if (operation == '+') {
        countHistory = parseInt($('#count-' + module + '-models').text()) + 1;
        $('#count-' + module + '-models').text(countHistory);
        $('#compare_bodels_block').removeClass('hidden');
    } else if (operation == '-') {
        countHistory = parseInt($('#count-' + module + '-models').text()) - 1;
        if (countHistory >= 0) {
            $('#count-' + module + '-models').text(countHistory);
        }
        if (countHistory == 0) {
            clearToolbarBlock(module, false);
        }
    }
}

function clearToolbarBlock(module, del_all) {
    if (module == 'history') {
        var countHistory = parseInt($('#count-' + module + '-models').text()) + $('#history-categories ul li').length;
        $('#head-' + module + '-list-models').addClass('hidden');
        $('#history-list-models').html('');
        if (countHistory == 0 || del_all)
        {
            $('#del-' + module + '-models').addClass('hidden');
            $('#head-history-categories').addClass('hidden');
            $('#history-categories').html('<p>Здесь сохраняется информация о недавно просмотренных товарах или категориях.<br/>Вы пока не просматривали ни одной категории и не выбирали еще ни одной модели.</p>');
            $('#head-history-empty').removeClass('hidden');
        } else {
            $('#head-history-categories').addClass('no_models');
        }
    } else if (module == 'compare') {
        $('#del-' + module + '-models').addClass('hidden');
        $('#compare-popup .divider-horisontal').addClass('hidden');
        $('#compare_bodels_block').hide();
        $('ul.other-pages').css('margin-bottom','1em');
        $('#compare-popup .button').addClass('hidden');
        $('#compare-list-models').html('<p>Вы пока не выбирали ни одной модели. Выберите минимум две для сравнения.</p>');
        $('#compare_models').empty();
    }
}

function UnCheck(id) {
	var checkbox = document.getElementById('compare_action_' + id);
	if(checkbox)
	{
		checkbox.checked = false;
	}
	return true;
}

function closeSelectCompareCat () {
    $('.show-category-popup').fadeTo('fast', 1);
    $('#select-category-popup').hide();
}

function showRightBazarBanner ()
{
    var banner_t = 0;
    if ($(document).scrollTop() > 0) banner_t += $(document).scrollTop();
    $('.bazar-banner').css('top', banner_t);
    $('.bazar-banner').show('fast');
}

function slideRightBazarBanner ()
{
    // -913 = -166 - 147 - 600, где 147 - это высота хидера, 196 - высота футера, 600 - высота самого баннера
    var doc_st = $(document).scrollTop();
    var offset_t = doc_st - 147;
    var h = $(document).height() - 910;
    if ( $.browser.safari ) h -= 20;
    if ( offset_t > 0 && doc_st <= h ) {
        $('.bazar-banner').css('top', offset_t);
    } else if (doc_st > h) {
        $('.bazar-banner').css({
            'top' : 'auto',
            'bottom' : 10
        });
    }
    else $('.bazar-banner').css('top', 0);
}

function openRegionFromHeader()
{
    var geo_left = $("#virt-port .regmenow ul li:first").offset().left - $("#virt-port").offset().left - 504;
    $("#geo-regions").css({top:30, height:328, width:475, left:geo_left, opacity: 1});
    $("#virt-port .regmenow ul li.region").addClass("opened");
    $("#geo-regions").removeClass("opened_from_content");
    $("#geo-regions").addClass("opened_from_header");
    $("#geo-regions").show('fast',function() {
        if ($.browser.msie) this.style.removeAttribute('filter');
    });
    pageTracker._trackEvent('region', 'show_dialog_from_header');
}

function animateRegionToHeader ()
{
    if ($("#virt-port").length)
    {
        $("#geo-regions").animate({
                            opacity: 0.5,
                            left: $("#virt-port .regmenow ul li.region").offset().left - $("#virt-port").offset().left + 80,
                            top: 10,
                            width: 0,
                            height: 0},
                            500,function() {
                                if ($.browser.msie) this.style.removeAttribute('filter');
                            });
    }
    $("#geo-regions").removeClass("opened_from_content");
}

function closeRegionFromHeader ()
{
    $("#geo-regions").removeClass("opened_from_header");
    $("#geo-regions").hide();
    $("#virt-port ul li.region").removeClass("opened");
}

function showUserToolbarPopup (current_item_id)
{
    var popup_id = current_item_id + '-popup';
    $('#user-toolbar .toolbar-item').removeClass('active');
    $('#' + current_item_id).addClass('active');
    $('#user-toolbar #' + popup_id).css('left', $('#' + current_item_id).offset().left - 4 - $('#user-toolbar .wrapper').offset().left);
    $('#user-toolbar #' + popup_id).fadeTo('fast', 1, function() {
        $(this).show('fast', function() {
            if ($.browser.msie) this.style.removeAttribute('filter');
        });
    });
}

function closeUserToolbarPopup (id, all)
{
    if ( all )
    {
        $('#user-toolbar .toolbar-popup').each(function() {
            $(this).fadeTo('fast', 0);
            $(this).hide('fast', function() {
                if ($.browser.msie) this.style.removeAttribute('filter');
            });
        });
        $('#user-toolbar .toolbar-item').each(function() {
            $(this).removeClass('active');
        });
    }
    else
    {
        $('#user-toolbar .toolbar-item#' + id).removeClass('active');
        $('#user-toolbar #' + id + '-popup').fadeTo('fast', 0, function() {
            $(this).hide('fast', function() {
                if ($.browser.msie) this.style.removeAttribute('filter');
            });
        });
    }
}

function showWhatThisPopup (left)
{
    var popup_right = ($("body").width() - 1000 ) / 2;
    var bottom_arrow_left;
    if (left != -1)
    {
        bottom_arrow_left = left;
    }
    else
    {
        bottom_arrow_left = popup_right + 900;
        $('#what-this-popup .del-model').removeClass('hidden');
    }
    $('#what-this-popup').css('right', popup_right);
    $('#what-this-popup .bottom-arrow').css('left', bottom_arrow_left);
    $('#what-this-popup').show();
}

function showHelpPopup(type, offset, left, cursor_pos)
{
    content_left = 0;
    content_top = 0;
    if ($('#priceua_content').css('position') == 'relative')
    {
        content_left = $('#priceua_content').offset().left;
        content_top = $('#priceua_content').offset().top;
    }
    popup_top = offset.top - popup_h - 35 - content_top;
    if (typeof left != "undefined")
    {
        popup_left = left;
        if (type == 'sell-this-model-popup' && $.browser.msie && $.browser.version == 7)
            popup_left = left + $('#page_model').offset().left;
    }
    else
    {
    popup_left = offset.left - 240 - content_left;
    }
    if (typeof cursor_pos != "undefined" && type == 'sell-this-model-popup')
    {
        content_left = $('#page_model').offset().left;
        var arrow_left = cursor_pos - content_left - 708;
        if (arrow_left > 268)
        {
            arrow_left = 268;
        }
        $('#' + type + ' .bottom-arrow').css({
            left: arrow_left
        });
    }
    $('#' + type).css({
        top: popup_top,
        left: popup_left
    });
}

var userPopupOnlyScript = false; // В ответ на AJAX запрос будет возвращен JS-код, без HTML
var regPage = '';
function showRegAuthPopup(url, params, page, size)
{
    regPage = page;
    pageTracker._trackEvent(regPage, 'show');
    $.post(url, params, function(html) {
        $('#user-popup-container').html(html);
        if (html == '') {
            hideRegAuthPopup();
            return false;
        }
        if (userPopupOnlyScript) return false;
        var p_width = 851;
        var p_height = 350;
        if (size == 'small') {
            p_width = 401;
            p_height = 410;
        }
        if ($('#user-popup').hasClass('credit')) p_height = $('#user-popup').height();
        $('#user-popup-overlay').css('height', $(document).height());
        var p_top = ($(window).height() - p_height) / 2 + $(document).scrollTop();
        $('#user-popup').css({
            top     : (p_top > 0 && p_top > $(document).scrollTop()) ? p_top : 10 + $(document).scrollTop(),
            left    : ($("body").width() - p_width) / 2
        });

        $('#user-popup-overlay').fadeTo('fast', 0.3, function() {
            $(this).css('display', 'block');
        });
        $('#user-popup').fadeTo('fast', 1, function() {
            $(this).show('fast', function() {
                if ($.browser.msie) this.style.removeAttribute('filter');
            });
        });
    }, 'html');
}

function hideRegAuthPopup()
{
    $('#user-popup-container').html('');
    $('#user-popup-overlay').css('display', 'none');
    if (link != '' && check_value && document.location.href != link) document.location.href = link;
}

//	Virtual Portal seo links over js
$(function() {
	var from_name = '?utm_source=price.ua&utm_medium=toolbar&bar=1';
	var href = '';
	$('.our_projects a').each(function(index, element){
        href = $(element).attr('href');
				$(element).attr('href', href + from_name);
				});
	});

function tempTrackCategory(currentCategoryId)
{
    if (typeof categoryIdForTracker == 'undefined') return false;
    pageTracker._trackEvent('main_menu', 'change_departament', categoryIdForTracker + '_TO_' + currentCategoryId);
}

function checkSubmitForm() 
{
    var sq = $("#q").val();
    if(sq == 'Что Вы хотите купить?') {
        $("#q").focus();
        alert('Пожалуйста, введите поисковый запрос');
        return false;
    } else if (sq.length <= 1) {
        $("#q").focus();
        alert('Пожалуйста, введите поисковый запрос более одного символа');
        return false;
    } else if (sq.length > 100) {
        $("#q").focus();
        alert('Пожалуйста, введите поисковый запрос не более ста символов');
        return false;
    } else {
        $("#f").submit();
        return false;
    }
}

function setAboutSystemPosition()
{
    $('#priceua_about-system').css({
        width : $('body').width(),
        left  : $('#priceua_content').offset().left * (-1)
    }).addClass('loaded');
}

function dgImageError(img) {
    $(img).attr({
        src: '/images/site_0/skin_1/nophoto_light-gray.png',
        width: 75,
        height: 75
    });
}

function getRemainingTime(share_end, pid)
{
    var sec_in_day = 86400;
    var sec_in_hour = 3600;
    var sec_in_minute = 60;
    var dt = new Date();
    var today = parseInt((dt.valueOf() / 1000)); //(оставляем только секунды до конца акции)
    var timeleft = Math.round(parseInt(share_end) - today); 
    
    var timer = window.setInterval(function()
    {
        var raznica = timeleft;
        var days_txt = "";
        days = Math.floor(raznica / sec_in_day);
        raznica -= days * sec_in_day;

        var hours_txt = "";
        hours = Math.floor(raznica / sec_in_hour);
        raznica -= hours * sec_in_hour;

        var minutes_txt = "";
        minutes = Math.floor(raznica / sec_in_minute);
        raznica -= minutes * sec_in_minute;

        seconds = raznica;
        if (days) days_txt = days + " " + trueEnd(days, 'дней', 'день', 'дня') + "<br/>";
        if (hours)  hours_txt = hours + ":";
        if (minutes) {
            if (minutes.toString().length == 1) minutes = "0" + minutes;
            minutes_txt = minutes + ":";
        }

        if (seconds.toString().length == 1) seconds = "0" + seconds;

        $('#timer_div_' + pid).html(days_txt + hours_txt + minutes_txt  + seconds);
        if (timeleft <= 0)
        {
            window.clearInterval(timer);
            $('#text_div_' + pid).html("");
            $('#timer_div_' + pid).html("<small>Акция завершилась</small>");
        }
        timeleft--;

    }, 1000);
}

function trueEnd(number, ending0, ending1, ending2)
{
    var num100 = number % 100;
    var num10 = number % 10;
    if (num100 >= 5 && num100 <= 20) {
        return ending0;
    } else if (num10 == 0) {
        return ending0;
    } else if (num10 == 1) {
        return ending1;
    } else if (num10 >= 2 && num10 <= 4) {
        return ending2;
    } else if (num10 >= 5 && num10 <= 9) {
        return ending0;
    } else {
        return ending2;
    }
}

function CompareActionToUserTollbar(cid, mid, isCheckbox, existInCompare)
{
    var id = "compare_action_" + mid;
    var checkboxChecked;
    if (isCheckbox) {
        checkboxChecked = document.getElementById(id).checked;
    } else {
        checkboxChecked = false;
    }
    
    if(checkboxChecked) {
        if(!existInCompare && checkboxChecked) {
            xajax_AddToCompare(mid);
        }
    } else {
        xajax_DeleteFromCampare(cid, mid);
        plusMinuseOne('compare', '-');
    }
    return true;
}

function anitaneModelToUserTollbar(mid)
{
    var image = $('#model_title_' + mid);
    var compareTolbarPanel = $('#compare');
    var hidenTolbarPanel = $('#user-toolbar-hided');
    var fromX = image.offset().left;
    var fromY = image.offset().top;
    var gotoX = compareTolbarPanel.offset().left + 50;
    var gotoY = compareTolbarPanel.offset().top + 50;
    if (hidenTolbarPanel.css('display') == 'block')
    {
        gotoX = hidenTolbarPanel.offset().left + 50
        gotoY = hidenTolbarPanel.offset().top + 50;
    }

    image.clone(true)
         .insertAfter('#user-toolbar')
         .css({'position' : 'absolute', 'top' : fromY, 'left' : fromX, 'z-index' : 10000})
         .attr('id', '')
         .animate({opacity: 0.8}, 200)
         .animate({
            left: gotoX,
            top: gotoY,
            width: 0,
            height: 0,
            opacity: 0},
         1500);
}

function fixIETitle()
{
    if ($.browser.msie && window.location.hash.length > 0) {
        var doc_title = $('title');
        var doc_title_pos = doc_title.text().indexOf('#');
        if (doc_title_pos != -1) {
            doc_title.text(doc_title.text().substring(0, doc_title_pos));
        }
    }
}
