/*
 * 
 * JavaScript dedicato al sito pubblico
 * 
 * */

var previousPage = "";
var selectedPage = "";

var pParam = ""

var contentClosed = false;
var backgroundPreloaded = true;
var canOpen = true;

var bgIndex = -1

var loadingTmrId = 0;
var bgFadeTmrId = 0;



// set pParam var according to the value of ?p=xxx
var params = location.search.replace("?","").split("&")
for (var i=0; i<params.length; i++) {
	var key_val = params[i].split("=")
	if (key_val[0]=="p")
		pParam = key_val[1]				
}
	

	
function updateScrollbars() {
	// reload scrollbar
	$('.overlay').data('jsp').reinitialise()
}
	
$(function() {
	
	// remove "default" content bg
	$("#content").css("background","")
	
	// scrollbar
	$('.overlay').jScrollPane({
		showArrows: true,
		verticalDragMinHeight: 20,
		verticalDragMaxHeight: 20,
		horizontalDragMinWidth: 20,
		horizontalDragMaxWidth: 20,
		hideFocus : true

	});
	
	
	
	$(window).resize(updateScrollbars);
	
	
	
	// menu li hover effect
	$(".menu li").hover(function(){
		$(".label",this).animate({top:'-10px'},300)
		$(".riflesso",this).animate({top:'10px',opacity:0.7},300)
	},function(){
		$(".label",this).animate({top:'0px'},300)
		$(".riflesso",this).animate({top:'0px',opacity:1},300)
	})
	
		

	// exteds menu a click to li click
	$(".menu li").click(function(){
		$("a",this).click()
	})

		
	// lang flags animation
	$("#langBar a")
		.css({opacity:0.5,right:'-10px'})
		.hover(function(){
			$(this).animate({right:'0px',opacity:1},200)
		},function(){
			$(this).animate({right:'-10px',opacity:0.7},200)
		})
	
		
	// hide php in-page loaded content
	$("#content").css({height:'0%',top: '50%',width:'0%',left:'50%'})
	$(".overlayContainer.right").css({right: '-40%',visibility: "hidden"})
	
		
		

	// address initialization
	$.address
		.init(function(event){
			if (pParam!="" || event.value!="/") { // if a specific page is requested, open the content bar
				$("#content").animate({
					width: "100%",
					left:'0%'
				},1000)	
			} 
		})
		.change(function(event) {
			if (event.value!="/" || pParam!="") { // if a specific page is requested, show it!
				var page = event.value.toString().replace("/","")
				page = (page) ? page : pParam
				if ( page != selectedPage ) {
					
					var pageName = page
					if (pageName.indexOf("?") > 0)
						pageName = pageName.toString().substring(0,pageName.indexOf("?"))

					if (_gaq) _gaq.push(['_trackPageview',"/"+pageName]);
					showPage(page);
				}
			} else {
				showIntro();
			}
	
		});
	
	
	
	
	

}) 





	//
	// Ajax FORMs
	function ajaxFormSubmit($form) {
		var action = $form.attr("action").substring($form.attr("action").indexOf("?p=")+3);
		var qString = $form.serialize();
		$form.attr("action"," ")
		location.href="#/"+action+"?"+qString;	
		return false;		
	}


function showPage(pageID) {

	//if (console) console.log("Content selected: "+pageID);
	
	
	previousPage = selectedPage
	
	pageID = pageID.replace("?","&")
	
	if (pageID.indexOf("&") > 0)
		selectedPage = pageID.toString().substring(0,pageID.indexOf("&"))
	else
		selectedPage = pageID
		
	
	closeContent()
			
	
	$.ajax({
		url: 'php/getContent.php',
		data: 'p='+pageID+"&lang="+$("html").attr("lang"),
		type: 'POST',
		dataType: "text",				
		success: function(data) {
			injectContent($($.parseXML( data )))
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
					
			// handle error
					
			alert("An error has occurred. Please, click OK and reload the page. Thank you. \nAjax Error in showPage(): "+errorThrown)
			
			// fadeOut loading div
			$("#loading").fadeTo(0,0);
		}
	});
	
	
	
	// change href of flags a according to the content selected
	$("#langBar a").each(function(){
		$(this).attr("href","?lang="+$(this).attr("class")+"#/"+selectedPage)
	})
			

}

function openContent() {
	
	if (!canOpen) {
		setTimeout(openContent,50);
		return false;
	}
	//console.log("openContent(): opening content...")
	
	var duration = 750
	
	if (loadingTmrId>0) {
		clearTimeout(loadingTmrId)
		loadingTmrId = 0;
	}
	// fadeOut loading div
	$("#loading").fadeTo(100,0);    
	
	contentClosed = false
	
	
		$("#content").animate({
			height: "99%",
			top: "0%"
		},duration,function(){

			
			//$(".overlayContainer.top").animate({ height: "40%"	},duration);
			
			$(".overlayContainer.right")
				.css("visibility","visible")
				.animate({ right: "0%"	},duration,function(){});
			
			//if ($('.overlayContainer.bottom .jspPane').children().size()>0) 
			//	$(".overlayContainer.bottom").animate({ height: "40%"	},duration);
			
			//$(".overlayContainer.left").animate({ left: "0%"	},duration);
			
			$("#content").children().animate({opacity:'1'},duration);
			
		})
	
	
	
	
}

