var img = '';
var cortoUrl='';
var semaforTxt=true;

$(document).ready(function() {
	$('div.menu a').click(function() { 
		carrega(this,this.href);
		return false;
	});
	escoltaSubmenu();
	
	$('.scroll-pane').jScrollPane({scrollbarWidth:18});

});

function escoltaSubmenu() {
	$('div.submenu a').click(function() { 
		carregaSub(this,this.href);
		return false;
	});	

	$('.formulariomagico').click(function() { 
		carregaSub(this,this.href);
		return false;
	});

}

function carrega(opcio, url) {

	semaforTxt=false;
	
	cortoUrl=url.split('/');
	cortoUrl=cortoUrl[cortoUrl.length-1].split('.');
	cortoUrl=cortoUrl[0];

	$('.menu a').removeClass("on");
	$(opcio).addClass("on");

	$('div.contenidor').animate({ opacity: 0 },'fast', function () {
		$.ajax({
			url: cortoUrl + '.php?ajax=1',
			cache: false,
			success: function(html){
						$("div.contenidor").html(html);
						semaforTxt=true;
			},
			error:function (m){
						alert('Error al carregar el texte');
						location.href=cortoUrl + ".php";
			},
			timeout:function (m){
						alert('Error al carregar el texte');
						location.href=cortoUrl + ".php";
			}     
		});
	});

	img = new Image();
	$(img)
		.load(function () {
			$('#fons').after('<div id="fonsTrans"></div>');
			$('#fonsTrans').append (img);
			$('#fons').stop(true, true).animate({ opacity: 0 },'slow', function () {
				//Ja ha acabat la fosa de canvi de imatge
				$('#fons').html('');
				$('#fons').append (img);
				$('#fons').css('opacity','1');
				$('#fonsTrans').remove();
				mostraTxt();
				escoltaSubmenu();
			});
		})
		.error(function () {
			alert("error al carregar la imatge de fons");
			location.href=cortoUrl + ".php";
		})
		.attr('src', 'img/' + cortoUrl + '.jpg');
}

function carregaSub(opcio, url) {

	cortoUrl=url.split('/');
	cortoUrl=cortoUrl[cortoUrl.length-1].split('.');
	cortoUrl=cortoUrl[0];

	$('div.contenidor').animate({ opacity: 0 },'fast', function () {
		$.ajax({
			url: cortoUrl + '.php?ajax=1',
			cache: false,
			success: function(html){
						$("div.contenidor").html(html);
						semaforTxt=true;
						mostraTxt();
						$("div.contenidor .espaia").addClass('parche');
						escoltaSubmenu();
			},
			error:function (m){
						alert('Error al carregar el texte');
						location.href=cortoUrl + ".php";
			},
			timeout:function (m){
						alert('Error al carregar el texte');
						location.href=cortoUrl + ".php";
			}     
		});
	});

}



function mostraTxt() {
	if (semaforTxt) {
		$('div.contenidor').animate({ opacity: 1 },'slow');
		$('.scroll-pane').jScrollPane({scrollbarWidth:18});
	} else {
		setTimeout('mostraTxt()',500);
	}
}

