/**
 * Invocazione load con passaggio id div chiamante e uri 
 */

$(function(){
	$('body').append('<img id="preloaded-loading-img" src="../img/ajax-loader.gif" style="display:none"/>');
	$('.ajaxLoading').hashchange(function (e, newHash) {
		$(this).loadFromHistory(newHash); 
	});
	$.hash.init('blank.html');
});

/**
 * Carica una sezione di pagina passandogli il post (d'appoggio per loadIn e refresh)
 * nel post vi è anche la pagina di riferimento
 */
jQuery.fn.charge=function(post,fn,dataType,opt){
	$(this).data('uri_call',post.elementUri);
	if(opt==null){
		opt={ 
			msg:'Loading...',
			in_obj:''
		};
	}else{
		if(opt.msg==null) opt.msg = 'Loading...';
		if(opt.in_obj==null) opt.in_obj='';
	}

	var in_obj = (opt.in_obj == '') ? $(this) : $('#'+opt.in_obj);		
	in_obj.loadingShow(opt);
	
	// POST	
	var obj = $(this);
	$.post(post.elementUri,post,function(data){
		if(post.elementUri == obj.data('uri_call')){
			in_obj.loadingHide(function(){
				obj.html(data);
				// Aggiorna il menu
				updateMenu();
			});
			if(fn!=null) fn();
		}
	},dataType);
	
};

/**
 * Carica una sezione di pagina e predispone per ventuale refresh
 */
jQuery.fn.loadIn=function( uri, post, fn, dataType, opt ){
	if(uri){
		var DIGIT = 10;
		
		$(this).each(function(){
			
			if(post==null)post={};
			
			$(this).data('uri_call',uri);
			$(this).addClass('ajaxLoading');
			
			post.elementId = $(this).attr('id');
			post.elementUri = uri;
			
			var new_hash = Math.floor((Math.random().toFixed(DIGIT))*Math.pow(10, DIGIT));
			
			if($(this).data('history')==null)$(this).data('history',{});
			$(this).data('history')[new_hash]=post;
			$(this).data('history').last=new_hash;
			
			if(opt){
				if(opt.toTrack)$.trackPage(post.elementUri);
				if(opt.trackAs)$.trackPage(opt.trackAs);
			}
			$(this).saveHistory();
			location.href = '#'+new_hash;
		});
	}
};

/**
 * Ricarica una sezione di pagina in base alla storia
 */
jQuery.fn.loadFromHistory=function(hash){
	
	$(this).each(function(){
		
		
		if($(this).data('history')==null)return false;
		
		var post;
		
		if($(this).data('history')[hash]==null){
			post =$(this).data('history')[$(this).data('history').last];
		}else{
			post =$(this).data('history')[hash];
		}

		$(this).charge(post);
		
	});
};
/**
 * Salva cronologia
 */
jQuery.fn.saveHistory=function(){
	$(this).each(function(){
		if($(this).data('history')==null)return;
		$.post('../core/ajaxLoading.php',{
			 elementId :$(this).attr('id'), 
			'ajaxLoading-history' : JSON.stringify($(this).data('history'))  
		});
		
	});
};

/**
 * Carica una sezione di pagina senza toccare la storia
 */
jQuery.fn.loadInNH=function( uri, post, fn, dataType, opt ){
	if(uri){
		$(this).each(function(){
			
			if(post==null)post={};
			
			$(this).data('uri_call',uri);
			$(this).addClass('ajaxLoading');
			
			post.elementId = $(this).attr('id');
			post.elementUri = uri;
			
			$(this).charge(post,fn,dataType,opt);			
		});
	}
};

/**
 * Nasconde una porzione di pagina specificata
 */
jQuery.fn.loadingShow=function(opt){
	if(opt==null) opt={ msg:'Loading...' };
	else if(opt.msg==null) opt.msg = 'Loading...';

	if($('#loading-div').attr('id')!=null) $('#loading-div').remove();
	$('html').css({cursor:'wait'});
	var loading = $('<div id="loading-div" style="display:none;z-index:5000;"><p style="padding-top:50px;"></p><p>'+opt.msg+'</p></div>');
	$(this).css({visibility: "hidden", display: "inline" });
	loading.css({
		position : 			'absolute',
		top: 				$(this).offset().top,
		left: 				$(this).offset().left,
		width: 				$(this).width(),
		height: 			($(this).height() + 50),
		backgroundColor: 	'white',
		textAlign: 			'center'
	});
	$(this).css({ visibility: "", display: "" });
	$('body').append(loading);
	loading = $('#loading-div');
	var img = $('#preloaded-loading-img').clone().attr('id','loading-img');
	loading.find('p:first').append(img);
		
	img.show();
	loading.show();
};

/**
 * Mostra una porzione di pagina specificata
 */
jQuery.fn.loadingHide=function(fn){
	if($('#loading-div').attr('id')!=null){
		$(this).css({visibility:'hidden'});
		if(fn!=null) fn();
		var loading = $('#loading-div');
		loading.css({
			top:	 			$(this).offset().top,
			left: 				$(this).offset().left,
			width:				$(this).width(),
			height:				($(this).height() + 50)
		});
		$(this).css({visibility:''});
		loading.fadeOut('slow',function(){
			$(this).remove();
		});
		$('html').css({cursor:'auto'});
	}
};

function updateMenu(){
	// Se il menu è stato inizializzato, lo aggiorna
	if($('#menu').data('opt')!=null){
		$('#menu').setSelectedLink();
	}else{
		// In caso contrario attende l'inizializzazione
		setTimeout("$('#menu').setSelectedLink();",50);
	}
}