function closeContent() {
	
	// if active, stop bg fading
	if (bgFadeTmrId>0) {
		clearTimeout(bgFadeTmrId)
		bgFadeTmrId=0;
	}

	var duration = 750
	
	
	//$(".overlayContainer.top").animate({ height: "0%"	},duration);
	
	$(".overlayContainer.right").animate({ right: "-40%"	},duration,function() {
		$(this).css("visibility","hidden")
	});

	//$(".overlayContainer.bottom").animate({ height: "0%"	},duration);
	
	//$(".overlayContainer.left").animate({ left: "-40%"	},duration);
	
	$("#content").children().not(".siteBg").animate({opacity:0},duration);
	
	setTimeout(function(){
	
		$("#content").animate({
			height: "0%",
			top: "50%"
		},duration,function(){
			contentClosed = true
			
			// fadeIn loading div
			loadingTmrId = setTimeout(function(){$("#loading").fadeTo(200,1);},300);  
		});
	},duration+1);
	
	
}


function preloadBackground(url) {
	backgroundPreloaded = false;
	
	
	$.loadImages(url,function(){
		backgroundPreloaded = true;
		canOpen=true
	})

}

function nextBackground() {
	
	if (!backgroundPreloaded) {
		//console.log("nextBg(): waiting...")
		bgFadeTmrId = setTimeout(nextBackground,50);
		return;
	}
	//console.log("nextBg(): changing bg.")
	
	bgIndex = (bgIndex +1) % $(".siteBg").size()
	
	showBackground(bgIndex)
	
	if ($(".siteBg").size()>1) {
		// preload next bg
		preloadBackground($(".siteBg").eq((bgIndex +1) % $(".siteBg").size()).attr("rel"))
		
		bgFadeTmrId = setTimeout(nextBackground,7000)
	}
		
	
}


function showBackground(index,duration) {
	
	
	if (!duration) duration = 1500
	
	var $bgDiv = $(".siteBg").eq(bgIndex)
	if ($bgDiv.css("background")=="" || !$bgDiv.css("background"))
		$bgDiv.css("background","url("+$bgDiv.attr("rel")+") no-repeat scroll center center transparent")
	
		
	$(".siteBg").fadeOut(duration)	
	$bgDiv.fadeIn(duration)
}



function injectContent(xml) {
	
	if ( (!contentClosed) ) {
		//if (console) console.log("rinvio injectContent()")
		setTimeout(function(){injectContent(xml)},50)
	} else {
		// change classes according to new content
		$(".overlayContainer").removeClass(previousPage).addClass(selectedPage)

		
		// change document title
		document.title='Gallo s.n.c. - '+$("response > title",xml).text()
		
		
		// load page css style from xml response
		//$('style#pageCss').html($("response > css",xml).text()); // IE have some problem with this...
		$('style#pageCss').remove()
		$("head").append("<style type='text/css' id='pageCss'>"+$("response > css",xml).text()+"</style>")
		
		
		
		
		// load page html content from xml response
		$('.overlayContainer.right .jspPane').html($("response > overlay",xml).text());
		$('#content')
			.html($("response > content",xml).text())
			.children().css({opacity:0});
		
		// load & inject background from response
		bgIndex = -1 // reset bgIndex
		$("response > backgrounds > image",xml).each(function() {
			var $div = $("<div>&nbsp;</div>")
			$div
				.addClass("siteBg")
				.attr("rel",$(this).attr("src"))
			$("#content").append($div)
			
		})
		
		canOpen=false
		preloadBackground($(".siteBg:first").attr("rel"))
		nextBackground()
		
		
		// execute page jscript from xml response
		jQuery.globalEval($("response > js",xml).text());
		
		// add address click event handler for new ajax-loaded links
		$('.overlayContainer a[rel^="address:/"]').address();
		
		// update scrollbar
		updateScrollbars()
		
		openContent()

	}
}


function showIntro() {
	
	//if (console) {console.log("Intro started")}
	
	$("#container, .menu li div.label, .menu li div.riflesso, div.underlineBg1, img#logo, div#langBar, #content > *").fadeTo(0,0)
	
	$("#content").css({height:'0%',top: '50%',width:'0%',left:'50%'})
	
	$(".overlayContainer.right").css({right: '-40%',visibility: "hidden"})
	
	$("#container").fadeTo(1500,1,function(){
		
		var logoW = parseInt($("img#logo").width())
		var logoH = parseInt($("img#logo").height())
		$("img#logo").css({
			width: logoW*2+"px",
			height: logoH*2+"px",
			top: (parseInt($(window).height())/2 - logoH*2/2)+"px",
			left: (parseInt($(window).width())/2 - logoW*2/2)+"px"
		})
		$("img#logo").fadeTo(750,1,function() {
			setTimeout(function(){
				$("img#logo").animate({
					width: logoW+"px",
					height: logoH+"px",
					top: "20px",
					left:"20px"
				},1500,function(){
					$("#content").animate({
						width: "100%",
						left:'0%'
					},1000,function(){
						location.href+="#/home"
	
						$(".menu li").each(function(){
							var $curLi = $(this)
							
							setTimeout(function() {
								$("div.underlineBg1",$curLi).fadeTo(500,1,function(){
									
									setTimeout(function() {
										$(".label",$curLi).fadeTo(500,1)
										$(".riflesso",$curLi).fadeTo(500,.7)										
									},200)
									
								})
							},500*$(".menu li").index($curLi))
							
							
							
						})
						
						$("#langBar").fadeTo(500,1)
						
					})
						
					
					
				})
			},100)
		})
	}) 

}
