var advancer_tooltip = '';

var dummy_select_template = "<div style='position: relative;'>\
						<div class='dummy-select'></div>\
						<div><div class='inpunts_cont' style='z-index: 899;'><span class='select_value' style='width: 134px;'>выберите</span><input type='hidden' value='выберите' name=''><div class='inpunts' style='width: 145px;'><div class='left-input'><div class='right-input'><div class='fill-input'><div class='jScrollPaneContainer hidden' style='width: 159px;'><div class='select_list' style='width: 134px;'><div class='odd'><a val='выберите' class=' selected' href='javascript:void(0);'>выберите</a></div></div></div></div></div></div></div></div></div>\
					</div>";

$(document).ready(function()
{
	// контроль отзывов
	$('.send-review-for-book .send-button input').click(function(){
		var iam = $(this).closest('form');
		var no = false;
		iam.find('.input-switch-text').each(function(){
		
			if (!no)
				if (this.value==$(this).attr('switchtext'))
				{
					alert("Вы должны заполнить поле ''"+$(this).attr('switchtext')+"''");
					no = true;
				}
		});
		
		if (no) return false;
	});

	$('.search-result-table td').click(function(){
		document.location.href = $(this).find('a:first').attr('href');
		return false;
	});

	// верхинй банер на главной
	$('.right-part .banner').hover(function(){
		$(this).stop().animate({opacity: 0.6},250);
		$(this).animate({opacity: 1},250);
	},
	function()
	{
		$(this).stop().animate({opacity: 1},250);
	});

	// превьюшка в таблице каталога
	WbrHoverPreview('.search-result-table tr');

	// кастомизация под бескриптовых юзеров
	$('#header .head-find .aggr-select-block,#header .head-find .find-param .extended-s a').show();

	$('#index').click(function(e){
		if ($('.form-for-extended-search').length>0)
		{
			if (($(e.target).closest('.form-for-extended-search').length==0) && 
			($(e.target).closest('.castom-select .find-param .input').length==0))
			{
				$('.form-for-extended-search').remove();
				//return false;
			}
		}
		/*if ($('.popup-map-offer').length>0)
		{
			if ($(e.target).closest('.popup-map-offer').length==0)
			{
				$('.popup-map-offer').remove();
				//return false;
			}
		}*/
	});

	// флажок "в наличии"
	if ($('.search-result').length>0)
	{
		$('.search-result').append("<span class='is-in-available'><input type='checkbox' id='is-in-available'/>\
								<label for='is-in-available'>в наличии</label></span>");
								
		if ($('#content .upshadow').length==0)
			$('.search-result').prepend('<div style="height:20px;"></div>');
		
		if (document.location.href.indexOf('AVAILABLE=N')>=0)
			$('#is-in-available').get(0).checked=false;
		else
			$('#is-in-available').get(0).checked=true;
								
		// событие флажка в наличии
		//var isinavailable = $('.is-in-available').get(0).checked;			
	
		$('#is-in-available').click(function()
		{
			//if (document.location.href.indexOf('?debug')>0)
			//	alert('!');
			var i = document.location.href.indexOf('?debug');
			link_ = document.location.href;
			
			flag = this.checked;
			if (!flag)
			{	
				if (link_.indexOf('AVAILABLE=N')<0)
				{					
					if (link_.indexOf('?')<0)
						link_ = link_+'?AVAILABLE=N';
					else
						link_ = link_+'&AVAILABLE=N';
				}		
			}
			else
			{
				if (link_.indexOf('AVAILABLE=N')>=0)
				{
					link_ = (link_.split('AVAILABLE=N')).join('');
				}
			}
			document.location.href = link_;	
		});
		
		// выпадающий список сортировки	
		$('.search-result').css('position','relative');
		/*$('#content .search-result .sort-params').addClass('sort-params-script-select');
		//$('#content .search-result .sort-params .link:last').remove();
		$('#content .search-result .sort-params .link').hide();
		
		if ($('#content .search-result .sort-params .desc').length>0)
		{
			$('#content .search-result .sort-params .desc').parent().addClass('active');
		}
		if ($('#content .search-result .sort-params .asc').length>0)
		{
			$('#content .search-result .sort-params .asc').parent().addClass('active');
		}
		if ($('#content .search-result .sort-params .active').length==0)
			$('#content .search-result .sort-params .link:first').addClass('active');
			
		$('#content .search-result .sort-params .active').show();
		
		$('#content .search-result .sort-params a').click(function(){
			if ($('.advancer-search-tooltip').length>0)
			{
				$('.advancer-search-tooltip').remove();
				return false;
			}
		
			$('#index').prepend('<div class="advancer-search-tooltip">'+
				$('#content .search-result .sort-params').html()+
				'</div>');

			$('.advancer-search-tooltip .active').remove();
			$('.advancer-search-tooltip span:first').remove();
			$('.advancer-search-tooltip span').show();
			advancer_tooltip = $('.advancer-search-tooltip').html();
					
			$('.advancer-search-tooltip')
				.css('left',$(this).offset().left+'px')
				.css('top',$(this).offset().top+'px')
				.show();
				
			return false;
		});
		*/
	}
	// 	коррекция положения флажка "в наличии"
	function isavailable_correction()
	{
		if ($('.search-result').length>0)
		{
			if ($('.search-result').width()<700)
			{
				$('.is-in-available').addClass('is-in-available-offset');
				$('.switch-link').addClass('switch-link-offset');
			}
			else
			{
				$('.is-in-available').removeClass('is-in-available-offset');
				$('.switch-link').removeClass('switch-link-offset');
			}
		}
	}

	// галерея
	WbrLoadGallery('.sertificates-list li a,.news-detail .photos-list li a','#index');
	
	// для расширенного поиска заменяем кнопку в форме типа сабмит на просто буттон
	$('.head-find .castom-select .find-param .findbutton').remove();
	$('.head-find .castom-select .find-param .input').append('<input type="button" value="" title="Быстрый поиск" class="findbutton">');
	$('.head-find .castom-select .find-param .findbutton,.form-for-extended-search .submit').live('click',function(){
		$('.form-for-extended-search .inputs:first input').each(function(){
			value_ = $(this).attr("value");
			if (value_==$(this).attr('switchtext')) value_='';
			$('.head-find form').append('<input type="hidden" name="'+$(this).attr('name')+'" value="'+
			value_+'" />');
		});
		
		$('.form-for-extended-search .checkboxs input').each(function(){
			if (this.checked)
			{
				$('.head-find form').append('<input type="hidden" name="'+$(this).attr('name')+'" value="'+
					$(this).get(0).value+'" />');	
			}
		});
			
		$('.head-find form').submit();
	});
	
	// раскукоживаем верхнее меню
	WbrCallbackOfResize(true,function()
	{
		isavailable_correction(); // 	коррекция положения флажка "в наличии"
	
		w_ = $("#header").width()-487;
		// первое верхнее
		s_ = 0;
		$("#header .up-menu span").each(function(){
			s_ = s_+$(this).innerWidth();
		});
		offs_ = 0.5*(w_-s_)/$("#header .up-menu span").length;
		
		$("#header .up-menu").width(w_);
		$("#header .up-menu span").css("margin-left",offs_+'px');
		$("#header .up-menu span:last").css("margin-left",'0px');
		
		// нижнее верхнее
		s_ = 0;
		$("#header .bottom-menu span").each(function(){
			s_ = s_+$(this).innerWidth();
		});
		offs_ = 0.5*(w_-s_)/$("#header .bottom-menu span").length;
		
		$("#header .bottom-menu").width(w_);
		$("#header .bottom-menu span").css("margin-left",offs_+'px');
		$("#header .bottom-menu span:first").css("margin-left",'0px');
	});	
	
	// селекты
	if ($('.castom-select').length>0)
		$('.castom-select').jCastomSelect({maxheight: 250,istitle: true});
		
	// вакансии
	$('.vacancy-form .fields,.vacancy-form .submit').hide();
	$('.vacancy-select div a,.vacancy-form .elem .jScrollPaneContainer div a,.select-type-1 div a').click(function()
	{
		$(this).closest('.inpunts_cont').find('.select_value').css("color","#373737");
		$(this).closest('.inpunts').removeClass('act');
		$(this).closest('.jScrollPaneContainer').addClass('hidden');
	});
	$('.vacancy-form .select-type-1 .jScrollPaneContainer div a').click(function(){
		$('#vac_id').attr("value",$(this).attr("val"));
		$('.vacancy-requirements')
						.height($('.vacancy-requirements').height())
						.html('<img src="/import/i/sand.gif" />');
		$.get('/vacancies/detail.php',{ID: $(this).attr("val")},function(data)
		{
			$('.vacancy-requirements').after(data);
			$('.vacancy-requirements:first').remove();
			$('.vacancy-form .fields,.vacancy-form .submit').show();
		});
	});
		
	// фильтрация в шапке сайта
	$('#header .head-find .jScrollPaneContainer div a').live("click",function()
	{
		wait_html = '<p class="preloader"><img src="/import/i/sand.gif" /></p>';
		value_ = $(this).attr("val");
		base_addr = '/catalog/search.php?ID='+value_;
		//'/catalog/search/'+value_+'/mode/images/pages/1/sort/name/asc/';
		if ($(this).closest('.fl').attr("class").indexOf('select-4')<0) // посл. селект ниче не возвращает
		{
			if ($('#header .head-find .select-4').length==0)
				$('#header .head-find .aggr-select-block:last').append('<div class="fl select-4"></div>');
		
			if ($(this).closest('.fl').attr("class").indexOf('select-1')>-1)
			{//первый селект
				$('#header .head-find .select-4 *,#header .head-find .select-3 *,#header .head-find .select-2 *').remove();
				$('#header .head-find .select-2').html(wait_html);
				$.get('/nav_options.php',{PARENT_ID: value_},function(data)
				{
					$('#header .head-find .select-2').html('<select>'+data+'</select>');
					$('.castom-select').jCastomSelect({maxheight: 250,istitle: true});
					
					$('#header .head-find .select-3').html(dummy_select_template);
				});
			}
			if ($(this).closest('.fl').attr("class").indexOf('select-2')>-1)
			{//2 селект
				$('#header .head-find .select-4 *,#header .head-find .select-3 *').remove();
				$('#header .head-find .select-3').html(wait_html);
				$.get('/nav_options.php',{PARENT_ID: value_},function(data)
				{
					if (data.length<2) 
					{
						document.location.href = base_addr;
						return false;
					}
					else
						$('#header .head-find .select-4').html(dummy_select_template);

					$('#header .head-find .select-3').html('<select>'+data+'</select>');
					$('.castom-select').jCastomSelect({maxheight: 250,istitle: true});
				});
			}
			if ($(this).closest('.fl').attr("class").indexOf('select-3')>-1)
			{//3 селект
				$('#header .head-find .select-4 *').remove();
				$('#header .head-find .select-4').html(wait_html);
				$.get('/nav_options.php',{PARENT_ID: value_},function(data)
				{
					if (data.length<2) 
					{
						document.location.href = base_addr;
						return false;
					}

					$('#header .head-find .select-4').html('<select>'+data+'</select>');
					$('.castom-select').jCastomSelect({maxheight: 250,istitle: true});
				});
			}
		}
		else
		{
			//alert( );
			//location.replace('http://metida.webrover.ru'+base_addr);
			document.location.href = base_addr;
			return false;
		}
	});
	// расширенный поиск
	$('.head-find .select-block .extended-s a').click(function(){
		a_ = $(this);
		$.get($(this).attr("href"),function(data)
		{
			$('.form-for-extended-search').remove();
			$('#index').prepend(data);
			$('.form-for-extended-search').css("left",a_.offset().left-469+'px').css("top",a_.offset().top-7+'px');
			
			WbrSwitchesInputs('.input-switch-text','input-active');
			$('.form-for-extended-search').keydown(function(event) //  .input-switch-text
			{
				if (event.keyCode==27)
					$('.form-for-extended-search').remove();
					
				if (event.keyCode==13)
					$('.form-for-extended-search .submit').click();				
			});
			
			val_ = 1*$('.head-find .select-1 input').get(0).value;
			if (val_>0)
			{
				$('.form-for-extended-search .checkboxs input').get(0).checked=false;
			
				if (val_==2226)
					$('.form-for-extended-search .checkboxs input').get(0).checked=true;
			
				if (val_==2227)
					$('.form-for-extended-search .checkboxs input').get(1).checked=true;
					
				if (val_==2228)
					$('.form-for-extended-search .checkboxs input').get(2).checked=true;
					
				advanser_search_filter();
			}	
		});
		
		return false;
	});
	$('.form-for-extended-search .return-button u').live('click',function(){
		$('.form-for-extended-search').remove();
	});
	$('.form-for-extended-search .checkboxs input').live('change',function(){
		advanser_search_filter();
	});
	function advanser_search_filter()
	{
		$('.form-for-extended-search .inputs:first').html('');
		
		$('.form-for-extended-search .checkboxs input').each(function(){
			if (this.checked)
			{
				type = $(this).parent().find('label').attr("type");
				if ($('.form-for-extended-search .inputs:first input').length==0)
				{
					$('.form-for-extended-search .inputs:first')
						.html($('.form-for-extended-search .inputs[type="'+type+'"]').html());
						
					WbrSwitchesInputs('.form-for-extended-search .inputs:first .input-switch-text','input-active');					
				}
				else
				{
					$('.form-for-extended-search .inputs[type="'+type+'"] input').each(function(){
						thisname = $(this).attr("name");
						if ($('.form-for-extended-search .inputs:first input[name="'
							+thisname+'"]').length==0)
								$('.form-for-extended-search .inputs:first input[name="'
							+thisname+'"]').parent().parent().remove();
					});
					
					$('.form-for-extended-search .inputs:first input').each(function(){
						thisname = $(this).attr("name");
						if ($('.form-for-extended-search .inputs[type="'+type+'"] input[name="'
							+thisname+'"]').length==0)
								$('.form-for-extended-search .inputs:first input[name="'
							+thisname+'"]').parent().parent().remove();
					});
					
					//$('.form-for-extended-search .inputs:first 
				}				
			}
		});		
		$('.form-for-extended-search .input-switch-text').keydown(function(event)
		{
			if (event.keyCode==27)
				$('.form-for-extended-search').remove();
				
			if (event.keyCode==13)
					$('.form-for-extended-search .submit').click();	
		});
	}

	WbrSwitchesInputs('.input-switch-text','input-active');
	/*if ($('.send-review-for-book').length>0)
	{
		$('.send-review-for-book .send-button input').hide();
		$('.send-review-for-book .send-button u').show();
	}
	$('.send-review-for-book .send-button u').click(function()
	{
		$('.send-review-for-book form').get(0).submit();
	});*/

	// ie6 не переходит по ссылке внутри карусели , при клике на картинку
	if (WbrIsIE6)
	{
		$('.carousel_conteiner li a').click(function()
		{
			document.location.href = $(this).attr("href");
		});
	}

	$(".carousel_conteiner.mouseWheel").each(function()
	{
		$(this).wbrcarousel({is_new: true,is_revolver: false});
		$(this).wbrcarousel({margin: 44,is_revolver:false});
	});
	
	//$(window).resize(_setrisize());
	var pause_for_ie = 0;
	$(".carousel_conteiner .carousel-button").hide();
	$(".carousel_conteiner").hover(function()
	{
		if ($(this).attr("nocarousel")=='')
		{
			if (pause_for_ie!=0)
			{
				WbrResetPause(pause_for_ie);
				pause_for_ie = 0;
			}
			$(this).find(".carousel-button").show();
		}
	},
	function()
	{
		if (!$.browser.msie)
			$(this).find(".carousel-button").hide();
		else
		{		
			obj_ = $(this);
			pause_for_ie = WbrSleep(500,function()
			{
				obj_.find(".carousel-button").hide();
			});
		}
	});
	
	// отзывы для книги
	WbrAccordion('.send-review-for-book','.send-review-for-book h3 a','.list-of-reviews',true);
	
	// ездяящая подсветка в меню карусели
	$('.content-block,.search-result').each(function()
	{
		if ($(this).find('.upmenu span.selection').length>0)
		{
			if ( $(this).find('.upmenu span.active').length>0)
			{
				activeL = $(this).find('.upmenu span.active').offset().left-$(this).find('.upmenu').offset().left-7;
				$(this).find('.upmenu span.selection').css("left",activeL+'px').width($(this).find('.upmenu span.active').innerWidth());
			}
		}
	});
	var is_loading = false;
	$('.content-block .upmenu span a').live('click',function()
	{		
		// slider
		_this = $(this);
		if ($(this).parent().attr("class")=='active') return false;		
		if (is_loading) return false;
		is_loading = true;
		
		_this.parent().parent().find(".active").removeClass("active");
		
		activeL = $(this).parent().offset().left-$('.content-block .upmenu').offset().left-7;
		activeW = $(this).parent().innerWidth();
		
		var type_ = $(this).closest('.upmenu').attr("type");
		mainobj = $(this).closest('.content-block');
		
		mainobj.height(mainobj.height());
		mainobj.find('.carousel_conteiner').remove();
		mainobj.addClass('content-block-catalog-loading');
		
		path = '/carousels'+$(this).attr("href");

		
		$(this).parent().parent().find(".selection").animate({left: activeL,width: activeW},500,function()
		{
			_this.parent().addClass("active");
			//AJAX
			$.get(path,{ajax: 'Y',type: type_},function(data)
			{
				mainobj.html('<p class="h1">'+mainobj.find('p.h1').html()+'</p>'+data);
				mainobj.removeClass('content-block-catalog-loading');
				if (mainobj.find('.carousel li').length>0)
				{
					mainobj.find('.carousel_conteiner').wbrcarousel({is_new: true,is_revolver: false});
					mainobj.find('.carousel_conteiner').wbrcarousel({margin: 44,is_revolver:false});
				}				
				else
				{
					if (_this.text().indexOf('акции')<0)
						text_ = 'популярных товаров еще нет';
					else
						text_ = 'акции в данной категории не проводятся';
						
					mainobj.find('.carousel').html('<h3>'+text_+'</h3>');
					mainobj.find('.carousel-button').remove();
				}

				activeL = mainobj.find('.upmenu span.active').offset().left-mainobj.find('.upmenu').offset().left-7;
				mainobj.find('.upmenu span.selection').css("left",activeL+'px').width(mainobj.find('.upmenu span.active').innerWidth());

				is_loading = false;
			});

		});

		return false;
	});
	
	// выпрыгивающий баннер
	$('.right-part .slide-banner a').removeClass("no-script");
	$('.right-part .slide-banner a').hover(function()
	{
		$(this).find("img").stop().animate({top: 0},250);
	},
	function()
	{
		$(this).find("img").stop().animate({top: 20},250);
	});
	
	// карта "оставить заявку" или карта в магазине
	$('.about-book .cost-and-offer .offer a,.market-list .about-market .yamap a').click(function()
	{		
		// когда в наличии 0 - не выводим карту
		if ($(this).closest('.cost-and-offer').length>0)
		{
			if ($(this).html().indexOf('(0)')>-1) return false;
		}
		
		$("#index").prepend("<div class='wbr-gallery'>\
				<div class='blend'></div>\
				<div class='content'></div>\
			</div>");			
		$(".wbr-gallery").prepend('<div class="spinner"></div>');
			
			//$(".wbr-gallery").animate({opacity: 1},250);

			$(".wbr-gallery .blend").height($('#index').height());
			$(".wbr-gallery .blend").css("display","block").animate({opacity: 0.5},250);
			$(".wbr-gallery .blend").click(function(){
				$(".wbr-gallery").remove();
			});
			
			if ($.browser.msie && $.browser.version=='6.0')
				$(".wbr-gallery").height($('#index').height());
			
			$(".wbr-gallery").css("left","0");
		
		if ($('.about-book .book-photo img,.photo-of-market').length>0)
			_left = $(this).offset().left-400;
		else
			_left = $(this).offset().left+50;

		_top = $(this).offset().top+43;
		
		href_ = $(this).attr("href");
		ths = this;		
		
		if ($('.popup-map-offer').length>0)
		{
			$('.popup-map-offer').remove();
			return false;
		}
		$(this).hide();
		$(this).parent().append('<i>подождите...</i>');
		
	
		$.get(href_,function(data)
		{
			$(".wbr-gallery .spinner").remove();
		
			if ($.browser.msie)
				$(".wbr-gallery .content").animate({opacity: 1},1);
			
			$(".wbr-gallery .content").html(data);
			
			h_ = $(".wbr-gallery .content .popup-map-offer").height();
			w_ = $(".wbr-gallery .content .popup-map-offer").width();
			$(".wbr-gallery .content").css("margin",-h_/2+"px 0 0 -"+w_/2+"px");
			$(".wbr-gallery .content").height(h_);
			$(".wbr-gallery .content").width(w_);

			$(".wbr-gallery .content").css("left","50%");
			$(".wbr-gallery .content").css("cursor","default");
			$(".wbr-gallery").removeClass("loaded");
			
			$('.popup-map-offer .shop').hover(function()
			{
				$(this).addClass('shop-hovered');
			},
			function()
			{
				$(this).removeClass('shop-hovered');
			});
			$(ths).show();
			$(ths).parent().find('i').remove();
		});

		return false;
	});	
	
	//
	$('.market-list .elem .photo-of-market p span img').click(function()
	{
		_href = $(this).attr("photo");
		mainobj = $(this).closest(".photo-of-market");
		mainobj.find("img.active").removeClass("active");
		$(this).addClass("active");
		//mainobj.addClass('photo-of-market-loading');
		
		_rW = mainobj.find('img.big').width();
		_rH = mainobj.find('img.big').height();
		mainobj.find('img.big').remove();
		if (mainobj.find('.rasporka').length==0)
			mainobj.prepend('<div class="rasporka" style="width:'+_rW+'px; height:'+_rH+'px;"> </div>');

		mainobj.prepend('<img class="big" style="position:absolute;" src="'+_href+'"/>');
				
		/*var _func = function()
		{			
			//mainobj.find('img.big').attr("style","");
			//mainobj.find('div').remove();
			//mainobj.removeClass('photo-of-market-loading');
		}
		
		if (mainobj.find('img.big').height()>50)
		{
			_func();
		}
		else
		{
			//alert("!");
			mainobj.find('img.big').load(_func());
		}*/	
	});
	
	// отзывы о компании
	if ($('.upper-filter.switch-reviews').length>0)
	{
		$('.send-review-for-book').hide();
		
		$('.upper-filter.switch-reviews p:first a').live('click',function()
		{
			$('.send-review-for-book').hide();
			$('.list-of-reviews').show();
			$(this).parent().html('<span>'+$(this).text()+'<u></u></span>').addClass("active");

			$('.upper-filter.switch-reviews p:last').html('<a href="#write">'+
				$('.upper-filter.switch-reviews p:last').text()+'<u></u></a>').removeClass('active');
				
			return false;
		});
		$('.upper-filter.switch-reviews p:last a').live('click',function()
		{
			$('.send-review-for-book').show();
			$('.list-of-reviews').hide();
			$(this).parent().html('<span>'+$(this).text()+'<u></u></span>').addClass("active");

			$('.upper-filter.switch-reviews p:first').html('<a href="#list">'+
				$('.upper-filter.switch-reviews p:first').text()+'<u></u></a>').removeClass('active');

			return false;
		});
	}
	
	// вакансии - формируем поле загрузки файла
	if ($('.vacancy-form').length>0)
	{
		obj = $('.vacancy-form .fields .inputfile').parent();
		html_ = obj.html();
		obj.html("<div class='input'>\
				<i></i><b></b><u></u><s></s><div style='overflow:hidden'>\
				<span class='filename'>выберите файл</span>"
				+html_+'</div></div>');
				
		$('.vacancy-form .elem .input .inputfile').change(function()
		{
			var fname = String(this.value);
			if (fname=="") return false;
		
			var i = fname.lastIndexOf("\\");
			if (i>0)
			{
				fname = fname.substr(i+1);
			}
			
			if (fname.length>30)
				fname = fname.substr(0,25)+'...'+fname.substr(fname.length-4);
			
			$(this).parent().find(".filename").html(fname).css("color","#373737");
		});
		$('.vacancy-form .elem-last input')
								.attr("value","Введите код с картинки")
								.attr("switchtext","Введите код с картинки");
	}
	
	// костыли 
	if (WbrIsIE6)
	{
		$('.market-list .elem .photo-of-market p span img').hover(function()
		{
			if ($(this).attr("class")!='active')
				$(this).animate({opacity: 1},1);
		},
		function()
		{
			if ($(this).attr("class")!='active')
				$(this).animate({opacity: 0.4},1);
		});
	}
});
