$(function() {

	/* Prelevo le dimensioni dell'area visibile dello schermo */
	//var h = $("body").height();
	//var w = $("body").width();


	//background();
	langBar();

	// first example
	$("#page_menu, #menu_clienti").treeview({
		animated: "fast",
		persist: "location",
		collapsed: true,
		unique: true
	});

	ajax();

});



// Loop Background images
function background()
{
	var second = false;
	var link = true;

//        if(stop == true) { second = true; link = false; }

	$('a').click(function()
	{

		if($(this).attr('class') != 'toggle')
		{
			switch($(this).attr('title'))
			{
				case 'homepage':
				case 'Servizi / competenze':
				case 'Services / skills':
				case 'LifeStyle':
					second = false;
					link = true;
					$("#sfondo").show(500);
					break;

				default:
					$("#sfondo").hide();
					link = false;
					second = true;
					return false;
					break;
			} // End-Switch
		}

	}); // End-method

	/* Prelevo le dimensioni dell'area visibile dello schermo */
	var h = $("body").height();
	var w = $("body").width();

	var ratio = ((w/h) > 1.6) ? 16 : 4;

	$.timer(3000, function (timer) {

		if (!second) {

			$.ajax({
				  url: 'http://www.lifepesaro.com/ajax.php?sfondi=true&ratio='+ratio ,
				  cache: false,
				  dataType: "text",
				  //beforeSend : onStartLoading,
			 	  success: function(text){					
			   	    var img = $('<img />').attr('src', text);  
			   	    
			   	    //alert(text);
					if(img)
		        	{ 
		        		timer.reset(5000);
		        		//$("#sfondo").fadeOut(3000);

		        		
		        		$("#sfondo img").attr('src',text);
		        		$("#sfondo").fadeIn(3000);
		        		
		        		if(link)
		        		{
			        		tmp = text.split('-k');
			        		if(tmp.length == 2) 
			        		{
			        			$("#sidebar a").css('color','#5d5d5d');
			        		} else 
			        		{
			        			$("#sidebar a").css('color','#c3c3c5');//alert(tmp.length + ' ' + tmp); 
			        		}
		        		} else {
		        			
		        			$("#sidebar a").css('color','#c3c3c5');
		        		}
		        		
		        		//$("body").css('background','url(' + item.media.m + ') no-repeat');
		        	} // End-if
					  
				  },
				  error : onError 
				});
			
			/*
			$.getJSON("ajax.php?sfondi=true",
					function(data){
					  $.each(data.items, function(i,item)
			          {
	        	    	
			        	//var img = $('<img />').attr('src', item.media.m);  
			        				        	
			        	//$("#debug").html(item.media.m);
				        //alert(item.media.m);
			        	//$("<img/>").attr("src", item.media.m).appendTo("#menu");
			            
			          });
			          
			          
			        });
			*/
			//alert('First time!');
			//second = true;
			//timer.reset(10000);
		}
	});
	
} // End-method




function langBar()
{
	$('.lang').hide();
	$('.toggle').click(function(){	$('.lang').toggle('slow'); });
        $('.lang a').click(function(){ window.location = $(this).attr('href')});
}

/* Motore Ajax per il sito */
function ajax()
{
	
	
	// Attivazione Lightbox
	$('#content .shutterset_fotografie').lightBox({fixedNavigation:true});		
	
	//jQuery.fx.off = true;
	$('#page a, #content a').click(function()
	{
		$("a").removeClass('selected');
		$(this).addClass('selected');
	
		// Prelevo l'anchor se c'è dall'URL 
		anchor = ''
		link = $(this).attr('href');
			
		token = link.split('#');
		if(token.length > 1) anchor = jQuery.trim(token[token.length-1]); 
				
		if($(this).attr('title') == 'LifeStyle')
		{
		  $('#content').hide();
		} else {
		var load = false;
		
		if(link != '#') // Blocco i link non attivi
		{
			// Iterazione Ajax
			$.ajax({
				  url: 'http://www.lifepesaro.com/ajax.php?link=' +  token[0] ,
				  cache: false,
			 	  beforeSend : onStartLoading,
				  success: onSuccess,
				  error : onError 
				});
	
			if(anchor)
			{
			//alert(anchor);
			// Eseguo lo scrolling sugli anchor interni
			/*$('#content').localScroll({// Only the links inside that jquery object will be affected
				lazy: true, // This is the KEY setting here, makes the links work even after an Ajax load.
				target: '#content', // The element that gets scrolled
				axis:'y', // Vertical scrolling
				duration:500,
				onBefore:function( e, subsec, $cont ){//'this' is the clicked link
					if(this.blur)
						this.blur(); // Remove the awful outline
				}
			});*/
			if(load = true)
			{	
				$('#content').scrollTo( $('a:[name="'+ anchor +'"]'), 800 ); // Sposta il link sull'anchor di Js
			}	
			
			}
		  }	
		}
		
		return false;
		
	}); 	

}


//Operazioni di loading
function onStartLoading() {
$("#loading").html('<span class="red">&nbsp; Attendere caricamento dati in corso ...</span> ');		
}

function onError(xhr, st, er) {
alert(er);         
} 

function onSuccess( msg )
{	

$("#loading").empty();
$('#content').show('slow');
$("#content").html(msg);
load = true; 
// Aggiungo il lightbox alle immagini
$('#content .shutterset_fotografie , #content .shutterset_gallery').lightBox({fixedNavigation:true});
//return false;

} // End-Function


/*
*
*	jQuery Timer plugin v0.1
*		Matt Schmidt [http://www.mattptr.net]
*
*	Licensed under the BSD License:
*		http://mattptr.net/license/license.txt
*
*/

jQuery.timer = function (interval, callback)
{
/**
 *
 * timer() provides a cleaner way to handle intervals  
 *
 *	@usage
 * $.timer(interval, callback);
 *
 *
 * @example
 * $.timer(1000, function (timer) {
 * 	alert("hello");
 * 	timer.stop();
 * });
 * @desc Show an alert box after 1 second and stop
 * 
 * @example
 * var second = false;
 *	$.timer(1000, function (timer) {
 *		if (!second) {
 *			alert('First time!');
 *			second = true;
 *			timer.reset(3000);
 *		}
 *		else {
 *			alert('Second time');
 *			timer.stop();
 *		}
 *	});
 * @desc Show an alert box after 1 second and show another after 3 seconds
 *
 * 
 */

	var interval = interval || 100;

	if (!callback)
		return false;
	
	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};
		
		this.internalCallback = function () {
			callback(self);
		};
		
		this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);
			
			var val = val || 100;
			this.id = setInterval(this.internalCallback, val);
		};
		
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		
		var self = this;
	};
	
	return new _timer(interval, callback);
};