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')
}

function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}

function ajaxAdd2Basket(arid, arq, f)
{
    if (typeof arid == 'number') arid=[arid];
    if (typeof arq == 'number') arq=[arq];

    $.post("/catalog/order.php", {"id[]" : arid, "q[]" : arq}, function(data)
    {
        var res = true;

        $('#basket div.goods').html($(data).filter('div.goods').html());
        $('#basket div.price').html($(data).filter('div.price').html());

        if(!basket.hidden)
            $('#basket').ishow();

        $("#basket-small div.goods").text($(data).filter('div.goods').find('a').text());

        if (typeof f == 'function')
            res = f(data);

        if (res)
            { 
            if ($(data).filter('div.mess').text()!='ok') //РќРµС‚ РІ РЅР°Р»РёС‡РёРё
                showPopupMessagePage('/catalog/not_available.php', {callbackOnShow: function(){
                    var html = $('#fancy_ajax').html() + $(data).filter('div.mess').html();
                    $('#fancy_ajax').html('<div id="fancy_ajax_content">'+html+'</div>');
                    $("#fancy_ajax_content").ready(function(){
                        $("#fancy_outer").height( $("#fancy_ajax_content").height()+30 )
                    });
            }});  
            if ($(data).filter('div.mess').text()=='ok') //Р”РѕР±Р°РІР»РµРЅ РІ РєРѕСЂР·РёРЅСѓ
                showPopupMessagePage('/catalog/available.php', {callbackOnShow: function(){
                    var html = $('#fancy_ajax').html() + $(data).filter('div.mess').html();
                    text_without_ok=$('#fancy_ajax').text();
                    $('#fancy_ajax').html('<div id="fancy_ajax_content">'+html+'</div>');

                    $("#fancy_ajax_content").ready(function(){
                        $("#fancy_outer").height( $("#fancy_ajax_content").height()+30 )
                    });
                    $('#fancy_ajax').text(text_without_ok);
            }});  
        } 
    });

    // РїСЂРё РґРѕР±Р°РІР»РµРЅРёРё РїРµСЂРІРѕРіРѕ С‚РѕРІР°СЂР° РїРѕРєР°Р·С‹РІР°РµРј Р±РѕР»СЊС€СѓСЋ РєРѕСЂР·РёРЅСѓ
    if ($('#basket-small').css('display')!="block")
        {
        $('#basket').show();
    }
}



// explode для javascript
function explode( delimiter, string ) {
    var emptyArray = { 0: '' };
    if ( arguments.length != 2
    || typeof arguments[0] == 'undefined'
    || typeof arguments[1] == 'undefined' )
        {
        return null;
    }
    if ( delimiter === '' || delimiter === false || delimiter === null ){
        return false;
    }
    if ( typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object' ){
        return emptyArray;
    }
    if ( delimiter === true ) {
        delimiter = '1';
    }

    return string.toString().split ( delimiter.toString() );
}





// Быстрая сортировка массива объектов по указанному полю. heap sort ( N log N  )
Array.prototype.sortByPropInt = function (propName, order) {
    var tmp, up = this.length - 1, i = up >> 1;

    while( i >= 0 ) this.siftByProp(i--, up, propName);

    i = up;

    while( i > 0 ){
        tmp = this[0];
        this[0] = this[i];
        this[i] = tmp;
        this.siftByProp(0,--i, propName);
    }

    if (!order) this.reverse();
}

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(){


    //if (GlobalPrint)
	//	return false;
	
	return this.fancybox({
        'hideOnContentClick': false, 
        'centerOnScroll': false, 
        'frameWidth' : 0, //(713-18*2), 
        'frameHeight': 0, //fancyboxFrameHeight,
        'padding'    : 15,
        'overlayOpacity' : 0.6,
        'callbackOnShow': fancyboxInit
        //'callbackOnClose' : function(){h = document.location.hash.split('/'); if (h.pop()=="") h.pop(); document.location.hash=h.join('/')+"/"; $('#ajax-loading').hide();}
    });
	
}

