jQuery(window).load(function(){
	currentLocation = window.location.toString();
	// ================================================ BROWSER DETECTION
	
	if ( $.browser.msie && parseInt($.browser.version)<7 ) {
		$("body").empty();
		$("body").html("<div style='width: 100%; text-align: center; margin-top: 100px'>Sorry but your browser is not supported.</div>");
	}
	
	// ==================================================================
	
	var galPos = 0; // currently viewed gallery item
	var menuWidths = [ 224 , 360 , 455 , 550 ];
	var currentLevel = 1;
	var currentItem = 1;
	var curHorizontal = "";
	var json;
	var horJSON;
	var imgJSON = {};
	var horizontalMenuGeneretedOnLevel = 0;
	var horizontalMenuItem = 0;
	var curGallery = 0;
	var textBoxGenerationMenu;
	var textBoxGenerationLevel;
	var overNavigation = []; // Array passed by News item links
	var menuStates = [];
	var start = new Date();	
	var imgTimer = null; 
	var boxTimer = null; 
	var resizeTimer = null;
	var textBoxSize = {
		width: 0,
		height: 0
	};	
	var textBoxPane = $('#textBoxContent').jScrollPane({
		autoReinitialise: true,
		contentWidth : "245px"
	});
	var api = $('#textBoxContent').data('jsp');
	var contentPane = textBoxPane.data('jsp').getContentPane();	
	
	var rightBox = 94; // textBox and galleryBox right positon
	
	//jQuery.easing.def = "easeInOutExpo"; // comment by pepe
	
	$.getJSON(
		jsonFile,
		function(data) {
			json = data;			
			generateMainMenu(data.menu);
		}
	);
	
	$("body").keypress(function(event) {
	  if ( event.which == 32 ) {
		 console.log("currentLevel:"+currentLevel);
		 console.log("currentItem:"+currentItem);
		 console.log("curHorizontal:"+curHorizontal);
		 console.log("horizontalMenuGeneretedOnLevel:"+horizontalMenuGeneretedOnLevel);
		 console.log("horizontalMenuItem:"+horizontalMenuItem);
		 console.log("curGallery:"+curGallery);
		 console.log("textBoxGenerationMenu:"+textBoxGenerationMenu);
	   } else {
	   }
	});
	
	$.fn.serializeObject = function() {
		var o = {};
		var a = this.serializeArray();
		$.each(a, function() {
			if (o[this.name] !== undefined) {
				if (!o[this.name].push) {
					o[this.name] = [o[this.name]];
				}
				o[this.name].push(this.value || '');
			} else {
				o[this.name] = this.value || '';
			}
		});
		return o;
	};
	
	function scalegallery(imgToScale) { 
		
		// ================================================================================== 		
		// call after loading any background image or after browser window is resized
		// to adjust te scale of background picture and match it with window width and height
		// ==================================================================================
		
		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
		var img = $('.fotoContainer img');
		var imgContainer = $('.fotoContainer');
		var imageWidth;
		var imageHeight;
		var heightRatio = windowHeight / imageHeight;
		var widthRatio = windowWidth / imageWidth;
		var nFotos = $('#gallery div.fotoContainer').length;
		var bckgWidth = ( nFotos * windowWidth ) + 10;
        var newImgWidth;
        var newImgHeight;
		
		$("#background, .fotoContainer").css("width", windowWidth);
		$("#background, .fotoContainer").css("height", windowHeight);
		
		if(typeof imgToScale == 'undefined') { 
			$("img#gaBG").each(function() {			
			
				// console.log("?"+$(this).parent().attr("id"));	
				setImageSize($(this), windowWidth, windowHeight);
				
			});		
		} else {
		
			// console.log("!"+$(imgToScale).parent().attr("id"));
			setImageSize($(imgToScale), windowWidth, windowHeight);
		
		}
		
		$("#gallery").css("width", bckgWidth);
		
		center($("#baner"));		
		$("#bRight, #bLeft").css("top", 64 + ((Math.floor(windowHeight / 2))-20));	
		
		$("#map").css("width", windowWidth);
		$("#map").css("height", windowHeight);

	//	moveBackground(0,1); rem pepe last
		// if($("#textBox").is(":visible")) 
	//	setTextBoxPositionAndSize();
		//$("#gallery").css("left", 0);
		
	}
	
	function setImageSize(el, windowWidth, windowHeight) {
	
		$(el).removeAttr("width"); 
		$(el).removeAttr("height");
		
		var newLeft = 0;
		var newTop = 0;		
		var imageWidth = $(el).width();
		var imageHeight = $(el).height();
		var heightRatio = windowHeight / imageHeight;
		var widthRatio = windowWidth / imageWidth;
		
		if(heightRatio>widthRatio) {
			newImgWidth = Math.floor(imageWidth*heightRatio);
			newImgHeight = Math.floor(imageHeight*heightRatio);
			newLeft = 0 - ( ( newImgWidth - windowWidth) / 2 );						
			
		} else {
			newImgWidth = Math.floor(imageWidth*widthRatio);
			newImgHeight = Math.floor(imageHeight*widthRatio);						
			newTop = 0 - ( ( newImgHeight - windowHeight ) / 2 );
		}
	
	
		$(el).css("width", newImgWidth);
		$(el).css("height", newImgHeight);
		$(el).css("top", newTop);
		$(el).css("left", newLeft);
		
		
	}
	
	function setTextBoxPositionAndSize() {
	
		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
		var textHeight = textBoxPane.find(".jspPane").height();
		var textWidth = textBoxPane.find(".jspPane").width();
		var freeHeight = windowHeight - 196;
		var freeWidth = windowWidth - ($("#leftMenu").width() + 32);
		var nonScrollersWindowHeight = textHeight + 64;		
		var newTop, newHeight, newWidht;
		
		// console.log("width:"+textBoxSize.width+" height:"+textBoxSize.height);
		
		// if(textHeight < 10) {
			// if(boxTimer) clearTimeout(imgTimer);
			// boxTimer = setTimeout(function() { 
				// setTextBoxPositionAndSize();				
			// }, 100);
			// return null;
		// }
		
		$("#textBox").css("top", "164px");		
		
		// if(freeHeight>nonScrollersWindowHeight) {			
			// newTop = 164 + Math.round((freeHeight - nonScrollersWindowHeight) / 2);
			// newHeight = nonScrollersWindowHeight;			
		// } else {
			// newTop = 164;
			// newHeight = freeHeight;
		// }
		
		newHeight = textBoxSize.height;
		newWidht = textBoxSize.width;
		
		
		
		var textH = $('#textBox .jspPane').height();
		if ( textH < newHeight ) newHeight = textH - (-64);
		
		
		
		if(freeHeight<newHeight) {			
			newHeight = freeHeight;
			newTop = 164;
		} else {
			//newHeight = textBoxSize.height;			
			newTop = 164 + Math.round((freeHeight - newHeight) / 2);
		}
		
		if(freeWidth<textBoxSize.width) {			
			newWidht = freeWidth;		
		} else {			
			//newWidht = textBoxSize.width;newWidth
			
		}
		
		// console.log(newHeight);
		// setTextBoxSize(newWidht,newHeight);
		
		
		$("#textBox").css("top", newTop);
		$("#textBox").css("width", newWidht); 
		$("#textBox").css("height", newHeight);
		$("#textBoxContentWrap").css("width", newWidht-125);
		$("#textBoxContentWrap").css("height", newHeight-64);
		
		if ( textH > newHeight ) { $("#textBoxContentWrap").css("width", newWidht-115); }
		
	}
	
	
	function scaleTextBoxWidth(w)
	{
		
		var tbW = $("#textBoxContentWrap .jspPane").width();
		var tbH = $("#textBoxContentWrap .jspPane").height();
		//console.log('start: '+tbH+' - '+tbW);
		try 
		{	
			if ( $("#textBoxContentWrap .jspPane").find('table').length > 0 )
			{
				return true;
			}
		}
		catch(e) {}
		
		
		for ( var i = 0; i < 100; i++ )
		{
			$("#textBoxContentWrap .jspPane").width(tbW-i);
			//console.log('h: '+$("#textBoxContentWrap .jspPane").height()+' '+tbH);
			if ( tbH < $("#textBoxContentWrap .jspPane").height() ) break;
		}
		//console.log('start: '+$("#textBoxContentWrap .jspPane").height()+' - '+$("#textBoxContentWrap .jspPane").width());
		$("#textBoxContentWrap").width($("#textBoxContentWrap .jspPane").width()-(-1-w));
		$("#textBox").width($("#textBoxContentWrap").width()-(-125));
		api.reinitialise();
		
		newHeight = textBoxSize.height;
		var textH = $('#textBox .jspPane').height();
		if ( textH < newHeight ) newHeight = textH - (-64);
		if ( textH > newHeight ) { $("#textBoxContentWrap").width($("#textBoxContentWrap").width()-(-15)); }
		
	}
	
	function center(el) {
	
		// ================================================================================== 		
		// Centers passed element (el) on page		
		// ==================================================================================
	
		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
		var hW = Math.floor(el.width() / 2);
		var hH = Math.floor(el.height() / 2);
		var hM = Math.floor(windowWidth / 2);
		var vM = Math.floor(windowHeight / 2);
		el.css("left", hM - hW-145);
		el.css("top", vM - hH-175);

	}
	
	function moveBackground(dur,turn,pos) {
	
		// ================================================================================== 		
		// slides background images with passed (dur) speed 
		// ==================================================================================
	 
		
		var pos = pos;	
		if ( pos == undefined ) { pos = 0; } else { galPos = pos };
			
			
		if ( normalClick ) addHash('slide',galPos);
		
		var windowWidth = $(window).width();
		// var newBckgPos = 0 - (galPos * windowWidth);
		var newBckgPos = 0;
		if(dur>0) newBckgPos = 0 - windowWidth;		
		newBckgPos = newBckgPos * turn;
		
		if ( pos > 1 )
		{				
		  newBckgPos = -(windowWidth*pos);
		}
		
		if ( turn < 0 ) 
	    {
	  		$("#gallery").prepend($("#gallery div.fotoContainer:last"));	
	    	$("#gallery").css("left", -windowWidth+'px');
	    	newBckgPos = 0;
	    }
		
		$("#gallery").animate({
			left: newBckgPos			
		}, 
		dur,
		function() {
			if(typeof imgJSON[galPos] == 'undefined') return;
			if(typeof imgJSON[galPos].name != 'undefined') {
				$("#imgDescr").text(imgJSON[galPos].name);	
				
				
				//var obj = findObjByMenuLink(imgJSON[galPos].menuLink);
			 {
				//console.log(imgJSON[galPos].obj);
				var obj = imgJSON[galPos];
					
					if ( obj.circleImg != undefined && obj.circleImg.length > 1 )
					{
						if ( obj.circleImg == 'transparent' ){ $('#baner').hide(); $('#baner').css('background','transparent'); }
						else
						{
							$('#baner').css('background','url('+obj.circleImg+')');
							$('#baner').fadeOut(0);
							$('#baner').fadeIn(0);
						}
					}
					else
					{
						$('#baner').css('background','url('+$('#baner').attr('data-bg')+')');
					}
					
					setTextBoxContent(obj.text);
						if ( obj.text.length < 1 ) $('#textBox').hide(0);
						else 						$('#textBox').show(0);
						
					
					//console.log('obj.width:'+obj.width+' '+obj.height);
						textBoxSize.width = obj.width;
						textBoxSize.height = obj.height;
						setTextBoxPositionAndSize();		
					
				}// catch(e) { }	
				
			}
			if(dur>0 && turn > 0) {
				$("#gallery").append($("#gallery div.fotoContainer:first"));
				$("#gallery").css("left", 0); 
			}
			if ( pos >= 1 ) 
			{
				for ( var a = 1; a <= pos; a++ )
				{ 					
					$("#gallery").append($("#gallery div.fotoContainer:first"));					

			    }	
			    $("#gallery").css("left", 0); 
			}
		});
	}
	
	$("#imgDescr").click(function() {
		$(this).hide(0);
		// console.log(imgJSON[galPos].menuLink);
		overNavigation = imgJSON[galPos].menuLink;
		setMenuItem(1,overNavigation[0]);
	});
	
	function foldMenu() {		
	
		// ================================================================================== 		
		// foldes left menu
		// ==================================================================================
	
		// $("#leftMenu ul").fadeOut("fast");
		// $("#bottomLeft").fadeOut("fast");
		$("#bFoldMenu").fadeOut("fast", function() {
			$('#leftMenu').animate({
					width: 52
				}, 1000,
				function() {
					$("#bUnfoldMenu").fadeIn("fast");	
				}
			);
		});			
		
	}
	
	$("#bFoldMenu").click(function() { foldMenu(); });	
	
	function hashMoveBackground()
	{
		var ghgp = galPos = getHashGalPos(); 
					if ( ghgp < 1 )
					{
						ghgp = undefined;
						galPos = 0;
					}
		moveBackground(0,1,ghgp);
	}

	function unfoldMenu() {
	
		// ================================================================================== 		
		// unfoldes left menu
		// ==================================================================================
		
		$("#bUnfoldMenu").fadeOut("fast");	
		var mw = getMenuWidth(currentLevel);
		// console.log(currentLevel);
		$('#leftMenu').animate({
				width: mw
			}, 1000,
			function() {
				// $("#menu_1").fadeIn("fast");
				// $("#bottomLeft").fadeIn("fast");
				$("#bFoldMenu").fadeIn("fast");
			}
		);
	}
	
	$("#bUnfoldMenu").click(function() { unfoldMenu(); });
	
	function loadImage(index, ver) {			
	
		// ================================================================================== 		
		// loads image with passed index
		// ==================================================================================
		
		if(typeof imgJSON=='undefined') return;
		// console.log(curGallery+":"+ver+":"+imgJSON[index].picture);
		var newImg = "<div id=\"pic_"+index+"\" class=\"fotoContainer hidden\" ><img id=\"gaBG\" src=\""+imgJSON[index].picture+"\" alt=\"Photo no."+index+"\" /></div>";		
		
		
		if(index==0) {
			galPos = 0;
			
			normalClick = false;
			moveBackground(0,1);
			normalClick = true;
			//$("#gallery").css("left", 0);
			if(typeof imgJSON[index].name != 'undefined') 
				$("#imgDescr").show(0);
				
			//rightBox = 94;
			//console.log('setRight '+rightBox); 	
				
		} else {
			$("#bRight, #bLeft").fadeIn(100);
		//	rightBox = 185;
			//console.log('setRight '+rightBox); 
		}
		
		$('#gallery').css("display", "block");
		$('#gallery').append(newImg);
		// scalegallery();
		$('#gallery #pic_'+index+" img").load(function(){
			if(ver!=curGallery) return null;
			else realImagePreloader($(this), index, ver);
			
		});
	} 	
	
	function realImagePreloader(el, index, ver) { 
		$(el).parent().css("visibility", "hidden");
		$(el).parent().css("display", "block");
		if($(el).height() > 1) {
			$(el).parent().css("visibility", "visible");
			$(el).parent().css("display", "none");
			$(el).parent().fadeIn("slow");
			scalegallery($(el));
			if(index<(imgJSON.length-1)) loadImage(index+1, ver);
			else { scalegallery(); hashMoveBackground(); }
		} else {			
			if(imgTimer) clearTimeout(imgTimer);
			imgTimer = setTimeout(function() { realImagePreloader(el, index, ver); }, 100);
		}
	}
	
	// ==================================================================================
	// Removes DIVs after clicking its close button
	// ==================================================================================
	
	$("div#baner .close").each(function() {		
		$(this).click(function() {			
			$(this).parent().fadeOut("slow", function() {
				// $(this).parent().remove();
			});
		});
	});
	
	$("div#contentBox .close").each(function() {				
		$(this).click(function() {	
		    $('#horizontalMenu a').removeClass('selected');
			$('#bRight, #bLeft').css('visibility','visible'); 				
			$(this).parent().fadeOut("slow", function() {
				if(textBoxGenerationMenu=="vertical") {
					setMenuItem(currentLevel,0);
				}
				if(textBoxGenerationMenu=="horizontal") {
					setHorizontal(-1);					
				}
				textBoxGenerationMenu = "";
			});
		});
	});
	
	// ==================================================================================
	// Watches the browser window size and calls scalegallery function 
	// after browser window size is changed
	// ==================================================================================
	
	$(window).bind('resize', function() {				
		if (resizeTimer) clearTimeout(resizeTimer);
		resizeTimer = setTimeout(function() { scalegallery();  setTextBoxPositionAndSize();}, 100);
		
	}); 
	
	// ==================================================================================
	// 
	// ==================================================================================
	
	var moveBgSem = false;
	$("#bRight").click(function() {		
		if ( moveBgSem ) return;
		moveBgSem = true;
		galPos = galPos -(-1); 				
		if(galPos>=$('.fotoContainer').length) galPos = 0;
		moveBackground(1000,1);
		setTimeout(function(){ moveBgSem = false; },500);
	});
	
	$("#bLeft").click(function() {	
		if ( moveBgSem ) return;
		moveBgSem = true;	
		galPos -= 1;				
		if(galPos< 0) galPos = $('.fotoContainer').length;
		moveBackground(1000,-1);
		setTimeout(function(){ moveBgSem = false; },500);
	});
	
	function traceTime(text) {
		var d = new Date();
		var time = Math.floor((d.getTime()-start.getTime())/100);
		console.log(text + "(" + time + ")");
	}

	// ================================================= MAIN NAVI

	function generateMenuButton(parent, item, name, button, style,link) {	
		/*
		$(parent).append("<li class=\"helv menuButton\" id=\"item_"+item+"\"" + style + "></li>");
		
		if(button) {			
			$(parent + " li#item_"+item).append("<a href=\"javascript:void(null);\" class=\"container\">"+name+"</a>");
			//$(par).append("<a href=\"javascript:void(null);\" class=\"container\">"+name+"</a>");
					
		} else {
			//$(parent + " li#item_"+item).append("<span class=\"grey\">"+name+"</span");
			$(parent + " li#item_"+item).append("<span href=\"javascript:void(null);\" class=\"container\">"+name+"</span>");
			//$(par).append("<span href=\"javascript:void(null);\" class=\"container\">"+name+"</span>");
		}
		*/

		var itemCount = item + 1;		
		var nameMod = urlCode(name);
		var jsHref = href = 'javascript:void(null);';
		var target = '';
		if ( link != undefined ) { href = link; target="target='_blank'"; jsHref = 'javascript:function(){window.open('+link+')}' }
		
		var data = $("<li class=\"helv menuButton\" id=\"item_"+item+"\"" + style + "></li>");
		if(button) {			
			$(data).append("<a data-name='"+itemCount+nameMod+"' href="+href+" "+target+"  class=\"container\">"+name+"</a>");	
		} else {			
			$(data).append("<span  href="+jsHref+" class=\"container\">"+name+"</span>");			
		}
		$(parent).append(data);		
	}
	
	function generateMainMenu(data) {
		$("#siteNavi").append("<ul id=\"menu_1\" class=\"topMenu\">");		
		$.each(data, function(i, d) {
			if(d.name.length>0) {				
				generateMenuButton("#menu_1", i, d.name, d.button, "",d.link);
			}
		});		
		assignHandlers();
		//Cufon.refresh();
		$("#jsonPreloader").fadeOut("slow", function() {
			$("#jsonPreloader").remove();
		});
		//setMenuItem(1,1);
		setMenuItem(1,setHashMainMenu());
	}
	
	function generateSubMenu(level, data) {		
		//$("#siteNavi").append("<ul id=\"menu_"+level+"\" class=\"subMenu\">"); // comment by pepe
		$("#siteNavi").append("<ul id=\"menu_"+level+"\" style='opacity:0;  filter: alpha(opacity=0)' class=\"subMenu\">"); // add by pepe
		$.each(data, function(i, d) {
			// console.log(d.name);
			if(d.name.length>0) {
				var style = "";
				if(typeof d.margintop != 'undefined') style = "style=\"margin-top: " + d.margintop + "\"";				
				generateMenuButton(("#menu_"+level), i, d.name, d.button, style,d.link);
			}
		});
		var bttns = $("#menu_"+level+" li a");			
		var item = -1;		// add 'var' pepe
		item = getHashByLevel(level);	
		if ( item == -1 ) { item = $(bttns[0]).parent().index()+1; normalClick = true; }	
		assignHandlers();
		//Cufon.refresh();
		if(overNavigation.length > 0) {
			setMenuItem(level, overNavigation[level-1]);
			return;
		}		
		if(item > 0) setMenuItem(level,item);
		else {
			// currentLevel = level;
			// currentItem = item;
			setMenuWidth(level);
		}
		// traceTime("generateSubMenu stop");
	}
	
	function generateHorizontalMenu(hor) {
		// var data = hor[0]//json.horizontal[0][hor][0];
		// console.log("horizontalMenuGeneretedOnLevel:"+horizontalMenuGeneretedOnLevel);
		
	
		horJSON = hor[0];
		var logoURL = horJSON.logo;
		// $("#bottomLeft").empty();
		$("#bottomLeft").hide();
		
		$("#bottomLeft").append("<ul id=\"horizontalMenu\">");
		
		$.each(horJSON.children, function(i,d){
			// mod pepe
			var selected = '';
			if ( horJSON.autoOpen != undefined ) { if ( i == horJSON.autoOpen ) selected = 'selected' }		
			if ( d.link != undefined ) 
			{
				$("#horizontalMenu").append("<li id=\""+d.name.toLowerCase()+"\" class=\"helv horizontalButton\"><a class='container "+selected+"' href="+d.link+" target='_blank'>"+d.name+"</a>");
			}
			else
			{
				$("#horizontalMenu").append("<li id=\""+d.name.toLowerCase()+"\" class=\"helv horizontalButton\"><a class='container "+selected+"' href=\"javascript:void(0)\">"+d.name+"</a>");
			}						
			$("#horizontalMenu li#"+d.name.toLowerCase()).append("<span class=\"helv sep\">|</span>");
		});		
		$("#horizontalMenu li:last .sep").remove(); // mod pepe
		
		//var countImages = 0;
		$.each(horJSON.children, function(i, v) {
			if(v.type=="gallery") {
				// console.log(v.content);				
				imgJSON = v.content;
				curGallery++;  
				loadImage(0, curGallery);	
				//countImages++;			
			}
		});
		//if ( countImages > 0 ) { rightBox=165; console.log(countImages); }
		
		if(typeof logoURL != 'undefined' && logoURL != null && logoURL != "") $("#bottomLeft").append("<div id=\"prodLogo\"><img src=\""+logoURL+"\" width=\""+horJSON.width+"\" height=\""+horJSON.height+"\">");
		curHorizontal = hor;
		// Cufon.refresh(['#leftMenu']);
		// add pepe
		//$("#bottomLeft").css('opacity','0');
		$("#bottomLeft").fadeIn("fast", function() {			
		// rem pepe	assignHandlers(); 
			setMenuWidth(currentLevel);
			var ghhm = getHashHorMenu();			
			if ( ghhm > -1 )
			{
				$('#horizontalMenu a').removeClass('selected');
				var count = 0;
				$('#horizontalMenu a').each(function() { if( count == ghhm) { $(this).addClass('selected'); return false; } count++; });
				normalClick = false;
				$('#horizontalMenu .selected').trigger('click');
				normalClick = true;
				
			}
			else
			{
				$('#horizontalMenu .selected').trigger('click');
			}
		});
		
		
	}
	
	function assignHandlers() {
	
		// traceTime("assignHandlers");
		/*
		$('.menuButton a').each(function() {
			
			$(this).unbind('mouseover');
			$(this).mouseover(function() {				
				// $(this).find(".red").stop(true,true).fadeIn(100);				
				// $(this).find(".grey").stop(true,true).fadeOut(100);				
				$(this).find(".red").css("display", "block");
				$(this).find(".grey").css("display", "none");				
			});
			
		});
		
		$('.menuButton a').each(function() {
			$(this).unbind('mouseout');
			$(this).mouseout(function() {
				// $(this).css("color", "#878787");
				// $(this).find(".red").stop(true,true).fadeOut(500);
				// $(this).find(".grey").stop(true,true).fadeIn(500);
				$(this).find(".red").css("display", "none");
				$(this).find(".grey").css("display", "block");				
			});
		});
		*/
		
		$(".menuButton a").each(function(){
		
		 
		
		//	rightBox = 94;
			//console.log('setRight '+rightBox); 
		
			$(this).unbind('click');
			$(this).click(function() { 
			
				
			
				// console.log($(this));
				// traceTime("button clicked start");
				overNavigation = [];				
				var level = $(this).parent().parent().index() + 1;
				var item = $(this).parent().index() + 1;
				if(level <= horizontalMenuGeneretedOnLevel) {
					// $("#bottomLeft").empty();
					$("#bottomLeft #prodLogo").remove();
					$("#bottomLeft #horizontalMenu").remove();
					curHorizontal = "";
					horizontalMenuItem = 0;
				}
				
				if($("#imgDescr").length>0) $("#imgDescr").hide(); 
				setMenuItem(level,item);
				
			});
		});
		
		
		
		// rem by pepe
		/*
		$(".horizontalButton a").each(function(){
			$(this).unbind('click');
			$(this).click(function() { 	
				var level = $(this).parent().index();
				setHorizontal(level);	
				// console.log($(".horizontalButton").length);
				// traceTime("horizontalButton clicked");
			});
		});
		*/
		// end rem by pepe
		
	}
		
		// add by pepe
		$(".horizontalButton a").live('click',function()
		{
			
			$('.horizontalButton a').each(function()
			{ 
				$(this).removeClass('selected');			
			});
			
			
			
			
			$(this).addClass('selected');			
			
			if ( $(this).attr('target') == '_blank' ) { return; }
			var level = $(this).parent().index();
			
			setHorizontal(level) 
					
		});
		// end add by pepe
	
	function setHorizontal(item) {
		var data = horJSON;		
	//	var el = $("#horizontalMenu li").get(item>=0 ? item : 1);
	//	el = $(el).children('a');	
	
		horizontalMenuItem = item;
		if(item<0) return;
		if ( normalClick ) addHash('hor',item);
		setContent(data.children[item].type, data.children[item].content, data.children[item].width, data.children[item].height,  data.children[item].scalable);
		textBoxGenerationMenu = "horizontal";
	}
	
	// rem by pepe
	/*
	function setHorizontal(item) {
		var data = horJSON;		
		var el = $("#horizontalMenu li").get(item>=0 ? item : 1);
		el = $(el).children('a');
		var sep = "<span class=\"helv sep\"></span>";		
		// console.log(item);
		el.parent().parent().find('.selected').each(function(){
			var cont = $(this).text();			
			var tar = $(this).parent();			
			if($(this).parent().index() < ($("#horizontalMenu li").length)-1) sep = "<span class=\"helv sep\">|</span>";
			tar.empty();			
			tar.html("<a href=\"javascript:void(0)\">"+cont+"</a>"+sep);
		})
		if(horizontalMenuItem>0) {
			// var selected = $("#horizontalMenu li:eq("+(horizontalMenuItem)+") .selected");
			// var cont = $(selected).text();	
			// var tar = $(selected).parent();	
			// tar.empty();			
			// tar.html("<a href=\"javascript:void(0)\">"+cont+"</a>"+sep);
			// $(selected).empty();
		}
		var cont = el.text();
		sep = "";
		if(item < ($("#horizontalMenu li").length-1)) sep = "<span class=\"helv sep\">|</span>";
		// if(item>=0) el.parent().html("<span class=\"selected\">"+cont+"</span>"+sep);
		if(item>=0) $("#horizontalMenu li:eq("+item+")").html("<span class=\"selected\">"+cont+"</span>"+sep);
		Cufon.refresh();
		assignHandlers();
		horizontalMenuItem = item;
		if(item<0) return;
		
		// $("#contentBox div").stop(true, true).animate({ 			
				// right: 0-$(this).width()
			// },
				// 250, function() {
			setContent(data.children[item].type, data.children[item].content, data.children[item].width, data.children[item].height);
			textBoxGenerationMenu = "horizontal";
		// });
		
	}
	*/
	// end rem by pepe
	
	function setMenuItem(level,item) {
		
		if($("#map").is(":visible") > 0) $("#map").hide(0);
		if(level <= textBoxGenerationLevel) {
			
			//console.log("chowaj");
			
			// mod pepe
			$("#contentBox #textBox, #contentBox #galleryBox").animate({ 			
				right: 0-$(this).width()
			},
				250
			);
			
			
		}
		if(level==1) menuStates = [];
		
		currentLevel = level;
		currentItem = item;		
		menuStates[level] = item;
		
		var el = $("#menu_"+level+" li").get(item>0 ? item-1 : item);
		el = $(el).children('a');		
		/*
		$("#menu_"+level+" li").each(function() {
			$(this).find("span.selected").css("display", "none");
			$(this).find("a.container span.red").css("display", "none");
			$(this).find("a.container").css("display", "block");
		});
		
		$("#menu_"+level+" li:eq("+(item-1)+") span.selected").css("display", "block");
		$("#menu_"+level+" li:eq("+(item-1)+") a.container").css("display", "none");
		*/
		$("#menu_"+level+" li a").removeClass('selected');
		$("#menu_"+level+" li:eq("+(item-1)+") a.container").addClass('selected');
		if(item==0) {
			// console.log(el);
			return;
		}
		
		var g = json.menu;
		var t;
		
		for(var i=1; i<=level; i++) {
			t = menuStates[i];
			content = g[t-1].content;
			wi = g[t-1].width;
			hi = g[t-1].height;
			type = g[t-1].type;
			ban = g[t-1].baner;
			hor = g[t-1].horizontal;
			bckg = g[t-1].background;
			scal = g[t-1].scalable;
			n = g[t-1].name;
			
			g = g[t-1].children;	
			
		}		
	
		if ( normalClick ) addHash(level,item+n);
				normalClick = true;
		 rightBox = 90;
		if ( bckg != undefined && ( bckg instanceof Object)  ) { if ( bckg.length > 1 ) rightBox = 184;  }
		
		var haveGallery = false;
		if(typeof hor != 'undefined') 
		$.each(hor[0].children, function(i, v) {
			if(v.type=="gallery") {								
				if ( v.content.length > 1 ) rightBox = 184;
				haveGallery = true;
			}
		});
		
		// shows horizontal menu in bottom left corner
		if(typeof hor != 'undefined') {
			$("#bRight, #bLeft").fadeOut(1);
			
				if ( haveGallery )
				{
					$("#gallery div").addClass('del');
					$("#gallery div:first").removeClass('del');
					$("#gallery .del").remove(); 
					$("#gallery div").addClass('tmp').css({'position':'absolute','left':'0px','top':'0px','z-index':'1'});
					$("#gallery .tmp").fadeOut(1000,function() { $(this).remove(); });
				}
			// rem by pepe
			//$("#gallery").fadeOut("fast", function() {
				//$(this).empty();		
				
				generateHorizontalMenu(hor);
				horizontalMenuGeneretedOnLevel = level;				
			//});	
		}	
		
		// sets text in textBox
		if(typeof type != 'undefined') {			
			setContent(type, content, wi, hi, bckg,scal);
		}
		
		if(typeof ban != 'undefined' && ban) $('#baner').fadeIn();
		else if($('#baner').is(":visible")) $('#baner').fadeOut();
		
		// checks if menu item has submenu and call function to generate it
		if(typeof g != 'undefined') {
			var newLevel = level + 1;
			if($("#menu_"+newLevel).length > 0) $("#menu_"+newLevel).remove();			
			generateSubMenu(newLevel,g);			
		} else {			
			for(var i=$("#siteNavi ul").length; i>level; i--) {				
				$("#menu_"+i).fadeOut(function() {
					$(this).remove();
				});
				$("#menu_"+i).remove();
			}
			if(typeof hor == 'undefined' || !haveGallery) 
			{
				setMenuWidth(level);
				$("#bRight, #bLeft").fadeOut(1);
			    rightBox = 60;
				$("#gallery div:first").addClass('tmp').css({'position':'absolute','left':'0px','top':'0px','z-index':'1'});
				$("#gallery div").addClass('del');
				
				$("#gallery div:first").removeClass('del');
				$("#gallery .del").remove(); 
				
				
				$("#gallery .tmp").fadeOut(1000,function() { $(this).remove(); });
			
			//	$("#gallery").fadeOut("0", function() {
					//$(this).empty(); 
					
				if(type == "news" || typeof bckg!='undefined') { loadImage(0, curGallery); 
				 }
			//	});
			}
		}
	}
	
	function setContent(type, content, width, height, bckg, scal) {
		// console.log("?"+type);
		textBoxGenerationLevel = currentLevel;
		//var right = 165;  - replaced by rightBox
		//console.log($('#gallery').children().length);
		// add pepe
		$('#bRight, #bLeft').css('visibility','visible'); // if not gallery show bRight		
		if(type == "list") {			
			$("#galleryBox").css("display", "none");
			$("#textBox").css("display", "block");
			
			if(typeof content!='undefined') {
				textBoxGenerationMenu = "vertical";
				var off = $("#textBox").offset();
				
				var list_content = '<ul class="list">';			
				
				$.each(content, function(i, v) {
					appnd = '';
					var clear ='';
					var url2 = '';	
					var url1 = '';		
					if ( v.url2 != undefined && v.url2 != '' )
					{
						url2 = '<span>|</span><a href="download.php?d='+v.url2+'">'+v.url2label+'</a>';
						
					}
					if ( v.url1 != undefined && v.url1 != '' )
					{						
						url1 = '<a href="download.php?d='+v.url1+'">'+v.url1label+'</a>';
					}
					
					if(typeof v.url1!= 'undefined' ) appnd = '<h6>'+v.title+'</h6>'+url1+url2+'</li>'
				 	if ( i > 1 && !( i %3) ) { list_content+='<li style="clear:both; width: 100%">&nbsp;</li>';  }
				 	if ( i > 1 && !( (i-(-1)) %3) ) clear='style="margin-right:0px"'
				 	list_content += '<li '+clear+'><div class="img"><img src="'+v.thumbnail+'"/></div>'+appnd;
				});			
				
				list_content += '</ul>';
				
					setTextBoxContent(list_content);
					if(typeof width!= 'undefined' && typeof height!= 'undefined') {
						textBoxSize.width = width;
						
						textBoxSize.height = height;
						setTextBoxPositionAndSize();		
					}				
					
					$("#textBox").show(0);	
					
					if ( scal == undefined || scal == 'true' ) {	setTimeout(function() {   scaleTextBoxWidth(18);   },900); }					
					$("#contentBox #textBox").animate({
						right: rightBox
					}, 250
					);
					
				// }
			}
			return 0;
		}
		// end add pepe
		if(type == "message" ) {			
			$("#galleryBox").css("display", "none");
			
			
			if(typeof content!='undefined') {
				$("#textBox").css("display", "block");
				textBoxGenerationMenu = "vertical";
				var off = $("#textBox").offset();
				//console.log("left:"+ off.left +", width:"+ $(window).width());
				// if(off.left < $(window).width()) {
					setTextBoxContent(content);
					
					if(typeof width!= 'undefined' && typeof height!= 'undefined') {
						textBoxSize.width = width;
						textBoxSize.height = height;
						setTextBoxPositionAndSize();		
					}				
										
					
					$("#textBox").show(0);		
				
					if (  scal == undefined || scal == 'true' ) { setTimeout(function() {  scaleTextBoxWidth(0);   },900);}		
					$("#contentBox #textBox").animate({
						right: rightBox
					}, 250
					);
					
				// }
			}
			
			
			if(typeof bckg!='undefined') {				
				$("#gallery").show(0);
				imgJSON = bckg;
				curGallery++; 
				// loadImage(0, curGallery);
			}
			return 0;
		}
		
		if(type == "form") {
			$("#galleryBox").css("display", "none");
			$("#textBox").css("display", "block");
			
			if(typeof bckg!='undefined') {
				imgJSON = bckg;
				curGallery++; 
				// loadImage(0, curGallery);
			}
			
			textBoxGenerationMenu = "vertical";
			if(typeof width!= 'undefined' && typeof height!= 'undefined') {
				textBoxSize.width = width;
				textBoxSize.height = height;
				setTextBoxPositionAndSize();			
				// setTextBoxSize(width, height);			
			}
			var form = "<form id=\"contact\" action=\"\">";		
			var tabIndex = 0;
			$.each(content, function(i, v) {
				if(v.id == "communications") coms = v;
				if(v.id == "inputs") content = v.content;
			});
			var formErrors = [];
			var formReq = [];
			var formType = [];
			$.each(content, function(i, v) {
				formErrors[v.id] = v.error;
				formReq[v.id] = v.required;
				formType[v.id] = v.type;
				if(v.type=="input") form += "<p><label><span>"+v.name+"</span><input type=\"text\" class=\"input-text\" id=\""+v.id+"\" name=\""+v.id+"\" tabindex=\""+tabIndex+"\"></label></p>";
				if(v.type=="email") form += "<p><label><span>"+v.name+"</span><input type=\"text\" class=\"valid-email\" id=\""+v.id+"\" name=\""+v.id+"\" tabindex=\""+tabIndex+"\"></label></p>";
				if(v.type=="radio") {
					form += "<fieldset>";
					$.each(v.options, function(ii,vv) {
						selected = vv.selected ? " checked " : " ";
						form += "<input type=\"radio\" class=\"radio\" id=\""+vv.name+"\" name=\""+v.id+"\" value=\""+vv.value+"\""+selected+"tabindex=\""+tabIndex+"\" /><label for=\""+vv.name+"\">"+vv.name+"</label>";
					});
					form += "</fieldset>";
				}
				if(v.type=="textarea") {
					form += "<p><label><span>"+v.name+"</span><textarea id=\""+v.id+"\" cols=\""+v.cols+"\" rows=\""+v.rows+"\" tabindex=\""+tabIndex+"\" name=\""+v.id+"\"></textarea></label></p>";
				}
				if(v.type=="submit") {
					form += "<p class=\"error hidden\"></p><p style=\"text-align: left;\"><input type=\"submit\" class=\"hand\" tabindex=\""+tabIndex+"\" value=\""+v.name+"\" id=\"submit\"></p>";
				}
				if(v.type=="select") {
					form += "<p><label><span>"+v.name+"</span><select id=\""+v.id+"\" name=\""+v.id+"\"tabindex=\""+tabIndex+"\">"
					$.each(v.options, function(ii,vv) {
						form += "<option value=\""+vv.value+"\">"+vv.select+"</option>"						
					});
					form += "</select></label></p>";
				}
				tabIndex++;
			});
			form += "</form>";
			// console.log(content);
			setTextBoxContent(form);
			setTextBoxPositionAndSize();	
			// $(".contentBox").hide();
			$("#textBox").css('right','0px'); //add by pepe
			$("#textBox").show();
			// $("#contentBox").fadeIn("fast");
		
			$("#contentBox #textBox").animate({
					right: rightBox
				}, 250
			);
			
			$('#contact').submit(function() {
				var formJSON = $("#contact").serializeObject();
				// console.log(formJSON);
				var status = "valid";
				$.each(formJSON, function(i, v) {
					
						if((v.length<=0 || (formType[i]=="email" && validEmail(v)==false)) && formReq[i] && status=="valid") {
							$("#contact .error").html(formErrors[i]);					
							$("#contact .error").stop(true, true).fadeIn(100, function() {
								$(this).fadeOut(10000);
							});
							status = "invalid";
						}
					
					// console.log("?"+formType[i]+":"+validEmail(v));
				});
				if(status=="invalid") return false;
				// setTextBoxSize(350,300);
				textBoxSize.width = 350;
				textBoxSize.height = 300;
				setTextBoxPositionAndSize();
				setTextBoxContent(coms.sending);
				$.post("success.php", formJSON, function (data) {
					if(data=="1") {
						setTextBoxContent(coms.success);
					} else if(data=="2") {
						setTextBoxContent(coms.error+"<p class=\"center\"><a id=\"restart\" href=\"javascript:void(0)\">"+coms.backbutton+"</a></p>");
						$("#restart").click(function() {
							setMenuItem(curuuurentLevel,currentItem);
						});
					} 
				});
				return false;		
			});
			return 0;
		}
		if(type == "gallery") { 
			$('#bRight, #bLeft').css('visibility','hidden'); // if gallery hidden bRight
			//$('#galleryBox')
			textBoxGenerationMenu = "vertical";
			$("#galleryBox").css("display", "block");
			
			//add pepe
			var galleryBoxTopSet = function()
			{ 
				var top = (($(window).height()+120)/2)-($("#galleryBox").height()/2);
				$("#galleryBox").css('top',top+'px'); 
			}
			galleryBoxTopSet();
			window.onresize = galleryBoxTopSet;
				
			$("#textBox").css("display", "none");
			$("#galleryBoxContent").empty();
			$("#galleryBoxContent").css("left", "0px");
			
			var galleryThmumWidth = 220; // add and mod pepe
			$("#galleryBoxContent").css("width", (content.length*galleryThmumWidth));
			var is_extend = false;
			$("#galleryBox").removeClass('extend');
			
			var countGalleryItems = 0;
			$.each(content, function(i, v) {
			countGalleryItems++;
				// console.log(i + ":" + v.thumbnail);
				// $("#galleryBoxContent").append("<div id=\""+i+"\" class=\"thumbnail\"><a class='img' href=\""+v.picture+"\" target=\"_blank\" style=\"background-image: url('"+v.thumbnail+"')\"></a><h6>"+v.title+"</h6><a class='link' href='"+v.url1+"'>"+v.url1label+"</a><span>|</span><a class='link' href='"+v.url2+"'>"+v.url2label+"</a></div>");
				// $("#galleryBoxContent").append("<div id=\""+i+"\" class=\"thumbnail\"><a class='img' href=\""+v.picture+"\" target=\"_blank\" style=\"background-image: url('"+v.thumbnail+"')\"></a></div>");
				var extend = '';				
				if ( v.title != '' && v.title != undefined && v.title != null )
				{ 	
					is_extend = true;
					var url2 = '';	
					var url1 = '';		
					if ( v.url2 != undefined && v.url2 !=''  )
					{						
						url2 = "<span>|</span><a class='link' href='download.php?d="+v.url2+"'>"+v.url2label+"</a>";
					}
					if ( v.url1 != undefined && v.url1 !=''  )
					{
						url1 = "<a class='link' href='download.php?d="+v.url1+"'>"+v.url1label+"</a>";
					}
					
					extend = "<h6>"+v.title+"</h6>"+url1+url2;
				}
				
				$("#galleryBoxContent").append("<div id=\""+i+"\" class=\"thumbnail\"><div class='img_cont'><a class='img' href=\""+v.picture+"\" target=\"_blank\"><img src=\""+v.thumbnail+"\" /></a></div>"+extend+"</div>");		
				//$("#galleryBoxContent").append("<div id=\""+i+"\" class=\"thumbnail\"><a class='img' href=\""+v.picture+"\" target=\"_blank\" style=\"background-image: url('"+v.thumbnail+"')\"></a></div>");				
				
			});
			var gbcw = 222;
			//console.log(countGalleryItems);
			if ( countGalleryItems < 3)
			{
				$('#galleryBox').width(countGalleryItems*gbcw-(-120));
			}
			
			var maxHeight = 0;
			try { if ( $("#galleryBox").attr('data-baseHeight') == undefined ) $("#galleryBox").attr('data-baseHeight',$("#galleryBox").css('height').replace('px','')); }
			catch(e) {  }
			$("#galleryBoxContent .thumbnail").each(function()
			{
				
				if ( $(this).height() > maxHeight ) maxHeight =  $(this).height();
			});
			maxHeight = maxHeight  - 150;
			if ( is_extend ) 
			{ 
				
				$("#galleryBox").height($("#galleryBox").attr('data-baseHeight')-(-maxHeight));
				$("#galleryBoxWrap").height($("#galleryBoxWrap").height()-(-maxHeight));
			}
			// $(".contentBox").hide();
			
			$('.thumbnail .img_cont').live('mouseenter',function(){
				
					off = $(this).offset();
					wdth = $(this).width();
					hgth = $(this).height();
					
					var off2 = $("#galleryBox").offset();
				
					if( $('#rollover').length > 0) {
						$('#rollover').empty();
						$('#rollover').remove();
					}
					$(this).parents('#galleryBox').append('<div id="rollover"></div>');
					$(this).clone().appendTo($('#rollover'));
					$('#rollover').css("left",off.left-off2.left);
					$('#rollover').css("top",off.top-off2.top);
					$('#rollover').css("width",wdth);
					$('#rollover').css("height",hgth);
					$('#rollover').css("overflow","hidden");
					$('#rollover .img_cont').css('overflow','visible');
					$('#rollover').animate({
						top: '-=10',
						left: '-=10',
						width: '+=20',
						height: '+=20'
					}, 100);
					imgW = $('#rollover img').width() + 20;
					$('#rollover img').css("width",wdth);
					$('#rollover img').animate({						
						width: '+=20'
					}, 100);
					
				});
				$('#rollover').live('mouseleave',function(){
					$('#rollover').empty();
					$('#rollover').remove();
				});
				$('#galleryBox').live('mouseleave',function(){
					$('#rollover').empty();
					$('#rollover').remove();
				});
				
				
			
			
			$("#galleryBox").show();
			$("#contentBox").fadeIn("fast");
			//Cufon.replace('#contentBox');
			showHideGalleryButtons();
			$("#galleryBox").animate({
						right: 90 //rightBox
					}, 250
					);
			$('#galNext').unbind('click');
			$('#galPrev').unbind('click');			
			$("#galNext").click(function() {
				$(this).hide();				
				ch = '-='+($("#galleryBoxWrap").width())+'px';
				var goToStart = Math.abs($("#galleryBoxContent").css('left').replace('px','') - $("#galleryBoxWrap").width() ) - $("#galleryBoxContent").width() ;
				if ( goToStart >= 0 ) ch = 0;
				$("#galleryBoxContent").animate({
					left: ch
				},
				500,
				function() {
					showHideGalleryButtons();
				});
			});
			$("#galPrev").click(function() {
				$(this).hide();				
				ch = '+='+($("#galleryBoxWrap").width())+'px';
				$("#galleryBoxContent").animate({
					left: ch
				},
				500,
				function() {
					showHideGalleryButtons();
				});
			});		
			return 0;	
		}
		if(type == "map") {
			// $("#background").empty();			
			// $("#map").load(content);
			// var map = new GMap(document.getElementById("map"));
			// map.addControl(new GSmallMapControl());
			// map.centerAndZoom(new GPoint(-56.07421875, 4.258768357307995), 10);			
			/*
			var options = {
				markers : [ 
					{
						latitude : 47.363121,
						longitude : 8.170188,
						html : content, 
						popup: true
					}
				],
				maptype: G_HYBRID_MAP,
				latitude : 47.363121,
				longitude : 8.170188,
				zoom : 16
			
			};
			if($("#map").length>0) {				
				$("#map").show(0);
				$("#map").css("width", $(window).width());
				$("#map").css("height", $(window).height());
				$gmap.setCenter(new GLatLng(47.363121, 8.170188), 16);
			} else {
				$("#background").append("<div id=\"map\">");
				$("#map").css("width", $(window).width());
				$("#map").css("height", $(window).height());
				$("#map").gMap(options);
			}
			return 0;
			*/
		}
		if(type == "news") {
			$("#galleryBox").css("display", "none");
			$("#textBox").css("display", "block");
			textBoxGenerationMenu = "vertical";
			setTextBoxContent(content[0].message);
			if(typeof width!= 'undefined' && typeof height!= 'undefined') {
				// $("#textBox").css("width", width);
				// $("#textBox").css("height", height);
				// $("#textBoxContentWrap").css("width", (width-115));				
				// $("#textBoxContentWrap").css("height", (height-95));
				textBoxSize.width = width;
				textBoxSize.height = height;
			}
			setTextBoxPositionAndSize();
			$("#gallery").show(0);
			imgJSON = content[0].products;
			curGallery++;
			// loadImage(0, curGallery);
			
			// $(".contentBox").hide();
			$("#textBox").show();
			setTextBoxPositionAndSize();			
			// $("#contentBox").fadeIn("fast");
			$("#contentBox #textBox").animate({
					right: rightBox
				}, 150, ( function() {
					
				})
			);
		}	
		return 0;	
	}
	
	function validEmail(email) {		
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		// console.log(email + ":" + reg.test(email))
		return reg.test(email);
	}
	
	function setTextBoxSize(width, height) {
		// $("#textBox").css("width", width);
		// $("#textBox").css("height", height);
		// $("#textBoxContentWrap").css("width", (width-115));				
		// $("#textBoxContentWrap").css("height", (height-95));
	}
	
	function setTextBoxContent(content) {		
		
		contentPane.html(content);		
		setTimeout(function(){
		setTextBoxPositionAndSize();		
		api.reinitialise();			
		},700);
		
	}
	
	function showHideGalleryButtons() {
		$("#galNext").hide(0);
		$("#galPrev").hide(0);
		
		
		if($("#galleryBoxContent").position().left > (($("#galleryBoxWrap").width())-$("#galleryBoxContent").width())) {  $("#galNext").show(0);  }
		//else if ( $("#galleryBoxContent").position().left < 0 ) $("#galNext").show(0);
		
		if($("#galleryBoxContent").position().left <= -($("#galleryBoxWrap").width())) $("#galPrev").show(0);
		
	}
	
	function getMenuWidth(level) {		
		var w = $('#menu_'+level).css("display", "inline");
		var w = $('#menu_'+level).width();
		var off = $('#menu_'+level).offset();
		var np = 40 + w + off.left;
		
		if($('#horizontalMenu').length <= 0) return np;
		
		var bw = $('#horizontalMenu').width();
		var boff = $('#horizontalMenu').offset();
		var bnp = 40 + bw + boff.left;
		if(np>=bnp) return np
		else return bnp
		
	}
	
	function setMenuWidth(level) {
		// console.log("setMenuWidth [level:"+level+", currentLevel:"+currentLevel+"]");	
		var np = getMenuWidth(level);
		
		var bottomLeftWidth = 0;		
		$('#bottomLeft').children().each(function()
		{
			bottomLeftWidth+=$(this).width();
		});
		//console.log(bottomLeftWidth);
		if ( np < bottomLeftWidth ) np = bottomLeftWidth;
		$('#leftMenu').stop(true, true).animate({
			width: np // menuWidths[level-1]
		}, 800, function() {
			// $('ul.subMenu').fadeIn();
			$(this).css("width", np);
			
			// add by pepe
			$(this).find('ul').animate({
			    opacity: 1			   
			  }, 500); 
		});		
	}
	
	// =============================================== Gallery Preloader
	
	var fotosDB = Array ("001","002","003","004","005","006");
	
	
	scalegallery();
	
	 
	  
	  function hashchange() {  			
  		if ( addHashSem ) {  return; }
  		  		
  		var cL = currentLocation.toString().split('#');
  		var wL = window.location.toString().split('#');
  		
  		/*
	  		if  ( cL[cL.length-1][0] == '^' ||  cL[cL.length-1][0] == '|')
	  		{	  		
		  		addHashSem = true;
		  		while( cL[cL.length-1][0] == '^' ||  cL[cL.length-1][0] == '|')
		  		{ 
		  			historyBackSlidesCounter++;
		  			window.history.go(-1);
		  			//if ( cL[cL.length-2][0] == '^' ||  cL[cL.length-2][0] == '|')
		  			//	window.history.go(-1);
		  				
		  			currentLocation = window.location;
		  			cL = currentLocation.toString().split('#');
		  			console.log(currentLocation);
		  			
		  			return;
		  		}		  			  	
	  		}
	  	
	  	*/
	  	if  ( cL[cL.length-1][0] == '^' ||  cL[cL.length-1][0] == '|')
	  		{	  	
	  			window.history.go(-1);	
	  		if  ( cL[cL.length-2][0] == '^' ||  cL[cL.length-2][0] == '|')
	  		{
	  			window.history.go(-1);	
	  		}
	  		currentLocation = window.location;
		  			cL = currentLocation.toString().split('#');
		  			return;
	  	}
	  	
  		
  		for ( var i = 1; i < wL.length; i++ )
  		{
  			wL[i] = parseFloat(wL[i])-1;
  		}
  		
  		
  		if ( ! isParent(wL) ) 
  			{
  				window.history.go(-1);
  			  	currentLocation = window.location;
  				return;  
  			}
  		else
  		{  			
  			currentLocation = window.location;  
  			$('#siteNavi, #bottomLeft').html('');
  			generateMainMenu(json.menu); 
  			historyBackSlidesCounter = 0;
  			//$(window).bind('hashchange', hashchange);
  			
  		}
  		
  		return;
  		 		
	 };
	 
	  var historyBackSlidesCounter = 0;
	  var historyHashFirstEntry = true;
	  $(window).bind('hashchange', hashchange);
	
	function isParent(cords)
	{	
	    var menu = json.menu;
		for ( var i = 1; i <= cords.length; i++ )
		{				
			if 	( menu[cords[i]] == undefined ) return false;	
			if ( menu[cords[i]].children == undefined ) return true ;			
			menu =  menu[cords[i]].children;			
		}
		return false;		
	}
	
	function getHashByLevel(level)
	{
	//console.log('getHashByLevel: '+level);
		normalClick = false;
		var location = decodeURI(window.location);
		location = location.toString().split('#');	
		var length = 0;
		for ( var a in location )
		{			
			if ( location[a][0] != '_' && location[a][0] != '^'  ) length++;
		}
		
		if ( length > level  )
		{
			var item = $('#menu_'+level+' a[data-name="'+location[level]+'"]').parent().attr('id').replace('item_','');
			//alert(item);
			return item-(-1);;
		}
		return -1;
	}
	
	function getHashHorMenu()
	{
		var location = decodeURI(window.location);
		location = location.toString().split('#|');	
		if ( location.length > 1 ) return location[1];
		return -1;		
	} 
	
	function getHashGalPos()
	{
		var location = decodeURI(window.location);
		location = location.toString().split('#');	
		var loc = -1;
		for ( var a in location )
		{
			if ( location[a][0] == '^' ) { loc = location[a].replace('^','');  }
		}
		return loc;
			
	} 
	
	function setHashMainMenu()
	{
		normalClick = false;
		var location = decodeURI(window.location);
		location = location.toString().split('#');	
		//console.log(location[1]);
		var length = 0;
		for ( var a in location )
		{			
			if ( location[a][0] != '_' && location[a][0] != '^'  ) length++;
		}
		
		if ( length > 1  )
		{
		
			var item = $('#menu_1 a[data-name="'+location[1]+'"]').parent().attr('id').replace('item_','');
			//alert(item);
			return item-(-1);
		}
		return 1;
	}
	
	function gotoHash(newLocation)
	{
		var location = decodeURI(window.location);
		location = location.toString().split('#');	
		
		var c = currentLocation.toString().split('#');	
		var diffLevel = 0;
		for ( var i = 0; i <= location.length; i++ )
		{
			diffLevel = i;
			if ( location[i] != c[i] ) { break; }
		}	
	//	console.log(diffLevel+' - '+location.length);
		/*
		for ( var i = diffLevel+1; i <= location.length; i++ )
		{
			
			location[i] = location[i].replace('%20',' ');
			console.log('loc: '+location[i]);
			normalClick = false;
			console.log('#menu_'+i+' a[data-name='+location[i]+']');
			$('#menu_'+i+' a[data-name='+location[i]+']').trigger('click');
		
			normalClick = true;
		}*/
		normalClick = false;
		generateSubMenu(1,1);
		normalClick = true;
		/*
		setMenuItem(1,4);
		$('#bottomLeft').html('');
		setMenuItem(2,3);
		*/
		//setMenuItem(3,2);
	}
	
	
	function findObjByMenuLink(ml)
	{
		var text = json.menu;
		
		for ( var i = 0; i < ml.length; i++ )
		{			
		    if ( i > 0 ) 
		    	{		    	  	
		    		text = text.children[ml[i]-1];		    	
		    	}
		    else
		    	{
					text = text[ml[i]-1];					
				}			
		}
		return text.horizontal[0].children[0];
		
	}
	
	
});


