$(document).ready(function(){
    
    if ($.browser.opera) // опера неправильно определяет ширину select
    {
        width=$("select[name=where]").width();
        $("select[name=where]").css("width", width+15);
    }; 
    
    /* main gallery */
    setInterval( function() { mainPictureChange() } , 5000)
    $('.main-gallery img:first').removeClass().addClass('picture-on');
    $('.main-gallery .picture-on').css('opacity', '1');
    $('.main-gallery .picture-off').css('opacity', '0');

    /* fancybox */
    if ($("a[rel^='lightbox']").length) {
        $("a[rel^='lightbox']").fancybox({
            'titleShow'     : false,
           hideOnContentClick: false,
           hideOnOverlayClick: true,
           enableEscapeButton: true
       });        
    }
    if ($("a.fancybox").length) {
        $("a.fancybox").fancybox({
            'titleShow'     : false,
           hideOnContentClick: false,
           hideOnOverlayClick: true,
           enableEscapeButton: true
       });        
    }
    if ($("a.show-ie6").length) {
        $("a.show-ie6").fancybox({
            'titleShow'     : false,
           hideOnContentClick: false,
           hideOnOverlayClick: true,
           enableEscapeButton: true,
           'frameWidth' : 920,
           'frameHeight': 490
       });        
    }
	if ($.browser.msie && $.browser.version < 7) $(".show-ie6").click();
	
	
    /* news main page */
    if ($("#title-news-line").length) {
         var newsoption1 = {
                    firstname: "title-news-line",
                    secondname: "showhere",
                    thirdname:"news_display",
                    fourthname:"news_button",
                    imagedir:'/images/',
                    newsspeed:'5555',
                    effectis:'1',
                    mouseover: false,
                    disablenewscount:true
                }
        $.init_news(newsoption1);         
    }

    /* top navigation */
    var navt_tds = $(".head-menu-td");
    var navt_pops = $(".navigation-popup");
    var navt_timeout = null;
    
    var navt_block_hide_ex = function(){navt_tds.removeClass('hover');}
    var navt_block_hide = function(){
        if (navt_timeout) clearTimeout(navt_timeout);
        navt_timeout = setTimeout(navt_block_hide_ex, 1000);
    }
    navt_tds.mouseover(
        function (){
            var number = $(this).parent().children(".head-menu-td").index(this);
            if (navt_timeout) clearTimeout(navt_timeout);
			var left = 0;
			for (var i=1; i<=number; i++) {
                left += $("#head-menu-td-" + i).width();
			}
            $(this).find(".navigation-popup").css("left", left+"px");
            navt_tds.removeClass('hover');  
            $(this).addClass('hover');
        }
    );
    navt_pops.mouseover(function (){if (navt_timeout) clearTimeout(navt_timeout);});
    navt_tds.mouseout(navt_block_hide);
    navt_pops.mouseout(navt_block_hide);

    var newsMainTitle = "";
    $("#news_next, #news_prev").hover(function(){
        if ($(this).attr("src") == '/images/next0.gif' || $(this).attr("src") == '/images/prev0.gif') {
            newsMainTitle = $(this).attr("title");
            $(this).css("cursor", "auto");
            $(this).attr("title", "");
        }
    }, function() {
        if ($(this).attr("src") == '/images/next0.gif' || $(this).attr("src") == '/images/prev0.gif') {
            $(this).css("cursor", "pointer");
            $(this).attr("title", newsMainTitle);
        }        
    });
    
    /* table class table */
    $('table.table').each(function(){
        $("table.table th:first").addClass("first");
        $("table.table tr:even").addClass("graytr");
    });
    
     $('.form-item').each(function(){
         if($(this).find("select").length) $(this).addClass("form-item-select");
    });
    
      $('.form').each(function(){
          if (!$(this).find(".niceBtn").length && !$(this).find("input:reset").length && !$(this).find("input:submit").length && !$(this).find("input:button").length) {
              $(this).find(".form-item:last").addClass("form-item-last2");
          }

    });  
    
    /* ie7 изврат с radio в заказе */   
    if ($(".sale_order_full_table").length) {
        if ($(".sale_order_full_table").hasClass("delivery")) {
            $(".sale_order_full_table").find(".radio:last").addClass("radio-last-label");
        }
        
    } 
    /* goods gallery */
    if ($(".catalog-gallery").length) {            
	    $(this).find(".jCarouselLite-prev-div").addClass("disabled");
        r=1;
        $("div.catalog-gallery").each(function() {            
            $(this).toggleClass("hide").toggleClass("none");
            $(this).find(".jCarouselLite-next-div").addClass("jCarouselLite-next-div"+r); // для уникальности
            $(this).find(".jCarouselLite-prev-div").addClass("jCarouselLite-prev-div"+r);
            if ($(this).find(".jCarouselLite img").length<5) $(this).find(".jCarouselLite-next-div"+r).addClass("disabled");
            
            /*carousel detail product page*/
            if ($(this).find(".jCarouselLite").length) {
                $(this).find(".jCarouselLite").jCarouselLite({
                    btnNext: ".jCarouselLite-next-div"+r,
                    btnPrev: ".jCarouselLite-prev-div"+r,
                    speed : 500,
                    visible : 4,
                    circular: false
                });
            } 
            
            
            // считаем высоту            
            heights=new Array();
            i=0;
            $(this).find(".detail-photo img").each(function(){
                heights[i]=$(this).height();
                i++;
            });
            var height=Math.max.apply(Math,heights);
            if(height > 0) $(this).find(".detail-photos").css("height", height+"px");
            $(this).find(".detail-photo img:first").removeClass("none");            
            
            $(this).find(".detail-photo").attr("rel", "img_fancybox_"+r)         
            
            $(this).find(".detail-photo").fancybox({
               'titleShow'     : false,
               hideOnContentClick: false,
               hideOnOverlayClick: true,
               enableEscapeButton: true
           });  
            $(this).toggleClass("hide").toggleClass("none");      
$(this).find(".gallery-carousel li a").attr("rel", "img_fancybox_s"+r)
			$(this).find(".gallery-carousel li a").fancybox({
               'titleShow'     : false,
               hideOnContentClick: false,
               hideOnOverlayClick: true,
               enableEscapeButton: true
           });  
           r++;   
        });
        $(".jCarouselLite img").hover(function() {
            var obj=$(this).parents("div.catalog-gallery");      
            var index = $(obj).find(".jCarouselLite img").index($(this));
            $(obj).find(".detail-photo img").addClass("none");
            $(obj).find(".detail-photo img").eq(index).toggleClass("none"); 

        });    
    }
    
    /* tabs */
    if ($("#text-tab1").length) {
        $("#text-tab1").show();
    }
    $(".tabs div").click(function(){
        if (!$(this).hasClass("active")) {
            var tabtext = $(this).attr("id").split("tab").join("");
            if ($("#text-tab" + tabtext).length) {
                $(".tab-text").hide();
                $("#text-tab" + tabtext).show();    
            }
            $(".tabs div.active").toggleClass("active");
            $(this).toggleClass("active");
        }
    });
    
    /* right bottom links */
    $(".right-bottom-link").hover(
        function(){
           var src = $(this).parent().find("img").attr("src").split(".").join("-active.");
           $(this).parent().find("img").attr("src", src); 
        }, function(){
           var src = $(this).parent().find("img").attr("src").split("-active.").join(".");
           $(this).parent().find("img").attr("src", src); 
    });
    $(".sale, .help").hover(function(){
        var src = $(this).attr("src").split(".").join("-active.");
        $(this).attr("src", src);
    }, function(){
        var src = $(this).attr("src").split("-active.").join(".");
        $(this).attr("src", src);
    });
    
    /*формы по центру на странице tools/history*/
    if($(".order-page").length && $(".user-info").length) {
        if ($("form[name=bform]").length) {
            $(".user-info").addClass("form-in-center");
            if ($.browser.msie && $.browser.version < 8) {
                $(".user-info").hide().show();
            }
        }
        if ($("form[name=form_auth]").length) {
            $(".user-info").addClass("form-in-center");
        }        
    }
    
    /* search form */
    $(".search-main-lupa").click(function(){
        $('#search-form').submit();    
    });
    /* subscribe form */
    var subText = "e-mail";
    $("#subscribe-form input:text").each(function(){
        if ($(this).val().length < 3) 
            $(this).val(subText);
        $(this).focus(function(){
            if($(this).val() == subText) {
                $(this).val("");
            }
        });
        $(this).blur(function(){
            if ($(this).val().length < 3)  $(this).val(subText);
        });
    });
    $(".subscribe-main-lupa").click(function(){
        $('#subscribe-form').submit();    
    });
    $('#subscribe-form').submit(function(){
        if($(this).find("input:text").val() == subText) {
            return false;
        } else {
            return true;
        }
    });
       //  Служба не имеет доставки в город Aleksandrov.
       /*buttons*/
    $('input:submit').transformBtn("niceBtn");
    $('input:button').transformBtn("niceButton");
    $('input:reset').transformBtn("niceButton");
    $('input:checkbox', this).each(CheckAdd);
    $('input:radio', this).each(RadioAdd);
    $("form").jNice(); // для select
    $(".brand-right").jNice();
    $("#select-brand").bind("change",function(){
		window.location=$(this).val();
	});
	$("#select-size").bind("change",function(){
		window.location=$(this).val();
	});
	$("#select-color").bind("change",function(){
		window.location=$(this).val();
	});
	
   /*баннеры на главной*/
    $(".main-bottom-edv").each(function(){
        var main_img_timeout = null;
        var main_img_div = $(this);
        var main_img_back = main_img_div.children("img.edv-main-bg");       
        var main_img_block_hide_ex = function(){
            if(main_img_div.find("div.main-edv-info").length) {
                var textDiv = main_img_div.find(".main-edv-info");
                textDiv.animate({marginTop: "0px"}, 100, function(){ main_img_back.removeClass('none');});
            }   
        }
        var main_img_block_hide = function(){
            if (main_img_timeout) clearTimeout(main_img_timeout);
                main_img_timeout = setTimeout(main_img_block_hide_ex, 100);
        }
        main_img_back.mouseover(function (){
            if (main_img_timeout) clearTimeout(main_img_timeout); 
            $(this).addClass("none"); 
            if($(this).siblings("div.main-edv-info").length) {   
                var textDiv = $(this).siblings(".main-edv-info");               
                height = textDiv.height();
                if ($.browser.version == 8) {height -= 1;} 
                textDiv.animate({ "marginTop": "-" + height + "px"}, 150);           
            }
        });
        main_img_div.mouseout(main_img_block_hide);
        main_img_div.mouseover(function (){if (main_img_timeout) clearTimeout(main_img_timeout); }); 
    })
    
    
    $(".items_list .colors a").mouseover(function(){
        SetPreviewImage(this);
    });

    $(".items_list .sprav-colors a").mouseover(function(){
        SetSpravPreviewImage(this);
    });    
    
    /* выравнивание формы подписки ie7 */
    if($.browser.msie && $.browser.version < 8)  $(".subscribe-form-item").find(".label").hide().show();
	// меню справа
	initMenu();
	$("body").oneTime(100,function(){
		UpdateHeightGallery();
	});
	$("body").oneTime(200,function(){
		UpdateHeightGallery();
	});
	$("body").oneTime(400,function(){
		UpdateHeightGallery();
	});
	$("body").oneTime(700,function(){
		UpdateHeightGallery();
	});
	$("body").oneTime(1000,function(){
		UpdateHeightGallery();
	});
	$("body").oneTime(2000,function(){
		UpdateHeightGallery();
	});
	$("body").oneTime(3000,function(){
		UpdateHeightGallery();
	});
	$("body").oneTime(5000,function(){
		UpdateHeightGallery();
	});
	$("body").oneTime(10000,function(){
		UpdateHeightGallery();
	});
});    