function showPopupMessagePage(href, opt)
{
	var opt = opt || {};

    $('<a>').attr('href', href).fancybox({
        'hideOnContentClick': false, 
        'centerOnScroll': false, 
        'frameWidth' : opt.width-30 || 400,
        'frameHeight': opt.height-30 || 80,
        'padding'    : 15,
        'overlayOpacity' : 0.6,
        'callbackOnShow': opt.callbackOnShow || fancyboxInit,
        //'callbackOnShow': opt.callbackOnShow || false,
        //'callbackOnShow': fancyboxInit,
        'callbackOnClose' : function(){$('#ajax-loading').hide()}
    }).click();
	
}



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/'+sid+'/') == -1)
            window.location = '/catalog/'+sid+'/'+document.location.hash;
        else
            $("<a>").attr('href', h).ipopup().click();
    }
};

function indexShowcaseAniAfter() // после анимации главной страницы
{
    $("#top-menu").unbind("topMenuAniEndEvent", indexShowcaseAniAfter);
    //if ($('#center-block').children().length > 2)
    //{

    //var href = $("#left-menu .content a.item:not([style])").eq(0).addClass('sel').attr('href') || $('#top-menu').find('div.sel a:first').attr('href');
	var href = $("#left-menu a.all-goods").attr('href');
    $.get(href, function(data){
        document.location.hash = '#url=' + href.substring(href.indexOf("/catalog/"));

        $('#center-block').html(data);
        $('.sl, #center-block').ishow().queue(function (){
            $(this).removeAttr('style');
            $(this).dequeue();

            //ie6 png fix
            if (typeof IEPNGFix !="undefined") IEPNGFix.update();
        });

        $('#left-menu').show();
        $.getScript('/catalog/catalog.js');

        $('input.btn').transformBtn();
        jScrollPaneInit();
        $('.banner-block').hide();
        //$('#basket').css({marginRight: 17, marginTop: -125}).ishow();
    });
    //} else {
    //	setTimeout("indexShowcaseAniAfter()", 500);
    //}

}


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;

        $(arImg).each(function(){
            $(this).css({position: 'absolute', top: x, left: y});

            x+=w; if (x>=w*3) {x=0; y+=h;}
        });

        $('#container, #middle, div.content-bg-layer').animate({height: 719}, 1000, "easeOutExpo").queue(function (){
            $(this).removeAttr('style');
            $(this).dequeue();
        });

        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"}, 1000, "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: "4px", left: (12+(103*i))+"px"}, 1000, "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);

						
						//url для формы вопрос консультанту
						$('.url_hidden_field').val(e);
						
                        // back-url для корзины
                        $.post("/back_to_catalog.php", { backurl: e }, function(url_data){});
                        
                        
						topMenuAni(e);
                    }
                });
            }		
        });

    }


}


ToLoad = false;

