$(window).load(function() 
{	
	//$(".search_input").autocomplete('/ajax_search_hint.php', {matchContains: true, minChars: 3, maxItemsToShow: 5, delay: 250, cacheLength: 1000, matchSubset: 1, autoFill: false, selectFirst: false});

	$("a[rel=mtgroup]").fancybox({
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'titlePosition' 	: 'over',
				'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
					return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
				}
	});
	
	$('.submenu #mainsubmenu a').each(function(){
	   $(this).hover(function() {
		  var submenu_href = $(this).attr('href');
		  submenu_href = submenu_href.replace('/cat/','').replace('/','');
		  show_sub_menu(submenu_href);
		});
	});

	$('#mainsubmenu').hover(function() {
		$('#mainsubmenu').addClass('currenthover');
	}, function() { 
		$('#mainsubmenu').removeClass('currenthover');
	});

	$('.submenus').each(function(){
		$(this).hover(function() {
			$('.submenus').addClass('currenthover');
		}, function() { 
			$('.submenus').removeClass('currenthover');
		});
	});
	
	var dotCounter = 0;
	var intId = setInterval(checkNav, 500);

	$('#slider img').show();
	$('#slider').nivoSlider({
		effect:'fade',
		slices: 10,
		animSpeed:500, //Slide transition speed
		pauseTime:3000,
		startSlide:0, //Set starting Slide (0 index)
		directionNav:true, //Next & Prev
		directionNavHide:true, //Only show on hover
		controlNav:true, //1,2,3...
		controlNavThumbs:true, //Use thumbnails for Control Nav
		controlNavThumbsFromRel:false, //Use image rel for thumbs
		controlNavThumbsSearch: '.jpg', //Replace this with...
		controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
		keyboardNav:false, //Use left & right arrows
		pauseOnHover:false, //Stop animation while hovering
		manualAdvance:false, //Force manual transitions
		captionOpacity:1, //Universal caption opacity
		beforeChange: function(){},
		afterChange: function(){},
		slideshowEnd: function(){} //Triggers after all slides have been shown
	});

	$('.msklink').attr('rel','4.50:2:3');
	$('.templink').attr('rel','4.50:2:3');
	
	$('.msklink a').attr('href','#msklink');
	$('.templink a').attr('href','#templink');

	$('#selectTown').change(function(){$('#selectTownForm').submit()});
	
	$('.nal_reserv').hover(function(e){
		xOffset = 2;
		yOffset = 15;
		botMarg = 35;
		if($.browser.msie) botMarg = 17;
        var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
        var texthere = '';
        var data = [];
            data = $(this).attr("rel").split(",");
        nal = data[0];
		reserv = data[1];
		phone = data[3];
		waiting = data[4];
		
		if (waiting) {waiting=1;}
		else waiting=0;

		if (nal==1) nal=1;
		else if (nal==2) nal=2;
		else if (nal==3) nal=3;
		else if (nal==4) nal=6;
		else if (nal==5) nal=12;
		else if (nal==6) nal=24;
		else if (nal==7) nal=35;
		else if (nal==8) nal=50;
		else if (nal==9) nal=70;
		else if (nal>=10) nal=71;
		if ((nal>3)&&(nal<=70)) nal='<'+nal+' шт.';
		else if (nal>70) nal='>70 шт.';
		else if (nal>0) nal=''+nal+' шт.';

		if (reserv==1) reserv=1;
		else if (reserv==2) reserv=2;
		else if (reserv==3) reserv=3;
		else if (reserv==4) reserv=6;
		else if (reserv==5) reserv=12;
		else if (reserv==6) reserv=24;
		else if (reserv==7) reserv=35;
		else if (reserv==8) reserv=50;
		else if (reserv==9) reserv=70;
		else if (reserv>=10) reserv=71;

		if ((reserv>3)&&(reserv<=70)) reserv='<'+reserv+' шт.';
		else if (reserv>70) reserv='>70 шт.';
		else if (reserv>0) reserv=''+reserv+' шт.';

		update_datetime = $('#update_time_'+data[2]).val();
        if (phone) phone_text = '<div class="nal_reserv_phone">'+phone+'</div>';
		else phone_text = '';
		
		texthere = '<div class="nal_reserv_nal">В наличии: '+nal+'</div><div class="nal_reserv_reserv">В резерве: '+reserv+'</div>'+phone_text+'<div class="nal_reserv_update_time" align="right">'+update_datetime+'</div>';
        if (waiting==1) texthere = '<div class="nal_reserv_nal">Приедет: '+nal+'</div>'+phone_text;

        $("body").append("<div id=\"nal_reserv_div\" class=\"nal_reserv_hover\">"+texthere+"</div>");
        var top = top = ((e.pageY - xOffset) > elTop - $("#nal_reserv_div").height() ? elTop - $("#nal_reserv_div").height() : e.pageY - xOffset);
        $("#nal_reserv_div")
            .css("top",top + "px")
            .css("left",(e.pageX + yOffset) + "px")
            .fadeIn("fast");
	},
	function(){
		$("#nal_reserv_div").remove();
	});

	$('.demo_upload').hover(function(e){
		$('.demo_upload img').attr('src','/i/yt_upload_h.gif');
	},
	function(){
		$('.demo_upload img').attr('src','/i/yt_upload.gif');
	});

	$('.image_upload').hover(function(e){
		$('.image_upload img').attr('src','/i/im_upload_h.gif');
	},
	function(){
		$('.image_upload img').attr('src','/i/im_upload.gif');
	});
	
	$('.m_slide').click(function(){
		var nal = $(this).attr('rel');
		$('.'+nal).toggle();
	});

	$('.image_upload').click(function(){
		if ($("#wishlistscreen").css("display") == undefined || $("#wishlistscreen").is(":hidden")) {
			$("body").append("<div id=\"closebg\"></div>");
			$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
			$('#wishlistscreen').empty();
			$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Загрузка изображения</div>"+
				"Вы можете загрузить фотографию товара, вставив ссылку на файл с изображением товара. Фотография появится на сайте после проверки модератором.<br /><br />"+
				"<table width=\"100%\" class=\"remindTable\"><tr><td colspan=\"2\">Ссылка на изображение:"+
				"<input id=\"image_link\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
				"</td><tr><td>"+
				"<small>Пример: http://www.ibanez.ru/catalog/ibanez-rg330.jpg</small>"+
				"</td></tr></table>"+
				"<div align=\"right\"><input type=\"button\" value=\"Добавить изображение\" onclick=\"upload_info(2);\" style=\"margin-top: 10px;\" /></div>"+
				"</div>");
			$("#wishlistscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"$('#wishlistscreen').remove();$('#closebg').remove();return false;\"></a></div>");

			$("#closebg").css("position","absolute").
				css("display","none").
				css("opacity",0.7).            
				css("z-index","10").
				css("width","100%").
				css("height",$("body").height()).
				css("top","0").
				css("left","0").
				css("background-color","#000").            
				show();   
				
			$("#wishlistscreen").
				css("position","fixed").
				css("top","50%").
				css("width","450px").
				css("margin-top","-125px").
				css("height","250px").
				css("left","50%").
				css("margin-left","-225px").
				css("z-index","15").
				show();
		} else {
			$("#wishlistscreen").remove();
		}    
		$(document).keydown(function(e){if(e.which == 27) { $("#wishlistscreen").remove(); $("#closebg").remove(); }});    
		return false;
	});

	$('.image_upload_small').click(function(){
		if ($("#wishlistscreen").css("display") == undefined || $("#wishlistscreen").is(":hidden")) {
			$("body").append("<div id=\"closebg\"></div>");
			$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
			$('#wishlistscreen').empty();
			$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Загрузка изображения</div>"+
				"Вы можете загрузить фотографию товара, вставив ссылку на файл с изображением товара. Фотография появится на сайте после проверки модератором.<br /><br />"+
				"<table width=\"100%\" class=\"remindTable\"><tr><td colspan=\"2\">Ссылка на изображение:"+
				"<input id=\"image_link\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
				"</td><tr><td>"+
				"<small>Пример: http://www.ibanez.ru/catalog/ibanez-rg330.jpg</small>"+
				"</td></tr></table>"+
				"<div align=\"right\"><input type=\"button\" value=\"Добавить изображение\" onclick=\"upload_info(4);\" style=\"margin-top: 10px;\" /></div>"+
				"</div>");
			$("#wishlistscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"$('#wishlistscreen').remove();$('#closebg').remove();return false;\"></a></div>");

			$("#closebg").css("position","absolute").
				css("display","none").
				css("opacity",0.7).            
				css("z-index","10").
				css("width","100%").
				css("height",$("body").height()).
				css("top","0").
				css("left","0").
				css("background-color","#000").            
				show();   
				
			$("#wishlistscreen").
				css("position","fixed").
				css("top","50%").
				css("width","450px").
				css("margin-top","-125px").
				css("height","250px").
				css("left","50%").
				css("margin-left","-225px").
				css("z-index","15").
				show();
		} else {
			$("#wishlistscreen").remove();
		}    
		$(document).keydown(function(e){if(e.which == 27) { $("#wishlistscreen").remove(); $("#closebg").remove(); }});    
		return false;
	});

	$('.demo_upload').click(function(){
		if ($("#wishlistscreen").css("display") == undefined || $("#wishlistscreen").is(":hidden")) {
			$("body").append("<div id=\"closebg\"></div>");
			$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
			$('#wishlistscreen').empty();
			$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Загрузка демо-записи</div>"+
				"Вы можете загрузить свою демо-запись, вставив ссылку на ваше видео на youtube. Видео появится на сайте после проверки модератором.<br /><br />"+
				"<table width=\"100%\" class=\"remindTable\"><tr><td colspan=\"2\">Ссылка на видео-ролик:"+
				"<input id=\"demo_link\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
				"</td><tr><td>"+
				"<small>Пример: http://www.youtube.com/watch?v=WlxlqgO5w_c</small>"+
				"</td></tr></table>"+
				"<div align=\"right\"><input type=\"button\" value=\"Добавить видео\" onclick=\"upload_info(1);\" style=\"margin-top: 10px;\" /></div>"+
				"</div>");
			$("#wishlistscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"$('#wishlistscreen').remove();$('#closebg').remove();return false;\"></a></div>");

			$("#closebg").css("position","absolute").
				css("display","none").
				css("opacity",0.7).            
				css("z-index","10").
				css("width","100%").
				css("height",$("body").height()).
				css("top","0").
				css("left","0").
				css("background-color","#000").            
				show();   
				
			$("#wishlistscreen").
				css("position","fixed").
				css("top","50%").
				css("width","450px").
				css("margin-top","-125px").
				css("height","250px").
				css("left","50%").
				css("margin-left","-225px").
				css("z-index","15").
				show();
		} else {
			$("#wishlistscreen").remove();
		}    
		$(document).keydown(function(e){if(e.which == 27) { $("#wishlistscreen").remove(); $("#closebg").remove(); }});    
		return false;
	});

	$('#region').change(function(){
		var region_ = $(this).val();
		changeRegion(region_);
	});
	
	$('.action_show').click(function(){
		
		var rel = $(this).attr('rel');
		if ($(this).attr('stat')==1)
		{
			$(this).removeClass('current_act');
			$(this).attr('stat',0);
			$('#act_info_'+rel).slideUp('slow', function() {});
		}
		else
		{
			$(this).addClass('current_act');
			$(this).attr('stat',1);

			$('#act_info_'+rel).html('Загружается...');
			$.get('/ajax_action_list.php', {tov_id: rel}, function(data) {
				data = data.replace('#e00','#bb0');
				$('#act_info_'+rel).html(data);
				$('#act_info_'+rel).slideDown('slow', function() {});
			});
		}
	});

	$('#desc_upload').click(function(){
		if($("#partnerorderscreen").css("display") == undefined || $("#partnerorderscreen").is(":hidden")) {
			$("body").append("<div id=\"closebg\"></div>");
			$("body").append("<div id=\"partnerorderscreen\" style=\"display: block;\"></div>");
			$('#partnerorderscreen').empty();
			$("#partnerorderscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Загрузка описания</div>"+
				"Вы можете загрузить своё описание, вставив текст описания в форму ниже. Новое описание появится на сайте после проверки модератором.<br /><br />"+
				"<table width=\"100%\" class=\"remindTable\"><tr><td><textarea id=\"desc_link\" style=\"width: 100%; font-size: 12px; height: 340px;\"></textarea></td></tr>"+
				"</table>"+
				"<div align=\"right\"><input type=\"button\" value=\"Добавить описание\" onclick=\"upload_info(3);\" /></div>"+
				"</div>");
			$("#partnerorderscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"$('#partnerorderscreen').remove();$('#closebg').remove();return false;\"></a></div>");

			$("#closebg").css("position","absolute").
				css("display","none").
				css("opacity",0.7).            
				css("z-index","10").
				css("width","100%").
				css("height",$("body").height()).
				css("top","0").
				css("left","0").
				css("background-color","#000").            
				show();   
				
			$("#partnerorderscreen").
				css("position","fixed").
				css("top","50%").
				css("width","450px").
				css("margin-top","-250px").
				css("height","500px").
				css("left","50%").
				css("margin-left","-225px").
				css("z-index","15").
				show();
		} else {
			$("#partnerorderscreen").remove();
		}    
		$(document).keydown(function(e){if(e.which == 27) { $("#partnerorderscreen").remove(); $("#closebg").remove(); }});    
		return false;
	});

	//Адреса магазинов
	$(".msklink").click(function(e){	
		if ($('#tt_region1').length>0)
		{
			$('#tt_region1').remove();
		}
		else
		{
			xOffset = 2;
			yOffset = 8;
			botMarg = 35;
			if($.browser.msie) botMarg = 17;
			var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
			var texthere = '';
			
			texthere = "<span style=\"font-size: 11px; z-index: 9999;\"><a href=\"/shops/taganka/\">Музторг (м.Таганская)</a><br/><a href=\"/shops/savel/\">Музторг (м.Савеловская)</a><br/><a href=\"http://www.muztorg-yamaha.ru/\" target=\"_blank\">Музторг-Yamaha (м.Савеловская)</a><br/><a href=\"/shops/maestro/\">Музторг-Маэстро (м.Кузнецкий мост)</a><br/><a href=\"/shops/discount/\">Музторг-Дисконт (м.Новогиреево)</a></span>";
			
			$("body").append("<p id=\"tt_region1\">"+texthere+"</p>");
			var top = ((e.pageY - xOffset) > elTop - $("#tt_region1").height() ? elTop - $("#tt_region1").height() : e.pageY - xOffset);
			$("#tt_region1")
				.css("top",top -10 + "px")
				.css("left",(e.pageX + yOffset) + "px")
				.fadeIn("fast");
		}
    });
	
	//Регионы

	$(".templink").click(function(e){
		if ($('#tt_region').length>0)
		{
			$('#tt_region').remove();
		}
		else
		{	
			xOffset = 2;
			yOffset = 8;
			botMarg = 35;
			if($.browser.msie) botMarg = 17;
			var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
			var texthere = '';
			
			texthere = "<span style=\"font-size: 11px; z-index: 9999;\"><a href=\"/shops/barnaul/\">Барнаул</a><br/><a href=\"/shops/vladimir/\">Владимир</a><br/><a href=\"/shops/volgograd/\">Волгоград</a><br/><a href=\"/shops/voronezh/\">Воронеж</a><br/><a href=\"http://www.muztorg.ua/shops/donetsk\">Донецк</a><br/><a href=\"/shops/ekat/\">Екатеринбург</a><br/><a href=\"/shops/izh/\">Ижевск</a><br/><a href=\"/shops/irk/\">Иркутск</a><br/><a href=\"/shops/kazan/\">Казань</a><br/><a href=\"/shops/kaluga/\">Калуга</a><br/><a href=\"/shops/kemerovo/\">Кемерово</a><br/><a href=\"http://www.muztorg.ua/shops/kiev\">Киев</a><br/><a href=\"/shops/krasnodar/\">Краснодар</a><br/><a href=\"/shops/krasn/\">Красноярск</a><br/><a href=\"/shops/novgorod/\">Нижний Новгород</a><br/><a href=\"/shops/tagil/\">Нижний Тагил</a><br/><a href=\"/shops/novosib/\">Новосибирск</a><br/><a href=\"/shops/omsk/\">Омск</a><br/><a href=\"/shops/orel/\">Орел</a><br/><a href=\"/shops/perm/\">Пермь</a><br/><a href=\"/shops/rnd/\">Ростов-на-Дону</a><br/><a href=\"/shops/samara/\">Самара</a><br/><a href=\"/shops/spb/\">Санкт-Петербург</a><br/><a href=\"/shops/saratov/\">Саратов</a><br/><a href=\"/shops/smol/\">Смоленск</a><br/><a href=\"/shops/tol/\">Тольятти</a><br/><a href=\"/shops/tumen/\">Тюмень</a><br/><a href=\"/shops/ufa/\">Уфа</a><br/><a href=\"/shops/chelyabinsk/\">Челябинск</a><br/><a href=\"/shops/yaroslavl/\">Ярославль</a><br/></span>";
			
			$("body").append("<p id=\"tt_region\">"+texthere+"</p>");
			var top = ((e.pageY - xOffset) > elTop - $("#tt_region").height() ? elTop - $("#tt_region").height() : e.pageY - xOffset);
			$("#tt_region")
				.css("top",top -4 + "px")
				.css("left",(e.pageX + yOffset) + "px")
				.fadeIn("fast");
		}
    });
	
	//Акции
	
	$(".tovaction").hover(function(e){
		xOffset = 2;
		yOffset = 5;
		botMarg = 35;
		if($.browser.msie) botMarg = 17;
		
        var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
        var texthere = '';
		if (($("#tt_actions").length)>0)
		{
			$("#tt_actions").fadeOut(150, function () {
				$("#tt_actions").remove();
			});
			$("#tt_actions").html("Загрузка...");
		}
        var tov_id = $(this).attr("id").replace('tovaction_','');
		tov_id = tov_id.substr(0,(tov_id.length-4));
		///////////////preved//////////////////
		jQuery.ajax({
			data: "tov_id="+tov_id,
			type: "GET",
			url: "/ajax_action_list.php",
			timeout: 10000,
			encoding: "cp1251",
			error: function(){$("#tt_actions").html("Не удалось загрузить информацию");},
			success: function(r){
				texthere = r;
				if (texthere)
				{		
					$("body").append("<p id=\"tt_actions\">"+texthere+"</p>");
					var top = top = ((e.pageY - xOffset) > elTop - $("#tt_actions").height() ? elTop - $("#tt_actions").height() : e.pageY - xOffset);
					$("#tt_actions")
						.show()
						.css("opacity",0)
						.css("top",top + "px")
						.css("left",(e.pageX + yOffset) + "px")
						.animate({
						  left: "+=5",
						  opacity: 1
						  }, 150 )

					}
				}
		});
    },
    function(){
		$("#tt_actions").fadeOut(150, function () {
			$("#tt_actions").remove();
		});
    });
	
	//Голоса
	$(".tovstars").hover(function(e){
		xOffset = 2;
		yOffset = 5;
		botMarg = 35;
		if($.browser.msie) botMarg = 17;
        var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
        var texthere = '';
        var data = [];
            data = $(this).attr("rel").split(":");
        var commentsnum = '';
        if(data[2] > 0) {commentsnum = "<img src=\"/i/comments.gif\" align=\"absmiddle\"> <span style=\"font-size: 10px;\">Отзывов:</span> "+data[2]}
        else { commentsnum = ''; }
        texthere = "<img src=\"/i/bigstar2.gif\" align=\"absmiddle\"> <span style=\"font-size: 10px;\">Оценка:</span> <strong>"+data[0]+"</strong><br/><img src=\"/i/people.gif\" align=\"absmiddle\"> <span style=\"font-size: 10px;\">Голосов:</span> "+data[1]+"<br/>"+commentsnum;
        
        $("body").append("<p id=\"tt_votes\">"+texthere+"</p>");
        var top = top = ((e.pageY - xOffset) > elTop - $("#tt_votes").height() ? elTop - $("#tt_votes").height() : e.pageY - xOffset);
        $("#tt_votes")
            .css("top",top + "px")
            .css("left",(e.pageX + yOffset) + "px")
            .fadeIn("fast");
    },
    function(){
        $("#tt_votes").remove();
    });

	//Картинки
	
	if ($(".r1 img").length>0)
	{
		$(".r1 img[src!='/i/nofoto.gif']").hover(function(e){
			xOffset = 10;
			yOffset = 30;
			botMarg = 35;
			if($.browser.msie) botMarg = 17; // for MSIE browsers, bottom margin = 17pixels.
			this.t = this.title;
			this.title = "";    
			var medium = this.src.slice(this.src.lastIndexOf('/') + 1);
			var c = (this.t != "") ? "<br/>" + this.t : "";
			var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
			$("body").append("<p id=\"preview\"></p>");  
			
			
			var img = new Image();
			
			
			$(img).load(function(){
				$(this).css("display","none");
				$("#preview img").remove();                              
				$("#preview").css("background","white").append(this);
				$("#preview img").fadeIn();
			}).attr('src','/news/preview/' + medium).css('display','none');
			

			var top = ((e.pageY - xOffset) > elTop - $("#preview").height() ? elTop - $("#preview").height() : e.pageY - xOffset);
			$("#preview")
				.css("top",top + "px" )
				.css("left",(e.pageX + yOffset) + "px")
				.css("background","white url('/i/ajax-loader.gif') no-repeat center center")
				.css("min-width","50px")
				.css("min-height","50px")
				.css("z-index","99999")
				.fadeIn("fast");        
		},
		function(){
			this.title = this.t;    
			$("#preview").remove();
		});  
		
		$(".r1 img").hover(function(e){
			var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
			var top = ((e.pageY - xOffset) > elTop - $("#preview").height() ? elTop - $("#preview").height() : e.pageY - xOffset);
			$("#preview")
				.css("top",top + "px")
				.css("left",(e.pageX + yOffset) + "px");
		});
	}
	//Комменты
	
	//Демо
	$(".demo_link").css("cursor","pointer");
	$(".demo_link").click(function()
	{
		show_demo($(this).attr("rel"));
	});

	//Кнопки
	$("#addBasketBtn").click(function(){
        addToCart($(this).attr("rel"));
    });
	$("#addRsvBtn").click(function(){
        addToCart($(this).attr("rel"));
    });
	$(".toOrder").click(function(){
        addToPartnerOrder($(this).attr("rel"),$(this).attr("title"));
    });
	$("#addOrderBtn").click(function(){
        addToCart($(this).attr("rel"));
    });
	$("#addRemindBtn").click(function(){
        addToRemindList($(this).attr("rel"));
    });
	$("#addRemindMeBtn").click(function(){
        addToRemindList($(this).attr("rel"));
    });
	$("#addWishListBtn").click(function(){
        addToWishList($(this).attr("rel"));
    });
	$("#removeWishListBtn").click(function(){
        RemoveFromWishList($(this).attr("rel"));
    });

	$(".toCart").click(function(){
        addToCart($(this).attr("rel"));
    });

	$("body").append('<div id="alertboxList"></div>');
    $.opt = {};
    $.opt = {
        cHeight: $.opt.cHeight = ($.browser.mozilla || $.browser.safari ? $(window).height() : document.documentElement.clientHeight),
        sTop: $(document).scrollTop(),
        wLoc: window.location.href.replace(window.location.hash,""),
        wHash: window.location.hash
    };


    // Button switching between Descriptions and Comments
    var dop = $(".inner .main .dop"),
        op = $(".inner .main .d"),
        comm = $(".inner .main .comments"),
		not = $(".inner .main .not_desc"),
		wish = $(".inner .main .wish_list"),
		addit = $("#addit_list"),
		alter = $("#alter_list"),
		sharel = $("#share_list"),
		actions = $("#actions_list"),
		spec_tov = $("#spec_tov_list"),
		new_tov = $("#new_tov_list"),
		hit_tov = $("#hit_tov_list"),
		char_tov = $(".char_desc"),
		view_tov = $("#view_tov_list");
    
	function removeSwitchButtons()
	{
		dop.hide(); op.hide(); comm.hide(); wish.hide(); addit.hide(); alter.hide(); sharel.hide(); actions.hide(); char_tov.hide(); not.hide();
        $("#desc").removeClass("sel");$("#not").removeClass("sel"); $("#comm").removeClass("sel"); $("#wish").removeClass("sel"); $("#addit").removeClass("sel"); $("#alter").removeClass("sel"); $("#share").removeClass("sel"); $("#actions").removeClass("sel"); $("#char").removeClass("sel");
	}
    
    $("#desc").click(function(){
            removeSwitchButtons();
			dop.show(); op.show();
			$("#desc").addClass("sel");
            window.location.href = $.opt.wLoc + "#description";
    });
	 $("#char").click(function(){
            removeSwitchButtons();
			char_tov.show();
			$("#char").addClass("sel");
            window.location.href = $.opt.wLoc + "#characteristic";
    });
    $("#comm").click(function(){
            removeSwitchButtons();
			comm.show();
			$("#comm").addClass("sel");
            window.location.href = $.opt.wLoc + "#comments";
    });
	$("#not").click(function(){
            removeSwitchButtons();
			not.show();
			$("#not").addClass("sel");
            window.location.href = $.opt.wLoc + "#notice";
    });
	$("#wish").click(function(){
            removeSwitchButtons();
			wish.show();
			$("#wish").addClass("sel");
            window.location.href = $.opt.wLoc + "#wish_list";
    });

	$("#addit").click(function(){
            removeSwitchButtons();
			addit.show();
			$("#addit").addClass("sel");
            window.location.href = $.opt.wLoc + "#additlist";
    });

	$("#alter").click(function(){
            removeSwitchButtons();
			alter.show();
			$("#alter").addClass("sel");
            window.location.href = $.opt.wLoc + "#alterlist";
    });

	$("#share").click(function(){
            removeSwitchButtons();
			sharel.show();
			$("#share").addClass("sel");
            window.location.href = $.opt.wLoc + "#sharelist";
    });

	$("#actions").click(function(){
            removeSwitchButtons();
			actions.show();
			$("#actions").addClass("sel");
            window.location.href = $.opt.wLoc + "#actionslist";
    });

	$("#hit_tov").click(function(){
			$("#view_tov").removeClass("sel");
			$("#spec_tov").removeClass("sel");
            $("#new_tov").removeClass("sel");
			new_tov.hide();
			spec_tov.hide();
			view_tov.hide();
			hit_tov.show();
			$("#hit_tov").addClass("sel");
            window.location.href = $.opt.wLoc + "#hittov";
    });
	
	$("#view_tov").click(function(){
			$("#hit_tov").removeClass("sel");
			$("#spec_tov").removeClass("sel");
            $("#new_tov").removeClass("sel");
			new_tov.hide();
			spec_tov.hide();
			hit_tov.hide();
			view_tov.show();
			$("#view_tov").addClass("sel");
            window.location.href = $.opt.wLoc + "#viewtov";
    });

	$("#spec_tov").click(function(){
			$("#hit_tov").removeClass("sel");
            $("#new_tov").removeClass("sel");
			$("#view_tov").removeClass("sel");
			new_tov.hide();
			hit_tov.hide();
			view_tov.hide();
			spec_tov.show();
			$("#spec_tov").addClass("sel");
            window.location.href = $.opt.wLoc + "#spectov";
    });

	$("#new_tov").click(function(){
			$("#spec_tov").removeClass("sel");
            $("#hit_tov").removeClass("sel");
			$("#view_tov").removeClass("sel");
			hit_tov.hide();
			spec_tov.hide();
			view_tov.hide();
			new_tov.show();
			$("#new_tov").addClass("sel");
            window.location.href = $.opt.wLoc + "#newtov";
    });
    // ^^ end of BSBDC
    
    // switching by URI
    switch($.opt.wHash) {
        case '#comments':
            removeSwitchButtons();
			comm.show();
            $("#comm").addClass("sel");
            break;
		case '#notice':
            removeSwitchButtons();
			not.show();
            $("#not").addClass("sel");
            break;
        case '#description':
			removeSwitchButtons();
            dop.show(); op.show();
            $("#desc").addClass("sel");           
            break;
		case '#characteristic':
			removeSwitchButtons();
            char_tov.show();
            $("#char").addClass("sel");           
            break;
		case '#wish_list':
			removeSwitchButtons();
			wish.show();
            $("#wish").addClass("sel");          
			break;
		case '#additlist':
			removeSwitchButtons();
			addit.show();
			$("#addit").addClass("sel");
			break;
		case '#alterlist':
			removeSwitchButtons();
			alter.show();
			$("#alter").addClass("sel");       
			break;
		case '#sharelist':
			removeSwitchButtons();
			sharel.show();
			$("#share").addClass("sel");       
			break;
		case '#actionslist':
			removeSwitchButtons();
			actions.show();
			$("#actions").addClass("sel");       
			break;
        default:
            //window.location.href = $.opt.wLoc;
    }               
    // ^^ end of SBU
    
    $("#vStar1").hover(function(){onhoverStars(1);},function(){onoutStars(1);}).click(function(){vfStar(1);});
    $("#vStar2").hover(function(){onhoverStars(2);},function(){onoutStars(2);}).click(function(){vfStar(2);});
    $("#vStar3").hover(function(){onhoverStars(3);},function(){onoutStars(3);}).click(function(){vfStar(3);});
    $("#vStar4").hover(function(){onhoverStars(4);},function(){onoutStars(4);}).click(function(){vfStar(4);});
    $("#vStar5").hover(function(){onhoverStars(5);},function(){onoutStars(5);}).click(function(){vfStar(5);});
    $(".delete_button").hover(function(){
        $(this).css("background-position","-360px -174px");
        $(this).css("cursor","Pointer");
        return false;
    },function(){
        $(this).css("background-position","-344px -174px");
        return false;
    }).mousedown(function(){
        $(this).css("background-position","-376px -174px");
        cartDelete($(this),$(this).attr("rel"));
    }).mouseup(function(){
        $(this).css("background-position","-344px -174px");
        return false;
    });
    $("#addBasketBtn").hover(function()
		{$(this).css("background-position","-347px -20px")},function(){$(this).css("background-position","-347px 0px")}).mousedown(function(e){
        document.getElementById("price").onselectstart = function() { return false; }
        document.getElementById("price").onmousedown = function() { return false; }
        $(this).css("background-position","-347px -40px");
        animatePlus(e);
    }).mouseup(function(){
        document.getElementById("price").onselectstart = "";
        document.getElementById("price").onmousedown = "";
        $(this).css("background-position","-347px -20px");
    });

	$("#addRsvBtn").hover(function()
		{$(this).css("background-position","-167px -20px")},function(){$(this).css("background-position","-167px 0")}).mousedown(function(e){
        document.getElementById("price").onselectstart = function() { return false; }
        document.getElementById("price").onmousedown = function() { return false; }
        $(this).css("background-position","-167px -40px");
        animatePlus(e);
    }).mouseup(function(){
        document.getElementById("price").onselectstart = "";
        document.getElementById("price").onmousedown = "";
        $(this).css("background-position","-167px -20px");
    });

	$("#addRemindBtn").hover(function()
		{$(this).css("background-position","-347px -134px")},function(){$(this).css("background-position","-347px -114px")}).mousedown(function(e){
        document.getElementById("price").onselectstart = function() { return false; }
        document.getElementById("price").onmousedown = function() { return false; }
        $(this).css("background-position","-347px -154px");
        animatePlus(e);
    }).mouseup(function(){
        document.getElementById("price").onselectstart = "";
        document.getElementById("price").onmousedown = "";
        $(this).css("background-position","-347px -134px");
    });

	$("#addOrderBtn").hover(function()
		{$(this).css("background-position","-257px -20px")},function(){$(this).css("background-position","-257px 0")}).mousedown(function(e){
        document.getElementById("price").onselectstart = function() { return false; }
        document.getElementById("price").onmousedown = function() { return false; }
        $(this).css("background-position","-257px -40px");
        animatePlus(e);
    }).mouseup(function(){
        document.getElementById("price").onselectstart = "";
        document.getElementById("price").onmousedown = "";
        $(this).css("background-position","-257px -20px");
    });

	$("#addWishListBtn").hover(function()
		{$(this).css("background-position","-257px -134px")},function(){$(this).css("background-position","-257px -114px")}).mousedown(function(e){
        document.getElementById("price").onselectstart = function() { return false; }
        document.getElementById("price").onmousedown = function() { return false; }
        $(this).css("background-position","-257px -154px");
        animatePlus(e);
    }).mouseup(function(){
        document.getElementById("price").onselectstart = "";
        document.getElementById("price").onmousedown = "";
        $(this).css("background-position","-257px -134px");
    });
	
	$("#removeWishListBtn").hover(function()
		{$(this).css("background-position","-304px -226px")},function(){$(this).css("background-position","-304px -206px")}).mousedown(function(e){
        document.getElementById("price").onselectstart = function() { return false; }
        document.getElementById("price").onmousedown = function() { return false; }
        $(this).css("background-position","-304px -246px");
        animatePlus(e);
    }).mouseup(function(){
        document.getElementById("price").onselectstart = "";
        document.getElementById("price").onmousedown = "";
        $(this).css("background-position","-304px -226px");
    });

	$(".voting .auth .vote_minus").hover(function(){$(this).css("background-position","left 39")},function(){$(this).css("background-position","left 52")})
	$(".voting .auth .vote_plus").hover(function(){$(this).css("background-position","right 39")},function(){$(this).css("background-position","right 52")})
	
	$(".voting .auth .vote_plus").click(function(){
		comment_n = $(this).attr("rel");
		$("#vote_"+comment_n).removeClass("voting");
		$("#vote_"+comment_n).addClass("voted");
		$("#vote_"+comment_n+" .vote_buttons").empty();
		$("#vote_"+comment_n+" .vote_buttons").append('<span rel="'+comment_n+'" class="vote_minus vote-for-comment" title="Плохой комментарий"></span><span rel="'+comment_n+'" class="voted_plus vote-for-comment" title="Хороший комментарий"></span>');
		changeVoteMark(comment_n,1);
    });

	$(".voting .auth .vote_minus").click(function(){
		comment_n = $(this).attr("rel");
		$("#vote_"+comment_n).removeClass("voting");
		$("#vote_"+comment_n).addClass("voted");
		$("#vote_"+comment_n+" .vote_buttons").empty();
		$("#vote_"+comment_n+" .vote_buttons").append('<span rel="'+comment_n+'" class="voted_minus vote-for-comment" title="Плохой комментарий"></span><span rel="'+comment_n+'" class="vote_plus vote-for-comment" title="Хороший комментарий"></span>');
		changeVoteMark(comment_n,-1);
    });

    $(".carttovar .count input").keyup(function(){
        cartUpdateTov($(this).attr("name"),$(this).attr("value"));
        $(".cart_bottom .nal").html(number_format(checkCartSum(),0,","," ") + " руб.");
    });
    $("#cashout").click(function(){
        $(".reginfo").toggle();
        //$(this).attr("disabled","disabled");
    });
    
    var mHeight = 0;
    $("#advices .column").each(function(){
        //alert($(this).height());
        if($(this).height() > mHeight) { mHeight = $(this).height(); }
    });
    $("#advices .column").each(function(){
        $(this).height(mHeight + "px");
    });
    
    
    // ########   FORMS
    // ######## 
    $("#ihave").click(function(){
        if($(this).attr("checked")) {
            $(".discountcard").show();
			$(".cardholder").show();
			$(".cardnumber").show();
        } else {
            $(".discountcard").hide();
            $("input[name=discountcard_fio]").attr("value","");
            $("input[name=discountcard_number]").attr("value","");
			$(".cardholder").hide();
			$(".cardnumber").hide();
        }
    });

	$('.comment_reply').click(function(){
		var rel = this.rel;
		$('.comment_reply_block').html('');
		$('.comment_reply_block').hide();
		$('#reply_'+rel).show();
		new_text = '<ul class="comment_ul"><li class="comment_li"><div id="reply_to_'+rel+'" class="addcomment"><form id="sendComment" method="post"><div class="forms_name">Ваш отзыв:</div><div class="forms_inputs"><div><textarea id="comment_text" name="text"></textarea></div><div align="right" style="margin-top: 5px;"><a href="#reply_to_0"  class="comment_cancel" onclick="cancelReply();">отменить</a><input type="hidden" id="comment_parent_id" name="comment_parent_id" value="'+rel+'" /><input type="submit" id="submit" value="Отправить" disabled="disabled"></div></div></form></li></ul>';
		$('#reply_'+rel).html(new_text);
		$('#comment_text').focus();
		bindBehaviors();
	});

	$("#ireg").click(function(){
        if($(this).attr("checked")) {
            $(".passwd_block").show();
        } else {
            $(".passwd_block").hide();
            $("input[name=passwd]").attr("value","");
        }
    });
	
    $("input[name=person]").click(function(){
        if($("#person").attr("checked")) {
            $("#props_div").show();
        } else {
            $("#props_div").hide();
        }
    });

	jQuery(function($){
	   $("#delivery_date").mask('99.99 99:99–99:99');
	});
	
    $("#town").change(function(){
		
		$('#delivery_date_tr').hide();

       if (($(this).attr("value") == "Москва")||($('#region').attr("value") == "Москва и Московская обл.")) {
			$('input[name="delivery_type"]').attr('checked', false);
			$('input[name="payment_type"]').attr('checked', false);
			$('#delivery_type_2').attr('checked', true);
			$('#payment_type_2').attr('checked', true);
			$('#delivery_type_3').attr('disabled', true);
			$('#delivery_type_2').attr('disabled', false);
			$('#delivery_type_1').attr('disabled', false);
			$('#delivery_type_4').attr('disabled', true);
			$('#delivery_type_5').attr('disabled', true);
			$('#delivery_type_6').attr('disabled', true);
			$('#payment_type_1').attr('disabled', false);
			$('#payment_type_2').attr('disabled', true);
			$('#payment_type_3').attr('disabled', false);
			$('#delivery_date_tr').show();
			$('#delivery_date_keyword').html('доставки');
			$('#delivery_date').val($('#bsk_delivery').val());
	   } else if (($(this).attr("value") == "Санкт-Петербург")||($('#region').attr("value") == "Санкт-Петербург и область")) {
			$('input[name="delivery_type"]').attr('checked', false);
			$('input[name="payment_type"]').attr('checked', false);
			$('#delivery_type_2').attr('checked', true);
			$('#payment_type_2').attr('checked', false);
			$('#delivery_type_3').attr('disabled', true);
			$('#delivery_type_2').attr('disabled', false);
			$('#delivery_type_1').attr('disabled', true);
			$('#delivery_type_4').attr('disabled', false);
			$('#delivery_type_5').attr('disabled', false);
			$('#delivery_type_6').attr('disabled', true);
			$('#payment_type_1').attr('disabled', false);
			$('#payment_type_2').attr('disabled', true);
			$('#payment_type_3').attr('disabled', false);
		} else if (($(this).attr("value") == "Екатеринбург")||($('#region').attr("value") == "Свердловская обл.")) {
			$('input[name="delivery_type"]').attr('checked', false);
			$('input[name="payment_type"]').attr('checked', false);
			$('#delivery_type_2').attr('checked', true);
			$('#payment_type_2').attr('checked', false);
			$('#delivery_type_3').attr('disabled', true);
			$('#delivery_type_2').attr('disabled', false);
			$('#delivery_type_1').attr('disabled', true);
			$('#delivery_type_4').attr('disabled', true);
			$('#delivery_type_5').attr('disabled', true);
			$('#delivery_type_6').attr('disabled', false);
			$('#payment_type_1').attr('disabled', false);
			$('#payment_type_2').attr('disabled', true);
			$('#payment_type_3').attr('disabled', false);
        } else {
			$('input[name="delivery_type"]').attr('checked', false)
			$('input[name="payment_type"]').attr('checked', false);
			$('#payment_type_3').attr('checked', true);
			$('#delivery_type_3').attr('checked', true);
			$('#delivery_type_3').attr('disabled', false);
			$('#delivery_type_2').attr('disabled', true);
			$('#delivery_type_1').attr('disabled', true);
			$('#payment_type_1').attr('disabled', true);
			$('#payment_type_2').attr('disabled', false);
			$('#payment_type_3').attr('disabled', false);
			$('#delivery_type_4').attr('disabled', true);
			$('#delivery_type_5').attr('disabled', true);
			$('#delivery_type_6').attr('disabled', true);
        }
		check_form_error();
    });
  
  $('input[name=payment_type]').click(function(){
    payment_type = this.value;
    if (payment_type=='Пластиковой картой')
    {
      $('#card_info').show();
    }
    else
    {
      $('#card_info').hide();
    }
  });
  
	$("input[name=delivery_type]").click(function(){
		delivery_value = this.value;
		$('#delivery_date_tr').hide();
		if (delivery_value=="Самовывоз")
		{
			$("#address").val("Самовывоз из магазина м. Таганская");
			$("#region option[value='Москва и Московская обл.']").attr("selected","selected");
			changeRegion("4312","1");
			$(".dop_address").hide();
			$('#delivery_date_tr').show();
			$('#delivery_date_keyword').html('самовывоза');
			$('#delivery_date').val($('#bsk_self_delivery').val());
		}
		else if (delivery_value=="Самовывоз СПБ1")
		{
			$("#address").val("Самовывоз из магазина м. Сенная площадь");
			$("#region option[value='Санкт-Петербург и область']").attr("selected","selected");
			changeRegion("4925","1");
			$(".dop_address").hide();
		}
		else if (delivery_value=="Самовывоз СПБ2")
		{
			$("#address").val("Самовывоз из магазина м. Выборгская");
			$("#region option[value='Санкт-Петербург и область']").attr("selected","selected");
			changeRegion("4925","1");
			$(".dop_address").hide();
		}
		else if (delivery_value=="Самовывоз ЕКБ1")
		{
			$("#address").val("Самовывоз из магазина м. Выборгская");
			$("#region option[value='Свердловская обл.']").attr("selected","selected");
			changeRegion("5080","1");
			$(".dop_address").hide();
		}
		else
		{
			$("#address").val("");
			$(".dop_address").show();
		}

		if ($('#region').attr("value") == "Москва и Московская обл.") {
			$('input[name="payment_type"]').attr('checked', false);
			$('#payment_type_2').attr('checked', true);
			$('#payment_type_1').attr('disabled', false);
			$('#payment_type_2').attr('disabled', true);
			$('#payment_type_3').attr('disabled', false);
			if (delivery_value!="Самовывоз")
			{			
				$('#delivery_date_tr').show();
				$('#delivery_date_keyword').html('доставки');
				$('#delivery_date').val($('#bsk_delivery').val());
			}
	   } else if ($('#region').attr("value") == "Санкт-Петербург и область") {
			$('input[name="payment_type"]').attr('checked', false);
			$('#payment_type_2').attr('checked', false);
			$('#payment_type_1').attr('disabled', false);
			$('#payment_type_2').attr('disabled', true);
			$('#payment_type_3').attr('disabled', false);
		} else if ($('#region').attr("value") == "Свердловская обл.") {
			$('input[name="payment_type"]').attr('checked', false);
			$('#payment_type_2').attr('checked', false);
			$('#payment_type_1').attr('disabled', false);
			$('#payment_type_2').attr('disabled', true);
			$('#payment_type_3').attr('disabled', false);
        } else {
			$('input[name="payment_type"]').attr('checked', false);
			$('#payment_type_3').attr('checked', true);
			$('#payment_type_1').attr('disabled', true);
			$('#payment_type_2').attr('disabled', false);
			$('#payment_type_3').attr('disabled', false);
        }
		check_form_error();
    });
	
	if($("#town").attr("value") == "Москва") {

    } else {

    }
	
	
    if($("#ihave").attr("checked")) {
        $(".discountcard").show();
    }
    if($("#person").attr("checked")) {
        $("#props_div").show();
    }
    
    $("#lastorder .image").click(function(){
        $(window).attr("location",$(this).find("span a").attr("href"));
    });

    $("#forgot").click(function(){
        var emailObj = $('form#authform input[name="email"]'), email = emailObj.attr("value");
        var par = emailObj.parent().parent();
        if(email.length == 0) {
            alert('Не забудьте ввести свой e-mail адрес.');            
            par.css("color","red");
            emailObj.focus();
            return false;
        }
        if(email.length < 6) {
            alert('Неправильно введен e-mail адрес.\nПожалуйста введите свой e-mail адрес, который был указан при регистрации.');
            par.css("color","red");
            emailObj.focus();
            return false;
        }
        jQuery.ajax({
            type: "GET",
            url: "/ajax_profile.php?forget=true&email=" + email,
            timeout: 10000,
            encoding: "cp1251",
            error: function(){ alert('We got an error during try to submit your request'); },
            success: function(r){
                alert(r);
                if(r.substr(0,2) == 'На') {
                    par.css("color","green");
                } else {
                    par.css("color","red");
                }
            }
        });   
    });
    
    $("#alogin").click(showLoginScreen);
    $("#alogin2").click(showLoginScreen);
   /* 
    $(".r1 img").each(function() { 
        var src = $(this).attr('src'), parenT = $(this).parent();
        if(src != '/i/nofoto.gif') {
            var img = new Image();
            $(this).parent().append('<div style="background: url(\'/i/ajax-loader.gif\') no-repeat center center; display: block; width: 140px; height: 50px;"></div>');
            $(this).remove();            
            $(img).load(function(){
                $(this).hide();
                parenT.find("div").remove();
                parenT.append(this);
                $(this).fadeIn();
            }).attr('src',src);            
        }
    });*/
    
    // Отображаем или скрываем вендоров
    $(".chng_region a").click(function (e) {
        var hV = $("#hiddenVendors"), hVa = hV.length;
        if($("#hiddenRegion_cont").length) {
            if(!hVa) {
                $("body").append("<div id=\"hiddenVendors\" style=\"display: none;\">" + $("#hiddenRegion_cont").html() +"</div>");
                var fromTop = (parseInt(($("#hiddenVendors").height() / 2)) * -1) + parseInt($(window).scrollTop()) + "px";
                var fromLeft = $("#hiddenVendors").width() / 2 + "px";
                $("#hiddenVendors")
                  .css("position","absolute")
                  .css("top","50%")
                  .css("min-height","310px")
                  .css("left","40%")
                  .css("margin-top",fromTop)
                  .css("margin-left","-" + fromLeft)
                  .css("padding","20px")
                  .css("z-index","900000")
                  .css("background-color","white")
                  .css("border","4px solid #E0E0E0")
                  .show();
                  $("div.sbutton_close").unbind("click");
                  $("div.sbutton_close").click(function() { 
                    $("div.sbutton a").html("<img src=\"/i/svdn.gif\"> Все бренды"); $("#hiddenVendors").remove(); return false; 
                  });  
            } else {
                $("#hiddenVendors").remove();
            }            
        } else {
            if($("ul.hd").is(":hidden")) {        
                $("ul.hd").show();
                return false;    
            } else {        
                $("ul.hd").hide();
                return false;
            }
        }   
    });
	
	$("div.sbutton").css("cursor","pointer").click(function (e) {
        var hV = $("#hiddenVendors"), hVa = hV.length;
        if($("#hiddenVendors_cont").length) {
            if(!hVa) {
                $("body").append("<div id=\"hiddenVendors\" style=\"display: none;\">" + $("#hiddenVendors_cont").html() +"</div>");
                var fromTop = (parseInt(($("#hiddenVendors").height() / 2)) * -1) + parseInt($(window).scrollTop()) + "px";
                var fromLeft = $("#hiddenVendors").width() / 2 + "px";
                $("#hiddenVendors")
                  .css("position","absolute")
                  .css("top","50%")
                  .css("min-height","310px")
                  .css("left","40%")
                  .css("margin-top",fromTop)
                  .css("margin-left","-" + fromLeft)
                  .css("padding","20px")
                  .css("z-index","900000")
                  .css("background-color","white")
                  .css("border","4px solid #E0E0E0")
                  .show();
                  $("div.sbutton_close").unbind("click");
                  $("div.sbutton_close").click(function() { 
                    $("div.sbutton a").html("<img src=\"/i/svdn.gif\"> Все бренды"); $("#hiddenVendors").remove(); return false; 
                  });  
            } else {
                $("#hiddenVendors").remove();
            }            
        } else {
            if($("ul.hd").is(":hidden")) {        
                $("ul.hd").show();
                $("div.sbutton a").html("<img src=\"/i/svup.gif\"> Все бренды");
                return false;    
            } else {        
                $("ul.hd").hide();
                $("div.sbutton a").html("<img src=\"/i/svdn.gif\"> Все бренды");
                return false;
            }
        }   
    });
    
    // Отправляем форму Options (сортировка, TovarsPerPage)
    $("select#tpp").change(function(){
        $(this).parents('form').submit();
    });
    $("select#sort").change(function(){
        $(this).parents('form').submit();
    });
	$("select#nalichie").change(function(){
        $(this).parents('form').submit();
    });
 
    // Открываем ссылки начинающиеся с '/news/cat_img/' в отдельном окне.

	$("a[href^='/news/cat_img/']").click(function(){        
        var name = $(this).attr('href').substr(14);
        var wName = $(this).attr('title');                
        nAma = wName.split(','); 
        wName = nAma[0];
        geometry = nAma[1].split('x');
        var width = parseInt(geometry[0]) + parseInt(30);
        var height = parseInt(geometry[1]) + parseInt(65);
        
        var left = parseInt((screen.availWidth/2) - (width/2));
        var top = parseInt((screen.availHeight/2) - (height/2));
        var options = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=no,width=" + width + ",height=" + height + ",top=" + top + ",left=" + left;
        
        myWindow = window.open('/news/preview/' + name, wName, options);
        myWindow.focus();               
        return false;
    });
	
    $(window).resize(function(){$.opt.cHeight = ($.browser.mozilla || $.browser.safari ? $(window).height() : document.documentElement.clientHeight);});
    $(window).scroll(function(){$.opt.sTop = $(document).scrollTop();});    

    checkCommentsInput();
	bindBehaviors();
    // ##################
    // ##################
	
	if ( $(".fancybox").length) $(".fancybox").fancybox({
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	600, 
		'speedOut'		:	200, 
		'overlayShow'	:	true,
		'overlayColor'	:	'#000',
		'overlayOpacity':	0.7
	});

	//countDown();
	if ($('.action_date').length>0)
	{
		setInterval('countDownActions()', 1000);
	}

});

