$(document).ready(function () {	
	//Подгонка размеров сайта под размер фона (для очень длинных или очень высоких мониторов)
	param_width=1280;
	param_height=900;
	animate=0;	
	toWidth=getClientWidth();
	toHeight=getClientHeight();
	minWidth=744;
	minHeight=186+$("#left_menu").height();
	if(param_width<toWidth){toWidth=param_width; animate=1;}
	if(param_height<toHeight){toHeight=param_height; animate=1;}
	if(toWidth<minWidth){ toWidth=minWidth; animate=1;}
	if(toHeight<minHeight){ toHeight=minHeight; animate=1;}
	if(animate){ $("#main_block").animate({width: toWidth+"px", height: toHeight+"px"}, 1000); }

	//Анализ адресной строки
	analyzeUrl();
	
	//Делаем скроллер перетаскиваемым
	$("#arrows").draggable({ axis: 'y', containment: 'parent', 
	start: function(event, ui) { 
		//window.status='start';
	},
	drag: function(event, ui) { 
		contentTop=-Math.ceil(1.2*ui.position.top*cH/bH);
		$("#innerText").css("top", contentTop+"px");
		//window.status=contentTop;
	},
	stop: function(event, ui) { 
		text='';
		for ( var i in ui.position.top )
		{
			text+=','+i;
		} 
		//alert(ui.position.top);
		//window.status='stop';
		
		
	}
	});

	//adding the event listerner for Mozilla
	if(window.addEventListener)
		document.addEventListener('DOMMouseScroll', moveObject, false);
	//for IE/OPERA etc
	document.onmousewheel = moveObject;
	
	$("a[rel^='prettyPhoto']").prettyPhoto();
	
});





function moveObject(event)
{
    var delta = 0; 
    if (!event) event = window.event; 
    // normalize the delta
    if (event.wheelDelta) { 
        // IE and Opera
        delta = event.wheelDelta ; 
    } else if (event.detail) { 
        // W3C
        delta = -event.detail ;
    }
     
	if(delta>0)
	{
		moveText("down");
	}
	else
	{
		moveText("up")
	}
}


function moveText(direction)
{
	if(cH>0)
	{
		if(cH>bH)
		{
			step=15;
			if(direction=="down") {	step=-1*step;}
			topPos=parseInt($("#arrows").css("top"))+step;
			if(topPos<0){topPos=0;}
			else if((topPos+pH)>bH){ topPos=bH-pH;}
			contentTop=-Math.ceil(1.2*topPos*cH/bH);
			$("#innerText").css("top", contentTop+"px");
			$("#arrows").css("top", topPos+"px");
		}
	}	
}


var cH=0;   //высота содержимого
var bH=0;   //высота контейнера для содержимого
var pH=0;   //Высота ползунка

$(window).bind('resize', 
	function() {
      resizeContent();
});


//Определение размеров рабочей области экрана
function getClientHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

function getClientWidth()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}



//-----------------------initialization of lists
var dropDownStates=new Array();

function listsInit()
{
	$(".dropdownText").each(
		function (i) 
		{
			//$(this).wrap("<div class='dropdownText' id='ddText_"+i+"'></div>");		
			$(this).html("<div class='dropdownText' id='ddText_"+i+"'>"+$(this).html()+"</div>");
			$("#ddText_"+i).hide();
		}
	);
	
	
	$(".dropdownCaption").each(
		function (i) 
		{
			dropDownStates[i]=0;
			$(this).attr("id","ddCaption_"+i);
			$(this).click(function(){
				hlDropDown(i, "ddCaption_"+i, "ddText_"+i)
			});			
		}
	);	
}
	
function hlDropDown(i, id, textId)
{
	if(dropDownStates[i])
	{
		$("#"+id).attr("class", "dropdownCaption");
	}
	else
	{
		$("#"+id).attr("class", "dropdownCaptionActive");		
	}
	$("#"+textId).slideToggle("slow");	
	dropDownStates[i]=1-dropDownStates[i];
}



	
//----------------PNG FIX---------------------
function bgFixPng() {
	if(is_ie6)
	{			
		$("div").each(function () {
			obgFixPng($(this));
		});		
	}
}

function obgFixPng(obj)
{		
	obj=$("#"+obj);	
	if(is_ie6)
	{
		var bg  = obj.css("background-image");				
		if(bg)
		{		
			if(bg.length)
			{
				var src = bg.substring(5, bg.length-2);
				var sizingMethod = (obj.css("background-repeat") == "no-repeat") ? "crop" : "scale";
				obj.css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + sizingMethod + "')");
				obj.css("background-image","url("+base_url+"public/css/pngfix.gif)");	
			}
		}		
	}	
	
}
//----------------------------------------	
	
//Функция подсветки пунктов меню
function mainmenu_hl(id, state)
{
	menuItem=$("#mainmenudiv_"+id);
	linkItme=$("#mainmenulink_"+id);
	menuClass=menuItem.attr("class");
	
	if(menuClass!="active_menu_container")
	{
		if(state)
		{
			menuItem.attr("class","highlighted_menu_container");
			linkItme.attr("class","highlighted_menu_link");
			//menuItem.css("background-color","#033");
		}
		else
		{
			menuItem.attr("class","passive_menu_container");
			linkItme.attr("class","passive_menu_link");
			//menuItem.css("background-color","#fff");
		}
	}
}