function topMenuAni(e)
{

    $('#top-menu div').removeAttr('style');

    if ($(e).parent().not('.sel')[0] && !topMenuAniFlag)
        {
        topMenuAniFlag = true;

        ToLoad = this;

        $('#top-menu .sel img').animate({width: "93px",	height: "61px"}, 400)
        .each(function(){this.src = this.src.replace('/middle/', '/small/')})
        .parent().parent().addClass('sh').removeClass('sel');

        $(e).find('img')
        .each(function(){this.src = this.src.replace('/small/', '/middle/')})
        .animate({width: "132px",	height: "87px"}, 500, function(){
            $(this).parent().parent().removeAttr('style');


            {//rebuild menu and load cat. page
                var s = this.src.indexOf('.gif');
                var e = this.src.lastIndexOf('/', n)+1;



                if (s>0 && e>0)
                    {
                    var n = parseInt(this.src.substring(s, e));
                    //alert (n);
                    if (n>0)
                        {
                        $('#left-menu').removeAttr('style');
                        $('#left-menu .content a.item').hide();
                        $('#left-menu .content a.mi_sid_n'+n).removeAttr('style');
                        topMenuAniFlag = false;

			   $lm = $('#left-menu');
			   var left_menu_height = parseInt($lm.height())+parseInt($lm.css('margin-top'))+parseInt($lm.css('margin-bottom'));
			   $bb = $('.banner-block');
			   var banner_height = parseInt($bb.height())+parseInt($bb.css('margin-top'))+parseInt($bb.css('margin-bottom'));
	
                        if ($('#left-menu a.item:visible')[0])
                            {	
                            if (left_menu_height+banner_height<620)
					$('.banner-block').show();
    				else
					$('.banner-block').hide(); 

                           


                            //$('a.all-goods').click();
                            //alert("!!!!");
                            //$('#left-menu a.item:visible').eq(0).click(); //$('#left-menu .content .mi_sid_n'+n).eq(0).click();
                            //$('a.all-goods').addClass('selected');
							
                            
                            var main_section = $('a.all-goods').attr('href').substring(9)
                            main_section = str_replace('/', '', main_section);
                            if (main_section>0)
                            {
                                loadCatalogPage(main_section);
                                $('a.all-goods').css('color', '#EA4301').addClass('selected');
                                $('#left-menu a').removeClass('sel')
								
								//url для формы вопрос консультанту
								$('.url_hidden_field').val('http://nv-shop.ru/catalog/'+main_section+'/');
							}
                            //else
                            //    $('#left-menu a.item:visible').eq(0).click(); //$('#left-menu .content .mi_sid_n'+n).eq(0).click();
							
							

                        }
                        else
                            $('#left-menu').hide();
                    }  
                }    
            }

            //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').animate({width: "100px",    height: "66px"}, 500);
        $('#top-menu .last-clicked img').css('width', '100px').css('height', '66px');
        //$('#top-menu .sh:not(.sel) img').animate({width: "93px",    height: "61px"}, 500);
        $('#top-menu .sh:not(.sel) img').css('width', "93px").css('height', "61px");
        //alert($(e).attr('href')); 
        
    }
	

}





function loadCatalogPage(sid, fHash)
{
    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/'+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 fancyboxInit()
{
    /*
    $('#fancy_outer').css('left', '450px');
    $('#fancy_outer').css('width', '1px');      
    /*
    $('#fancy_outer').animate({width: "707px", height: fancyboxFrameHeight, left: "260px"}, 900, 'linear', function(){
    $('#fancy_content').show();            
    });
    */

    //niceBtn
    $('input.btn').transformBtn();

    //tabs
    $('div.tab-block div.title-tabs div.item').click(function(){
        if ($(this).is('div:not(.sel)'))
            {
            $('div.tab-block div.title-tabs div.sel').removeClass('sel');
            $(this).addClass('sel');

            $('div.tab-block div.tabs-txt').hide();
            id = $(this).children('a').attr('href');
            id = id.substring(id.indexOf('#'));
            $(id).show();
            $(id).children('.scroll-pane').jScrollPane({showArrows:true, scrollbarWidth: 20});                    
        }
        return false;
    }); 

	
	
    //scrollable
    if (($('div.scrollable-container')[0])&&(!cycling))
        {
        //if (!scrolableLoaded)
        //    {
            scrolableLoaded=true;
            $.getScript("/bitrix/templates/nv-shop/js/tools.scrollable-1.0.5/tools.scrollable-1.0.5.min.js",	function(){
                cycling = false;
				$("div.scrollable-container").scrollable({vertical:true, size: 3, prev: '#scroll-prev', next: '#scroll-next'});
            });
        //}
        //else
        //   {
        //    cycling=true;
        //    scrolableLoaded=true; // мое
        //    $("div.scrollable-container").scrollable({vertical:true, size: 3, prev: '#scroll-prev', next: '#scroll-next'});
        //} 



        $('div.scrollable div.items div img').wrap('<table class="valign-middle-tab"><tr><td></td></tr></table>');

    }

	
 
    $('.scrollable > .items').find('img').click(function(){
        var img_src=$(this).attr('title');
        $('#video-div > div').remove();
        $('#video-div > img').show();
        $('.big-img').attr('src', img_src);
    });

  
    $('.video-pic').click(function(){
        $.post("/play.php", {video_path:$(this).attr('alt')}, function(video_data){
            //alert(video_data);
            $('#video-div > img').hide();
            $('#video-div').append(video_data);
            $('#video-div > div').show();
        });        
    });


    //////////////////////////////////////////////////////////                                                        
    //// ПОДГРУЖАЕМ РЕКОМЕНДУЕМЫЙ ТОВАР ПРИ КЛИКЕ НА НЕГО ////
    //////////////////////////////////////////////////////////
	
    $('#detail-recommended a').click(function(){

        var arhref = new Array();
        arhref = explode("#url=", $(this).attr('href'));

        $.get(arhref[1], { is_recomended: "_recomended" }, function(recomended_data){
            //alert(arhref[1]);
            $('.recomended').show('slow');
            $('#fancy_close').hide();
            $('#detail-recommended_recomended').hide();
            $('.recomended').append(recomended_data);

            $('#scroll1_recomended').jScrollPane({showArrows:true, scrollbarWidth: 20});  

            //niceBtn
            $('.recomended input.btn').transformBtn();

            //scrollable
            if ($('.recomended div.scrollable-container')[0])
                {
                if (!scrolableLoaded)
                    {
                    scrolableLoaded=true;
                    $.getScript("/bitrix/templates/nv-shop/js/tools.scrollable-1.0.5/tools.scrollable-1.0.5.min.js",    function(){
                        $(".recomended div.scrollable-container").scrollable({vertical:true, size: 3, prev: '#scroll-prev_recomended', next: '#scroll-next_recomended'});
                    });
                }
                else
                    {
                    $(".recomended div.scrollable-container").scrollable({vertical:true, size: 3, prev: '#scroll-prev_recomended', next: '#scroll-next_recomended'});
                }

                $('.recomended div.scrollable div.items div img').wrap('<table class="valign-middle-tab"><tr><td></td></tr></table>');
            }            
			
            //вывод картинок по клику в детальной
            $('.recomended .scrollable > .items').find('img').click(function(){
                var img_src=$(this).attr('src');
                $('#video-div_recomended > div').remove();
                $('#video-div_recomended > img').show();
                $('.recomended .big-img').attr('src', img_src);
            });

            // вывод видео
            $('.recomended #video-pic').click(function(){
                $.post("/play.php", {video_path:$(this).attr('alt')}, function(video_data){
                    //alert(video_data);
                    $('#video-div > img').hide();
                    $('#video-div').append(video_data);
                    $('#video-div > div').show();
                });        
            });

            //tabs
            $('.recomended div.tab-block div.title-tabs div.item').click(function(){
                if ($(this).is('.recomended div:not(.sel)'))
                    {
                    $('.recomended div.tab-block div.title-tabs div.sel').removeClass('sel');
                    $(this).addClass('sel');

                    $('.recomended div.tab-block div.tabs-txt').hide();
                    id = $(this).children('a').attr('href');
                    id = id.substring(id.indexOf('#'));
                    $(id).show();
                    $(id).children('.recomended .scroll-pane').jScrollPane({showArrows:true, scrollbarWidth: 20});                    
                }
                return false;
            });             

            //quantity control
            if (DETAIL_ELEMENT_Q<1)
                {    
                $('#detail-buy-line-form_recomended').submit(function(){
                    //showPopupMessagePage('/catalog/not_available.php');
                    ajaxAdd2Basket(parseInt($('#tovar-id_recomended').text()), $('.recomended .buy-line').find('input').val());
                    return false;
                });
            }

            if (DETAIL_ELEMENT_Q>0)
                {    
                $('#detail-buy-line-form_recomended').submit(function(){
                    //showPopupMessagePage('/catalog/available.php');
                    ajaxAdd2Basket(parseInt($('#tovar-id_recomended').text()), $('.recomended .buy-line').find('input').val());
                    return false;
                });
            }            

            // CLOSE
            $('.recomended .close').click(function(){
                $('.recomended').hide('slow');
                $(this).parent().empty().append('<div class="close"></div>');

                $('#fancy_close').show();
            });
        });    
    });      

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	

    // убираем стрелку вниз если меньше 4 картинок (косяк скролла в детальной)
    if ($('.scrollable .items div').size()<4)
        $('#scroll-next').css('visibility', 'hidden');

    /*
	
	из-за этого была ошибка в ie
	
	if ((!no_ajax)&&(!cycling))
        {
        $('#scroll1').jScrollPane({showArrows:true, scrollbarWidth: 20});
    }*/


    //hints
    $('#fancy_content').find(".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();});
    });
	
    /*prev|next elements switching*/
    var arItems=$("#catalog-v-table-form input:[name='id[]']").get();
    var arItemsLinks=$("#catalog-v-table-form td.img a").get();  /* было так   var arItemsLinks=$("#catalog-v-table-form td.img a").get() */
    if (arItems.length>0 && DETAIL_ELEMENT_ID>0)
        {
        var cur = $(arItems).index( $(arItems).filter("[value='"+DETAIL_ELEMENT_ID+"']")[0] );
        var i = arItemsLinks[cur].href.indexOf('/catalog/');
		
		if (i!=-1) document.location.hash = '#url='+arItemsLinks[cur].href.substring(i);

        if (cur > 0)
            {
            $('#fancy_ajax .detail-title a.prev img').attr('src', IMAGE_DIR+"/btn-detail-prev-arrow-act.gif")
            .parent().attr('href', arItemsLinks[cur-1].href)
            .click(function(){
                $('#fancy_ajax').load(this.href, {}, fancyboxInit);
                  
                return false;
            });
        } else {
            $('#fancy_ajax .detail-title a.prev img').attr('src', IMAGE_DIR+"/btn-detail-prev-arrow.gif").parent().attr('href', '#');
        }

        if (cur < arItemsLinks.length-1)
            {
            $('#fancy_ajax .detail-title a.next img').attr('src', IMAGE_DIR+"/btn-detail-next-arrow-act.gif")
            .parent().attr('href', arItemsLinks[cur+1].href)
            .click(function(){
                $('#fancy_ajax').load(this.href, {}, fancyboxInit);
                
                return false;
            });
        } else {
            $('#fancy_ajax .detail-title a.next img').attr('src', IMAGE_DIR+"/btn-detail-next-arrow.gif").parent().attr('href', '#');
        }   

        
    }

    //quantity control
    if (DETAIL_ELEMENT_Q<1)
        {	
        $('#detail-buy-line-form').submit(function(){
            //showPopupMessagePage('/catalog/not_available.php');
            ajaxAdd2Basket(parseInt($('#tovar-id').text()), $('.buy-line').find('input').val());
            return false;
        });
    }

    if (DETAIL_ELEMENT_Q>0)
        {	
        $('#detail-buy-line-form').submit(function(){
            //showPopupMessagePage('/catalog/available.php');
            ajaxAdd2Basket(parseInt($('#tovar-id').text()), $('.buy-line').find('input').val());
            return false;
        });
    }

}

function jScrollPaneInit()
{
    /*
    $('.scroll-block').each(function(){
    if ($(this).is(':visible'))
    $(this).jScrollPane({showArrows:true, scrollbarWidth:20});
    else
    $(this).parent().show().end().jScrollPane({showArrows:true, scrollbarWidth:20}).parent().parent().hide();
    });
    */	
}

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" : "");
}


MWEvent = false;
$(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
    $('#top-menu a img, #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 ($('#top-menu').is(':visible'))
        {
        $('#top-menu a').click(function(){topMenuAni(this); return ($('#catalog-v-showcase')[0] ? false : true);});
    }

    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(){

        if (getCookie("basket_nofirsttime")!="true") // если анимация уже была то сворачивать корзину не так пафосно
            doScrollTo(0, 800, 50);
        setCookie("basket_nofirsttime", "true");

        $('#basket').animate({left: '495px', top: '760px'}, 2000, 'easeOutBack', 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').css('cursor', 'pointer').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}, 2000, 'easeOutBack', function(){
            basket.hidden = false;
            setCookie("basket_hidden", basket.hidden);
        });

        return false;
    });

    $('a.popup').ipopup();
    jScrollPaneInit();

    $('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;});
    $('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();});
    });

    //ajax animation
    $('<div id="ajax-loading"><img src="/images/ajax-loader.gif" alt="Загрузка..." /></div>')
    .css({position: 'absolute', right: 0, padding: '10px', 'z-index': 10000, display: 'none'})
    .prependTo('body')
    .ajaxStart(function(){$(this).show();})
    .ajaxStop(function(){$(this).hide();});

    //pagePopupLoader
    setTimeout('pagePopupLoader()', 1);

    //косяки подсвечивания при наведении	
    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($('#top-menu').width()!=980)
    {
    $('#basket-small').show();
    }
    */  


    // прячем большую корзину если есть маленькая
    /*
    if ($('#basket-small').css('display')=="block")
    {
    $('#basket').hide();
    }
    if ($('#basket').css('display')=="block")
    {
    $('#basket-small').hide();
    }
    */

    // прячем пустые корзины
    if ($('div.goods > a').text()=="")
        {
        $('#basket-small').hide();
        $('#basket').hide();
    }

    // берем из куков состояние корзины (свернута или нет)
    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();
    }


    /////////////////////////////////////////
    ///// НЕАЯКСОВАЯ ДЕТАЛЬНАЯ СТРАНИЦА /////
    /////////////////////////////////////////

    if($('#fancy_outer').css('display')=='none')
        {
        $('.next').hide();
        $('.prev').hide();
        //$('.tab-block').hide()
        //$('#container').height(900);
        no_ajax=true;
        fancyboxInit();
        no_ajax=false;
        $('#detail-scroll').jScrollPane({showArrows:true, scrollbarWidth: 20});
        $('#scroll-block .title-tabs div.item:eq(3)').hide();        
        $('#scroll1').parent().css('height', '100%');
        $('#scroll1').css('height', '100%');
        $('#scroll2').parent().css('height', '100%');
        $('#scroll2').css('height', '100%');

        //$('.star-div').hide();

    }

    /////////////////////////////////////////
    ////// ВСПЛЫВАЮЩИЕ ТОВАРЫ В КОРЗИНЕ /////
    /////////////////////////////////////////

    $('.basket-items a').click(function(){
        var arhref = new Array();
        arhref = explode("#url=", $(this).attr('href'));        

        showPopupMessagePage(arhref[1]);
        //fancyboxInit();     
    });
    /*
    $('.basket a').click(function(){
    var arhref = new Array();
    arhref = explode("#url=", $(this).attr('href'));        

    showPopupMessagePage(arhref[1]);
    //fancyboxInit();     
    });
    */

    //скрываем баннер, если слишком длинное меню
    $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 (left_menu_height2+banner_height2<620)
	$('.banner-block').show();
    else
	$('.banner-block').hide(); 	
                         

    // прячем корзину в корзине
    if ($('.basket-items').length)
        {
        $('#basket').hide();
        $('#basket-small').show();
    }
	
	
	
});