function countDownActions() {      
	$('.action_date').each(function() 
	{
		time_diff=$(this).attr('rel');
		$(this).attr('rel',(time_diff-1));
		work_number = time_diff--;
		days = Math.floor(work_number / 86400);      
		work_number -= days * 86400;
		hours = Math.floor(work_number / 3600);
		work_number -= hours * 3600;
		minutes = Math.floor(work_number / 60);
		work_number -= minutes * 60;
		seconds = Math.floor(work_number % 60);
		values = [
			declOfNum(days, ['день', 'дня', 'дней'],1),
			declOfNum(hours, ['час', 'часа', 'часов'],1),
			declOfNum(minutes, ['мин', 'мин', 'мин'],1),
			declOfNum(seconds, ['сек', 'сек', 'сек'],1)
		];
		var ret = values.join(' ');
		values_for_title = [
			declOfNum(days, ['день', 'дня', 'дней'],0),
			declOfNum(hours, ['час', 'часа', 'часов'],0),
			declOfNum(minutes, ['мин', 'мин', 'мин'],0),
			declOfNum(seconds, ['сек', 'сек', 'сек'],0)
		];
		var ret_title = 'До окончания акции осталось '+values_for_title.join(' ');
		$(this).html(ret);
		$(this).attr('title',ret_title);
	});
}