function initMenu() {
    var clactive = null;
  if($("#menu").find(".selected").length) {
      var activeBrand = $("#menu").find(".selected").parents("ul.catalog-level2");
      activeBrand.slideDown('normal');
      clactive = activeBrand.parent().find("div").attr("class", activeBrand.parent().find("div").attr("class")+"-active");
  }
  else if($("#menu").find(".item-selected").length) {
      var activeBrand = $("#menu").find(".item-selected").parents("ul.catalog-level2");
      activeBrand.slideDown('normal');
      clactive = activeBrand.parent().find("div").attr("class", activeBrand.parent().find("div").attr("class")+"-active");
  } 
  else if($("#menu").find(".root-item-selected").length) {
      var activeBrand = $("#menu").find(".root-item-selected").next("ul.catalog-level2");
	  activeBrand.slideDown('normal');
      clactive = activeBrand.parent().find("div").attr("class", activeBrand.parent().find("div").attr("class")+"-active");
  } 
else {
      var activeBrand = $("#menu").find("ul.catalog-level2:first");
      activeBrand.slideDown('normal');
      clactive = activeBrand.parent().find("div").attr("class", activeBrand.parent().find("div").attr("class")+"-active");
}  
  
  /*$('#menu li span').click(function() {
      var checkElement = $(this).next();
      if((checkElement.is('ul.catalog-level2')) && (checkElement.is(':visible'))) {
          checkElement.slideUp('normal');
          if (clactive) {
            clactive.attr("class", clactive.attr("class").split("-active").join(""));
          }
          clactive = null;
      }
      else if((checkElement.is('ul.catalog-level2')) && (!checkElement.is(':visible'))) {
        $('#menu ul.catalog-level2:visible').each(function(){
            $(this).slideUp('normal');
        });
        if (clactive) {
            clactive.attr("class", clactive.attr("class").split("-active").join(""));
        }
        if ($(this).find("div").length) {
            var cl = $(this).find("div").attr("class")+"-active";
            $(this).find("div").attr("class", cl);
            clactive = $(this).find("div");
        }
        else {
            clactive = null;
        }
        checkElement.slideDown('normal');
        return false;
      }
    });*/
  }

