var begin_height;
var block_height = 4.5;
var filterINI = false;
var filterButtonINI = false;

function showPagePreloader(){preloaderTitle='Загрузка...';document.title=preloaderTitle;}
function settitle(title){document.title=title+'';}

function nextPage(obj)
{
	if (!$.browser.msie)
	{	
		var textBlock = "";
		var rightside = "";
		
		var className = $.trim($(obj).attr("class"));
		var relName = $(obj).attr("rel");
		
		var url = $(obj).attr("href");
		var reg = /firms|#/;
		r = reg.test(url);
		
		if (!r && relName!='nofollow' && url!="javascript:;" && className!='highslide' && className!='ext' && className!='stuffHref' && className!='adm_edit_link2 cboxElement' && className!='adm_edit_link' && className!='firmLinkToWeb')
		{
			$(document).scrollTop(0);
			$('.textBlock').html("<div class='loader'>Подождите идет загрузка данных с сервера...</div>");
			showPagePreloader();
			
			$.get(url, function(data)
			{				
				if (className!='filterSubmit')
					history.pushState(null,null,url);
				
				
				var textBlock = $(data).find(".textBlock").html();
				var rightside = $(data).find(".rightside").html();
				//так как я не знаю в чем косяк... а он есть - то покашто кастыль:
				if(rightside === null)
					$(data).each(function(i,d){if($(d).hasClass('rightside')) rightside = $(d).html()});
				
				re = /<title>(.*)<\/title>/i
				found = data.match(re);
				var pageTitle = found[1];
				if (pageTitle=='') settitle(''); else settitle(pageTitle);

				$('.textBlock').html(textBlock);
				
				if (className!='filterSubmit')
				{
					$('.rightside').html(rightside);
					getFilterUl();
				}
				iniPage();
				
				if (filterINI==false) 
				{
					getFilterpanelHeight(0);
					
				}
				//alert(pageTitle);
			});
			return false;
		}
	} else return true;
}