function declOfNum(number, titles,style) {
	cases = [2, 0, 1, 1, 1, 2];
	if (number>0)
	{
		if (style==0)
		{
			return number + ' ' + titles[ (number%100>4 && number%100<20)? 2 : cases[Math.min(number%10, 5)] ];
		}
		else
		{
			return '<span class="decs">' + number + '</span> ' + titles[ (number%100>4 && number%100<20)? 2 : cases[Math.min(number%10, 5)] ];
		}
	}
}

function bindBehaviors() {
	
    // Sending comments by ajax.
    $("#sendComment :input").keyup(checkCommentsInput);
    $('#sendComment').submit(function(){
        var inputs = [];
		nameok=false;
		typeok=false;
        $(':input',this).each(function(){
            if (this.name=='tov_id') {nameok=true;}
			if (this.name=='comment_type') {typeok=true;}
			inputs.push(this.name + '=' + $(this).attr("value").replace(/&/g,'::amp::'));
        });

		if (nameok==false) {inputs.push('tov_id=' + $('#tov_id').attr("value").replace(/&/g,'::amp::'));}
		if (typeok==false) {inputs.push('comment_type=' + $('#comment_type').attr("value").replace(/&/g,'::amp::'));}

		jQuery.ajax({
			data: inputs.join('&'),
			type: "POST",
			url: '/addComment.php',
			timeout: 10000,
			encoding: "cp1251",
			error: function(e) {
				alert('We got an error during try to submit comment: '+inputs);
			},
			success: function(r) {
				var data = [];
					data = r.split("\n");
				var result = data[0];
					data.shift();
					data = data[0];
				if(result == 202) {
					var comment_parent_id = $('#comment_parent_id').val();
					if (comment_parent_id>0)
					{
						$("#li_"+comment_parent_id+"").append('<ul class="comment_ul"><li class="comment_li">'+data+'</li></ul>');
						$('.comment_reply_block').html('');
						$('.comment_reply_block').hide();
						$('#reply_0').show();
						new_text = '<div id="reply_to_0" class="addcomment"><form id="sendComment" method="post"><div class="forms_name">Ваш отзыв:</div><div class="forms_inputs"><div><textarea id="comment_text" name="text"></textarea></div><div align="right" style="margin-top: 5px;"><input type="submit" id="submit" value="Отправить"></div></form><div class="clear"></div></div>';
						$('#reply_0').html(new_text);
						bindBehaviors();
					}
					else
					{
						$("#comments_list").prepend(data);
					}
					$("#sendComment textarea").val("");
					$("#sendComment #submit").attr("disabled","disabled");
					showAlert('Комментарий был добавлен!');
					var inc = $("#comm .tov_count").html().replace("(","").replace(")","");                                                
						inc = parseInt(inc) + 1;
					$("#comm .tov_count").html("("+inc+")");
				}
				else { alert("We\'re so sorry, but some error catched during try to post your comment"+inputs); }
			}
		});        
        return false;
    });
	
}