//--------------------------------------------AJAX
var selectedLink="-1";
var selectedDiv="-1";
var selectedLinkClass="-1";
var selectedDivClass="-1";

var menu_id="-1";
var menu_source="-1";


function nHlTooltip(id, state)
{
	if(state)
	{
		$("#nSubProd"+id).show();
		//$("#nProdName"+id).css("background-color","#ddac67");
	}
	else
	{
		$("#nSubProd"+id).hide();
		//$("#nProdName"+id).css("background-color","none");
	}
}


var nQ='';
function nQuery(q)
{
	nQ=q;
	
	//alert(q);
	
	//Подсветка нужного пункта меню
	hlMenu(-1, 2);
	hideScroller();	
	
	if(pannelstate==1)
	{
		nLoadData();
	}
	else
	{
		//Показать информационную панель и разблуриваем фон
		nShowPannel();
	}	
}



function nTurnPannel(num)
{
	
	if(num==1)
	{
		$("#nCatList").show();
		$("#nProdList").hide();
		$("#nBut1").attr("class","nButtonAct");
		$("#nBut2").attr("class","nButtonPas");
	}
	else
	{
		$("#nCatList").hide();
		$("#nProdList").show();	
		$("#nBut2").attr("class","nButtonAct");
		$("#nBut1").attr("class","nButtonPas");
	}
}

var nOldCat=-1
function nSelectCatalog(id)
{
	if(nOldCat!=id)
	{
		if(nOldCat>=0)
		{
			$("#nCat"+nOldCat).slideUp();
			//$("#nCat"+nOldCat).fadeOut();
		}
		$("#nCat"+id).slideDown();
		//$("#nCat"+id).fadeIn();
		nOldCat=id;	
	}
}


//Функция вызывается при клике на любой из пунктов меню
function selectMenu(id, source)
{
	menu_id=id;
	menu_source=source;
	
	//Подсветка нужного пункта меню
	hlMenu(id, source)
	hideScroller();	
	if(pannelstate==1)
	{
		loadData();
	}
	else
	{
		//Показать информационную панель и разблуриваем фон
		showPannel();
	}
}


//Отправляет Ajax-запрос на сервер и обновляет данные на страничке
function nLoadData()
{
	$("#preloader").css("display","block");
	$("#innerText").css("visibility","hidden");
	
	ajax_url=base_url+"page/ajax/catalog/"+nQ+"/";
	
	document.location=base_url+'#'+nQ;
	
	$.ajax({
		type: "GET",
		url: ajax_url,
		data: "",
		success: function(msg){
			msg=eval('('+msg+')');
			$("#preloader").css("display","none");
			$("#innerText").css("visibility","visible");
			document.title=msg["title"];
			$("#innerText").html(msg["content"]);			
			
			$("a[rel^='prettyPhoto']").prettyPhoto();
			
			containerH=parsePx($("#srollerBlock").height());
			contentH=parsePx($("#innerText").height());
			cH=contentH;
			bH=containerH;
			$("#innerText").css("top","0px");
			$("#arrows").css("top","0px");
			if(containerH<contentH)
			{
				//Расчёт высоты ползунка
				calculatePolzunokH();
				showScroller();
			}
		}
	});

}



//Отправляет Ajax-запрос на сервер и обновляет данные на страничке
function loadData()
{
	$("#preloader").css("display","block");
	$("#innerText").css("visibility","hidden");
	
	if(menu_source==1)
	{
		ajax_url=base_url+"page/ajax/"+menu_id+"/";
	}
	else
	{
		ajax_url=base_url+"page/ajax/catalog/"+menu_id+"/";
	}
	
	$.ajax({
		type: "GET",
		url: ajax_url,
		data: "",
		success: function(msg){
			msg=eval('('+msg+')');
			$("#preloader").css("display","none");
			$("#innerText").css("visibility","visible");
			document.title=msg["title"];
			$("#innerText").html(msg["content"]);			
			
			$("a[rel^='prettyPhoto']").prettyPhoto();
			
			containerH=parsePx($("#srollerBlock").height());
			contentH=parsePx($("#innerText").height());
			cH=contentH;
			bH=containerH;
			$("#innerText").css("top","0px");
			$("#arrows").css("top","0px");
			if(containerH<contentH)
			{
				//Расчёт высоты ползунка
				calculatePolzunokH();
				showScroller();
			}
		}
	});

}


function parsePx(px)
{
	px=parseInt(px);
	return px;
}