function iniPage()
{
/////////////////////////////////////////////
(function(jQuery) {
jQuery(function() {

  jQuery('ul.tabs-noajax').delegate('li:not(.current2)', 'click', function() {
    jQuery(this).addClass('current2').siblings().removeClass('current2')
      .parents('div.section').find('div.box').hide().eq(jQuery(this).index()).fadeIn(150);
  })

})
})(jQuery)



/////////////////////////////////////////////////////////////////////
	if ($("#brandCarousel").length) $("#brandCarousel").jcarousel();
	if ($("#stuffCarousel").length) $("#stuffCarousel").jcarousel();
	
	var catid = 255;
	if($('#catid').length)
		catid = $('#catid').val();
		
	var catAll = 36;
	if($('#catAll').length)
		catAll = $('#catAll').val();
	
	if ($("#paginator").length)
		paginator_example = new Paginator ("paginator", catAll, 5, 1, "#city=all&catid=" + catid + "&pageid=%page%");
	
	
	$(".textBlock a").click(function(){ return nextPage(this);});

	if ($(".stuffItem").length) $(".stuffItem tr:even td").css("background", "#F2F2F2");
	
	$(".stuffHref").click(function()
	{
		$(".jcarousel-skin-tango").hide();
		var stuffHref = $(this).attr('href');
		$('#CardViewBlock').html("<div class='loader'>Подождите идет загрузка данных с сервера...</div>");
		// alert(stuffHref);
		
		$.get("/"+stuffHref, function(data)
		{
			var parseData = $(data).find(".parseInfo").html();
			$('#CardViewBlock').html('<div class="parseDataPadding">'+parseData+'</div>');
		});
		
		$(".filterTitle").html("Список товар");
		return false;
	});
	if($(".brandHref").length)
	{
		$(".brandHref").click(function()
		{
			$(".jcarousel-skin-tango").hide();
			$('#CardViewBlock').html("<div class='loader'>Подождите идет загрузка данных с сервера...</div>");
			var brandHref = $(this).attr("id");
			
			$.get("/index.php?id=1173&docid="+brandHref ,function(data)
			{
				//alert(data);
				$('#CardViewBlock').html(data);				
			});
			
			$(".filterTitle").html("Список брендов");
			return false;
		});
	}


	if ($(".filterTitleOrderA").length)
		$(".filterTitleOrderA").colorbox({iframe:true, innerWidth:425, innerHeight:344});

	reloadWordStat = function()
	{		
		$.get('/index.php?id=1111&nocach='+Math.random(), function(data)
		{
			if (data.length>5)
			{
				var wordStat = $("#wordStat").html();
				var lastText = $("#wordStat div:first").html();			
				exp = data.split("^#^");
				
				if (lastText!=exp[1])
				{
					$("#wordStat").html("<div style='display:none;' class='"+exp[0]+"'>"+exp[1]+"</div>"+wordStat);
					$("#wordStat div:hidden").slideDown();
				}
			}
		});
	}
	
	// setInterval(reloadWordStat, 5000);
	
	/* TEST */
	$(".wordStatTest").click(function()
	{
			
		return false;		
	});
	/* TEST	*/	
	

	reloadMap = function(x, y, adress, obj, img, name)
	{
		$("div.cols div.address a").attr("class", "");
		$(obj).attr("class", "bLink");
		
		$("#YMapsID2").css("width", "100%");
		$("#YMapsID2").css("height", "319px");		

		// Создание экземпляра карты и его привязка к созданному контейнеру
		var map = new YMaps.Map(YMaps.jQuery("#YMapsID2")[0]);

		// Установка для карты ее центра и масштаба
		map.setCenter(new YMaps.GeoPoint(x, y), 16);

		if (img!='')
		{
			var placemark = new YMaps.Placemark(new YMaps.GeoPoint(x, y));
			placemark.name = "<table width='400'><tr><td><img style='padding-right:10px;' src='"+img+"' /></td><td>"+name+"<br /><br /><p style='font-weight:normal;'>"+adress+"</p></td></tr></table>";
			map.addOverlay(placemark);
			placemark.openBalloon();
		}
		else
		{
			map.openBalloon(new YMaps.GeoPoint(x, y), adress);
		}
		// Добавление элементов управления
		map.addControl(new YMaps.ToolBar());
		map.addControl(new YMaps.Zoom());
		
		return false;
	}

	if ($('.companyTabs a').length)
	{
		$('.companyTabs a').click(function(){
			if(!$(this).is('.current')){
				var indexNumber = $('a', $(this).parent('.companyTabs')).index(this);
				var currentContent = $($(document).find('div.tabContent').get(indexNumber));
				$(this).siblings('a').removeClass('current');
				$(this).addClass('current');
				$('.tabContentCurrent').removeClass('tabContentCurrent');
				currentContent.addClass('tabContentCurrent');
			}
			return false;
		})
	}

	if ($(".screenshot[title]").length)
		$(".screenshot[title]").tooltip();

	$('.leftMenu ul ul').prev('a').click(function(){
		$(this).parent('li').toggleClass('active');
		return false;
	})
	
	$(".search_field").click(function()
	{
		$(this).attr("value", "");
	});
	
	//$("#tabs").tabs();
	
	$("#tabs").tabs({
		select: function(event, ui) { 
			if(ui.index == 2)
			{
				$("#reloadContent").html("<div class='loader'>Подождите идет загрузка данных с сервера...</div>");
				$.get("http://www.vrsamara.ru/catalog", function(data)
				{
					var oldText = $("#reloadContent").html();
					var parse = $(data).find("#parseContent").html();
					
					if (parse!='')
						$("#reloadContent").html(parse);
					else
						$("#reloadContent").html(oldText);
				});
				return false;
			}
		}
	});
	

	$('#quantity').change(function()
	{
		if ($(this).val()!='')
		{
			window.location = $('#src_quantity').val() + '&quantity=' + $(this).val();					
		}
	});

	if (document.getElementById('annotation_show'))
	{
		begin_height = document.getElementById('annotation_show').clientHeight;
	}
	
	if(begin_height > block_height) {
		$('#annotation_show').css({height:block_height+"em"});
	
		$('#show_link').click(function(){
			$('#annotation_show').animate({
				height:begin_height
			});
			
			$(this).hide();
			$("#hide_link").show();
		});
	
		$('#hide_link').click(function(){
			$('#annotation_show').animate({
				height:block_height+"em"
			});
		
			$(this).hide();
			$('#show_link').show();
		});
	}
	else {		
		$("#show_link").css("display", "none");		
	}
	
	$('.filter .item > span').click(function(){
		if(!$(this).parent().is('.active')){
			$(this).parent('.item').siblings('.item.active').find('.popup').fadeOut(200);
			$(this).next('.popup').fadeIn(200);
			$(this).parent('.item').siblings().removeClass('active');
			$(this).parent('.item').addClass('active');
		}
	});
	var _timer = null;
	$('.filter .popup').hover(function(){
		clearTimeout(_timer);
	},function(){
		var _this = this;
		_timer = setTimeout(function () {
			$(_this).fadeOut(200);
			$(_this).parent('.item').removeClass('active');
		}, 700);
	});
	
	if($.browser.msie && $.browser.version == 6){
		DD_belatedPNG.fix('.title1, .title2, .title3, .btn, .btn span, .leftMenu li.current, .main .title, .main .titleInside, .main .titleInside2, .icon img, .links a');
		DD_belatedPNG.fix('.footer img, .catalog_head_lnk img, .category_icon img, .footer_copyright a img, .footer_center, .footer_link');
	};
	
	if ($(".adm_edit_link").length)
		$(".adm_edit_link").colorbox({width:"800px", height:"100%", iframe:true});
		
	if ($(".stuff_full").length)
		$(".stuff_full").colorbox({width:"800px", height:"500px", iframe:true});	
	
	if ($(".adm_edit_link2").length)
		$(".adm_edit_link2").colorbox({width:"800px", height:"100%", iframe:true});
	
	$("#adm_save_btn").click(function(){
		$(this).html("<span>Сохранение...</span>");		
	});
	
	pagin_reload = function(href)
	{
		if ($(".jcarousel-skin-tango").length) $(".jcarousel-skin-tango").show();
		$(".filterTitle").html("Список компаний");
		document_href = $(location).attr('href');
		dh = document_href.split("#");
		document_href = dh[0];
		$(location).attr('href', document_href + '#Firm');
		
		$('#CardViewBlock').html("<div class='loader'>Подождите идет загрузка данных с сервера...</div>");
		var exp = href.split("#");		
		
		$.get("/index.php?id=638&"+exp[1], function(data)
		{
			$('#CardViewBlock').html(data);
		});		
		
		return false;
	}
	
	$('div.popupContent a').click(function()
	{
		$('div.popupContent a').attr("class", "normal");
		$(this).attr("class", "bold");
		$('.filter .popup').hide();
		$('#CardViewBlock').html("<div class='loader'>Подождите идет загрузка данных с сервера...</div>");
		
		var href = $(this).attr("href");
		var exp = href.split("#");		
		
		$.get("/index.php?id=638&"+exp[1], function(data)
		{			
			$('#CardViewBlock').html(data);
		});
		
		return false;
	});
		
	$("ul.adm_category li a").click(function()
	{
		var obj = $(this).next(".adm_sub_category");
		var css = $(obj).css("display");
		
		if (css=='none') obj.show();
		else obj.hide();
	});
	
	$('.details').click(function(){
		if($(this).prev('.block_1').find('.hidden').is(':visible'))
		{
			$(this).prev('.block_1').find('.hidden').slideUp(200);
			$(this).html('<span>Читать полностью</span> &darr;');
		}
		else
		{
			$(this).prev('.block_1').find('.hidden').slideDown(200);
			$(this).html('<span>Скрыть</span> &uarr;');
		}
		return false;
	});
	
	if ($(".mainpage_category_btn").length)
		$(".mainpage_category_btn").tooltip({position: 'bottom center', offset:[-58,-400]});
	
	$('.filter_2 ul li').hover(function(){
		$(this).find('.submenu').show();
		$(this).addClass('submenuHover');
	},function(){
		$(this).find('.submenu').hide();
		$(this).removeClass('submenuHover');
	});
	
	savePos = function(cardid, catid, posid, obj)
	{		
		ClassName = $(obj).attr("class");
		$("#"+ClassName+"HTML").html("<img src='/i/ajax_img/38-0.gif' /> Сохранение...");
		
		pos = $("#"+ClassName).val();		
		$.get("/index.php?id=845&pos="+pos+"&posid="+posid+"&cardid="+cardid+"&catid="+catid, function(data)
		{
			if (data=="ok")
			{
				$("#"+ClassName+"HTML").html("<span style='color:green'><b>Сохранено</b></span> (Для обновления нажмите <b>Ctrl+F5</b>)");
			}
			else
			{
				$("#"+ClassName+"HTML").html(data);
			}
		});
		
	}
	
	$("#fil_title a").click(function()
	{
		dsp = $(this).next("#fill_descr").css("display");
		exp = $(this).attr("class").split("_");	
		
		if (dsp=='none')
		{	
			$(this).css("color", "#EBAC15");
			$(this).next("#fill_descr").show();
			eval("showMap_"+exp[1]+"();");
		}
		else
		{
			$(this).css("color", "#0071D1");
			$(this).next("#fill_descr").hide();
		}
	});
	
	if (filterINI==false)
	{
		getFilterpanelHeight(0);
		getFilterUl();
	}
}