function addToCart(tovid) {
    jQuery.ajax({
        data: { tov_id: tovid },
        type: "POST",
        url: "/ajax_cart.php?add",
        timeout: 5000,
        error: function(e) {
            alert(e);
        },
        success: function(r) {
            var data = [];
                data = r.split(":");
            if($("#cartDiv").length <= 0) {
                //$("#con_left").prepend("<div class=\"leftcolumn\" id=\"cartDiv\">Ваша корзина<br/>В корзине <strong id=\"pos\">"+data[0]+"</strong> позиция<br/>на сумму <strong id=\"summ\">"+data[1]+"</strong> руб.</div>");
                $("#con_left").prepend("<div class=\"leftcolumn\" id=\"cartDiv\"><div class=\"yC\"><a href=\"/cart/\"><u>Ваша корзина</u></a></div><div class=\"St\">В корзине <strong id=\"pos\">"+data[0]+"</strong> позиция<br/>на сумму <strong id=\"summ\">"+data[1]+"</strong> руб.</div></div>");
            } else {
                $("#cartDiv #pos").text(data[0]);   
                $("#cartDiv #summ").text(data[1]);
            }
			showAlert('Товар #'+tovid+' добавлен в корзину!');
        }
    });
};

function onhoverStars(num) { for(var i = 1; i <= num; i++) {$("#vStar"+i).css("background-position","-182px -257px");} return false; };
function onoutStars(num) { for(var i = 1; i <= num; i++) {$("#vStar"+i).css("background-position","-168px -257px");} return false; };
function vfStar(num) {

    voteErrors = new Array();
    voteErrors[105] = "Для того, чтобы иметь возможность голосовать,\nВам необходимо зарегистрироваться на сайте,\nесли Вы этого не сделали раньше и авторизироваться.";
    voteErrors[106] = 'Вы уже отдали свой голос за этот товар';
    voteErrors[107] = 'Внутренняя ошибка БД';

    // ajax here.
    jQuery.ajax({
        data: "vote="+num,
        type: "POST",
        url: "/addVote.php",
        timeout: 10000,
        encoding: "cp1251",
        error: function(){ alert('We got an error during try to submit your vote choice'); },
        success: function(r){
            var data = [];
                data = r.split("\n"); 
            if(voteErrors[r]) { alert(voteErrors[r]); return false; }
            if(data[0] == 0) {
                displayMark(data[1],data[2],num);
				showAlert('Оценка была поставлена!');
                return false;
            }
            alert(r);
        }
    });     
};