function SetPreviewImage(obj)
{
    image=$(obj).attr("rel");//href
    link=$(obj).attr("href");//href
    
    $(obj).parents(".item").find(".list_img img").attr("src", image);
    $(obj).parents(".item").find(".top_item a").attr("href", link);
    
    $(obj).siblings("a").children("img").removeClass("active");
    $(obj).children("img").addClass("active");
    
    
}

function SetSpravPreviewImage(obj)
{
    var number = $(obj).parent().children("a").index(obj);
    $(obj).parents(".item").find(".list_img a:not(:hidden)").hide();
    $(obj).parents(".item").find(".list_img").find("a:eq("+number+")").show();
    $(obj).parent().find("img").removeClass("active");
    $(obj).children("img").addClass("active");
    
    
}


function mainPictureChange(){
    var speed = 500;
    
    next=$('.main-gallery .picture-on').next('.picture-off');
    if (next.length==0) next=$('.main-gallery .picture-off:first');
    
    $(next).animate({opacity: "1"}, speed).siblings().animate({opacity: "0"}, speed); 
    $('.main-gallery .picture-on').removeClass().addClass('picture-off')
    $(next).removeClass().addClass('picture-on');
    
    return;
}

function UpdateHeightGallery()
{
	if ($(".catalog-gallery").length) {
		$("div.catalog-gallery").each(function() {
			heights=new Array();
			i=0;
			$(this).find(".detail-photo img").each(function(){
				heights[i]=$(this).height();
			i++;
			});
			var height=Math.max.apply(Math,heights);
			if(height > 0) $(this).find(".detail-photos").css("height", height+"px");
		});
	}
}