function getFilterpanelHeight(integer)
{
	filterINI = true;
	var filterPanelH = $(".filterPanel").css('height');
	filterPanelH = parseInt(filterPanelH) + integer;
	$(".filterPanelHeight").css('height', filterPanelH+"px");
	// alert($(".filterPanelHeight").css('height'));
}

function getFilterUl()
{
	if ($(".filterOption").length)
	{
		getFilterpanelHeight(30);		
		$(".filterOption").click(function()
		{
			var ulId = $(this).attr('id');
			
			if ($("ul#"+ulId).css("display")=='none')
				$(this).addClass("active");
			else
				$(this).removeClass("active");
			$("ul#"+ulId).toggle();
			
			getFilterpanelHeight(0);
			
			return false;
		});
	}
}

function getFilterButtonClick(obj)
{
	var filterLink = "";
	$(".formFilter ul").each(function(i)
	{
		var subLink = "";
		var ulID = $(this).attr('id');
		
		$("ul#"+ulID+" input[type='checkbox']:checked").each(function(i2)
		{
			if ( ($("ul#"+ulID+" input[type='checkbox']:checked").length-1) == i2 )
				subLink = subLink + $(this).val();
			else
				subLink = subLink + $(this).val() + "|";
		});
		
		if ( subLink!='' && filterLink!='' ) filterLink = filterLink + "," + subLink;
		if ( subLink!='' && filterLink=='' ) filterLink = subLink;				
	})
	
	docLocation = document.location.pathname;
	$(obj).attr("href", docLocation+"?filters="+filterLink);
	nextPage(obj);
	$(obj).attr("href", "#");
	return false;
}