function displayMark(mark,people,own) {
    var stars = '';
    for(var i = 1; i <= 5; i++) { 
        if(i <= Math.round(mark)) stars += '<img src="/i/star.gif">';
        else stars += '<img src="/i/star_.gif">'; 
    }
    $(".rating").append("\n<div class=\"o\" id=\"displayNums\">Средняя оценка: <strong title=\"Голосовало: "+people+" чел.\">"+stars+"</strong><em>("+mark+")</em></div>");
    //$("#displayNums").find("strong").html(stars);
    //$("#displayNums").find("em").html("("+mark+")");
    $("#displayStars").html("<font size=\"1\" style=\"color:#ACACAC; white-space: nowrap;\">Ваша оценка данному товару: <strong>"+own+"</strong> бал.</font>");
    //$("#displayNums").find("strong").attr("title","Голосовало: "+people+" чел.");
	$("#displayStars").css('width','100%');
    
};

function checkCommentsInput() {    
	$(":input","#sendComment").each(function(){            
		if(this.name == 'text') {
			if(this.value.replace(/(^\s+)|(\s+$)/g, "").length > 0) $("#sendComment #submit").removeAttr("disabled");
			else $("#sendComment #submit").attr("disabled","disabled");
		}
	});
};

function changeVoteMark(comment_n,vote_val)
{
	old_val = $("#vote_"+comment_n+" .vote_mark .vote_num").html();
	new_val = old_val*1+vote_val;
	
	jQuery.ajax({
	data: { comment_id: comment_n,vote_value: vote_val},
	type: "POST",
	url: "/addCommentVote.php",
	timeout: 10000,
	encoding: "cp1251",
	error: function(){ alert('We got an error during try to submit your vote choice'); },
	success: function(r){
			if (new_val>0)
			{
				$("#vote_"+comment_n+" .vote_mark span").removeClass("vote_red");
				$("#vote_"+comment_n+" .vote_mark span").addClass("vote_green");
				$("#vote_"+comment_n+" .vote_mark .vote_symbol").html('+');
			}
			else if (new_val==0)
			{
				$("#vote_"+comment_n+" .vote_mark span").removeClass("vote_red");
				$("#vote_"+comment_n+" .vote_mark span").removeClass("vote_green");
				$("#vote_"+comment_n+" .vote_mark .vote_symbol").html('');
			}
			else
			{
				$("#vote_"+comment_n+" .vote_mark span").addClass("vote_red");
				$("#vote_"+comment_n+" .vote_mark span").removeClass("vote_green");
				$("#vote_"+comment_n+" .vote_mark .vote_symbol").html('');
			}
			$("#vote_"+comment_n+" .vote_mark .vote_num").html(new_val);
			showAlert('Оценка была поставлена!');
		}
	});
}



