﻿/// <reference path="jquery-1.4.4-vsdoc.js" />

$(window).load(setNewScroll);
	




function setNewScroll(){
	var catalog_width = $('#catalog-scroll').show();
	var this_cont = $('.new_content_block .this_content');

	this_cont.jScrollPaneRemove();
	this_cont.jScrollPane({ showArrows: true, scrollbarWidth: 20, wheelSpeed: 10 });

	var this_jscroll = $('.new_content_block .jScrollPaneContainer');


	function update_width(){
		this_jscroll.width(catalog_width.width()-30);
		this_cont.width(catalog_width.width()-50);
	}

	update_width();

	$(window).resize(update_width);
}


$(function(){
	if($.browser.msie)
	{
		$('#left-menu a.item').addClass('itemFixIe');
		if($.browser.version == 8)
			$('.bottom-variant').css({top:17});
		if($.browser.version == 7)
			$('.bottom-variant').css({top:22});
	}
});


(function ($) {
    $.fn.jCarouselLite = function (o) {
        o = $.extend({
            btnPrev: null,
            btnNext: null,
            btnGo: null,
            mouseWheel: false,
            auto: null,

            speed: 200,
            easing: null,

            vertical: false,
            circular: true,
            visible: 3,
            start: 0,
            scroll: 1,

            beforeStart: null,
            afterEnd: null
        }, o || {});

        return this.each(function () {                           // Returns the element collection. Chainable.

            var running = false, animCss = o.vertical ? "top" : "left", sizeCss = o.vertical ? "height" : "width";
            var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;

            if (o.circular) {
                ul.prepend(tLi.slice(tl - v - 1 + 1).clone())
              .append(tLi.slice(0, v).clone());
                o.start += v;
            }

            var li = $("li", ul), itemLength = li.size(), curr = o.start;
            div.css("visibility", "visible");

            li.css({ overflow: "hidden", float: o.vertical ? "none" : "left" });
            ul.css({ margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1" });
            div.css({ overflow: "hidden", position: "relative", "z-index": "2", left: "0px" });

            var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
            var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
            var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

            li.css({ width: li.width(), height: li.height() });
            ul.css(sizeCss, ulSize + "px").css(animCss, -(curr * liSize));

            div.css(sizeCss, divSize + "px");                     // Width of the DIV. length of visible images

            if (o.btnPrev)
                $(o.btnPrev).click(function () {
                    return go(curr - o.scroll);
                });

            if (o.btnNext)
                $(o.btnNext).click(function () {
                    return go(curr + o.scroll);
                });

            if (o.btnGo)
                $.each(o.btnGo, function (i, val) {
                    $(val).click(function () {
                        return go(o.circular ? o.visible + i : i);
                    });
                });

            if (o.mouseWheel && div.mousewheel)
                div.mousewheel(function (e, d) {
                    return d > 0 ? go(curr - o.scroll) : go(curr + o.scroll);
                });

            if (o.auto)
                setInterval(function () {
                    go(curr + o.scroll);
                }, o.auto + o.speed);

            function vis() {
                return li.slice(curr).slice(0, v);
            };

            function go(to) {
                if (!running) {

                    if (o.beforeStart)
                        o.beforeStart.call(this, vis());

                    if (o.circular) {            // If circular we are in first or last, then goto the other end
                        if (to <= o.start - v - 1) {           // If first, then goto last
                            ul.css(animCss, -((itemLength - (v * 2)) * liSize) + "px");
                            // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
                            curr = to == o.start - v - 1 ? itemLength - (v * 2) - 1 : itemLength - (v * 2) - o.scroll;
                        } else if (to >= itemLength - v + 1) { // If last, then goto first
                            ul.css(animCss, -((v) * liSize) + "px");
                            // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
                            curr = to == itemLength - v + 1 ? v + 1 : v + o.scroll;
                        } else curr = to;
                    } else {                    // If non-circular and to points to first or last, we just return.
                        if (to < 0 || to > itemLength - v) return;
                        else curr = to;
                    }                           // If neither overrides it, the curr will still be "to" and we can proceed.

                    running = true;

                    ul.animate(
                    animCss == "left" ? { left: -(curr * liSize)} : { top: -(curr * liSize) }, o.speed, o.easing,
                    function () {
                        if (o.afterEnd)
                            o.afterEnd.call(this, vis());
                        running = false;
                    }
                );
                    // Disable buttons when the carousel reaches the last/first, and enable when not
                    if (!o.circular) {
                        $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                        $((curr - o.scroll < 0 && o.btnPrev)
                        ||
                       (curr + o.scroll > itemLength - v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");
                    }

                }
                return false;
            };
        });
    };

    function css(el, prop) {
        return parseInt($.css(el[0], prop)) || 0;
    };
    function width(el) {
        return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
    };
    function height(el) {
        return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
    };

})(jQuery);
$(document).ready(function () {

    /*Hide left navigation*/
    if (location.toString().indexOf('/catalog-page/') != -1)
        $('#left-menu .content a').css({ 'display': 'none' });

    /* ANTI JS */



    /* END ANTI JS */

    var print_is_set = false;
    var scrolableLoaded = false, topMenuAniFlag = false;
    var arGoods = Array(); //for sort
    var DETAIL_ELEMENT_ID = 0; //for detail page
    var DETAIL_ELEMENT_Q = 0; //for detail page
    var cycling = false;
    var no_ajax = false;
    var basket = {
        hidden: (getCookie("basket_hidden") || false),
        top: (getCookie("basket_top") || '125px'),
        left: (getCookie("basket_left") || '770px')
    }

    jQuery.fn.extend({
        disableSelection: function () {
            this.each(function () {
                this.onselectstart = function () { return false; };
                this.unselectable = "on";
                jQuery(this).css('-moz-user-select', 'none');
            });
        },
        enableSelection: function () {
            this.each(function () {
                this.onselectstart = function () { };
                this.unselectable = "off";
                jQuery(this).css('-moz-user-select', 'auto');
            });
        }
    });

    Array.prototype.siftByProp = function (low, up, prop) {

        var c, lCache = this[low], lv = lCache[prop] - 0; // left value cache

        while (true) {
            c = (low << 1) + 1;
            if (c > up) break;
            if (c < up && (this[c + 1][prop] - this[c][prop]) > 0) c++;
            if (lv >= this[c][prop]) break;

            this[low] = this[c];
            low = c;
        }

        this[low] = lCache;
    }

    Array.prototype.sortByProp = function (field, order) {
        var saveO = Object.prototype.toString;
        var saveA = Array.prototype.toString;
        Object.prototype.toString = function () { return this.field };
        Array.prototype.toString = function () { return this[field] };
        this.sort();
        if (!order) this.reverse();
        Array.prototype.toString = saveA;
        Object.prototype.toString = saveO;
    }

    jScrollPaneContainerStyle = '';
    swjScrollPaneContainerStyle = '';
    wrapperStyle = '';
    wrapperHeight = '';
    catalogscrolltableStyle = '';
    catalogscrollStyle = '';

    function setPrintCSS(isPrint) {
        /*
        static jScrollPaneContainerStyle;
        static wrapperStyle;
        static catalogscrollStyle;
        */

        if (isPrint) {

            swjScrollPaneContainerStyle = $('#catalog-v-showcase .jScrollPaneContainer').attr('style');
            wrapperStyle = $('#wrapper').attr('style');
            wrapperHeight = $('#wrapper').height();
            catalogscrollStyle = $('#catalog-scroll').attr('style');

            var link;
            if (document.getElementsByTagName)
                link = document.getElementsByTagName('link');
            else if (document.all)
                link = document.all.tags('link');
            else
                return;
            for (var index = 0; index < link.length; index++) {
                if (link[index].title == 'print')
                    link[index].disabled = !isPrint;
            }

            $('font').hide();

            // дофига скроллов - теперь этот способ не катит =(
            $('#catalog-scroll').jScrollPane({ showArrows: false, scrollbarWidth: 0, wheelSpeed: 0 });
            //$('.jScrollPaneContainer').eq(0).unbind();
            //$('#catalog-scroll').unbind();

            // вместо этого прячем скрол
            /*$('.jScrollPaneTrack').hide();
            $('.jScrollArrowUp').hide();
            $('.jScrollArrowDown').hide();		*/

            $('#catalog-v-showcase .jScrollPaneContainer').attr('style', '');
            $('#catalog-scroll').attr('style', '');

            $('#catalog-v-showcase .jScrollPaneContainer').css({ overflow: 'visible', height: $('#catalog-scroll').height() });

            $('#wrapper').height($('#catalog-scroll').height() + 180);
            //alert(1);

            $('.detail-pic').unbind('click').click(function () {
                $('#catalog-scroll').css('top', 0);
                return false;
            });

            $('.popup').unbind('click').click(function () {
                $('#catalog-scroll').css('top', 0);
            });

            // шамаство с версией печати (список уезжал вверх), согласен что идиотизм, но другого выхода не вижу..
            intervalID = setInterval(function () {
                $('#catalog-scroll').css('top', 0);
            }, 100);
        }
        else {
            document.location.hash = "";

            $('#catalog-v-showcase a').ipopup();

            // отмена шаманства
            clearInterval(intervalID);

            var link;
            if (document.getElementsByTagName)
                link = document.getElementsByTagName('link');
            else if (document.all)
                link = document.all.tags('link');
            else
                return;
            for (var index = 0; index < link.length; index++) {
                if (link[index].title == 'print')
                    link[index].disabled = !isPrint;
            }
            $('font').show();

            $('#wrapper').attr('style', wrapperStyle);
            $('#wrapper').height(wrapperHeight);


            // открываем скролл отбратно
            /*$('.jScrollPaneTrack').show();
            $('.jScrollArrowUp').show();
            $('.jScrollArrowDown').show();*/


            //$('#catalog-scroll').jScrollPane({showArrows:true, scrollbarWidth: 20});  
            $('#catalog-scroll').attr('style', catalogscrollStyle);
            $('#catalog-v-showcase .jScrollPaneContainer').attr('style', swjScrollPaneContainerStyle);
            $('#catalog-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20, wheelSpeed: 10 });


        }

        //$('#catalog-v-table').hide();
        $('#catalog-v-showcase').show();


    }


    function setPrintCSS_table(isPrint) {
        var link;

        if (document.getElementsByTagName)
            link = document.getElementsByTagName('link');
        else if (document.all)
            link = document.all.tags('link');
        else
            return;

        for (var index = 0; index < link.length; index++) {
            if (link[index].title == 'print')
                link[index].disabled = !isPrint;
        }
        if (isPrint) {
            //$('#close_print').click(function(){setPrintCSS_table(false); return false;})
            jScrollPaneContainerStyle = $('#catalog-v-table .jScrollPaneContainer').attr('style');
            wrapperStyle = $('#wrapper').attr('style');
            catalogscrolltableStyle = $('#catalog-scroll-table').attr('style');
            wrapperHeight = $('#wrapper').height();

            var link;

            if (document.getElementsByTagName)
                link = document.getElementsByTagName('link');
            else if (document.all)
                link = document.all.tags('link');
            else
                return;

            for (var index = 0; index < link.length; index++) {
                if (link[index].title == 'print')
                    link[index].disabled = !isPrint;
            }

            $('font').hide();
            $('#catalog-scroll-table').jScrollPane({ showArrows: false, scrollbarWidth: 0, wheelSpeed: 0 });
            $('#catalog-v-table .jScrollPaneContainer').attr('style', '');
            $('#catalog-scroll-table').attr('style', '');

            $('#catalog-v-table .jScrollPaneContainer').css({ overflow: 'visible', height: $('#catalog-scroll-table').height(), width: '990px' });
            $('#catalog-scroll-table').css({ width: '990px' });
            $('#wrapper').height($('#catalog-scroll-table').height() + 210);
            $('.minus').hide();
            $('.plus').hide();
            //alert(-1);

            //$('.catalog-tab th:last').hide();
            $('.catalog-tab tr').each(function () {
                $(this).find('.quantity').hide();
            })

            $('td').unbind('click');

            // шаманство для ie (при клике список ехал вверх из-за скрола)
            $('*').click(function () {
                $('#catalog-scroll-table').css('top', 0);
            });

        }
        else {
            var link;

            if (document.getElementsByTagName)
                link = document.getElementsByTagName('link');
            else if (document.all)
                link = document.all.tags('link');
            else
                return;

            for (var index = 0; index < link.length; index++) {
                if (link[index].title == 'print')
                    link[index].disabled = !isPrint;
            }

            $('font').show();
            $('#catalog-scroll-table').attr('style', catalogscrolltableStyle);
            $('#catalog-v-table .jScrollPaneContainer').attr('style', jScrollPaneContainerStyle);
            $('#wrapper').attr('style', wrapperStyle);
            $('#catalog-scroll-table').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
            $('.minus').show();
            $('.plus').show();
            $('#wrapper').height(wrapperHeight);
            //alert(-2);

            //$('.catalog-tab th:last').show();
            $('.catalog-tab tr').each(function () {
                $(this).find('.quantity').show();
            })

            $('table.catalog-tab td.img a, table.showcase-tab tr.img a').ipopup();
            $('table.catalog-tab tr').each(function () {
                $(this).find('td:lt(4)').css('cursor', 'pointer').unbind('click').click(function () {
                    $(this).parent().find('a').click();
                });
            });


        }
        //$('#catalog-v-showcase').hide();
        $('#catalog-v-table').show();
    }

    function setPrintCSSAll(isPrint) {
        if (!GlobalPrint && isPrint) {
            isPrint = true;
            GlobalPrint = true;
        }
        else if ((!GlobalPrint && !isPrint) || (GlobalPrint && isPrint))
            return false;
        else {
            isPrint = false;
            GlobalPrint = false;
        }
        vs = $('#catalog-v-showcase').css('display');
        if (vs == "block" || vs == '') {
            setPrintCSS(isPrint);
        }
        else {
            setPrintCSS_table(isPrint);
        }
        return false;
    }

    GlobalPrint = false;
    $('head').ready(function () { SetupPrint(); GlobalPrint = false; });

    function SetupPrint() {
        //$('.link-print').click(function(){setPrintCSSAll(true); return false;});
        //$('#close_print').click(function(){setPrintCSSAll(false); return false;});

        //if (document.location.hash == '#print') setPrintCSS(true);
        //if (document.location.hash == '#print-table') setPrintCSS_table(true);
    }

    function doScrollTo(y1, y2, s) {
        y1 += s; window.scrollBy(0, s);
        return (y1 < y2 ? setTimeout('doScrollTo(' + y1 + ',' + y2 + ',' + s + ')', 10) : false);
    }
    //function startScrollBottom(){typeof( window.pageYOffset ) == 'number' ? window.pageYOffset : document.documentElement.scrollTop}

    $.preloadImages = function () {
        for (var i = 0; i < arguments.length; i++)
            $("<img>").attr("src", arguments[i]);
    }

    $.fn.swapClass = function (c1, c2) { return this.each(function () { $(this).toggleClass(c1).toggleClass(c2); }); };

    function addMethod(object, name, fn) {
        var old = object[name];
        object[name] = function () {
            if (fn.length == arguments.length)
                return fn.apply(this, arguments);
            else if (typeof old == 'function')
                return old.apply(this, arguments);
        }
    }
    addMethod($.prototype, "index", function () { return this.parent().children().index(this[0]) })

    $.fn.ishow = $.browser.msie ? function () { return this.show(); } : function () { return this.fadeIn(); };
    $.fn.ihide = $.browser.msie ? function () { return this.hide(); } : function () { return this.fadeOut(); };

    $.fn.ifadeOut = function () {
        return this.ihide();
    }
    $.fn.ifadeIn = function () {
        return this.ishow();
    }

    $.fn.transformBtn = function () {
        return $(this).each(function () {
            var btn = $('<button type="' + this.type + '" value="' + this.value + '" class="niceBtn"><span><span>' + this.value + '</span></span></button>');
            btn.focus(function () { $(this).addClass('niceBtnFocus') }).blur(function () { $(this).removeClass('niceBtnFocus') });

            if (typeof this.name != 'undefined' && this.name != '') btn.attr('name', this.name);
            if (typeof this.id != 'undefined' && this.id != '') btn.attr('id', this.id);

            $(this).replaceWith(btn);
        });
    };

    // карточка товара
    var fancyboxFrameHeight = 800 - 30;
    $.fn.ipopup = function () {


    }

    function showPopupMessagePage(href, opt) {
        var opt = opt || {};

    }

    function pagePopupLoader() {
        var h = document.location.hash;
        if (h.indexOf('#url=') === 0) h = h.substring('5'); //cut '#url='
        if (h.match(/^\/catalog\/\d+\/?$/))
            window.location = h;
        else if (h.match(/^\/catalog\/\d+\/\d+\/?$/)) {
            var sid = parseInt(h.split('/')[2]);

            if (window.location.pathname.indexOf('/catalog-page/' + sid + '/') == -1)
                window.location = '/catalog-page/' + sid + '/' + document.location.hash;
            else
                $("<a>").attr('href', h).ipopup().click();
        }
    };

    function loadCatalogPage(sid, fHash) {
        /*not used*/
        cycling = false;
        scrolableLoaded = false;
        var fHash = fHash || false;

        if (!topMenuAniFlag) {
            topMenuAniFlag = true;
            $('#cb-overlay').fadeTo(0, '0').show()
        .fadeTo(100, '1', function () {
            $.get("/catalog/" + sid + "/", function (data) {
                if (!fHash)
                    document.location.hash = '#url=/catalog-page/' + sid + '/';
                $('#center-block').html(data);
                $('#cb-overlay').fadeTo(100, '0', function () {
                    $('input.btn').transformBtn();
                    if (typeof onLoadCatalogPage == 'function')
                        onLoadCatalogPage();
                    else
                        $.getScript('/catalog/catalog.js');

                    jScrollPaneInit();

                    $(this).hide();

                    document.title = windowTitle;
                    topMenuAniFlag = false;
                });
            });
        });
        }
        //url для формы вопрос консультанту
        if (sid > 0) {
            $('.url_hidden_field').val('http://nv-shop.ru/catalog/' + sid + '/');

            // back-url для корзины
            $.post("/back_to_catalog.php", { backurl: "/catalog/" + sid + "/" }, function (url_data) { });
        }
    }

    function togglePopup(s) {
        $('div.popup-block:visible').not(s).hide();
        $(s).toggle();
    };

    function getCookie(name) {
        var cookie = " " + document.cookie;
        var search = " " + name + "=";
        var setStr = null;
        var offset = 0;
        var end = 0;
        if (cookie.length > 0) {
            offset = cookie.indexOf(search);
            if (offset != -1) {
                offset += search.length;
                end = cookie.indexOf(";", offset)
                if (end == -1) {
                    end = cookie.length;
                }
                setStr = unescape(cookie.substring(offset, end));
            }
        }
        return (setStr);
    }
    function setCookie(name, value, expires, path, domain, secure) {
        var today = new Date();
        var expire = new Date();
        expire.setTime(today.getTime() + 3600000 * 24 * 14);
        document.cookie = name + "=" + escape(value) +
    "; expires=" + ((expires) ? +expires : expire.toGMTString()) +
    "; path=" + ((path) ? path : "/") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
    }
    jQuery.preloadImages = function () {
        var images = (typeof arguments[0] == 'object') ? arguments[0] : arguments;
        for (var i = 0; i < images.length; i++) {
            jQuery("<img>").attr("src", images[i]);
        }
    }

    MWEvent = false;
    var dataSubcatalog3Level = [];
    var nav3LevelItemSelectedId = 0;
    var nav3Level = $('#catalog-3-nav');
    $(document).ready(function () {

        // левое меню - родительская секция
        $('#left-menu a.all-goods').text($('#top-menu .sel img').attr('alt'));

        if ($('#YMapsID-432').width() != 450) {
            //рисованный скроллинг для статей
            $('#scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });

            // если MWEvent = true скролить мышкой нельзя (в плагине скрола jquery.mousewheel.js проверка на эту переменную)   

            $('html').click(function (e) {
                var target = $(e.target);
                if (target.is('select') || target.parents('select').length) return;
                MWEvent = false;
                //console.log('unfocus');
                $('select').click(function () {
                    MWEvent = true;
                    //console.log('focus');
                });
            });

        }
        // косяки в FF2
        jQuery.each(jQuery.browser, function (i, val) {
            if (i == "mozilla" && jQuery.browser.version.substr(0, 3) == "1.8")
            //alert("Do stuff for firefox 2")
                $('body').addClass('ff2');
            //$('#catalog-v-table-form > div:last').css("padding-top", "0");
        });

        //top-menu hover
        $('#showcase a img').hover(
    function () { $(this).parent().parent().not('.sel').swapClass('sh', 'bsh'); },
    function () { $(this).parent().parent().not('.sel').swapClass('bsh', 'sh'); }
    );
        //regular page
        if (typeof onLoadCatalogPage == 'function') {
            if (basket.hidden) {
                $('#basket').css({ top: basket.top, left: basket.left });
                $('#basket-small').show();
            } else {
                if (b_auth || basketItemsCount > 0)
                    $('#basket').css({ top: basket.top, left: basket.left }).ishow();
            }
        }
        if (basket.top !== null && basket.left !== null)
            $('#basket').css({ top: basket.top, left: basket.left });

        $('#basket').draggable({ cursor: 'move', containment: 'document' });
        $('#basket').bind('dragstop', function (event, ui) {
            basket.left = $('#basket').css("left");
            basket.top = $('#basket').css("top");

            setCookie("basket_top", basket.top);
            setCookie("basket_left", basket.left);
        });

        $('#basket .close').click(function () {
            var $basketOffset = $('#basket-small').parent().offset();
            if (getCookie("basket_nofirsttime") != "true") // если анимация уже была то сворачивать корзину не так пафосно
                doScrollTo(0, 800, 50);
            setCookie("basket_nofirsttime", "true");

            $('#basket').animate({ left: $basketOffset.left - 160, top: $basketOffset.top }, 1000, 'easeInBack', function () {
                $(this).ihide();

                //if (b_auth || parseInt($(this).find('.goods a').text())>0)
                $('#basket-small').show();

                //startScrollTop();
                basket.hidden = true;
                setCookie("basket_hidden", basket.hidden);
            });
        });
        $('#basket div.leaf').click(function () {
            var e = $(this).find('a')[0];
            if (e && e.href) window.location = e.href;
        });

        $('#basket-small').click(function () {
            $('#basket-small').hide();
            $('#basket').ishow().animate({ left: basket.left, top: basket.top }, 1500, 'easeInOutSine', function () {
                basket.hidden = false;
                setCookie("basket_hidden", basket.hidden);
            });

            return false;
        });

        $('a.popup').ipopup();

        $('input.btn').transformBtn();

        $('div.contacts-link-block a.link').click(function () { togglePopup('#all-contacts-block'); return false; });
        $('#head-tools-div').find('a.link-question').click(function () {
            $('div.question-form a:first').attr('href', window.location).next().val(window.location);
            togglePopup('div.question-form');
            $('div.YMaps-button').toggle();
            return false;
        });
        $('#head-tools-div').find('a.link-login').click(function () { togglePopup('div.auth-form'); return false; });
        $('#head-tools-div').find('a.link-login-on').click(function () { togglePopup('div.auth-form'); return false; });
        $('div.close-btn').click(function () { $(this).parent().hide() });

        //popup hints
        $('.hint[title]').each(function () {
            var title = $(this).attr('title');
            $(this).removeAttr('title');

            $(this).mousemove(function (e) {
                $('#hint-box').css({ left: e.pageX + 22, top: e.pageY - 20 });
            });
            $(this).mouseover(function (e) {
                $('#hint-box').mousemove(e).find('div.content').text(title).end().show();
            });
            $(this).mouseout(function () { $('#hint-box').hide(); });
        });

        //косяки подсвечивания при наведении	
        if ($('div.sh > a > img').css('height') == "61px") {
            if ($('#container > div').attr('class') == "sh")
                $('div.sh').mouseover(function () {
                    $(this).removeClass().addClass('bsh');
                });
            if ($('#container > div').attr('class') == "bsh")
                $('div.bsh').mouseout(function () {
                    $(this).removeClass().addClass('sh');
                });
        }


        // берем из куков состояние корзины (свернута или нет)
        if ((getCookie("basket_hidden") == "true") && ($('div.goods > a').text() != "")) {
            $('#basket-small').show();
            $('#basket').hide();
        }
        if ((getCookie("basket_hidden") == "false") && ($('div.goods > a').text() != "")) {
            $('#basket-small').hide();
            $('#basket').show();
        }


        //скрываем баннер, если слишком длинное меню
        $lm = $('#left-menu');
        var left_menu_height2 = parseInt($lm.height()) + parseInt($lm.css('margin-top')) + parseInt($lm.css('margin-bottom'));
        $bb = $('.banner-block');
        var banner_height2 = parseInt($bb.height()) + parseInt($bb.css('margin-top')) + parseInt($bb.css('margin-bottom'));
        //console.log(left_menu_height2 + banner_height2);


        // прячем корзину в корзине
        if ($('.basket-items').length) {
            $('#basket').hide();
            $('#basket-small').show();
        }

        // инициализируем меню 3-го уровня
        var nav3LevelItems = $('#catalog-3-nav a:not(.nav3-all-catalogs)');
        dataSubcatalog3Level = [];
        nav3LevelItems.each(function () {
            var $this = $(this);
            dataSubcatalog3Level.push({ 'id': $this.attr('id').substring(9), 'title': $('span span', $this).html(), 'href': $this.attr('href') });
        });
    });
    /*сам json массив*/
    var dataCatalog = [];
    /* init selected good array after page load. if we came to page with direct link, dataCatalog is empty. */
    var nav3levelSelItems = $('#catalog-3-nav .sel');
    var catalogComment = null;
    var selCat = nav3levelSelItems.length > 0 ? nav3levelSelItems.eq(0).attr('id').substring(9) : 0;
    if (selCat == 0 || isNaN(selCat)) {
        var nav2SelItems = $('#left-menu .item.def.sel');
        selCat = nav2SelItems.length > 0 ? nav2SelItems.eq(0).attr('id').substring(3) : 0;
    }
    if (!isNaN(selCat) && selCat != 0) {
        $.ajax({
            url: "/catalog/" + selCat, // Куда обращаемся
            data: null,
            dataType: "json",
            beforeSend: function () { },
            error: function (jsonResponse) {
                alert('запрос не выполнен для ' + jsonResponse)
            },
            success: function (jsonResponse) {
                dataCatalog = jsonResponse.goods;
                dataSubcatalog3Level = jsonResponse.catalogs3level;
                catalogComment = jsonResponse.comment;
            }
        });
    }
    /*если находимся не в каталоге, то анимация верхнего меню не происходит*/
    if ($('body').hasClass('catalog'))
        $('#top-menu a').click(function () {
            if (!$(this).parent().hasClass('sel')) {
                $('#left-menu .content').animate({ opacity: "0" }, 500, function () {
                    $(this).hide().removeAttr('style');
                    $(this).children().css('display', 'none');
                    $('.banner-block').addClass('hidden');
                });
                $(this).find('img').each(function () {
                    $(this).css({ 'width': '93px', 'height': '61px' });
                    this.src = this.src.replace('gif', 'png');
                    $(this).parent().parent().css({ 'background': 'none' });
                    $('#top-menu div').removeAttr('style');

                    topMenuAni($(this).parent());
                });
                ToLoad = false;
            }
            return ($('#catalog-v-showcase')[0] ? false : true);
        });

    function indexShowcaseAniAfter() // после анимации главной страницы
    {
        $("#top-menu").unbind("topMenuAniEndEvent", indexShowcaseAniAfter);
        //if ($('#center-block').children().length > 2)
        //{
        if ($('body').hasClass('catalog')) {
            $('#left-menu .content a.item').removeClass('sel');
            var visible_menu_items = $('#left-menu .content a.item:visible').eq(0);
            var href = visible_menu_items.attr('href'); //тут запрашиваем ссылку на каталог
            visible_menu_items.addClass('sel');
        }

    }

    function loadSubcatalogs(catalogA) {
        /*used when top menu reload*/
        var numCat = getCatalogNum(catalogA);
        catalogA.parent().prependTo('#top-menu');
        var $thisObj = $('#left-menu .mi_sid_n' + numCat).eq(0);
        var catGet = getCatalogNum($thisObj);
        $thisObj.addClass('sel');
        $.ajax({
            url: "/catalog/" + catGet, // Куда обращаемся
            data: null, // Запрос к серверу, для получения json объекта
            //url: "json.txt", 
            //data: catGet,  // для локальной версии сайта
            dataType: "json",
            beforeSend: function () { },
            error: function (jsonResponse) {
                alert('запрос не выполнен для ' + jsonResponse)
            },
            success: function (jsonResponse) {
                dataCatalog = jsonResponse.goods;
                dataSubcatalog3Level = jsonResponse.catalogs3level;
                catalogComment = jsonResponse.comment;
                nav3LevelItemSelectedId = 0;
                //topMenuAni(thisObj);                
                catalogA.find('img').each(function () { this.src = this.src.replace('gif', 'png') })
                catalogA.find('img').animate({ width: "179px", height: "117px" }, 550, function () {
                    catalogA.parent().addClass('sel');
                });
                listInit();
                userMenuOver();
                NavMenu3LevelInit();
                $('#left-menu .content a.mi_sid_n' + numCat).slideDown(1200, function () {
                    renderBredPath();
                });
                //----------------------------
            }
        });
    }
    function renderBredPath() {
        var bread = $('.bred-path').eq(0);
        var breadFirstItem = $('a', bread).eq(0)
        bread.empty();
        var activeParentA = $('#top-menu div.sel a').eq(0);
        var parentNavItem = { id: activeParentA.attr('id').substring(3), href: activeParentA.attr('href'),
            title: $('img', activeParentA).eq(0).attr('alt')
        };
        var activeA = $('.item.def.sel').eq(0);
        /*if ($('.item.def.sel').length == 0) {
            /*bread.append(breadFirstItem);
            bread.append('<span></span><a href="' + parentNavItem.href + '">' + parentNavItem.title + '</a>');
            return;
        }*/

		//console.log(activeA.attr('id'));
		if(activeA.attr('id') == undefined)
		{
			var attrId = '';
		} else {
			var attrId = activeA.attr('id').substring(3);
		}



		
        var navItem = { id: attrId, href: activeA.attr('href'), title: $('.img-text', activeA).eq(0).html() };
        //bread.append(breadFirstItem);

        var nav3ItemCol = $('a.sel', nav3Level);
        var nav3Item = nav3ItemCol.length > 0 ? nav3ItemCol.eq(0) : null;

        /*if (nav3Item)
            bread.append('<span></span><a href="' + parentNavItem.href + '">' + parentNavItem.title + '</a><span></span>'
                + '<a href="' + navItem.href + '">' + navItem.title + '</a><span></span>'
                + '<label>' + $('span span', nav3Item).eq(0).html() + '</label>');
        else
            bread.append('<span></span><a href="' + parentNavItem.href + '">' + parentNavItem.title + '</a><span></span>'
                + '<label>' + navItem.title + '</label>');
         */
        if (nav3Item)
            bread.append('<a class="bred-level-1" href="' + navItem.href + '"><span>' + navItem.title + '</span></a><span></span>'
                + '<label class="bred-level-2"><span>' + $('span span', nav3Item).eq(0).html() + '</span></label>');
        else
            bread.append('<label class="bred-level-1"><span>' + navItem.title + '</span></label>');
    }

    var catalogCommentContainer = $('.new_content_block');
    function renderCatalogComment() {
        var needAddComment = (catalogComment != null && catalogComment != '');
        catalogCommentContainer.css(!needAddComment ? { 'display': 'none', 'visibility': 'hidden'} : { 'display': 'block', 'visibility': 'visible' });
        $('.this_content', catalogCommentContainer).html(catalogComment);
        $('#middle').css({ 'height': (needAddComment ? '1070px' : '712px') });
    }

    var countZero = true;
    var tmpCount = true;
    function indexShowcaseAni(e) {
        if ($('#showcase')[0]) {
            $(e).parent().attr('class', 'sh');
            $('#showcase img').unbind();

            var arImg = $('#showcase img').get();
            var h = 320, w = 170;
            var x = 0, y = 0;
            var tmpObj;
            $(arImg).each(function () {
                $(this).css({ position: 'absolute', top: x, left: y });

                x += w; if (x >= w * 3) { x = 0; y += h; }
            });

            var topString = getCatalogNum($(e));
            var c = new Array(
        [192, 365], [164, 213], [239, 216],
        [124, 258], [170, 320], [123, 375],
        [202, 257], [216, 323], [255, 347]
        );
            for (var i = 0; i < arImg.length; i++)
                $(arImg[i]).animate({ top: c[i][0] + "px", left: c[i][1] + "px", width: "93px", height: "61px" }, 600, "easeOutExpo", function () {
                    //step 2
                    if (arImg[8] === this) {
                        $(arImg).each(function () { this.src = this.src.replace('/big/', '/small/') });

                        for (var i = 0; i < arImg.length; i++)
                            $(arImg[i]).animate({ top: "12px", left: (12 + (103 * i)) + 5 + "px" }, 600, "easeOutExpo", function () {
                                //step 3
                                if (arImg[8] === this) {
                                    $(arImg).removeAttr('style').css({ width: "93px", height: "61px" });
                                    $('#showcase').attr('id', 'top-menu').find('a').click(function () { topMenuAni(this); return false });
                                    $("#top-menu").bind("topMenuAniEndEvent", indexShowcaseAniAfter);

                                    $('#top-menu div.sh a').each(function () {
                                        if (topString == getCatalogNum($(this))) tmpObj = $(this);
                                    });
                                    if (tmpCount) {
                                        tmpCount = false;
                                        loadSubcatalogs(tmpObj);
                                    }
                                    if ($('#catalog-v-showcase').css('display') == 'block') {
                                        $('#catalog-scroll').jScrollPaneRemove();
                                        $('#catalog-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
                                    }
                                    else if ($('#catalog-v-table').css('display') == 'block') {
                                        $('#catalog-scroll-table').jScrollPaneRemove();
                                        $('#catalog-scroll-table').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
                                    }
                                }
                                var countOne = true;
                                $('#content, #top-menu, div.sidebar,#user-menu,#user-menu-c').each(function () {
                                    $(this).removeClass('hidden');
                                    if (countZero) {
                                        $('#showcase').remove();

                                    }
                                });
                                if (countZero) {
                                    $('#carouselCont').removeClass('hidden');
                                    $('#bannerCarousel').jCarouselLite({
                                        btnNext: ".ban-next",
                                        btnPrev: ".ban-prev"
                                    });
                                    countZero = false;
                                }

                            });
                    }

                });
        }
    }
    function userMenuOver() {
        if ($('body').width() > 1060 && $('#user-menu-c').is(':visible')) {
            if ($('#user-menu').is(':hidden'))
                $('#user-menu').removeClass('hidden');
            if ($('body').width() - 1050 < $('#user-menu .u-m-l').length * 100) {
                for (i = 0; i <= Math.round(($('#user-menu .u-m-l').length * 100 - ($('body').width() - 1050)) / $('#user-menu .u-m-l').length); i++) {
                    $('#user-menu .u-m-l').eq($('#user-menu .u-m-l').length - 1).prependTo('#user-menu-c');
                }
                if ($('#user-menu .u-m-l').length == 0) {
                    $('#user-menu-c')
							.removeAttr('style')
							.css("top", "139px");
                }
                else if ($('#user-menu .u-m-l:last-child').length) $('#user-menu-c').css("left", $('#user-menu .u-m-l:last-child').offset().left);
                if ($('#user-menu-c .u-m-l').length > 0 && $('#user-menu .u-m-l').length != 0) $('#content, #fullpage-content').css("padding-right", $('body').width() - $('#user-menu-c').offset().left + 25);
                else if ($('#user-menu-c .u-m-l').length == 0) $('#content, #fullpage-content').removeAttr('style')
                else $('#content, #fullpage-content').css("padding-right", "138px");
            }
            else if ($('body').width() - 1050 > ($('#user-menu .u-m-l').length + 1) * 100 && $('#user-menu-c').is(':visible')) {
                for (i = 0; i <= Math.round((($('body').width() - 1050) - ($('#user-menu .u-m-l').length + 1) * 100) / $('#user-menu .u-m-l').length); i++) {
                    $('#user-menu-c .u-m-l').eq(0).appendTo('#user-menu .u-m-list');
                    //alert(1);
                }
                if ($('#user-menu .u-m-l').length == 0) {
                    $('#user-menu-c')
						.css("top", "201px");
                }
                else $('#user-menu-c').css({ "left": $('#user-menu .u-m-l:last-child').offset().left, "top": "78px" });
                if ($('#user-menu-c .u-m-l').length > 0 && $('#user-menu .u-m-l').length != 0) $('#content, #fullpage-content').css("padding-right", $('body').width() - $('#user-menu-c').offset().left + 25);
                else if ($('#user-menu-c .u-m-l').length == 0) $('#content, #fullpage-content').removeAttr('style');
                else $('#content, #fullpage-content').css("padding-right", "138px");

            }
        }
        else if ($('body').width() < 1060 && $('#user-menu-c .u-m-l').length == 0) {
            $('#content, #fullpage-content').css("padding-right", "138px");
            $('#user-menu .u-m-l').appendTo('#user-menu-c');
            if (!$('#user-menu').is(':hidden'))
                $('#user-menu').addClass('hidden');
            $('#user-menu-c')
				.removeAttr('style')
				.css("top", "139px");
        }
        if ($('#catalog-v-showcase').css('display') == 'block') {
            $('#catalog-scroll,#auth-scroll').jScrollPaneRemove();
            $('#catalog-scroll,#auth-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
        }
        else if ($('#catalog-v-table').css('display') == 'block') {
            $('#catalog-scroll-table,#auth-scroll').jScrollPaneRemove();
            $('#catalog-scroll-table,#auth-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
        }
        if ($('#cont-scroll').length > 0 && $('#cont-scroll').height() > 410) {
            $('#cont-scroll').height($('#cont-scroll').height() + 1);
            $('#cont-scroll').jScrollPaneRemove();
            $('#cont-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
        }
    }
    ToLoad = false;
    var firstCall = true;
    function getCatalogNum(thisObj) {
        /*var reg = /\/(\d*)/\/
        var */
        /*id = cat100*/
        return thisObj ? thisObj.attr("id").substring(3) : 0;
    }

    function topMenuAni(e) {
        if (!topMenuAniFlag) {
            topMenuAniFlag = true;
            ToLoad = this;

            var numCat = getCatalogNum(e);

            $('#top-menu .sel img').animate({ width: "93px", height: "61px" }, 400)
			.each(function () { this.src = this.src.replace('png', 'gif') })
			.parent().parent().addClass('sh').removeClass('sel');

            $(e).find('img').animate({ width: "0", height: "0", opacity: "0" }, 500, function () {
                $(this).parent().parent().each(function () {
                    $(this)
					.removeAttr('style')
					.css({ 'background': 'none' })
					.prependTo($('#top-menu')).find('img').animate({ width: "179px", height: "117px", opacity: "1" }, 550, function () {
					    $(this).parent().parent().removeAttr('style');

					    if (numCat > 0) {
					        var Count = 0;
					        $('#left-menu').removeAttr('style');
					        $('#left-menu .content a.mi_sid_n' + numCat).slideDown(700, function () {
					            if (Count == $('#left-menu .content a.mi_sid_n' + numCat).length - 1) dataToContent();
					            Count++;
					        });

					        indexShowcaseAniAfter();
					        topMenuAniFlag = false;

					        //скрываем баннер, если слишком длинное меню
					        $lm = $('#left-menu').height();
					        $bb = $('.banner-block').height();
					        if ($('#left-menu .content a.mi_sid_n' + numCat).length * 44 + $bb < 540 && $('.banner-no-border').length) $('.banner-block').removeClass('hidden');
					        else $('.banner-block').addClass('hidden');
					    }

					});
                });

                //indexShowcaseAniAfter();           

                //topMenuAniFlag = false;
                $("#top-menu").trigger("topMenuAniEndEvent");
            })
		.parent().parent().addClass('sel').removeClass('sh bsh').css('background-image', 'none');

            $('#left-menu a.all-goods').attr('href', $('#top-menu div.sel a').attr('href') || $('#top-menu div:first a').attr('href'));
            $('#left-menu a.all-goods').text($('#top-menu .sel img').attr('alt'));


            ToLoad = false;
        }
        else {

            $('#top-menu .sh').each(function () {
                $(this).removeClass('last-clicked');
            })
            $(e).parent().addClass('last-clicked');

            $('#top-menu .sel').each(function () {
                $(this).removeClass('last-clicked');
            })

            $('#top-menu .last-clicked img').css('width', '100px').css('height', '66px');
            $('#top-menu .sh:not(.sel) img').css('width', "93px").css('height', "61px");
        }
    }

    /*сортировка json массива*/
    var sort_by = function (field, reverse, primer) {
        reverse = (reverse) ? -1 : 1; //reverse = false - сортировка в обратном порядке
        return function (a, b) {
            a = a[field];
            b = b[field];

            if (typeof (primer) != 'undefined') {
                a = primer(a);
                b = primer(b);
            }
            if (field != 'price') {
                if ('' + a < '' + b) return reverse * -1;
                if ('' + a > '' + b) return reverse * 1;
                if ('' + a == '' + b) return 0;
            }
            else return reverse * (a * 1 - b * 1);

            return 0;
        }
    }
    /*-----------------------------*/
    $.preloadImages(
		"images/catalog/small/190.png",
		"images/catalog/small/192.png",
		"images/catalog/small/194.png",
		"images/catalog/small/196.png",
		"images/catalog/small/198.png",
		"images/catalog/small/200.png",
		"images/catalog/small/202.png",
		"images/catalog/small/204.png",
		"images/catalog/small/210.png",
		"images/ajax-loader.gif",
		"images/popup.png"
		);
    indexShowcaseAniAfter();

    $('#bottom-nav-div .item').css('cursor', 'pointer').click(function () {
        if ($(this).not('.selected')[0]) {
            $('#bottom-nav-div .selected').removeClass('selected');
            $(this).addClass('selected');

            $('#footer .bottom-texts').children('div').hide();
            $($(this).children('a').attr('href')).show();

            return false;
        }
    });

    $('#showcase a').each(function () {
        this.onclick = function () {
            indexShowcaseAni(this);
            return false;
        }
    });

    var sortObj, reverse;
    var catScroll = $('#catalog-scroll');
    var cat3Level = $('#catalog-3-nav');
    var catScrollTable = $('#catalog-scroll-table');
    var tabsClick = $('#content .title-tabs .item, #content .title-tabs-bottom .item');
    var $regYur = $('.reg-yur');
    var $regFiz = $('.reg-fiz');
    var $isFiz = $('#isFizFaceField');
    tabsClick.click(function (e) {
        if (!$(this).hasClass('sel')) {
            if ($('#catalog-v-table').hasClass('hidden')) {
                /*if (dataCatalog.length > 0)*/tableInit();
                $('#catalog-v-showcase').addClass('hidden');
                $('#catalog-v-table').removeClass('hidden');
                //userMenuOver();
            }
            else {
                $('#catalog-v-table').addClass('hidden');
                $('#catalog-v-showcase').removeClass('hidden');
                if (dataCatalog.length > 0) {
                    //listInit();
                    //userMenuOver();
                }
            }
            if ($(this).parent().hasClass('register-tab')) {
                $regYur.toggleClass('hidden');
                $regFiz.toggleClass('hidden');
            }
            if ($regYur.hasClass('hidden'))
                $isFiz.val('true');
            else $isFiz.val('false');

            $('#content div.title-tabs div.item, #content div.title-tabs-bottom div.item').removeClass('sel');
            $(this).addClass('sel');
        }
        e.preventDefault();
    });
    $refreshCaptcha = $('#refresh-captcha');
    $refreshCaptcha.click(function (e) {
        var tmpSrc = randomNumber(100, 999);
        $('#reg-captcha').attr('src', '/captcha-small.ashx?ix=reg&' + tmpSrc);
        e.preventDefault();
    });
    $refreshCaptcha = $('#refresh-captcha-gc-popup');
    $refreshCaptcha.live('click', function (e) {
        var tmpSrc = randomNumber(100, 999);
        $('#gc-popup-captcha').attr('src', '/captcha-small.ashx?ix=gc-popup&' + tmpSrc);
        e.preventDefault();
    });
    $('#CreateGoodCommentBtn').live('click', function () {
        $.ajax({
            url: "/good/addcomment",
            data: { 'n': $('#gc-nick').val(), 't': $('#gc-text').val(),
                'c': encodeURIComponent($('#gc-captcha').val()), 'g': encodeURIComponent($('.good-comment-handler').attr('id').substring(3))
            },
            dataType: "json",
            beforeSend: function () { },
            error: function (jsonResponse) {
                viewGoodCommentError({ type: 'error', msg: jsonResponse });
            },
            success: function (jsonResponse) {
                CreateCommentProcessing(false);
                if (jsonResponse.status == "500") {
                    viewGoodCommentError({ type: 'error', msg: jsonResponse.message });
                    return;
                }
                viewGoodCommentError({ type: 'status', msg: 'спасибо, Ваш комментарий успешно добавлен. После проверки он будет опубликован.' });
                clearGoodCommentForm();
            }
        });
        CreateCommentProcessing(true);
        return false;
    });
    function CreateCommentProcessing(processing) {
        if (processing) {
            $('#gc-loading').removeClass('hidden');
            $('#fancy-paste-gc input').attr('disabled', 'disabled');
            $('#fancy-paste-gc textarea').attr('disabled', 'disabled');
            $('#fancy-paste-gc button').attr('disabled', 'disabled');
        }
        else {
            $('#gc-loading').addClass('hidden');
            $('#fancy-paste-gc input').attr('disabled', '');
            $('#fancy-paste-gc textarea').attr('disabled', '');
            $('#fancy-paste-gc button').attr('disabled', '');
        }
    }
    function clearGoodCommentForm() {
        $('#fancy-paste-gc input').val('');
        $('#fancy-paste-gc textarea').val('');
    }
    /*data = {type:'error',msg:'...'}*/
    /*data = {type:'status',msg:'...'}*/
    function viewGoodCommentError(data) {
        var $errorMessageGc = $('#error-message-gc');
        var $statusMessageGc = $('#status-message-gc');
        if (data.type == 'error') {
            $errorMessageGc.removeClass('hidden').html(data.msg); ;
            $statusMessageGc.addClass('hidden');
        }
        if (data.type == 'status') {
            $statusMessageGc.removeClass('hidden').html(data.msg);
            $errorMessageGc.addClass('hidden');
        }
    }
    function randomNumber(m, n) {
        m = parseInt(m);
        n = parseInt(n);
        return Math.floor(Math.random() * (n - m + 1)) + m;
    }
    function liSort(sortObj, reverse) {
        if (window.__cart_goods__) {
            dataCatalog = __cart_goods__;
            __cart_goods__ = null;
        }

        dataCatalog.sort(sort_by(sortObj, reverse, function (a) { return a.toUpperCase() }));
        if (catScrollTable.is(':hidden') /*&& dataCatalog.length > 0*/) listInit();
        if (catScroll.is(':hidden') /*&& dataCatalog.length > 0*/) tableInit();
    }
    function listInit() {
        var cListHtml = '<ul id="cat-list">';
        for (i = 0; i < dataCatalog.length; i++) {
            cListHtml += '<li id="c' + dataCatalog[i].id + '" class="cat-list-item"><a title="' + dataCatalog[i].cScrHover + '"  href="/good-info/' + dataCatalog[i].fineUrl + '"><img class="item-img" src="' + dataCatalog[i].cScr + '" alt="' + dataCatalog[i].title + '"/></a><div class="item-title"><p class="item-art">' + dataCatalog[i].art + '</p><a>' + dataCatalog[i].title + '</a></div><div class="b-p-t"><b>' + dataCatalog[i].price + '</b> руб.</div></li>'
        }
        cListHtml += '</ul>';
        catScroll.html(cListHtml);
        reHover();
        renderCatalogComment();
    }
    function NavMenu3LevelInit() {
        var subcListHtml = '<a class="nav3-all-catalogs hint" alt="Показать все товары категории \'' + $('#left-menu .item.def.sel').text() + '\'"><span><span>&nbsp;</span></span></a>';
        for (i = 0; i < dataSubcatalog3Level.length; i++) {
            subcListHtml += '<a ' + (dataSubcatalog3Level[i].id == nav3LevelItemSelectedId ? 'class="sel" ' : '') + 'id="nav3level' + dataSubcatalog3Level[i].id + '" href="' + dataSubcatalog3Level[i].href + '"><span><span>' + dataSubcatalog3Level[i].title + '</span></span></a>';
        }
        cat3Level.html(subcListHtml);
    }
    var tInit = false;
    function tableInit() {
        /*---------------------------Проверить*/
        var cTableHtml = '<table class="main catalog-tab"><col width="55" /><col width="100" /><col /><col width="115" /><col width="100" />';
        for (i = 0; i < dataCatalog.length; i++) {
            cTableHtml += '<tr id="t' + dataCatalog[i].id + '"><td class="img"><a href="/good-info/' + dataCatalog[i].fineUrl + '">';
            if (dataCatalog[i].star) {
                cTableHtml += '<i class="hit ' + dataCatalog[i].star + '"></i>'
            }
            cTableHtml += '<img src="' + dataCatalog[i].cScr + '" width="37" alt="' + dataCatalog[i].cScrHover + '" title="' + dataCatalog[i].title + '" /></a></td><td><small>' + dataCatalog[i].art + '</small></td><td><a href="/good-info/' + dataCatalog[i].fineUrl + '">' + dataCatalog[i].title + '</a></td><td class="big-price-text"><b>' + dataCatalog[i].price + '</b></td><td class="quantity added"><a class="minus"></a><div class="ib"><input type="text" class="inputtext"/></div><a class="plus"></a></td></tr>';
        }
        cTableHtml += '</table>';
        catScrollTable.html(cTableHtml);
        reHover();
    }
    //сортировка

    var isRev = true;
    var $bonusCheck = $('#BonusCheck');
    $('#center-block .title a').click(function () {
        if ($(this).hasClass('sel')) isRev = !isRev;
        if (!$(this).hasClass('sel')) isRev = false;

        $('.title').find('a.sel').removeClass('sel');
        $(this).addClass('sel');
        liSort($(this).attr('title'), isRev);
    });
    $bonusCheck.click(function () {
        updateTotalCost();
    });

    function updateTotalCost() {
        $('#total-cost').html(calculateTotalCost() + ' руб.');
    }

    function calculateTotalCost() {
        var deliveryCost = isNaN(parseFloat($('#delivery-pay').html())) ? 0 : parseFloat($('#delivery-pay').html());
        var cartCost = parseFloat($('#card-sum').html());
        var totalCost = (cartCost - getUserBonus() + deliveryCost) > 0 ? (cartCost - getUserBonus() + deliveryCost) : 0;
        totalCost = totalCost.toFixed(2);
        return totalCost;
    }

    function getUserBonus() {
        if ($bonusCheck.is(':checked')) return $('#BonusQuantity').val();
        else return 0;
    }
    $linkPrint = $('.link-print');
    $linkPrint.click(function () {
        if (!$('#fancy-item').length) {
            $('body').append('<div id="print-wrap"><div id="print-me"></div></div>');
            $('#print-me').append('<div class="p-head"></div>');
            $('#logo,.partner-logo,.contacts').clone().appendTo('.p-head');
            $('.partner-logo').append('<span>Официальный партнер</span>');
            $('.p-head').append('<span  title="Вернуться"  class="link-back">Вернуться</span>');
            $('#cont-scroll').children().clone().appendTo($('#print-me'));
            $('#cat-list').clone().appendTo($('#print-me'));
        }
        else {
            $('body').append('<div id="print-wrap"><div id="print-me"></div></div>');
            $('#print-me').append('<div class="p-head"></div>');
            $('#logo,.partner-logo,.contacts').clone().appendTo('.p-head');
            $('.partner-logo').append('<span>Официальный партнер</span>');
            $('.p-head').append('<span  title="Вернуться"  class="link-back">Вернуться</span>');
            var tmpHtml = '<h1>' + $('.news-item .detail-title h1').text() + '</h1><div>' + $('.news-item #video-div').html() + '</div><div>' + $('.news-item .big-price').html() + '</div><div><h3>Описание</h3>' + $('.news-item #scroll1').html() + '</div><div><h3>Технические характеристики</h3>' + $('.news-item #scroll2').html() + '</div>';
            $('#print-me').append('<div class="p-cont"></div>');
            $('.p-cont').html(tmpHtml)
            $('.p-cont').appendTo($('#print-me'));
        }

        window.print();

        $('.link-back').click(function () {
            $('#print-wrap,.partner-logo span').remove();
        });
    });
    //ajax запрос	
    if ($('#left-menu').length > 0 && $('body').hasClass('catalog')) {
        $('#top-menu a').click(function () {
            var thisObj = $(this);
            var leftNavItem = $('#left-menu .mi_sid_n' + getCatalogNum($(this)));
            $('#left-menu .content a.sel').removeClass('sel');
            if (leftNavItem.length > 0) {
                var catGet = thisObj.parents().hasClass('content') ? getCatalogNum($(this)) :
                getCatalogNum($('#left-menu .mi_sid_n' + getCatalogNum($(this))).eq(0));
                document.location.hash = '#url=/catalog-page/' + catGet + '/';
                $.ajax({
                    url: "/catalog/" + catGet, // Куда обращаемся
                    data: null, // Запрос к серверу, для получения json объекта
                    dataType: "json",
                    beforeSend: function () { },
                    error: function (jsonResponse) { alert('запрос не выполнен для ' + jsonResponse) },
                    success: function (jsonResponse) {
                        if ($(this).parents().hasClass('content')) $(this).addClass('sel');
                        dataCatalog = jsonResponse.goods;
                        dataSubcatalog3Level = jsonResponse.catalogs3level;
                        catalogComment = jsonResponse.comment;
                        nav3LevelItemSelectedId = 0;
                        if (thisObj.parents().hasClass('content')) dataToContent();
                    }
                });
            }
            else {
                dataCatalog = [];
                catalogComment = null;
                dataSubcatalog3Level = [];
                nav3LevelItemSelectedId = 0;
                listInit();
                renderBredPath();
            }

            return false;
        });

function animateLeftMenu(a){
	var speed = 600;
	var one = $('#left-menu .content a.item:visible').eq(0);
	var index = one.index(a);
	if(index == 0) return false;

	

	a.hide(speed,function(){
		var cln = $(this).clone();
		if (a.parents().hasClass('content')) cln.addClass('sel');
		$(this).remove();
		one.before(cln.show().css({overflow:'hidden', width:0, height:0, opacity:0}).animate({width:176, height:50, opacity:1},speed));
		renderBredPath();
	});
}

        $('#left-menu .content a.item').live('click',function () {
			
            var thisObj = $(this);
			
            var catGet = getCatalogNum(thisObj);
            document.location.hash = '#url=/catalog-page/' + catGet + '/';
            $('#left-menu .content a.sel').removeClass('sel').height(37);
            animateLeftMenu(thisObj);
            $.ajax({
                url: "/catalog/" + catGet, // Куда обращаемся
                data: null, // Запрос к серверу, для получения json объекта
                dataType: "json",
                beforeSend: function () { },
                error: function (jsonResponse) { alert('запрос не выполнен для ' + jsonResponse) },
                success: function (jsonResponse) {
                    dataCatalog = jsonResponse.goods;
                    dataSubcatalog3Level = jsonResponse.catalogs3level;
                    catalogComment = jsonResponse.comment;
                    nav3LevelItemSelectedId = 0;
                    /*if (thisObj.parents().hasClass('content')) {*/dataToContent();/*}*/
                }
            });
            return false;
        });
        /* function leftMenuClickHandler(menuItem) {
        var thisObj = menuItem;
        var catGet = getCatalogNum(menuItem);
        document.location.hash = '#url=/catalog-page/' + catGet + '/';
        $('#left-menu .content a.sel').removeClass('sel');
        if (menuItem.parents().hasClass('content')) menuItem.addClass('sel');
        $.ajax({
        url: "/catalog/" + catGet, // Куда обращаемся
        data: null, // Запрос к серверу, для получения json объекта
        dataType: "json",
        beforeSend: function () { },
        error: function (jsonResponse) { alert('запрос не выполнен для ' + jsonResponse) },
        success: function (jsonResponse) {
        dataCatalog = jsonResponse.goods;
        dataSubcatalog3Level = jsonResponse.catalogs3level;
        nav3LevelItemSelectedId = 0;
        if (thisObj.parents().hasClass('content')) dataToContent();
        }
        });
        return false;
        }*/
        $('#catalog-3-nav a:not(.nav3-all-catalogs)').live('click', function () {
            var catGet = $(this).attr('id').substring(9);
            nav3LevelItemSelectedId = !isNaN(catGet) ? catGet : 0;
            $.ajax({
                url: "/catalog/" + catGet,
                data: null,
                dataType: "json",
                beforeSend: function () { },
                error: function (jsonResponse) { alert('запрос не выполнен для ' + jsonResponse) },
                success: function (jsonResponse) {
                    dataCatalog = jsonResponse.goods;
                    catalogComment = jsonResponse.comment;
                    dataToContent();
                }
            });
            return false;
        })
    }
    function dataToContent() {
        var sortParam = $('#center-block .title a.sel').attr('title');
        dataCatalog.sort(sort_by(sortParam, reverse, function (a) { return a.toUpperCase() }));
        if (catScrollTable.is(':hidden')) {
            /*if (dataCatalog.length > 0) {*/
            listInit();
            $('#catalog-scroll').jScrollPaneRemove();
            $('#catalog-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
            userMenuOver();
            /*}*/
        }
        if (catScroll.is(':hidden')) {
            /*if (dataCatalog.length > 0) {*/
            tableInit();
            $('#catalog-scroll-table').jScrollPaneRemove();
            $('#catalog-scroll-table').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
            userMenuOver();
            /*}*/
        }

		setNewScroll();

        NavMenu3LevelInit();
        renderBredPath();
    }
    $('.good-comment-handler').unbind().click(function () {
        $('#fancy-paste').parent().before('<div id="fancy-cont-gc" class="hidden"><div id="fancy-paste-gc">' +
            '<a title="закрыть" id="fancybox-close-gc"></a>' +
            '<div class="news-item">' +
                '<div class="recomended">' +
                        '<div class="close">' +
                        '</div>' +
                '</div>' +
                '<div class="detail-title"><h1>Оставить отзыв о товаре: </h1></div>' +
                '<div><span class="error-text hidden" id="error-message-gc"></span></div>' +
                '<div><span class="status-text hidden" id="status-message-gc"></span></div>' +
                '<dl class="iform w100"><dt class="form-title">Имя:<span class="starrequired">*</span></dt>' +
                '<dd class="qfield"><input id="gc-nick" maxlength="255" class="inputtext-v w50" type="text"></dd>' +
                '<dt class="form-title">Комментарий:<span class="starrequired">*</span></dt>' +
                '<dd class="qfield"><textarea id="gc-text" class="inputtextarea-v w50"></textarea></dd>' +
                '<dt class="form-title">Защита от автоматической регистрации</dt>' +
                '<dd class="qfield"><img alt="CAPTCHA" src="/captcha-small.ashx?ix=gc-popup" class="captcha" id="gc-popup-captcha" width="140" height="40">' +
                    '<a id="refresh-captcha-gc-popup" title="обновить">Обновить</a></dd>' +
                '<dt class="form-title">Введите слово на картинке:<span class="starrequired">*</span></dt>' +
                '<dd class="qfield"><input id="gc-captcha" maxlength="255" class="inputtext-v w50" type="text" autocomplete="off"></dd>' +
            '</dl><div class="iform-foot">' +
                '<div class="form_info"><span class="required">*</span> обязательные для заполнения поля</div>' +
                '<div><button type="submit" value="Создать" class="niceBtn left" id="CreateGoodCommentBtn"><span><span>Создать</span></span></button>' +
                '<img src="/images/ajax-loader.gif" alt="" class="left ml20 hidden" id="gc-loading"/>' +
            '</div></div>' +
            '</div></div>');
        $('#fancy-paste-gc').css({ 'left': ($('body').width() - 700) / 2, 'top': '190px' });
        $('#fancy-cont-gc').removeClass('hidden');
        return false;
    });

    if ($('#ActiveCatalog').length && $('#ParentCatalog').length) {
        var numSlide;

        numSlide = $('#ParentCatalog').val();
        $('#left-menu .content a.mi_sid_n' + numSlide).each(function () {
            if ($('#ActiveCatalog').val() == getCatalogNum($(this)))
                $(this).addClass('sel');
        });

        var topObj;
        $('#top-menu a').each(function () {
            if ($('#ParentCatalog').val() == getCatalogNum($(this)))
                topObj = $(this);
        });
        if(topObj!= undefined){
			topObj.parent().removeClass('sh').addClass('sel');
			topObj.find('img').each(function () {
				this.src = this.src.replace('gif', 'png');
				$(this)
					.parent()
					.parent()
					.prependTo($('#top-menu'));
			});
		}
        $('#left-menu .content a.mi_sid_n' + numSlide).slideDown(1200);
        if ($('#left-menu .content a.mi_sid_n' + numSlide).length > 6)
            $('.banner-block').addClass('hidden');
    }

    $('.nav3-all-catalogs').live('click', function () {
        var nav2SelItem = $('#left-menu a.item.sel');
        nav2SelItem = nav2SelItem.length > 0 ? nav2SelItem.eq(0) : null;
        if (!nav2SelItem)
            return false;

        var thisObj = nav2SelItem;
        var catGet = getCatalogNum(thisObj);
        $('#left-menu .content a.sel').removeClass('sel');
        if (thisObj.parents().hasClass('content')) thisObj.addClass('sel');
        $.ajax({
            url: "/catalog/" + catGet, // Куда обращаемся
            data: null, // Запрос к серверу, для получения json объекта
            dataType: "json",
            beforeSend: function () { },
            error: function (jsonResponse) { alert('запрос не выполнен для ' + jsonResponse) },
            success: function (jsonResponse) {
                dataCatalog = jsonResponse.goods;
                dataSubcatalog3Level = jsonResponse.catalogs3level;
                catalogComment = jsonResponse.comment;
                nav3LevelItemSelectedId = 0;
                if (thisObj.parents().hasClass('content')) dataToContent();
            }
        });
        return false;
    });

    // загрузка json массива для вывода в строке поиска	
    var cache = {}, lastXhr;
    $("#search_top").autocomplete({
        minLength: 3,
        source: function (request, response) {

            var term = request.term.toLowerCase();
            if (term in cache) {
                response(cache[term]);
                return;
            }
            lastXhr = $.getJSON("/good/Search?term=" + term, null, function (data, status, xhr) {
                cache[term] = data;
                if (xhr === lastXhr) {
                    response(data);
                }
            });
        },
        open: function (event, ui) {
        },
        select: function (event, ui) {
		    location.replace('/search?q=' + encodeURIComponent(ui.item.value) + '&a=s');
			return false;
        }
    });

    $('#search_top').bind({ focus: function () { $('#DoFastSearchFlag').val("1"); }, blur: function () { $('#DoFastSearchFlag').val("0"); } });
    var catItem = $('#center-block .cat-list-item');
    var catItemLink = $('#center-block .cat-list-item a');
    var hint = $('#popup');
    var hintCon = $('#popup #p-content');
    var tmpHtml, cHeight, catId;
    var hoverGoodId = 0;

    window.getGetalogId = function (currentId) {
        var thisCount;
        if (window.__cart_goods__) {
            dataCatalog = __cart_goods__;
            __cart_goods__ = null;
        }

        for (i = 0; i < dataCatalog.length; i++) {
            if (dataCatalog[i].id == currentId) {
                thisCount = i;
                break;
            }
        }
        return thisCount;
    }

    function reHover() {
        $('#center-block .cat-list-item').hover(
		function () {
		    var _this = $(this);
		    hoverGoodId = _this.attr("id").substring(1);
		    _this.append('<button class="niceBtn" value="В корзину" type="button"><span><span>В корзину</span></span></button>');
		    $('.niceBtn').click(function () {
		        $.get("/shopping-cart/AddGood/" + hoverGoodId, function (data) {
		            if (data.Status != "ok") alert(data.ErrorMessage);
		            else {
		                updateBasketState(data);
		                alert("Товар добавлен в корзину");
		            }
		        });
		        return false;
		    });
		},
		function () {
		    $(this).find('.niceBtn').remove();
		    hoverGoodId = 0;
		    $('.niceBtn').unbind();
		});
        $('.scroll-pane .main img').hover(
		function () {
		    var pScr = $(this).attr('alt');
		    tmpHtml = '<h3 class="full-title">' + $(this).parent().parent().parent().find('td').eq(2).text() + '</h3><p class="full-art">' + $(this).parent().parent().parent().find('td').eq(1).text() + '</p><div class="item-img"><img class="load" src="./images/ajax-loader.gif" alt="" /><img class="item-img" src=' + pScr + ' width="280" alt="" /></div><div class="item-text">Чтобы получить больше информации - кликните по товару</div>';
		    hintCon.html(tmpHtml);
		    $(this).mousemove(function (e) {
		        if ($(this).parent().parent().parent().parent().hasClass('basket-items')) hint.css({ left: e.pageX - 30, top: e.pageY - 340 - $('#popup #p-content h3').height() }).show();
		        else hint.css({ left: e.pageX - 136, top: e.pageY - 340 - $('#popup #p-content h3').height() }).show();
		    });
		},
		function () { hint.hide(); });
		$('.hint').live('hover',
		    function () {
		        var pScr = $(this).attr('alt');
		        $('#hint-box .content').html(pScr);
		        $(this).mousemove(function (e) {
		            $('#hint-box').css({ left: e.pageX + 30, top: e.pageY - 15 }).removeClass('hidden');
		        });
		    }).live('mouseleave',
		    function () { $('#hint-box').addClass('hidden'); });
            $('.catalog-tab td.img a,#cont-scroll .basket-items td img,#cont-scroll .basket-items td a').click(function (e) {
                catId = $(this).parent().parent().attr('id').substring(1, $(this).parent().parent().attr('id').length);
                var thisCount = getGetalogId(catId);
                $(this).attr('href', '');
                fancyNext(catId, thisCount);
                $('#fancy-paste').css('left', ($('body').width() - 700) / 2);
                $('#fancy-cont').removeClass('hidden');
                $(".item-input .inputtext").val("1");
                $(".buy-line .item-btn").unbind('click').click(function () {
                    var count = $(".item-input .inputtext").val();
                    if (count == 0) return;
                    if (isNaN(count)) count = 1;
                    $.get("/shopping-cart/AddGood/" + catId + "?count=" + count, function (data) {
                        if (data.Status != "ok") alert(data.ErrorMessage);
                        else {
                            updateBasketState(data);
                            alert("Товар добавлен в корзину");
                        }
                    });
                });
                e.preventDefault();
            });
        $('#center-block .cat-list-item a').unbind('click').bind('click', function (e) {
            $(this).parents().each(function () {
                if ($(this).hasClass('cat-list-item')) catId = $(this).attr('id').substring(1, $(this).attr('id').length);
            });
            $('input.btn').transformBtn();
            var thisCount;
            if (window.__cart_goods__) {
                dataCatalog = __cart_goods__;
                __cart_goods__ = null;
            }
            for (i = 0; i < dataCatalog.length; i++) {
                if (dataCatalog[i].id == catId) {
                    thisCount = i;
                    break;
                }
            }
            fancyNext(catId, thisCount);
            $('#fancy-paste').css({ 'left': ($('body').width() - 700) / 2, 'top': '20px' });
            $('#fancy-cont').removeClass('hidden');
            $(".item-input .inputtext").val("1");
            $(".buy-line .item-btn").unbind('click').click(function () {
                var count = $(".item-input .inputtext").val();
                if (count == 0) return;
                if (isNaN(count)) count = 1;
                $.get("/shopping-cart/AddGood/" + catId + "?count=" + count, function (data) {
                    if (data.Status != "ok") alert(data.ErrorMessage);
                    else {
                        updateBasketState(data);
                        alert("Товар добавлен в корзину");
                    }
                });
            });
            e.preventDefault();
        });

        $('.GoodBuyBtn').unbind('click').bind('click', function () {
            var count = $(".item-input .inputtext").val();
            if (count == 0) return false;
            if (isNaN(count)) count = 1;
            $.get("/shopping-cart/AddGood/" + $(this).attr('id').substr(1, $(this).attr('id').length) + "?count=" + count, function (data) {
                if (data.Status != "ok") alert(data.ErrorMessage);
                else {
                    updateBasketState(data);
                    alert("Товар добавлен в корзину");
                }
            });
            return false;
        });
        $("table.catalog-tab td.quantity").find('a.plus,a.minus').click(function () {
            var val = 0;
            if ($(this).hasClass('plus')) {
                val = parseInt($(this).parent().find('.inputtext').val());
                val = isNaN(val) ? 1 : val + 1;
                $(this).parent().find('.inputtext').val(val);
            }
            else if ($(this).hasClass('minus')) {
                val = $(this).parent().find('.inputtext').val();
                val = isNaN(val) || val <= 1 ? '' : val - 1;
                $(this).parent().find('.inputtext').val(val);
            }
            return false;
        });
        $('#fancybox-close,#fancy-cont').unbind('click').bind('click', function () {
            if (steck[0] != null) {
                fancyNext(steck[0].id, 1, true, true);
            }
            else {
                $('#fancy-cont').addClass('hidden');
                if ($("#player").length)
                    $("#player").remove();
                $('#video-div .big-img').remove();
            }
        });
        $('#fancy-paste').unbind('click').bind('click', function () {
            return false;
        });
        $('#fancy-paste-gc').live('click', function (e) {
            e.stopPropagation();
            return false;
        });
        $('#fancybox-close-gc,#fancy-cont-gc').unbind('click').live('click', function () {
            $('#fancy-cont-gc').addClass('hidden');
        });

        //показать выбранные товары в таблице
        $('#btn-show-selected-goods').unbind('click').bind('click', function () {
            var trs, $trs;
            trs = $('#catalog-v-table .catalog-tab tr .inputtext');
            trs.each(function () {
                if (!$(this).val()) {
                    $(this).parent().parent().parent().addClass('displaynone');
                    $('#catalog-scroll-table')[0].scrollTo(-1000);
                }
                $('#btn-show-all-goods').show();
                $('#btn-show-selected-goods').hide();
            });
            return false;
        });
        //показать все товары
        $('#btn-show-all-goods').unbind('click').click(function () {
            $('#catalog-v-table .catalog-tab tr.displaynone').removeClass('displaynone');
            $('#btn-show-all-goods').hide();
            $('#btn-show-selected-goods').show();
            return false;
        });

        $("#btn-add-all-goods-2-basket").unbind('click').click(function () {
            var tmpHtml;
            tmpHtml = '';
            $('#catalog-scroll-table .catalog-tab tr .inputtext').each(function () {
                if ($(this).val()) {
                    tmpHtml += '&id' + $(this).parent().parent().parent().attr('id').substring(1, $(this).parent().parent().parent().attr('id').length) + '=count' + $(this).val();
                }
            });
            tmpHtml = tmpHtml.substring(1, tmpHtml.length);
            $.ajax({
                url: "/shopping-cart/AddGoods/452", // Куда обращаемся
                data: tmpHtml, // Запрос к серверу
                beforeSend: function () { },
                error: function () {
                    alert('запрос не выполнен')
                },
                success: function (data) {
                    if (data.Status != "ok") alert(data.ErrorMessage);
                    else {
                        alert("Товар добавлен в корзину");
                        updateBasketState(data);
                    }
                }
            });
            return false;
        });
    }

    $('.detail-title a.next').unbind('click').click(function () {
        if ($(this).hasClass('no-fancy'))
            return false;
        var nextId, nextCount, i;
        if (window.__cart_goods__) {
            dataCatalog = __cart_goods__;
            __cart_goods__ = null;
        }
        for (i = 0; i < dataCatalog.length; i++) {
            if (dataCatalog[i].id == catId) {
                if (i <= dataCatalog.length) {
                    nextId = dataCatalog[i + 1].id;
                    nextCount = i + 1;
                    break;
                }
            }
        }
        $(".item-input .inputtext").val("1");
        $('#video-div .big-img').remove();
        fancyNext(nextId, nextCount);
        return false;
    });
    $('.detail-title a.prev').click(function () {
        if ($(this).hasClass('no-fancy'))
            return false;
        var prevId, prevCount, i;
        if (window.__cart_goods__) {
            dataCatalog = __cart_goods__;
            __cart_goods__ = null;
        }
        for (i = 0; i < dataCatalog.length; i++) {
            if (dataCatalog[i].id == catId) {
                if (i > 0) {
                    prevId = dataCatalog[i - 1].id;
                    prevCount = i - 1;
                    break;
                }
            }
        }
        $(".item-input .inputtext").val("1");
        $('#video-div .big-img').remove();
        fancyNext(prevId, prevCount);
        return false;
    });
    var state;

    var basketCount = $('#basket-small .goods').text();
    var basketNumber = basketCount.match(/\d+$/);
    basketNumber = parseInt(basketNumber, 10);
    if (isNaN(basketNumber) || basketNumber < 1)
        $('#basket-small').hide();

    //var state={"GoodCount":"1","TotalCost":"67","Status":"ok","ErrorMessage":"ERROR!!!"};
    function updateBasketState(state) {
        if (state.GoodCount == 0) {
            if (getCookie("basket_nofirsttime") != "true") // если анимация уже была то сворачивать корзину не так пафосно
                doScrollTo(0, 800, 50);
            setCookie("basket_nofirsttime", "true");

            $('#basket').animate({ left: '880px', top: '690px' }, 1000, 'easeInBack', function () {
                $(this).ihide();

                $('#basket-small').show();

                basket.hidden = true;
                setCookie("basket_hidden", basket.hidden);
            });
        }
        else {
            if (state.GoodCount % 10 == 1 && state.GoodCount % 10 + 10 != 11) $('#basket .goods').html('<a href="/cart">' + state.GoodCount + '</a>Товар');
            else if (state.GoodCount % 10 >= 2 && state.GoodCount % 10 <= 4 && state.GoodCount != 12 && state.GoodCount != 13 && state.GoodCount != 14) $('#basket .goods').html('<a href="/cart">' + state.GoodCount + '</a>Товара');
            else $('#basket .goods').html('<a href="/cart">' + state.GoodCount + '</a>Товаров');
            $('#basket .price').html(state.TotalCost);
            $('#basket-small .goods').html(state.GoodCount);

            $('#basket-small').fadeOut();
            $('#basket').ishow().animate({ left: basket.left, top: basket.top }, 2000, 'easeOutBack', function () {
                basket.hidden = false;
                setCookie("basket_hidden", basket.hidden);
            });
        }
    }
    function getBasketState() {
        $.get("/shopping-cart/GetState/", function (data) {
            if (data.Status != "ok") alert(data.ErrorMessage);
            else if (data.GoodCount > 0) {
                if (data.GoodCount % 10 == 1 && data.GoodCount != 1) $('#basket .goods').html('<a href="/cart">' + data.GoodCount + '</a>Товар');
                else if (data.GoodCount % 10 >= 2 && data.GoodCount % 10 <= 4 && data.GoodCount != 12 && data.GoodCount != 13 && data.GoodCount != 14) $('#basket .goods').html('<a href="/cart">' + data.GoodCount + '</a>Товара');
                else $('#basket .goods').html('<a href="/cart">' + data.GoodCount + '</a>Товаров');
                $('#basket .price').html(data.TotalCost);
                $('#basket-small .goods').html(data.GoodCount);
                if ($('#basket-small').is(':hidden')) $('#basket-small').show();
            }
        });
    }

    window.getBodyScrollTop = function () {
        return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
    }

    window.getBodyScrollLeft = function () {
        return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);
    }

    window.getClientWidth = function () {
        return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientWidth : document.body.clientWidth;
    }

    window.getClientHeight = function () {
        return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientHeight : document.body.clientHeight;
    }

    var newWindow = $('a.new-window');
    newWindow.click(function (e) {
        var newWidth = getClientWidth() > 1024 ? 1024 : getClientWidth();
        var newHeight = getClientHeight() > 1024 ? 1024 : getClientHeight();
        return !window.open(this.href, 'ct', 'toolbar="no",location="no",directories="no",status="no",menubar="no",copyhistory="no",width=' + newWidth + ',height=' + newHeight + '');
    })

    $('#DeleteAllChb').click(function () {
        if ($(this).is(':checked'))
            $('.delete-chb').attr('checked', 'checked');
        else
            $('.delete-chb').attr('checked', '');
    });
    $('#DeleteAllChbDelay').click(function () {
        if ($(this).is(':checked'))
            $('.d-delete-chb').attr('checked', 'checked');
        else
            $('.d-delete-chb').attr('checked', '');
    });
    $('#DelayAllChbDelay').click(function () {
        if ($(this).is(':checked'))
            $('.d-delay-chb').attr('checked', 'checked');
        else
            $('.d-delay-chb').attr('checked', '');
    });
    $('#DelayAllChb').click(function () {
        if ($(this).is(':checked'))
            $('.delay-chb').attr('checked', 'checked');
        else
            $('.delay-chb').attr('checked', '');
    });
    getBasketState();
    var steck = [];
    var isSteck = false;
    $('.scrollable-container').disableSelection();
    var isRecomended = false;
    window.fancyNext = function (curId, IdCount, isRecomended, isSteck) {
        $('#video-div .big-img').remove();
        IdCount = IdCount != undefined ? IdCount : 0;
        catId = curId;
        if (IdCount <= 0 || isRecomended)
            $('#btn-prev')
                .attr('src', '/images/btn-prev.gif')
                .parent().addClass('no-fancy');
        else
            $('#btn-prev')
                .attr('src', '/images/btn-prev-active.gif')
                .parent().removeClass('no-fancy');
        if (IdCount >= dataCatalog.length - 1 || isRecomended)
            $('#btn-next')
                .attr('src', '/images/btn-next.gif')
                .parent().addClass('no-fancy');
        else
            $('#btn-next')
                .attr('src', '/images/btn-next-active.gif')
                .parent().removeClass('no-fancy');
        if (isSteck) {
            fancyFill(steck[0]);
            if (steck != null)
                steck[0] = null;
            $('#btn-next')
                .attr('src', '/images/btn-next-active.gif')
                .parent().removeClass('no-fancy');
            $('#btn-prev')
                .attr('src', '/images/btn-prev-active.gif')
                .parent().removeClass('no-fancy');
        }
        else {
            $.ajax({
                url: "/good/get/" + catId, // Куда обращаемся
                data: null, // Запрос к серверу, для получения json объекта
                //url: "jsonObj.txt", 
                //data: catId,  // для локальной версии сайта
                dataType: "json",
                beforeSend: function () {
                    $('#fancy-ajax').show();
                    $('#fancy-paste #video-div img')
                        .attr('src', '');
                },
                error: function (jsonResponse) {
                    alert('запрос не выполнен для ' + jsonResponse)
                },
                success: function (jsonResponse) {
                    fancyFill(jsonResponse);
                }
            });
            isSteck = true;
        }
    }
    var goodResponse;
    function fancyFill(goodResponse) {
        $('#fancy-ajax').hide();
        ObjDescr = goodResponse;

        var imgHtml = '';
        if (ObjDescr.imgs != null) {
            imgHtml = '<ul>';
            for (i = 0; i < ObjDescr.imgs.length; i++) {
                imgHtml += '<li><a href="#" alt="' + ObjDescr.imgs[i].bigImg + '"><img src="' + ObjDescr.imgs[i].smallImg + '" alt="" /></a></li>';
            }
            for (i = 0; i < ObjDescr.videos.length; i++) {
                imgHtml += '<li><a class="video-play" href="#" alt="' + ObjDescr.videos[i].path + '"><img src="./images/video.jpg" alt="" /></a></li>';
            }
            imgHtml += '</ul>'
        }

        var techHtml = '';
        if (ObjDescr.techData != null) {
            var techCount = ObjDescr.techData.length;
            for (i = 0; i < techCount; i++) {
                techHtml += '<div class="name"><span>' + ObjDescr.techData[i].title + '</span></div><div class="value">' + ObjDescr.techData[i].value + '</div>';
            }
        }
        var recomendCount = '', recomendHtml = '';

        if (ObjDescr.recomendData != null && ObjDescr.recomendData.length > 0) {
            recomendCount = ObjDescr.recomendData.length;
            var recomendHtml = '<ul>';
            for (i = 0; i < recomendCount; i++) {
                recomendHtml += '<li class="cat-list-item" id="c' + ObjDescr.recomendData[i].id + '"><a alt="' + ObjDescr.recomendData[i].title + '"><img title="' + ObjDescr.recomendData[i].title + '" src="' + ObjDescr.recomendData[i].img + '" class="item-img"/></a><div class="item-title"><a>' + ObjDescr.recomendData[i].title + '</a></div><div class="b-p-t"><b>' + ObjDescr.recomendData[i].price + '</b> руб.</div></li>';
            }
            recomendHtml += '</ul>';
        }

        var discountBlock = ObjDescr.prices.discountPrice != '-1' ? '<div class="big-price-text">Цена c Вашей скидкой: <b>' + ObjDescr.prices.discountPrice + '</b> руб.</div>' : '';

        var goodCommentCount = 0;
        if (ObjDescr.goodComment != null && ObjDescr.goodComment.length > 0) {
            goodCommentCount = ObjDescr.goodComment.length;
            var goodComment = '';
            for (i = 0; i < goodCommentCount; i++) {
                goodComment += '<div class="mb20" id="gc' + ObjDescr.goodComment[i].id + '"><div><span class="news-date-time">' + ObjDescr.goodComment[i].created + '</span>&nbsp;<strong>' + ObjDescr.goodComment[i].nick + '</strong></div><div>' + ObjDescr.goodComment[i].text + '</div></div>';
            }
        }

        $('#fancy-paste .big-price').html('<b>Артикул: </b>' + ObjDescr.art + '<div class="big-price-text">Цена: <b>' + ObjDescr.prices.price + '</b> руб.</div>' + discountBlock + '<div class="big-price-text">Бонусные баллы (за шт.): <b>' + ObjDescr.prices.bonus + '</b></div></div>');
        $('#fancy-paste .detail-title h1').html(ObjDescr.mainTitle);
        $('#player').addClass('hidden');
        $('.GoodBuyBtn').attr('id', 'g' + ObjDescr.id);
        $('#fancy-paste #video-div').append('<img height="295" class="big-img" alt="" src=""/>');
        if (ObjDescr.imgs.length)
            $('#fancy-paste #video-div img').attr("src", ObjDescr.imgs[0].bigImg);

        $('#fancy-paste #scroll1').html('<p class="scroll_text">' + ObjDescr.desc + '</p>');
        $('#fancy-paste #scroll2').html(techHtml);
        $('.good-comment-handler').attr('id', 'gch' + ObjDescr.id);

        if (recomendCount > 0) {
            $('#fancy-paste #scroll3').html(recomendHtml);
            $('#tab-3').removeClass('hidden');
        }
        else {
            $('#tab-3').addClass('hidden');
            if ($('#tab-3').hasClass('sel')) {
                $('#tab-1').addClass('sel');
                $('#tab-3').removeClass('sel');
                $('#detail-recommended').addClass('hidden');
                $('#detail-goodcomemnt').addClass('hidden');
                $('#detail-description')
                            .removeClass('hidden')
                            .children()
                            .jScrollPane({ showArrows: true, scrollbarWidth: 20 });
            }
        }
        if (goodCommentCount > 0) {
            $('#fancy-paste #scroll4').html(goodComment);
            $('#tab-4').removeClass('hidden');
        }
        else {
            $('#tab-4').addClass('hidden');
            if ($('#tab-4').hasClass('sel')) {
                $('#tab-1').addClass('sel');
                $('#tab-4').removeClass('sel');
                $('#detail-recommended').addClass('hidden');
                $('#detail-goodcomemnt').addClass('hidden');
                $('#detail-description')
                            .removeClass('hidden')
                            .children()
                            .jScrollPane({ showArrows: true, scrollbarWidth: 20 });
            }
        }
        $('#fancy-paste .carousel').html(imgHtml);
        $('#fancy-paste .carousel li').eq(0).addClass('sel');

        $('#scroll1,#scroll2,#scroll3').jScrollPaneRemove();
        $('#scroll1,#scroll2,#scroll3').jScrollPane({ showArrows: true, scrollbarWidth: 20 });

        $('#fancy-paste .cat-list-item').click(function () {
            steck[0] = ObjDescr;
            fancyNext($(this).attr('id').substr(1, $(this).attr('id').length), 0, true);
        });

        if (ObjDescr.imgs.length + ObjDescr.videos.length > 3) {
            $('.c-prev,.c-next').removeClass('hidden');
            $("#fancy-paste .carousel").jCarouselLite({
                btnNext: ".c-next",
                btnPrev: ".c-prev",
                vertical: true
            });
        }
        else $('.c-prev,.c-next').addClass('hidden');
        //смена большой картинки		
        $('#fancy-paste .carousel li a').click(function () {
            if ($(this).hasClass('video-play')) {
                $(this).parent().parent().find('.sel').removeClass('sel');
                $(this).parent().addClass('sel');
                //$('#player').removeClass('hidden');
                $('#player').remove();
                $('#video-div').append('<div id="video-cont"></div>')
                $('#video-div img').addClass('hidden');
                play($(this).attr('alt'));
            }
            else {
                $('#player').addClass('hidden');
                $('#video-div img').removeClass('hidden');
                $(this).parent().parent().find('.sel').removeClass('sel');
                $(this).parent().addClass('sel');
                $('#fancy-paste #video-div img').attr("src", $(this).attr('alt'));
                return false;
            }
        });

    }

    reHover(); // инициализация функции всплывающего окна
    /*var $contScroll = $('#cont-scroll');
    if ($contScroll.length) {
    $('#cont-scroll').jScrollPaneRemove();
    $('#cont-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
    $('#left-menu a').click(function () {
    $('#cont-scroll').jScrollPaneRemove();
    $('#cont-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
    });
    }*/

    function play(url) {
        var flashvars = { m: "video", file: url };
        var params = { bgcolor: "#ffffff", allowFullScreen: "true", allowScriptAccess: "always" };
        var attributes = { id: "player", name: "player" };
        swfobject.embedSWF("./flash/uppod.swf", "video-cont", "500", "295", "9.0.0", false, flashvars, params, attributes);
    }
    $('ul.u-m-list a.u-m-hover').click(function () {
        var tmpThis = $(this);
        if ($('.u-m-l .hidden').is(':visible')) {
            $(this).parent().find('.hidden').stop(true, true);
            $('.u-m-l .hidden').fadeOut('middle', function () {
                tmpThis.parent().find('.hidden').fadeIn('middle');
            });
        }
        else {
            $(this).parent().find('.hidden').stop(true, true);
            $(this).parent().find('.hidden').fadeIn('middle');
        }
        return false;
    });
    $('#content,.u-m-not')
		.hover(function () { $('#user-menu').find('.show').fadeOut('fast'); })
		.mousemove(function () { $('#user-menu').find('.show').fadeOut('fast'); });

    // popup window tabs
    $('.tab-block .title-tabs .item, .tab-block .title-tabs-bottom .item').click(function () {
        if (!$(this).hasClass('sel')) {
            $('div.tab-block div.title-tabs div.sel, div.tab-block div.title-tabs-bottom div.sel').removeClass('sel');
            $(this).addClass('sel');

            var tabId = $(this).attr('id').substring(4, 5);
            $('#scroll1,#scroll2,#scroll3').jScrollPaneRemove();
            $('div.tab-block div.tabs-txt')
                .addClass('hidden');
            $('div.tab-block div.tabs-txt').eq(tabId - 1)
                .removeClass('hidden')
                .children()
                .jScrollPane({ showArrows: true, scrollbarWidth: 20 });
        }
        return false;
    });
    $(window).bind('resize', function () { userMenuOver(); });
    userMenuOver();
    if ($('#fancy-item').length) {
        $('#fancy-item .carousel li a').live('click', function () {
            if ($(this).hasClass('video-play')) {
                $(this).parent().parent().find('.sel').removeClass('sel');
                $(this).parent().addClass('sel');
                //$('#player').removeClass('hidden');
                $('#player').remove();
                $('#video-div').append('<div id="video-cont"></div>')
                $('#video-div img').addClass('hidden');
                play($(this).attr('alt'));
            }
            else {
                $('#player').addClass('hidden');
                $('#video-div img').removeClass('hidden');
                $(this).parent().parent().find('.sel').removeClass('sel');
                $(this).parent().addClass('sel');
                $('#fancy-item #video-div img').attr("src", $(this).attr('alt'));
                return false;
            }
        });
        $('#fancy-item #detail-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });

        if ($("#fancy-item .carousel").length && $("#fancy-item .carousel li").length > 3)
            $("#fancy-item .carousel").jCarouselLite({
                btnNext: ".c-next",
                btnPrev: ".c-prev",
                vertical: true
            });
        else
            $('#fancy-item  .c-next,#fancy-item  .c-prev').addClass('hidden');
    }
    if ($("#datepicker1").length > 0) {
        $("#datepicker1").datepicker({
            showAnim: 'fadeIn',
            showOn: "button",
            changeMonth: true,
            changeYear: true,
            showWeek: true,
            buttonImage: "images/icon.gif",
            buttonImageOnly: true
        });
        $("#datepicker2").datepicker({
            showAnim: 'fadeIn',
            showOn: "button",
            changeMonth: true,
            changeYear: true,
            showWeek: true,
            buttonImage: "images/icon.gif",
            buttonImageOnly: true
        });
    }

    if (!$('.banner-no-border').length)
        $('.banner-block').addClass('hidden');

    if ($('.order_form').length) {
        $hiddenMe = $('.hidden-me');
        if ($('.new-profile').is(':checked')) {
            $hiddenMe.removeClass('hidden');
            /*$('#cont-scroll').jScrollPaneRemove();
            $('#cont-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
            $('#cont-scroll')[0].scrollTo('#sof-prof-div');*/
        }

        if ($hiddenMe.is(':hidden'))
            $('.new-profile').click(function () {
                $hiddenMe.removeClass('hidden');
                /* $('#cont-scroll').jScrollPaneRemove();
                $('#cont-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
                $('#cont-scroll')[0].scrollTo('#sof-prof-div');*/

                theForm.onsubmit = function () {
                    return validateOrder();
                };
            });

        $('.list-profile').click(function () {
            theForm.onsubmit = null;
            $hiddenMe.addClass('hidden');
            $('#cont-scroll').jScrollPaneRemove();
            $('#cont-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
        });

        $('#OrderLocation').change(function () { getCities($(this).val()); });
    }

    $('#scroll1').jScrollPaneRemove();
    $('#auth-scroll,#scroll1').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
    $('#generate_new_login').click(function () {
        $('.generate_new').addClass('hidden');
        $('#auth-scroll').jScrollPaneRemove();
        $('#auth-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
    });
    $('#set_login').click(function () {
        $('.generate_new').removeClass('hidden');
        $('#auth-scroll').jScrollPaneRemove();
        $('#auth-scroll').jScrollPane({ showArrows: true, scrollbarWidth: 20 });
    });
    function validateOrder() {
        var tmpBool = false;
        var errorText = '<b>Не заполнены некоторые поля:</b><br/>';

        if ($('#OrderEmail').val().trim() == "") {
            errorText += '- Email, ';
            tmpBool = true;
        }
        if ($('#OrderPhone').val().trim() == "") {
            errorText += '- телефон, ';
            tmpBool = true;
        }
        if ($('#NotInListCity').val() == "" && $('#OrderLocationCity').val() <= 1) {
            errorText += '- город, ';
            tmpBool = true;
        }
        if ($('#OrderZip').val().trim() == "") {
            errorText += '- индекс, ';
            tmpBool = true;
        }
        if ($('#OrderAddress').val().trim() == "") {
            errorText += '- адрес, ';
            tmpBool = true;
        }
        if ($('#OrderFax').length) {
            if ($('#OrderYName').val().trim() == "") {
                errorText += '- полное наименование компании, ';
                tmpBool = true;
            }
            if ($('#OrderYAdrress').val().trim() == "") {
                errorText += '- юридический адрес, ';
                tmpBool = true;
            }
            if ($('#OrderYINN').val().trim() == "") {
                errorText += '- ИНН, ';
                tmpBool = true;
            }
            if ($('#OrderYKPP').val().trim() == "") {
                errorText += '- КПП, ';
                tmpBool = true;
            }
        }
        if (tmpBool) $('#center-block .title').html(errorText.substr(0, errorText.length - 2));

        return !tmpBool;
    }
    function getCities(countryId) {
        $.ajax({
            url: 'geo/getcities/' + countryId,
            dataType: "json",
            beforeSend: function () { },
            error: function (data) { alert('запрос не выполнен для ' + data); },
            success: function (data) {
                tmpHtml = '<option value="0">(выберите город)</option><option value="-1">(нет в списке)</option>'
                for (i = 0; i < data.length; i++) {
                    tmpHtml += '<option value="' + data[i].id + '" >' + data[i].title + '</option>';
                }
                $('#OrderLocationCity').html(tmpHtml);

                $('#OrderLocationCity option').each(function () {
                    if ($(this).text().toLowerCase() == 'москва') {
                        $(this).attr('selected', 'selected');
                        $('#OrderZip').val('109012');
                        $('#orderZipTr').addClass('hidden');
                    }
                });

                $('#OrderLocationCity').unbind('change').change(function () {
                    if ($(this).val() == "-1") $('#NotInListDiv').removeClass('hidden');
                    else $('#NotInListDiv').addClass('hidden');

                    var selectedOption = $('option:selected', this);
                    if (selectedOption && selectedOption.html().toLowerCase() == 'москва') {
                        $('#OrderZip').val('109012');
                        $('#orderZipTr').addClass('hidden');
                    }
                    else {
                        $('#OrderZip').attr('disabled', '').val('');
                        $('#orderZipTr').removeClass('hidden');
                    }
                });
            }
        });
    }

    if ($('#OrderLocationCity').length)
        getCities(1);

    //if ($('#OrderLocation').val() != '0' && !isNaN($('#OrderLocation').val()))
    //    getCities($('#OrderLocation').val());
    var deliverySel;
    calcDelivery();
    $delivery = $('#delivery');
    $delivery.change(function () {
        if ($('#delivery option:selected').val() == 0) {
            var errorText = '<span class="error-text">Пожалуйста, выберите способ доставки</span>';
            $('#cont-scroll').prepend(errorText).append(errorText);
            $(this).addClass('red-border');
        }
        else {
            $(this).removeClass('red-border');
            $('#cont-scroll').find('.error-text').remove();
        }
    });

    $('.order-dl dd select').change(function () {
        calcDelivery();
    });

    $('#delivery-city').change(function () {
        if (!$('#delivery option:selected').val() == 4) return;
        ajaxEnable(true);
        $.ajax({
            url: 'http://www.emspost.ru/api/rest?&method=ems.calculate&from=city--moskva&to=' + $('#delivery-city option:selected').attr('value') + '&weight=' + (parseFloat($('#TotalOrderWeight').val()) / 1000),
            dataType: "jsonp",
            beforeSend: function () { ajaxEnable(true); },
            error: function (data) {
                alert('запрос не выполнен для ' + data);
                ajaxEnable(false);
            },
            success: function (data) {
                ajaxEnable(false);
                /*jsonp1295168844364({"rsp":{"stat":"ok","price":"920","term":{"min":3,"max":4}}})*/
                if ($('#delivery-city').val() == 0) {
                    $('#delivery-pay').html('--').next().next().html('--');
                    $('#DeliveryPeriod').val('');
                    $('#span-delivery').html('Не выбран город(область) доставки');
                    return;
                }
                saveOrderDeliveryPaymentData();
                if (data.rsp.stat != "ok") {
                    $('#span-delivery').html('данный вид доставки не доступен на данный момент');
                    $('.basket-right').eq(1).children()
                    .css("cursor", "default")
                    .find('span span').css("color", "#ccc");
                    $('#TotalOrderCostWithAdd').val($('#TotalOrderCost').val());
                    $('#DeliveryCost').val(0);
                    $('#DeliveryPeriod').val('');
                }
                else {
                    var deliveyPay = parseFloat(data.rsp.price) + parseFloat(data.rsp.price) * 0.1 + parseFloat($('#TotalOrderCost').val()) * 0.01;
                    deliveyPay = deliveyPay.toFixed(2);
                    $('#delivery-pay').html(deliveyPay + ' руб.');
                    var totalCost = calculateTotalCost();
                    $('#total-cost').html(totalCost + ' руб.');
                    $('#delivery-pay').next().next().html('от ' + data.rsp.term.min + ' до ' + data.rsp.term.max + ' дней');
                    $('#DeliveryPeriod').val('от ' + data.rsp.term.min + ' до ' + data.rsp.term.max + ' дней');
                    $('#span-delivery').html($('#delivery-city option:selected').html());
                    $('#TotalOrderCostWithAdd').val(totalCost);
                    $('#DeliveryCost').val(deliveyPay);
                    updateTotalCost();
                }
            }
        });
        $('#DeliveryCity').val($('#delivery-city option:selected').val());
    });
    var PickUpOption = 1;
    var CourierOption = 2;
    var RussiaPostOption = 3;
    var EMSPostOption = 4;
    var CashPay = 2;


    function calcDelivery() {
        if (__ajaxLoading__) return;
        $('#delivery-city').removeAttr('disabled');
        $('#pay-replace').addClass('hidden');
        $('.basket-right').eq(1).children()
				.removeAttr("cursor")
				.find('span span').css("color", "#fff");
        var $selectedDeliveryVal = $('#delivery option:selected').val();
        //--------Cамовывоз
        if ($selectedDeliveryVal == PickUpOption) {

            //$('#PayMethodList option').eq(1).attr('selected', 'selected');
            $('#delivery-city,#delivery-zip')
					.parent().addClass('hidden')
					.prev().addClass('hidden');
            $('#delivery-pay')
					.html('--')
					.next().next().html('--');
            $('#DeliveryPeriod').val('');
            $('#span-delivery').html('Ваш заказ Вы сможете забрать <a href="/store">по адресу</a>');
            $('#TotalOrderCostWithAdd').val($('#TotalOrderCost').val());
            $('#DeliveryCost').val(0);
            $('#DeliveryPeriod').val('');

            updateTotalCost();

            saveOrderDeliveryPaymentData();
        }
        //--------Доставка курьером
        if ($selectedDeliveryVal == CourierOption) {
            $('#delivery-zip')
					.parent().addClass('hidden')
					.prev().addClass('hidden');
            $('#delivery-city')
					.parent().addClass('hidden')
					.prev().addClass('hidden');
            $('#delivery-city .msk').attr('selected', 'selected');
            $('#delivery-city').attr('disabled', 'disabled');
            var courierCost = 0;
            if ($('#TotalOrderCost').length > 0 && parseFloat($('#MoscowFreeDeliveryCost').val()) > parseFloat($('#TotalOrderCost').val().replace(/\s/g, ""))) {
                $('#delivery-pay').html($('#MoscowDeliveryCost').val() + ' руб.').next().next().html('до 3-х дней');
                $('#DeliveryPeriod').val('до 3-х дней');
                courierCost = $('#MoscowDeliveryCost').val();
            }
            else {
                $('#delivery-pay').html('бесплатно').next().next().html('до 3-х дней');
                $('#DeliveryPeriod').val('до 3-х дней');
                courierCost = 0;
            }
            $('#span-delivery').html('возможна оплата наличными курьеру, при заказе более, чем на ' + $('#MoscowFreeDeliveryCost').val() + ' руб. - доставка по Москве - бесплатно');
            $('#TotalOrderCostWithAdd').val($('#TotalOrderCost').val() + courierCost);
            $('#DeliveryCost').val(courierCost);
            $('#DeliveryPeriod').val('до 3-х дней');

            updateTotalCost();

            saveOrderDeliveryPaymentData();
        }
        //--------Почта России
        if ($selectedDeliveryVal == RussiaPostOption) {

            $('#delivery-zip')
					.parent().removeClass('hidden')
					.prev().removeClass('hidden');
            $('#delivery-city')
					.parent().addClass('hidden')
					.prev().addClass('hidden');
            if ((/^[0-9]{6}$/i).test($('#delivery-zip').val()))
                $('#span-delivery').html('Укажите индекс места назначения');
            $('#delivery-zip').blur(function () {
                if ((/^[0-9]{6}$/i).test($('#delivery-zip').val())) {
                    $.ajax({
                        url: '/service/russianpost?viewPost=36&countryCode=643&typePost=1&viewPostName=Ценная посылка&countryCodeName=Российская Федерация&typePostName=НАЗЕМН.&weight=' + $('#TotalOrderWeight').val() + '&value1=' + Math.floor(parseFloat($('#TotalOrderCost').val().replace(/\s/g, ""))) + '&postOfficeId=' + $('#delivery-zip').val(),
                        dataType: "json",
                        beforeSend: function () { ajaxEnable(true); },
                        error: function (data) {
                            alert('запрос не выполнен для ' + data);
                            ajaxEnable(false);
                        },
                        success: function (data) {
                            ajaxEnable(false);
                            if (data.Status != "ok") {
                                $('#span-delivery').html(data.ErrorMessage);
                                $('.basket-right').eq(1).children()
                                .css("cursor", "default")
                                .find('span span').css("color", "#ccc");
                                $('#delivery-pay').html('--');
                                $('#TotalOrderCostWithAdd').val($('#TotalOrderCost').val());

                                $('#DeliveryCost').val(0);
                                $('#DeliveryPeriod').val('');
                            }
                            else {
                                var ruPostDeliveryCost = data.PackageCost + data.Tax + parseFloat($('#RussianPostAdditional').val());
                                var totalCost = calculateTotalCost();
                                $('#delivery-pay').html(ruPostDeliveryCost.toFixed(2) + ' руб.');
                                //{PackageCost: [стоимость бандероли], Tax:[Страховой сбор]}
                                $('#span-delivery').html('Почта России')
                                $('#TotalOrderCostWithAdd').val(totalCost);
                                $('#DeliveryCost').val(ruPostDeliveryCost);
                                $('#DeliveryPeriod').val('от 7 до 30 дней');
                                $('#delivery-pay').next().next().text('от 7 до 30 дней');
                                updateTotalCost();
                                saveOrderDeliveryPaymentData();
                            }
                        }
                    });
                }
                else $('#span-delivery').html('<span class="orange">Укажите верный индекс места назначения</span>');
            });

            updateTotalCost();
        }
        //--------EMS Почта России
        if ($selectedDeliveryVal == EMSPostOption) {

            $('#delivery-zip')
					.parent().addClass('hidden')
					.prev().addClass('hidden');
            $('#delivery-city')
					.parent().removeClass('hidden')
					.prev().removeClass('hidden');
            if (deliverySel != 3) {
                ajaxEnable(true);
                $.ajax({
                    url: "http://emspost.ru/api/rest/?method=ems.get.locations&type=russia&plain=true",
                    dataType: "jsonp",
                    beforeSend: function () { ajaxEnable(true); },
                    error: function (data) {
                        alert('запрос не выполнен для ' + data);
                        ajaxEnable(false);
                    },
                    success: function (data) {
                        ajaxEnable(false);
                        $('#TotalOrderCostWithAdd').val($('#TotalOrderCost').val());
                        $('#DeliveryCost').val(0);
                        $('#DeliveryPeriod').val('');
                        if (data.rsp.stat != 'ok') {
                            $('.order-comment').html(data.rsp.err.msg);
                            return;
                        }
                        var tmpHtml = '<option value="0" class="option-empty">--Выберите город или регион доставки</option>';
                        var tmpCount = true;
                        for (i = 0; i < data.rsp.locations.length; i++) {
                            if (data.rsp.locations[i].type == "regions" && tmpCount) {
                                tmpHtml += '<option value="" class="option-empty">--Выберите область доставки</option>';
                                tmpCount = false;
                            }
                            tmpHtml += '<option value="' + data.rsp.locations[i].value + '">' + data.rsp.locations[i].name + '</option>';
                        }
                        $('#delivery-city').html(tmpHtml);
                        deliverySel = 3;
                        $('#span-delivery').html('Выберите город доставки');
                        updateTotalCost();
                        saveOrderDeliveryPaymentData();
                    }
                });
                updateTotalCost();
            }
        }

        if ($('#PayMethodList option:selected').val() == CashPay
        && $selectedDeliveryVal == EMSPostOption
        && ($('#delivery-city option:selected').val() != 'region--moskovskaja-oblast' && $('#delivery-city option:selected').val() != 'city--moskva')) {
            $('#delivery-city').addClass('red-border');
        }
        else {
            $('#delivery-city').removeClass('red-border');
        }

        if (($('#delivery option:selected').val() != 1 && $('#delivery option:selected').val() != 2)
        && $('#PayMethodList option:selected').val() == CashPay) {
            $('#PayMethodList option').eq(0).attr('selected', 'selected');
        }
    }

    $('.delivery-list .cover')
			.removeClass('hidden')
			.click(function () {
			    if ($('#pay-replace').hasClass('hidden')) setTimeout(showPayList, 40);
			});
    $('body').click(function () {
        if (!$('#pay-replace').hasClass('hidden')) setTimeout(hidePayList, 20);
        if ($('.u-m-l .hidden').is(':visible')) {
            $('.u-m-l .hidden').stop(true, true);
            $('.u-m-l .hidden').fadeOut('fast');
        }
    });
    function hidePayList() {
        $('#pay-replace').addClass('hidden');
    }
    function showPayList() {
        $('#pay-replace').removeClass('hidden');
    }
    var $PayMethodText = $('#span-pay-method');

    $('#pay-replace li').click(function () {
        var tmpEq = $(this).attr('id').substring(5, 6);
        if (tmpEq == 2 && $('#delivery option:selected').val() != 1 && $('#delivery option:selected').val() != 2)
            return false;
        $('#PayMethodList option[value=' + tmpEq + ']').attr('selected', 'selected');
        var $SelectedPayment = $('#PayMethodList option:selected');

        var wrapStart;
        if ($SelectedPayment.val() == 1)
            wrapStart = '<span class="payment sber">';
        else if ($SelectedPayment.val() == 2)
            wrapStart = '<span class="payment cash">';
        else if ($SelectedPayment.val() == 3)
            wrapStart = '<span class="payment rbk">';
        else if ($SelectedPayment.val() == 5)
            wrapStart = '<span class="payment master">';
        else if ($SelectedPayment.val() == 6)
            wrapStart = '<span class="payment visa">';

        $PayMethodText.html(wrapStart + $SelectedPayment.text() + '</span>');
        saveOrderDeliveryPaymentData();
        calcDelivery();
    });
    $(window).error(function () {
        ajaxEnable(false);
        return false;
    });

    /* start for catalog.aspx */
    var activeA = $('#top-menu a[href="../' + $('#ActiveCatalog').val() + '/index.htm"]');
    if (activeA.length > 0) {
        loadSubcatalogs(activeA.eq(0));
    }
    /* end for catalog.aspx */
    $('#head-tools-div .link-question').click(function () {
        $('#QuestionFormInput').removeClass('hidden');
        $('#QuestionFormAfter').removeClass('show');
    });

    function getClientHeight() {
        return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientHeight : document.body.clientHeight;
    }

    $wrapperH = $('#wrapper').height();
    $headerH = $('#header').height();
    $showcaseH = $('#showcase').height();
    $footerH = $('#footer').height();
    $showcase = $('#showcase');
    //alert($wrapperH + '-' + $headerH + '-' + $footerH + '-' + $showcaseH)
    $showcase.css('margin-top', ($wrapperH - $headerH - $footerH - 567) / 2);

    if ($("#bannerCarousel").length && !$('#showcase').length) {
        $('#carouselCont').removeClass('hidden');
        $("#bannerCarousel").jCarouselLite({
            btnNext: ".ban-next",
            btnPrev: ".ban-prev"
        });
    }
});
var __ajaxLoading__ = false;
function ajaxEnable(enable) {
    if (enable)
        $('.order-inf').addClass('order-ajax');
    else
        $('.order-inf').removeClass('order-ajax');
    if ($('#delivery').length)
        $delivery.attr('disabled', enable ? 'disabled' : '');
    $('#delivery-zip').attr('disabled', enable ? 'disabled' : '');
    $('#PayMethodList').attr('disabled', enable ? 'disabled' : '');
    $('#delivery-city').attr('disabled', enable ? 'disabled' : '');
    __ajaxLoading__ = enable;
}
function saveOrderDeliveryPaymentData() {
    setOrderDeliveryPaymentData({ DeliveryMethod: $('#delivery option:selected').val(), DeliveryCity: $('#delivery-city option:selected').html(), DeliveryZip: $('#delivery-zip').val(), PayMethod: $('#PayMethodList option:selected').val() });
}
function setOrderDeliveryPaymentData(data) {
    $('#DeliveryMethod').val(data.DeliveryMethod);
    $('#DeliveryCity').val(data.DeliveryCity);
    $('#DeliveryZip').val(data.DeliveryZip);
    $('#PayMethod').val(data.PayMethod);
}
function setFormActionPars(pars) {
    theForm.action = '?' + encodeURI(pars);
}