var addHashSem = false;
var isHistory = false;
function addHash(level,name)
{	
	
  addHashSem = true;

 //console.log('addHash: '+level+' '+name);
	var location = window.location;

	
		
	location = location.toString().split('#');	
	location[level] = name;
				
	var newLocation = '';
	
	if ( level == 'slide' )
	{		
		location = decodeURI(window.location);
		location = location.toString().split('#^');
		//console.log(location.length);
		if ( location.length > 1 )
		{
			var location2 = location[location.length-1].split('#');
			location2[0] = '#^'+name;
			locaation2 = location2.join('#');
			location[location.length-1] = locaation2 ;//'#^'+name;
			//console.log(location.join(''));
			window.location = location.join('');
		}
		else	
			window.location = window.location +'#^'+name;
		
		setTimeout(function(){addHashSem = false; },500);
		currentLocation = window.location.toString();
		return;
	}	
	
	
	if ( level == 'hor' )
	{		
		location = decodeURI(window.location);
		location = location.toString().split('#|');
		if ( location.length > 1 )
		{
			location[location.length-1] = '#|'+name;
			//console.log(location.join(''));
			window.location = location.join('');
		}
		else	
			window.location = window.location +'#|'+name;
			
		setTimeout(function(){addHashSem = false; },500);
		currentLocation = window.location.toString();
		return;
	}	
	
	for ( var i = 0; i <= level; i++)
	{
		if ( i > 0 ) newLocation+='#';
		newLocation+=location[i];
		
	}
	window.location = newLocation;		
	setTimeout(function(){addHashSem = false; },1000);
	currentLocation = window.location.toString();
}


function urlCode(str)
{
	str = str.replace("'","&#39;");
	str = str.replace('"',"&#34;");
	return str;
	
}