$(document).ready(function()
{
	iniPage();		
	$(window).scroll(function()
	{
		//$("title").html($(document).scrollTop());
		if ($(document).scrollTop()>=140)
			$(".filterPanel").addClass('filterPanelfixed');
		else
			$(".filterPanel").removeClass('filterPanelfixed');		
	});
	
	if ($('.main .title .tab a').length)
	$('.main .title .tab a').click(function(){
		if(!$(this).parent().is('.current')){
			var tabIndex = $(this).parent().index('.tab');
			$(this).parent().siblings().removeClass('current');
			$(this).parent().addClass('current');
			$('.newsBlock.tabInfo.active').removeClass('active');
			$($('.newsBlock.tabInfo').get(tabIndex)).addClass('active');
		}
		return false;
	})
});

//Когда вы нажмете на ссылку с классом poplight и HREF начинается с a #
jQuery('a.poplight[href^=#]').click(function() {
var popID = jQuery(this).attr('rel'); //Get Popup Name
var popURL = jQuery(this).attr('href'); //Получить Popup HREF и определить размер
//Запрос и Переменные от HREF URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Возвращает первое значение строки запроса
// Добавить кнопку "Закрыть" в наше окно, прописываете прямой путь к картинке
jQuery('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"><img src="close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');
//Определяет запас на выравнивание по центру (по вертикали по горизонтали)мы добавим 80px к высоте / ширине, значение полей вокруг содержимого (padding) и ширину границы устанавливаем в CSS
var popMargTop = (jQuery('#' + popID).height() + 80) / 2;
var popMargLeft = (jQuery('#' + popID).width() + 80) / 2;
//Устанавливает величину отступа на Popup
jQuery('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
jQuery('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
jQuery('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Постепенное исчезание слоя - .css({'filter' : 'alpha(opacity=80)'}) используется для фиксации в IE , фильтр для устранения бага тупого IE
return false;
});
//Закрыть всплывающие окна и Fade слой
jQuery('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
jQuery('#fade , .popup_block').fadeOut(function() {
jQuery('#fade, a.close').remove(); //fade them both out
});
return false;
});

jQuery(document).ready(function(){
						   		   
	//When you click on a link with class of poplight and the href starts with a # 
	jQuery('a.poplight[href^=#]').live('click', function() {
		var popID = jQuery(this).attr('rel'); //Get Popup Name
		var popURL = jQuery(this).attr('href'); //Get Popup href to define size
				
		//Pull Query & Variables from href URL
		var query= popURL.split('?');
		var dim= query[1].split('&');
		var popWidth = dim[0].split('=')[1]; //Gets the first query string value
 
		//Fade in the Popup and add close button
		jQuery('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"><img src="images/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');
		
		//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
		var popMargTop = (jQuery('#' + popID).height() + 80) / 2;
		var popMargLeft = (jQuery('#' + popID).width() + 80) / 2;
		
		//Apply Margin to Popup
		jQuery('#' + popID).css({ 
			'margin-top' : -popMargTop,
			'margin-left' : -popMargLeft
		});
		
		//Fade in Background
		jQuery('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
		jQuery('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer 
		
		return false;
	});
	
	
	//Close Popups and Fade Layer
	jQuery('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
	  	jQuery('#fade , .popup_block').fadeOut(function() {
			jQuery('#fade, a.close').remove();  
	}); //fade them both out
		
		return false;
	});
 
	
});