/*buttons*/
$.fn.transformBtn = function(varclass){
    return $(this).each(function(){
        var onclick='';
        for (var i = 0; i < this.attributes.length; i++) {
            if (this.attributes[i].nodeName=='onclick'){
             onclick = ' onclick="'+this.attributes[i].nodeValue+'"';
             //console.log(onclick )         
            }
        } 
        var btn = $('<button type="'+ this.type +'" ' + onclick + ' value="'+ this.value +'" class="'+varclass+'"><span><span><span><nobr>'+this.value+'</nobr></span>'+this.value+'</span></span></button>');
        btn.focus(function(){ $(this).addClass('niceBtnFocus')}).blur(function(){ $(this).removeClass('niceBtnFocus')});
        btn.mouseover(function(){ $(this).addClass('niceBtnHover')}).mouseout(function(){ $(this).removeClass('niceBtnHover')}); 
        if (typeof this.name != 'undefined') btn.attr('name', this.name);
        if (typeof this.id != 'undefined') btn.attr('id', this.id);

        $(this).replaceWith(btn);
    });
};


    var CheckAdd = function(){
        var $input = $(this).addClass('jNiceHidden').wrap('<span class="jCheckboxWrapper jNiceWrapper"></span>');
        var $wrapper = $input.parent().append('<span class="jNiceCheckbox"></span>');
        /* Click Handler */
        var $a = $wrapper.find('.jNiceCheckbox').click(function(){
                var $a = $(this);
                var input = $a.siblings('input')[0];
                if (input.checked===true){
                    input.checked = false;
                    $a.removeClass('jNiceChecked');
                }
                else {
                    input.checked = true;
                    $a.addClass('jNiceChecked');
                }
                return false;
        });
        $input.click(function(){
            if(this.checked){ $a.addClass('jNiceChecked');     }
            else { $a.removeClass('jNiceChecked'); }
        }).focus(function(){ $a.addClass('jNiceFocus'); }).blur(function(){ $a.removeClass('jNiceFocus'); });
        
        /* set the default state */
        if (this.checked){$('.jNiceCheckbox', $wrapper).addClass('jNiceChecked');}
    };


    var RadioAdd = function(){
        var $input = $(this).addClass('jNiceHidden').wrap('<span class="jRadioWrapper jNiceWrapper"></span>');
        var $wrapper = $input.parent();
        
                var onclick='';

             for (var i = 0; i < this.attributes.length; i++) {
               if (this.attributes[i].nodeName=='onclick'){
                 onclick = ' onclick="'+this.attributes[i].nodeValue+'"';
                 //console.log(onclick )         
               }
             } 
             
        var $a = $('<span class="jNiceRadio"' + onclick + '></span>');
        $wrapper.prepend($a);
        /* Click Handler */
        $a.click(function(){
                var $input = $(this).addClass('jNiceChecked').siblings('input').attr('checked',true);
                /* uncheck all others of same name */
                $('input:radio[name="'+ $input.attr('name') +'"]').not($input).each(function(){
                    $(this).attr('checked',false).siblings('.jNiceRadio').removeClass('jNiceChecked');
                });
                return false;
        });
        $input.click(function(){
            if(this.checked){
                var $input = $(this).siblings('.jNiceRadio').addClass('jNiceChecked').end();
                /* uncheck all others of same name */
                $('input:radio[name="'+ $input.attr('name') +'"]').not($input).each(function(){
                    $(this).attr('checked',false).siblings('.jNiceRadio').removeClass('jNiceChecked');
                });
            }
        }).focus(function(){ $a.addClass('jNiceFocus'); }).blur(function(){ $a.removeClass('jNiceFocus'); });

        /* set the default state */
        if (this.checked){ $a.addClass('jNiceChecked'); }
    };
    
 function strpos (haystack, needle, offset) {
    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
} 
    
    
   /* var CheckAdd = function(){
        var $input = $(this).addClass('jNiceHidden').wrap('<span class="jNiceWrapper"></span>');
        var $wrapper = $input.parent().append('<span class="jNiceCheckbox"></span>');
        var $a = $wrapper.find('.jNiceCheckbox').click(function(){
                var $a = $(this);
                var input = $a.siblings('input')[0];
                if (input.checked===true){
                    input.checked = false;
                    $a.removeClass('jNiceChecked');
                }
                else {
                    input.checked = true;
                    $a.addClass('jNiceChecked');
                }
                return false;
        });
        $input.click(function(){
            if(this.checked){ $a.addClass('jNiceChecked');     }
            else { $a.removeClass('jNiceChecked'); }
        }).focus(function(){ $a.addClass('jNiceFocus'); }).blur(function(){ $a.removeClass('jNiceFocus'); });
        
        if (this.checked){$('.jNiceCheckbox', $wrapper).addClass('jNiceChecked');}
    };*/