function getFlashVersion()
{
	var v = 0;
	var n = navigator;
	if (n.platform == 'Win32' && n.userAgent.indexOf('Opera') == (-1) && window.ActiveXObject)
	{
		for (var i = 9; i > 2; i--)
			if (new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i))
				return i;
	}
	else if(n.plugins)
	{
		for (var i = 0, l = n.plugins.length; i < l; i++)
			if (n.plugins[i].name.indexOf('Flash') != -1)
				v = parseInt(n.plugins[i].description.substr(16, 2));
	}
	return v;
}

function showFLVPlayer(id, mess)
{
	var oDiv = document.getElementById(id + '_div');
	if (!oDiv) return;
	oDiv.style.display = 'block';
	if (getFlashVersion() < 9)
		oDiv.innerHTML = mess;
}

function print_r_old( array, return_val ) { // Prints human-readable information about a variable 
	    //  
	    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) 
	    // + namespaced by: Michael White (http://crestidg.com) 
	  
	    var output = "", pad_char = " ", pad_val = 4; 
	  
	    var formatArray = function (obj, cur_depth, pad_val, pad_char) { 
	        if(cur_depth > 0) 
	            cur_depth++; 
	  
	        var base_pad = repeat_char(pad_val*cur_depth, pad_char); 
	        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char); 
	        var str = ""; 
	  
	        if(obj instanceof Array || obj instanceof Object) {
	            str += "Array\n" + base_pad + "(\n"; 
	            for(var key in obj) { 
	                if(obj[key] instanceof Array || obj[key] instanceof Object) {
	                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char); 
	                } else { 
	                    str += thick_pad + "["+key+"] => " + obj[key] + "\n"; 
	                } 
	            } 
	            str += base_pad + ")\n"; 
	        } else { 
	            str = obj.toString(); // They didn't pass in an array.... why? -- Do the best we can to output this object. 
	        }; 
	  
	        return str; 
	    }; 
	  
	    var repeat_char = function (len, char) { 
	        var str = ""; 
	        for(var i=0; i < len; i++) { str += char; }; 
	        return str; 
	    }; 
	  
	    output = formatArray(array, 0, pad_val, pad_char); 
	  
	    if(return_val !== true) { 
	        document.write("<pre>" + output + "</pre>"); 
	        return true; 
	    } else { 
	        return output; 
	    } 
	}
	
function print_r( array, return_val ) {    // Prints human-readable information about a variable
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + namespaced by: Michael White (http://crestidg.com)
 
    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if(cur_depth > 0)
            cur_depth++;
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if(obj instanceof Array || obj instanceof Object) {
            str += "Array\n" + base_pad + "(\n";
            for(var key in obj) {
                if(obj[key] instanceof Array /*|| obj[key] instanceof Object*/) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else {
            str = obj.toString(); // They didn't pass in an array.... why? -- Do the best we can to output this object.
        };
 
        return str;
    };
 
    var repeat_char = function (len, char) {
        var str = "";
        for(var i=0; i < len; i++) { str += char; };
        return str;
    };
 
    output = formatArray(array, 0, pad_val, pad_char);
 
    if(return_val !== true) {
        return output;
    } else {
        return output;
		document.write("<pre>" + output + "</pre>");
        return true;
    }
}