//this.cartUpdateTov = function(tovid,num) {
//    $.post("/ajax_cart.php?update",{ tov_id: tovid, number: num });
//};
/*
this.cartDelete = function(e,tovid) {
    jQuery.ajax({
        data: { tov_id: tovid },
        type: "POST",
        url: "/ajax_cart.php?del",
        timeout: 10000,
        error: function(){},
        success: function(r){
            if(r == 0) {
                e.parent().parent().fadeOut("slow",function(){
                    $(this).remove();
                    $(".cart_bottom .nal").html(number_format(checkCartSum(),0,","," ") + " руб.");
                });
            } else {
                alert("Возникли некоторые трудности.");
            }
        }
    });
};
*/
this.number_format = function ( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}
this.checkCartSum = function() {
    var summ = 0;
    $(".cartcont .carttovar").each(function(i){
        summ += $(this).find("input").attr("value") * $(this).find(".price").html().replace(" руб.","").replace(/ /g,"");
    });
    return summ;
};
this.animatePlus = function(e) {
    return false;
    $("body").append("<p style=\"display: none\" id=\"plusik\">+1</p>");
    $("#plusik")
        .css("position","absolute")
        .css("top",e.pageY + "px")
        .css("left",e.pageX + "px")
        .fadeIn("slow");
        //.animate({ opacity: 1 }, { queue:false, duration:3000 });
};

this.showLoginScreen = function() {    
    if($("#loginscreen").css("display") == undefined || $("#loginscreen").is(":hidden")) {
        $("body").append("<div id=\"closebg\"></div>");
        $("body").append("<div id=\"loginscreen\" style=\"display: none;\">" +
            "<form id=\"loginform\" method=\"post\" style=\"position: relative; z-index: 99999999\">"+
            "<span style=\"position: relative; top: 20px; left: 45px; font-family: Tahoma, Arial; font-size: 170%; color: #000\">Вход</span>"+
            "<table style=\"position: relative; top: 28px; left: 11px; z-index: 99999999999999\" class=\"logintable\"><tr><td align=\"right\" style=\"font-family: Tahoma, Arial; font-size: .95em;\">E-mail:</td><td><input type=\"text\" name=\"email\"></td></tr>"+
            "<tr><td align=\"right\" style=\"font-family: Tahoma, Arial; font-size: .95em;\">Пароль:</td><td><input type=\"password\" name=\"passwd\"> <img src=\"/i/forgot.gif\" id=\"forgot_btn\" width=\"16\" height=\"16\" align=\"absmiddle\" title=\"Восстановить пароль немедленно!\"></td></tr>"+
            "<tr><td>&nbsp;</td><td style=\"padding-top: .8em; \"><input type=\"submit\" value=\"Войти\"></td></tr></table></form></div>");        
        $("#loginform").append("<input type=\"hidden\" name=\"trytologin\" value=\"1\">");
        $("#loginscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"$('#loginscreen').remove();$('#closebg').remove();return false;\"></a></div>");
        
        $("#loginform #forgot_btn").css("opacity","0.3").css("cursor","pointer").hover(function(){
            $(this).css("opacity","1");
        },function(){
            $(this).css("opacity","0.3");
        }).click(function(){
            var email = $('form#loginform input[name="email"]').attr("value");
            if(email.length == 0) {
                alert('Не забудьте ввести свой e-mail адрес.');
                return false;
            }
            if(email.length < 6) {
                alert('Неправильно введен e-mail адрес.\nПожалуйста введите свой e-mail адрес, который был указан при регистрации.');
                return false;
            }
            jQuery.ajax({
                type: "GET",
                url: "/ajax_profile.php?forget=true&email=" + email,
                timeout: 10000,
                encoding: "cp1251",
                error: function(){ alert('We got an error during try to submit your request'); },
                success: function(r){ alert(r); }
            });   
        });
        
        $("#closebg").css("position","absolute").
            css("display","none").
            css("opacity",0.7).            
            css("z-index","99").
            css("width","100%").
            css("height",$("body").height()).
            css("top","0").
            css("left","0").
            css("background-color","#000").            
            show();   
            
        $("#loginscreen").
            css("position","absolute").
            css("top","50%").
            css("width","310px").
            css("margin-top","-100px").
            css("height","170px").
            css("left","50%").
            css("margin-left","-85px").
            css("z-index","100").
            show();
        $("#loginscreen input:first").focus();
    } else {
        $("#loginscreen").remove();
    }    
    $(document).keydown(function(e){if(e.which == 27) { $("#loginscreen").remove(); $("#closebg").remove(); }});    
    return false;
};

function doRegistrationByWishList()
{
	$("#wishlistscreen").remove(); $("#closebg").remove();showLoginScreen();
}

this.showPartnerOrderListScreen = function(t,tit)
{
	if($("#partnerorderscreen").css("display") == undefined || $("#partnerorderscreen").is(":hidden")) {
        $("body").append("<div id=\"closebg\"></div>");
		$("body").append("<div id=\"partnerorderscreen\" style=\"display: block;\"></div>");
		$('#partnerorderscreen').empty();
		$("#partnerorderscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Заказ товара</div>"+
			"Вы можете оставить нам свои контактные данные и мы привезём Вам "+tit+"<br /><br />"+
			"<table width=\"100%\" class=\"remindTable\"><tr><td>Контактное лицо:"+
			"<input id=\"remindListName\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td></tr><tr><td>"+
			"Email:"+
			"<input id=\"remindListEmail\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td></tr>"+
			"<tr><td>Телефон:"+
			"<input id=\"remindListPhone\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td></tr>"+
			"<tr><input type=\"hidden\" id=\"remindListDelivery\" value=\"Заказ с музторг.ру\" /><td class=\"remindListpad\">Город:<select id=\"remindListCity\"><option>Москва</option><option>Санкт-Петербург</option><option>Регионы</option></select></td></tr>"+
			"<tr><td class=\"remindListpad\">Адрес доставки:<textarea id=\"remindListAddress\"></textarea></td></tr>"+
			"</table>"+
			"<div align=\"right\"><input type=\"button\" value=\"Оформить заказ\" style=\"margin-top: 2px;\" onclick=\"sendToPartnerOrderList('"+t+"')\" /></div>"+
			"</div>");
        $("#partnerorderscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"document.getElementById('partnerorderscreen').style.display='none';document.getElementById('closebg').style.display='none';return false;\"></a></div>");

        $("#closebg").css("position","absolute").
            css("display","none").
            css("opacity",0.7).            
            css("z-index","10").
            css("width","100%").
            css("height",$("body").height()).
            css("top","0").
            css("left","0").
            css("background-color","#000").            
            show();   
            
        $("#partnerorderscreen").
            css("position","fixed").
            css("top","50%").
            css("width","450px").
            css("margin-top","-250px").
            css("height","500px").
            css("left","50%").
            css("margin-left","-225px").
            css("z-index","15").
            show();
    } else {
        $("#partnerorderscreen").remove();
    }    
    $(document).keydown(function(e){if(e.which == 27) { $("#partnerorderscreen").remove(); $("#closebg").remove(); }});    
    return false;		
};