//Функция подсвечивающая активный пункт меню и гасящая пассивный пункт меню
function hlMenu(id, source)
{
	if(source==1)
	{
		divPrefix='mainmenudiv_';
		linkPrefix='mainmenulink_';
		activeDivClass='active_menu_container';
		passiveDivClass='passive_menu_container';
		activeLinkClass='active_menu_link';
		passiveLinkClass='passive_menu_link';			
	}
	else
	{
		divPrefix='catdiv_';
		linkPrefix='catlink_';
		activeDivClass='cat_div_active';
		passiveDivClass='cat_div';
		activeLinkClass='cat_link_active';
		passiveLinkClass='cat_link';		
	}
	
	if((linkPrefix+id)!=selectedLink)
	{
		
		
		//document.location=base_url+'#'+id;
		
		$('#'+divPrefix+id).attr("class", activeDivClass);
		$('#'+linkPrefix+id).attr("class", activeLinkClass);
		if(selectedLink!="-1")
		{
			$('#'+selectedDiv).attr("class", selectedDivClass);
			$('#'+selectedLink).attr("class", selectedLinkClass);
		}
		selectedLink=linkPrefix+id;
		selectedDiv=divPrefix+id;
		selectedLinkClass=passiveLinkClass;
		selectedDivClass=passiveDivClass;		
	}
}

var pannelstate=0;

//Функция, показывающая информационную панель
function showPannel()
{
		$("#allcontent").css("display","block");
		$("#innerText").html('&nbsp;');
		$("#allcontent").animate({left: "0px"}, 1500,  
		function(){
			//toHeight=getClientHeight()-220;
			toHeight=$("#main_block").height()-220;
			$("#contentblock").animate({ 
				height: toHeight        
			}, 1500, 
			function(){
				$("#preloader").css("margin-top", Math.floor($("#srollerBlock").height()/2-40)+"px");
				//Замена фона
				if($("#main_block2").css("background-image")!='url('+bg_blur+')')
				{$("#main_block2").css("background-image","url("+bg_blur+")");}
				pannelstate=1;
				loadData();
			});
		});		
}


//Функция, показывающая информационную панель
function nShowPannel()
{
		$("#allcontent").css("display","block");
		$("#innerText").html('&nbsp;');
		$("#allcontent").animate({left: "0px"}, 1500,  
		function(){
			//toHeight=getClientHeight()-220;
			toHeight=$("#main_block").height()-220;
			$("#contentblock").animate({ 
				height: toHeight        
			}, 1500, 
			function(){
				$("#preloader").css("margin-top", Math.floor($("#srollerBlock").height()/2-40)+"px");
				//Замена фона
				if($("#main_block2").css("background-image")!='url('+bg_blur+')')
				{$("#main_block2").css("background-image","url("+bg_blur+")");}
				pannelstate=1;
				nLoadData();
			});
		});		
}

//Функция анализирует УРЛ на предмет наличия якорей и при их нахождении загружает нужную страничку
function analyzeUrl()
{
	locator=document.location.href;
	pos=locator.indexOf("#");
	if(pos>0)
	{
		locator=locator.substring(pos+1, locator.length);
		source=1;
		if(parseInt(locator))
		{
			source=0;
		}
		
		if(locator.indexOf(".")>0)
		{
		}
		else
		{
			selectMenu(locator, source);
		}
	}
}

function resizeContent()
{
	hideScroller();	
	resizeDocument();
	//toHeight=getClientHeight()-220;
	toHeight=$("#main_block").height()-220;
	$("#contentblock").animate({ 
		height: toHeight        
	}, 500, 
	function (){
		//$("#preloader").css("margin-top", (Math.floor($("#main_block").height()/2-40))+"px");
		containerH=parsePx($("#srollerBlock").css("height"));
		contentH=parsePx($("#innerText").css("height"));
		cH=contentH;
		bH=containerH;
		$("#innerText").css("top","0px");
		$("#arrows").css("top","0px");
		if(containerH<contentH)
		{
			calculatePolzunokH();
			showScroller();
		}
		resizeDocument();
		$("#preloader").css("margin-top", Math.floor($("#srollerBlock").height()/2-40)+"px");
	});
	
}


function hideScroller()
{
	$("#scroller").css("display","none");
}

function showScroller()
{
	$("#scroller").css("height", ($("#main_block").height()-232)+"px");
	$("#scroller").css("display","block");
}

function calculatePolzunokH()
{
	polzunokH=Math.floor(containerH*containerH/contentH);
	if(polzunokH<42){polzunokH=42}
	pH=polzunokH;
	$("#arrows").css("height", polzunokH + "px");
}

function resizeDocument()
{
	//Подгонка размеров сайта под размер фона (для очень длинных или очень высоких мониторов)
	param_width=1280;
	param_height=900;
	
	minWidth=744;
	minHeight=186+$("#left_menu").height();
	
	toWidth=getClientWidth();
	toHeight=getClientHeight();		
	if(param_width<toWidth){toWidth=param_width; }
	if(param_height<toHeight){toHeight=param_height; }	
	
	if(toWidth<minWidth){ toWidth=minWidth;}
	if(toHeight<minHeight){ toHeight=minHeight;}
	//$("#main_block").animate({width: toWidth+"px", height: toHeight+"px"}, 1000);	
	$("#main_block").css("width", toWidth+"px")
	$("#main_block").css("height", toHeight+"px");	
}