this.showRemindListScreen = function(t)
{
	if($("#wishlistscreen").css("display") == undefined || $("#wishlistscreen").is(":hidden")) {
        $("body").append("<div id=\"closebg\"></div>");
		$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
		$('#wishlistscreen').empty();
		$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Напоминание</div>"+
			"Вы можете оставить нам свои контактные данные и мы уведомим Вас когда товар появится в нашем магазине:<br /><br />"+
			"<table width=\"100%\" class=\"remindTable\"><tr><td colspan=\"2\">Вас зовут:"+
			"<input id=\"remindListName\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td><tr><td width=\"50%\" class=\"remindListpad\">"+
			"Email:"+
			"<input id=\"remindListEmail\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td><td>"+
			"Телефон:"+
			"<input id=\"remindListPhone\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td></tr></table>"+
			"<div align=\"right\"><input type=\"button\" value=\"Оставить заявку\" style=\"margin-top: 2px;\" onclick=\"sendToNotifyList('"+t+"')\" /></div>"+
			"</div>");
        $("#wishlistscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"document.getElementById('wishlistscreen').style.display='none';document.getElementById('closebg').style.display='none';return false;\"></a></div>");

        $("#closebg").css("position","absolute").
            css("display","none").
            css("opacity",0.7).            
            css("z-index","10").
            css("width","100%").
            css("height",$("body").height()).
            css("top","0").
            css("left","0").
            css("background-color","#000").            
            show();   
            
        $("#wishlistscreen").
            css("position","fixed").
            css("top","50%").
            css("width","450px").
            css("margin-top","-125px").
            css("height","250px").
            css("left","50%").
            css("margin-left","-225px").
            css("z-index","15").
            show();
    } else {
        $("#wishlistscreen").remove();
    }    
    $(document).keydown(function(e){if(e.which == 27) { $("#wishlistscreen").remove(); $("#closebg").remove(); }});    
    return false;		
};

this.showWishListScreen = function(r,t,type) {    
    if($("#wishlistscreen").css("display") == undefined || $("#wishlistscreen").is(":hidden")) {
        $("body").append("<div id=\"closebg\"></div>");
        if ((type==0)&&(r>0))
        {
			$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
			$('#wishlistscreen').empty();
			$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Вишлист</div>"+
				"Напишите, пожалуйста, комментарий к желанию:"+
				"<textarea id=\"wishListComment\" style=\"width: 100%; height: 120px;\"></textarea>"+
				"<div align=\"right\"><input type=\"button\" value=\"Сохранить\" style=\"margin-top: 2px;\" onclick=\"sendToWishList('"+t+"')\" /></div></div>");
		}
		else if ((type==1)&&(r>0))
		{
			$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
			$('#wishlistscreen').empty();
			$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Вишлист</div>"+
				"Вы действительно собираетесь удалить товар из вишлиста?"+
				"<textarea id=\"wishListComment\" style=\"width: 100%; height: 120px; visibility: hidden;\"></textarea>"+
				"<div align=\"right\"><input type=\"button\" value=\"Удалить\" style=\"margin-top: 2px;\" onclick=\"deleteFromWishList('"+t+"')\" /></div>"+
				"</div>");
		}
		else if (r==0)
		{
			$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
			$('#wishlistscreen').empty();
			$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Вишлист</div>"+
				"Для чего нужен список желаний?<br /><br />"+
				"<strong>Чтобы не забыть, что вы хотите купить.<br />"+
				"Чтобы ваши друзья знали, что подарить вам.<br />"+
				"Чтобы вы знали, что хотят ваши друзья.</strong><br /><br />Подробнее о вишлистах на МузТорге можно прочитать <a href=\"/service/wishlist/\">здесь</a>.<br /><br />"+
				"Мы предупредим вас, когда ваше желание станет доступней!<br /><br />"+
				"Для того, чтобы пополнить свой список в вишлисте &mdash; <a href=\"#login\" onclick=\"doRegistrationByWishList();\">авторизуйтесь</a>, либо <a href=\"/registration/\">зарегистрируйтесь</a>.</div>");
			/*
			$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\">"+
			"<div style=\"margin: 20px;\"<div style=\"font-size: 20pt; margin-bottom: 10px;\">Вишлист</div>"+
				"Для чего нужен список желаний?<br /><br /><br />"+
				"<strong>Чтобы не забыть, что вы хотите купить.<br />"+
				"Чтобы ваши друзья знали, что подарить вам.<br />"+
				"Чтобы вы знали, что хотят ваши друзья.</strong><br /><br />"+
				"Мы предупредим вас, когда ваше желание станет доступней!<br /><br /><br />"+
				"Для того, чтобы пополнить свой список в вишлисте &mdash; <a href=\"#login\" onclick=\"doRegistrationByWishList();\">авторизуйтесь</a>, либо <a href=\"/registration/\">зарегистрируйтесь</a>.</div>"+
			"</div>");
			*/
		}
        $("#wishlistscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"$('#wishlistscreen').remove();$('#closebg').remove();return false;\"></a></div>");

        $("#closebg").css("position","absolute").
            css("display","none").
            css("opacity",0.7).            
            css("z-index","10").
            css("width","100%").
            css("height",$("body").height()).
            css("top","0").
            css("left","0").
            css("background-color","#000").            
            show();   
            
        $("#wishlistscreen").
            css("position","fixed").
            css("top","50%").
            css("width","450px").
            css("margin-top","-125px").
            css("height","260px").
            css("left","50%").
            css("margin-left","-230px").
            css("z-index","15").
            show();
    } else {
        $("#wishlistscreen").remove();
    }    
    $(document).keydown(function(e){if(e.which == 27) { $("#wishlistscreen").remove(); $("#closebg").remove(); }});    
    return false;
};

this.addToRemindList = function(tovid) {
	showRemindListScreen(tovid);
};

this.addToPartnerOrder = function(tov_id,tovname) {
	showPartnerOrderListScreen(tov_id,tovname);
};

this.addToWishList = function(tovid) {
	var user_n = $('#user_n').val();
	showWishListScreen(user_n,tovid,0);
};

this.RemoveFromWishList = function(tovid) {
	var user_n = $('#user_n').val();
	showWishListScreen(user_n,tovid,1);
};

function sendToWishList(tovid)
{
	comment = $('#wishListComment').val();
	jQuery.ajax({
        data: { tov_id: tovid,comment_text: comment },
        type: "POST",
        url: "/ajax_wish_list.php?add",
        timeout: 5000,
        error: function(e) {
            alert(e);
        },
        success: function(r) {
			$("#wishlistscreen").remove(); $("#closebg").remove();
			$("#addWishListBtn").remove();
			$("#removeWishListBtn").show();
			showAlert('Товар добавлен в вишлист!');
        }
    });
}

function deleteFromWishList(tovid)
{
	jQuery.ajax({
        data: { tov_id: tovid },
        type: "POST",
        url: "/ajax_wish_list.php?delete",
        timeout: 5000,
        error: function(e) {
            alert(e);
        },
        success: function(r) {
			$("#wishlistscreen").remove(); $("#closebg").remove();
			$("#removeWishListBtn").remove();
			$("#addWishListBtn").show();
			showAlert('Товар удалён из вишлиста!');
        }
    });
}

function sendToNotifyList(tovid)
{
	var n_email = $('#remindListEmail').val();
	var n_name = $('#remindListName').val();
	var n_phone = $('#remindListPhone').val();
	jQuery.ajax({
        data: { tov_id: tovid, email: n_email,fio: n_name,phone: n_phone },
        type: "POST",
        url: "/ajax_notify_list.php",
        timeout: 5000,
        error: function(e) {
            alert(e);
        },
        success: function(r) {
			$("#wishlistscreen").remove(); $("#closebg").remove();
			//$("#removeWishListBtn").remove();
			//$("#addWishListBtn").show();
			showAlert('Напоминание было активировано!');
        }
    });
}

function sendToPartnerOrderList(tovid)
{
	var n_email = $('#remindListEmail').val();
	var n_name = $('#remindListName').val();
	var n_phone = $('#remindListPhone').val();
	var n_city = $('#remindListCity').val();
	var n_delivery = $('#remindListDelivery').val();
	var n_address = $('#remindListAddress').val();
	if ((n_email)&&(n_name)&&(n_phone)&&(n_city)&&(n_address))
	{
		jQuery.ajax({
			data: { tov_id: tovid, email: n_email,fio: n_name,phone: n_phone,city: n_city,address: n_address,delivery: n_delivery },
			type: "POST",
			url: "/ajax_order_list.php",
			timeout: 5000,
			error: function(e) {
				alert(e);
			},
			success: function(r) {
				$("#partnerorderscreen").remove(); $("#closebg").remove();
				//$("#removeWishListBtn").hide();
				//$("#addWishListBtn").show();
				showAlert('Товар был заказан!');
			}
		});
	}
	else
	{
		alert('Заполните все необходимые поля!');
	}
}

function show_demo(yid)
{
	var html = '<object style="height: 420px; width: 700px"><param name="movie" value="http://www.youtube.com/v/'+yid+'?version=3?version=3&border=1&color1=0xb1b1b1&color2=0xcfcfcf&iv_load_policy=3&feature=player_embedded"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><embed src="http://www.youtube.com/v/'+yid+'?version=3?version=3&border=1&color1=0xb1b1b1&color2=0xcfcfcf&iv_load_policy=3&feature=player_embedded" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="700" height="419"></object>';
	if($("#wishlistscreen").css("display") == undefined || $("#wishlistscreen").is(":hidden")) {
        $("body").append("<div id=\"closebg\"></div>");
		$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
		$('#wishlistscreen').empty();
		$("#wishlistscreen").append(html);
        $("#wishlistscreen").append("<div align=\"center\" style=\"margin-top: 5px;\"><a href=\"#\" onclick=\"$('#wishlistscreen').remove();$('#closebg').remove();return false;\">Закрыть</a></div>");

        $("#closebg").css("position","absolute").
            css("display","none").
            css("opacity",0.7).            
            css("z-index","10").
            css("width","100%").
            css("height",$("body").height()).
            css("top","0").
            css("left","0").
            css("background-color","#000").            
            show();   
            
        $("#wishlistscreen").
            css("position","fixed").
            css("top","50%").
            css("width","700px").
            css("margin-top","-220px").
            css("height","440px").
            css("left","50%").
            css("margin-left","-350px").
            css("z-index","15").
            show();
    } else {
        $("#wishlistscreen").remove();
    }    
    $(document).keydown(function(e){if(e.which == 27) { $("#wishlistscreen").remove(); $("#closebg").remove(); }});    
    return false;	
}

function upload_info(type)
{
	if (type==1)
	{
		var tov_id = $('.demo_upload').attr('rel');
		var demo_link = $('#demo_link').val();
		$("#wishlistscreen").remove(); $("#closebg").remove();
	}
	else if (type==2)
	{
		var tov_id = $('.image_upload').attr('rel');
		var demo_link = $('#image_link').val();
		$("#wishlistscreen").remove(); $("#closebg").remove();
	}
	else if (type==3)
	{
		var tov_id = $('#desc_upload').attr('rel');
		var demo_link = $('#desc_link').val();
		$("#partnerorderscreen").remove(); $("#closebg").remove();
	}
	else if (type==4)
	{
		var tov_id = $('.image_upload_small').attr('rel');
		var demo_link = $('#image_link').val();
		$("#wishlistscreen").remove(); $("#closebg").remove();
	}
	$.post('/ajax_upload_info.php', {tov_id: tov_id,link: demo_link,type: type}, function(data) {
		showAlert(data);
	});
}

function showAlert(text)
{
	$("#alertboxList").append('<div class="alertbox">'+text+'</div>');
	$("alertbox").css({ opacity: 0 }); // works in all browsers
	$('.alertbox').show();
	$(".alertbox").animate({
		opacity: 1
		}, 2000, function() {
		$(".alertbox").animate({
			opacity: 0
			}, 1000, function() {
			$('#alertboxList').empty();
		});
	});
	}

function number_format( number, decimals, dec_point, thousands_sep ) {	// Format a number with grouped thousands
	// 
	// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +	 bugfix by: Michael White (http://crestidg.com)

	var i, j, kw, kd, km;

	// input sanitation & defaults
	if( isNaN(decimals = Math.abs(decimals)) ){
		decimals = 2;
	}
	if( dec_point == undefined ){
		dec_point = ",";
	}
	if( thousands_sep == undefined ){
		thousands_sep = ".";
	}

	i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

	if( (j = i.length) > 3 ){
		j = j % 3;
	} else{
		j = 0;
	}

	km = (j ? i.substr(0, j) + thousands_sep : "");
	kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
	//kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
	kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");


	return km + kw + kd;
}

function recalc_sum()
{
	var total_num = $("#total_tovs").val();
	var total_sum = 0;
	var good_tov = 0;
	for (i=1;i<=total_num;i++)
	{
		var count = $('#count_'+i).val();
		var price = $('#price_'+i).val();
		if ((price>=1500)&&(count>=1))
		{
			good_tov++;
		}
		var summ = price*count;
		total_sum=total_sum+summ;
	}
	
	if (good_tov==0)
	{
		$('#error_price').show();
		$('#error_price').html("К сожалению, мы не сможем выполнить Ваш заказ. Для оформления заказа необходимо, чтобы один из товаров стоил больше 1 500 рублей. Вы можете приобрести данные товары в наших розничных магазинах.");
		$('#order_button').attr("disabled","disabled");
	}
	else if (total_sum<2000)
	{
		$('#error_price').show();
		$('#error_price').html("На данный момент мы не осуществляем приём заказов с итоговой суммой менее 2 000 рублей.<br>Вы можете приобрести данные товары в наших розничных магазинах.");
		$('#order_button').attr("disabled","disabled");
	}
	else
	{
		$('#error_price').hide();
		$('#order_button').removeAttr("disabled");

	}

	total_sum = number_format(total_sum,0,","," ");
	total_sum = 'Итоговая стоимость '+total_sum+' руб.';
	$('#total_nal').text(total_sum);
}

function change_sum(position_n)
{
	var count = $('#count_'+position_n).val();
	if (count<0)
	{
		count = 0;
		$('#count_'+position_n).val(count);
	}
	
	var price = $('#price_'+position_n).val();
	var summ = price*count;
	summ = number_format(summ,0,","," ");
	summ = summ+' руб.';
	$('#display_summ_'+position_n).text(summ);
	recalc_sum();
}

function check_label(label)
{
	var inp_value = $("input[name='"+label+"']").val();
	if (inp_value=='') inp_value = $("input[name='"+label+"']").value;

	if (inp_value)
	{
		
		$('#'+label+'_label').removeClass('redy');
		return 0;
	}
	else
	{
		$('#'+label+'_label').addClass('redy');
		return 1;
	}
}

function check_address()
{
	var inp_value = $("#address").val();
	if (inp_value)
	{
		$('#address_label').removeClass('redy');
		return 0;
	}
	else
	{
		$('#address_label').addClass('redy');
		return 1;
	}
}

function check_region()
{
	var inp_value = $("#region option:selected").val();
	if ((inp_value)&&(inp_value!='-'))
	{
		$('#region_label').removeClass('redy');
		return 0;
	}
	else
	{
		$('#region_label').addClass('redy');
		return 1;
	}
}

function checkNav()
{
	var timer = ($('#navi_timeout').val()*1)+1;
	if ($('#mainsubmenu').hasClass('currenthover'))
	{
		timer=0;
	}
	$('.submenus').each(function(){
		if ($(this).hasClass('currenthover'))
		{
			timer=0;
		}
	});
	$('#navi_timeout').val(timer);
	if (timer==1)
	{
		$('#submenu_hover .submenus').hide();
		$('#navi_timeout').val(0);
	}
}

function show_sub_menu(submenu_href)
{
	$('#submenu_hover .submenus').hide();
	$('#submenu_hover .submenus').each(function(){
		$(this).removeClass('subactive');
	});
	$('#submenu_'+submenu_href).show();
	$('#submenu_'+submenu_href).addClass('subactive');
	$('#navi_timeout').val(0);
}

function check_town()
{
	var inp_value = $("#town option:selected").val();
	if ((inp_value)&&(inp_value!='-'))
	{
		$('#town_label').removeClass('redy');
		return 0;
	}
	else
	{
		$('#town_label').addClass('redy');
		return 1;
	}
}

function build_address()
{
	if (($("input[name=delivery_type]:checked").val()!="Самовывоз")&&($("input[name=delivery_type]:checked").val()!="Самовывоз СПБ1")&&($("input[name=delivery_type]:checked").val()!="Самовывоз СПБ2")&&($("input[name=delivery_type]:checked").val()!="Самовывоз ЕКБ1"))
	{
		var ret_val = $('#town').val()+', ул. '+$('#street').val()+', '+$('#house').val();
		if ($('#building').val()) {ret_val = ret_val+'/'+$('#building').val();}
		if ($('#room').val()) {ret_val = ret_val+', кв.'+$('#room').val();}
		$('#address').val(ret_val);

		var m_region = $('#region').val();
		var m_town = $('#town').val();
		var m_street = $('#street').val();
		var m_house = $('#house').val();
		var m_building = $('#building').val();
		if ((m_region)&&(m_town)&&(m_street)&&(m_house))
		{
			var m_address = m_town+', ул. '+m_street+', '+m_house;
			if (m_building) {m_address = m_address+'/'+m_building;}
			$.get('/ajax_get_image.php', {address: m_address}, function(data) {
				if (data!=0)
				{
					$('#yMap').html(data);
					$('.map_view').hide();
				}
				else
				{
					$('.map_view').hide();
				}
			});
		}
		else
		{
			$('.map_view').hide();
		}
	}
	else
	{
		$('#address').val('Самовывоз');
	}
}

function check_form_error()
{
	var err=0;
	build_address();
	err += check_label('f');
	err += check_label('im');
	err += check_label('o');
	err += check_label('phones');
	err += check_label('email');
	err += check_label('delivery_type');
	err += check_region();
	err += check_town();
	err += check_address();
	if ($('#usl:checked').length==0) err += 1;
	return err;
}

function submitOrder()
{
	var total_errors = check_form_error();
	if (total_errors>0)
	{
		alert("Вы не заполнили обязательные поля. Каждый заказ должен включать в себя:\n\n— Фамилию;\n— Имя;\n— Отчество;\n— Мобильные телефон;\n— Email;\n— Регион;\n— Город или область доставки;\n— Метод доставки;\n— Адрес доставки;\n— Согласие с условием работы.\n\nПожалуйста, проверьте ещё раз заполнение необходимых полей и нажмите на кнопку отправить заказ. Если у Вас не получается отправить нам заказ — оформите Ваш заказ по телефону.\n\nИзвините за неудобства.");
	}
	else
	{
		$('#frmOrder').submit();
	}
}

function add_alternate(tov_id,depend_id)
{
	var tovrelationid = $('#tov_relation_id').val();
	if (tovrelationid)
	{
		$.post('/ajax_add_alternate.php', {tov_id: tov_id,tov_relation_id:tovrelationid,tovar_relation_depend_id:depend_id}, function(data) {
		  $('#additional_list').html(data);
		  $('#tov_relation_id').val('');
		  showAlert('Аксессуар был добавлен!');
		});
	}
}


function cancelReply()
{
	var rel = 0;
	$('.comment_reply_block').html('');
	$('.comment_reply_block').hide();
	$('#reply_'+rel).show();
	new_text = '<div id="reply_to_0" class="addcomment"><form id="sendComment" method="post"><div class="forms_name">Ваш отзыв:</div><div class="forms_inputs"><div><textarea id="comment_text" name="text"></textarea></div><div align="right" style="margin-top: 5px;"><input type="submit" id="submit" value="Отправить"></div></form><div class="clear"></div></div>';
	$('#reply_'+rel).html(new_text);
	bindBehaviors();
}

function show_comment(comment_id)
{
	var val = $('#commentvalue_'+comment_id).html();
	$('#commenttext_'+comment_id).html(val);
}

function logggin()
{
	$("#wishlistscreen").remove();
	showLoginScreen();
}

function show_all_review()
{
	if ($("#wishlistscreen").css("display") == undefined || $("#wishlistscreen").is(":hidden")) {
		$("body").append("<div id=\"closebg\"></div>");
		$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
		$('#wishlistscreen').empty();
		$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Показ всех отзывов</div>"+
			"Показ всех отзывов ограничен для незарегистрированных пользователей.<br /><br />"+
			"Для того, чтобы посмотреть все отзывы — <a style=\"text-decoration: none;\" class=\"dashed\" href=\"#do_login\" onclick=\"logggin()\">авторизируйтесь</a>, либо <a href=\"/registration/\">зарегистрируйтесь</a>.<br /><br />"+
			"Регистрация бесплатная и занимает ровно одну минуту. Зарегистрированные пользователи смогут выбрать необходимые музыкальные инструменты на основании 25 тысяч отзывов наших клиентов.");
		$("#wishlistscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"$('#wishlistscreen').remove();$('#closebg').remove();return false;\"></a></div>");

		$("#closebg").css("position","absolute").
			css("display","none").
			css("opacity",0.7).            
			css("z-index","10").
			css("width","100%").
			css("height",$("body").height()).
			css("top","0").
			css("left","0").
			css("background-color","#000").            
			show();   
			
		$("#wishlistscreen").
			css("position","fixed").
			css("top","50%").
			css("width","450px").
			css("margin-top","-125px").
			css("height","250px").
			css("left","50%").
			css("margin-left","-225px").
			css("z-index","15").
			show();
	} else {
		$("#wishlistscreen").remove();
	}    
	$(document).keydown(function(e){if(e.which == 27) { $("#wishlistscreen").remove(); $("#closebg").remove(); }});    
	return false;
};
