var AJAX = '/ajax/ajax.php';
var FB_AJAX = '/ajax/facebook.php';

function les_noticies( lloc ) {

	if( lloc == 'mes_comentats' )
	{
		$("#darrers_comentaris").hide();
		$("#mes_llegit").hide();
		$("#mes_comentat").fadeIn('slow');
		
		$("#comentaris_tag").removeClass("plantilla_actualitat_tag_inactiu");
		$("#comentaris_tag").addClass("plantilla_actualitat_tag_actiu");
		
		$("#noticies_tag").removeClass("plantilla_actualitat_tag_actiu");
		$("#noticies_tag").addClass("plantilla_actualitat_tag_inactiu");
		$("#darrers_comentaris_tag").removeClass("plantilla_actualitat_tag_actiu");
		$("#darrers_comentaris_tag").addClass("plantilla_actualitat_tag_inactiu");
	}
	else if( lloc == 'darrers_comentaris' )
	{
		$("#darrers_comentaris").fadeIn('slow');
		$("#mes_llegit").hide();
		$("#mes_comentat").hide();
		
		$("#darrers_comentaris_tag").removeClass("plantilla_actualitat_tag_inactiu");
		$("#darrers_comentaris_tag").addClass("plantilla_actualitat_tag_actiu");
		
		$("#comentaris_tag").removeClass("plantilla_actualitat_tag_actiu");
		$("#comentaris_tag").addClass("plantilla_actualitat_tag_inactiu");
		$("#noticies_tag").removeClass("plantilla_actualitat_tag_actiu");
		$("#noticies_tag").addClass("plantilla_actualitat_tag_inactiu");
	}
	else
	{
		$("#darrers_comentaris").hide();
		$("#mes_llegit").fadeIn('slow');
		$("#mes_comentat").hide();
		
		$("#noticies_tag").removeClass("plantilla_actualitat_tag_inactiu");
		$("#noticies_tag").addClass("plantilla_actualitat_tag_actiu");
		
		$("#comentaris_tag").removeClass("plantilla_actualitat_tag_actiu");
		$("#comentaris_tag").addClass("plantilla_actualitat_tag_inactiu");
		$("#darrers_comentaris_tag").removeClass("plantilla_actualitat_tag_actiu");
		$("#darrers_comentaris_tag").addClass("plantilla_actualitat_tag_inactiu");
	}
}

function comprovaCamp ( id_camp )
{
	if( $("#"+id_camp).val() == "" )
	{
		$("#"+id_camp).addClass("comentari-error");
		$("#"+id_camp).removeClass("comentari");
	}
	else
	{
		$("#"+id_camp).addClass("comentari");
		$("#"+id_camp).removeClass("comentari-error");
	}
}

function comprovaMail ( id_camp )
{
	if ( $("#"+id_camp).val() == "" || !echeck( $("#"+id_camp).val() ) )
	{
		$("#"+id_camp).addClass("comentari-error");
		$("#"+id_camp).removeClass("comentari-color");
	}
	else
	{
		$("#"+id_camp).addClass("comentari-color");
		$("#"+id_camp).removeClass("comentari-error");
	}
}


function enviar_comentari()
{
	var error = false;
	var error_text = '';
	var id_article;
	var facebook_uid = 0;
	var facebook_foto = '';
	var nom = '';
	var ae = '';
	var comentari;
	var poblacio = '';
	var tmp;
	var email;
	var notifica;
	
	$("#comentari-error").html();
	$("#comentari-error").hide();
	var id_article = $("#id_article").val();
	var id_blog = $("#id_blog").val();

	if( $("input[@name='notifica']:checked").attr("value") )
		notifica = 'si';
	else
		notifica = 'no';

	if( $("#facebook_uid").val() )
	{
		var facebook_uid = $("#facebook_uid").val();
		var facebook_foto = $("#facebook_foto").val();
	}
	
	if( $("#email").val() ) return false;
	if( $("#nom").val() )
	{
		$("#nom").removeClass("comentari-error");
		$("#nom").addClass("comentari");
		var nom = $("#nom").val();
	}
	else if( !facebook_uid )
	{
		$("#nom").addClass("comentari-error");
		$("#nom").removeClass("comentari");
		error_text += "<li>Has de posar el teu nom</li>\n";
		error = true;
	}
	
	if( $("#ae").val() )
		var ae = $("#ae").val();
		
	if( $("#poblacio").val() )
		var poblacio = $("#poblacio").val();

	//if( $("#ae").val() )
	//{
	//	var ae = $("#ae").val();
	//	if( echeck( ae ) )
	//	{
	//		$("#ae").removeClass("comentari-error");
	//		$("#ae").addClass("comentari-color");
	//	}
	//	else
	//	{
	//		$("#ae").addClass("comentari-error");
	//		$("#ae").removeClass("comentari");
	//		error_text += "<li>El correu elctrònic que has posat és erroni</li>\n";
	//		error = true;
	//	}
	//}
	//else
	//{
	//	$("#ae").addClass("comentari-error");
	//	$("#ae").removeClass("comentari");
	//	error_text += "<li>Has de posar el correu electrònic</li>\n";
	//	error = true;
	//}
	
	if( $("#comentari").val() )
	{
		var comentari = $("#comentari").val();
		$("#comentari").removeClass("comentari-error");
		$("#comentari").addClass("comentari-color");
	}
	else
	{
		$("#comentari").addClass("comentari-error");
		$("#comentari").removeClass("comentari");
		error_text += "<li>Has d'escriure un comentari</li>\n";
		error = true;
	}
	
	$.post( AJAX, { accio: 'controlar_spam_comentaris' },
	function( resposta )
	{
		//if( resposta == 'true' )
		//{
		//	error_text += "<li>S'han detectat masses enviaments a través d'aquesta ip, torna-ho a provar d'aquí una estona</li>";
		//	$("#comentari-error").fadeIn("slow");
		//	$("#comentari-error").html( '<ul class="error">' + error_text + '</ul>' );
		//}
		//else
		//{
			$("#comentari-formulari").html( '<img src="/img/icones/loading.gif" alt="loader" style="margin: 100px 0px 100px 250px" />' );
			$.getJSON( AJAX, { id_article: id_article, id_blog: id_blog, facebook_uid: facebook_uid, facebook_foto: facebook_foto,
					  nom: nom, poblacio: poblacio, email: ae, notifica: notifica, comentari: comentari, accio: 'enviar_comentari' },
			function( resposta )
			{
				$("#comentari-error").css("display", "")
				$("#comentari-formulari").fadeOut("slow");
				
				if( facebook_uid )
				{
					var message = resposta.comentari;
					if( resposta.imatge )
					{
						var attachment = {
								'name': resposta.titol,
								'href': resposta.url,
								'media': [{
									'type': 'image',
									'src': resposta.imatge,
									'href': resposta.url
									}] };
					}
					else
					{
						var attachment = {
								'name': resposta.titol,
								'href': resposta.url
								};
					}
					var action_links = [{'text':resposta.titol, 'href':resposta.url}];
					FB.Connect.streamPublish(message, attachment, action_links);
					
					$("#comentari-enviat").fadeIn("slow");
				}
				else{
					alert ('hola');
					window.location.reload()
				}
			});
		//}
	});
	
	if( error )
	{
		$("#comentari-error").fadeIn("slow");
		$("#comentari-error").html( '<ul class="error">' + error_text + '</ul>' );
	}
}


function genera_comentaris( pagina, id_article )
{
 	if( pagina && id_article )
	{
		$("#comentaris-cnt").html( '<img src="/img/icones/loading.gif" alt="loader" style="margin: 100px 0px 100px 250px" />' );
		$.post( AJAX, { id_article: id_article, pagina: pagina, accio: 'genera_comentaris' },
		function( resposta )
		{
			$("#comentaris-cnt").html( resposta );
			window.location.hash = "comentaris";
		});
	}
	else
	{
		alert("Error");
	}
}

function veure_comentari( id_comentari )
{
 	if( id_comentari )
	{
		$.getJSON( AJAX, { id_comentari: id_comentari, accio: 'veure_comentari' },
		function( resposta )
		{
			$("#comentari-cnt-" + resposta.id_comentari ).html( resposta.text );
		});
	}
	else
	{
		alert("Error");
	}
}

function limitacio( numero, id_article )
{
 	if( numero && id_article )
	{
		$("#comentaris-cnt").html( '<img src="/img/icones/loading.gif" alt="loader" style="margin: 100px 0px 100px 250px" />' );
		$.post( AJAX, { numero: numero, accio: 'limitacio' },
		function()
		{
			genera_comentaris( "1", id_article );
		});
	}
	else
	{
		alert("Error");
	}
}





function echeck(str)
{
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	
	if (str.indexOf(at)==-1)
		return false;

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
		return false;

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
		return false;

	if (str.indexOf(at,(lat+1))!=-1)
		return false;

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
		return false;

	if (str.indexOf(dot,(lat+2))==-1)
		return false;

	if (str.indexOf(" ")!=-1)
		return false;

	return true;
}




function buildCal( mes, any )
{
	var m = mes;
	var y = any;
	var id_blog = $("#id_blog").val();
		
	$('#calendari').html( '<img src="/img/icones/loading.gif" alt="loader" style="margin: 40px 0px 0px 100px" />' );
	$.getJSON( AJAX, { id_blog: id_blog, mes: m, any: y, accio: 'arxiu' },
	function( resposta )
	{
		var dies_actes = new Array();
	
		for( var i = 1; i <= 31; i++ )
		{
			dies_actes[i] = false;
		}
	
		if( resposta.dies )
		{
			for(var i = 0; i < resposta.total; i++)
			{
				dies_actes[resposta.dies[i]] = true;
			}
		}
		
		mes_actual = m;
		any_actual = y;
	
		var mn=['gener','febrer','mar&#231;','abril','maig','juny','juliol','agost','setembre','octubre','novembre','desembre'];
		var dies=['dl','dt','dc','dj','dv','ds','dg'];
		
		var dim=[31,0,31,30,31,30,31,31,30,31,30,31]; /* dies dels mesos */
		var dim_ant=[31,31,0,31,30,31,30,31,31,30,31,30]; /* dies dels mesos anteriors */
		var dim_seg=[0,31,30,31,30,31,31,30,31,30,31,31]; /* dies dels mesos posteriors */
	
		var oD = new Date(y, m-1, 1);
		oD.od = oD.getDay(); /* dia de la setmana 0 - dg, 6 - ds */
	
		var data_avui = new Date();
		var avui = (y == data_avui.getFullYear() && m == data_avui.getMonth() + 1) ? data_avui.getDate() : 0;
		var setmana_avui = parseInt( (avui-1) / 7 ) + 1; /* la setmana del dia d'avui, més una setmana del mes anterior */
		setmana_actual = setmana_avui;
		
		// dies que té el febrer
		dim[1] = (((oD.getFullYear()%100!=0)&&(oD.getFullYear()%4==0))||(oD.getFullYear()%400==0))?29:28;
		dim_ant[2] = dim[1];
		dim_seg[0] = dim[1];
		
		var bloc = resposta.blog;
						
		var html = '<table class="calendari_mes"><tr><td>';
		html += '	<a onclick="mes_anterior();"><img src="img/icones/fletxa_e.png" alt="fletxa esquerra" /></a>';
		html += '</td><td class="desplacament">';
		html += '	<a href="/agenda/'+ y +'/'+ m +'">'+mn[m-1]+' '+y+'</a>';
		html += '</td><td>';
		html += '	<a onclick="mes_seguent();"><img src="img/icones/fletxa_d.png" alt="fletxa dreta" /></a>';
		html += '</td></tr></table>';
		
		html += '<table class="calendari_dies" cols="7" cellpadding="3" cellspacing="0">';
		html += '<tr class="cal_cap_dia">';
		
		for( s = 0; s < 7; s++ )
			html += '<td class="">'+dies[s]+'</td>';
		
		html += '</tr><tr class="cal_dies">';
		
		var dia = 1;
		var setmana = 0;
		var classes = '';
		var uri = resposta.blog;
		
		/* posa els dies del mes anterior */
		for( i = ( dim_ant[m-1] - 7 - oD.od + 2 ); i <= dim_ant[m-1]; i++ )
		{
			html += '<td></td>';
			if( dia%7 == 0 )
			{
				html += '</tr><tr class="cal_dies">';
				setmana++;
			}
			dia++;
		}
		
		for( i = 1; i <= dim[m-1]; i++ )
		{
			classes = '';
			var x = i;
			
			if( dia%7 == 0 ) classes += 'cal_fest ';
			if( x == avui ) classes += 'cal_avui ';
			
			if( dies_actes[x] == true )
			{
				classes += 'cal_acte ';
				
				html += '<td id="id-'+ x +'" unselectable="on"><a class="'+classes +'" href="/'+bloc+'/agenda/'+ y +'/'+ m +'/'+ x +'">' + x + '</a></td>';
			}
			else
				html += '<td unselectable="on"><span class="'+classes+'">' + x + '</span></td>';
	
			if( dia%7 == 0 )
			{
				html += '</tr><tr class="cal_dies">';
				setmana++;
			}
			dia++;
		}
		var ultim_dia = oD.od + dim[m-1]%7;
		
		
		for( i = 1; i < 14 - ultim_dia + 2; i++ )
		{
			html += '<td></td>';
			if( dia%7 == 0 )
			{
				html += '</tr><tr class="cal_dies">';
				setmana++;
			}
			dia++;
		}
		
		html += '</tr></table>';
		
		$('#calendari').html( html );	
	});
}


function mes_anterior()
{
	if( mes_actual == 1 )
	{
		mes_actual = 12;
		any_actual--;
	}
	else mes_actual--;
	
	buildCal( mes_actual, any_actual );
}
function mes_seguent()
{
	if( mes_actual == 12 )
	{
		mes_actual = 1;
		any_actual++;
	}
	else mes_actual++;
	
	buildCal( mes_actual, any_actual );
}

function cerca_apartat( seccio )
{
	var seccions = new Array(4) 
	seccions[0] = 'noticia';
	seccions[1] = 'presencia';
	seccions[2] = 'arxiu';
	seccions[3] = 'enllac';
	
	for (i=0;i<4;i++)
	{
		seccio_sel = seccions[i]
		if( seccio == seccions[i] )
		{
			$('#boto_'+seccio_sel).removeClass('inactiu');
			$('#boto_'+seccio_sel).addClass('actiu');
			$('#cerca_'+seccio_sel).show();
		}
		else
		{
			$('#boto_'+seccio_sel).removeClass('actiu');
			$('#boto_'+seccio_sel).addClass('inactiu');
			$('#cerca_'+seccio_sel).hide();
		}
	}
}


// Variables
var ratings_mouseover_image = new Image();
ratings_mouseover_image.src = "/img/icones/valora_over.png";

// When User Mouse Over Ratings
function valora_actual(rating, rating_text)
{
	var id_article = $('#id_article').val();

	for(i = 1; i <= rating; i++)
		document.images['valora_' + i].src = eval("ratings_mouseover_image.src");
		
	$('#valora_text').html( rating_text );
	$('#valora_text').css("display", "inline");
}


// When User Mouse Out Ratings
function valora_off(rating_score, insert_half)
{
	for(i = 1; i <= 5; i++)
	{
		if(i <= rating_score)
			document.images['valora_' + i].src = '/img/icones/valora_on.png';
		else if(i == insert_half)
			document.images['valora_' + i].src = '/img/icones/valora_meitat.png';
		else
			document.images['valora_' + i].src = '/img/icones/valora_off.png';
	}
	
	$('#valora_text').html( '' );
	$('#valora_text').css("display", "inline");
}

function valora_article( valor )
{
	var id_article = $('#id_article').val();
	var lloc = $('#lloc').val();
	
	$('#valora_estrelles').css("display", "none");
	$('#valora_loading').css("display", "inline");
	
	$.getJSON( AJAX, { lloc: lloc, valor: valor, id_article: id_article, accio: 'valorar' },
	function( resposta )
	{
		$('#valora_estrelles').css("display", "inline")
		$('#valora_loading').css("display", "none")
		
		$('#valora_estrelles').html( '' );
		var html = '';
		
		var textos=['','Molt dolent','Fluix','Interessant','Molt bo','Excepcional'];

		for( var i = 1; i <= 5; i++ )
		{
			if( resposta.mitja >= i )
				html += '<img src="/img/icones/valora_on.png" alt="estrella" />';
			else if( resposta.meitat == i )
				html += '<img src="/img/icones/valora_meitat.png" alt="estrella" />';
			else
				html += '<img src="/img/icones/valora_off.png" alt="estrella" />';
		}
		
		if( resposta.vots == 1 )
			html += ' <small>( <strong>'+ resposta.vots +'</strong> vot )</small>';
		else
			html += ' <small>( <strong>'+ resposta.vots +'</strong> vots )</small>';

		$('#valora_estrelles').html( html );
	});
}


function comparteix( url )
{
	if ($("#comparteix").length === 0) {
		var html = '<a href="http://latafanera.cat/submit.php?url=' + url + '" title="Envia a La Tafanera"><img src="img/icones/tafanera.png" alt="La Tafanera" /></a> ';
		html += '<a href="http://technorati.com/search/' + url + '" title="Cerca a Technorati"><img src="img/icones/technorati.png" alt="Technorati" /></a> ';
		html += '<a href="http://del.icio.us/post?url=' + url + '" title="Envia a Delicious"><img src="img/icones/delicious.png" alt="Delicious" /></a> ';
		html += '<a href="http://www.facebook.com/share.php?u=' + url + '" title="Comparteix a Facebook"><img src="img/icones/peu_facebook.png" alt="Facebook" /></a> ';
		html += '<a href="http://www.google.com/bookmarks/mark?op=edit&bkmk==' + url + '" title="Comparteix a Google"><img src="img/icones/google.png" alt="Google" /></a>';
		$(".llegenda_article").append('<div id="comparteix">'+ html +'</div>');
	}
}


function actualitzar_usuari()
{
	$('#div-facebook').html( "<fb:profile-pic uid='loggedinuser' facebook-logo='true'></fb:profile-pic>"
	+ "<br />Benvingut, <fb:name uid='loggedinuser' useyou='false'></fb:name>. T'has identificat amb el teu compte de Facebook. "
	+ "<a href=\"#\" onclick=\"FB.Connect.logout(function() { window.location.reload(); }); return false;\">Sortir</a>" );
	
	FB.XFBML.Host.parseDomTree();

	$('#div-nom').hide();
	$('#div-ae').hide();
	$('#div-poblacio').hide();
	$('#div-notifica').hide();

	var api = FB.Facebook.apiClient;
	var uid = [api.get_session().uid]
	$('#facebook_uid').val( uid );

	$.getJSON( FB_AJAX, { uid: uid, accio: 'actualitzar_usuari' },
	function( resposta )
	{
		$('#facebook_foto').val( resposta.foto );
		$('#nom').val( resposta.nom );
		$('#poblacio').val( resposta.poblacio );
		$('#ae').val( resposta.ae );
	});
}


function votar_comentari( id_comentari, vot, lloc)
{
	$.post( AJAX, { id_comentari: id_comentari, vot: vot, lloc: lloc, accio: 'votar_comentari' },
	function( resposta )
	{
		$("#comentari-vots-" + id_comentari ).hide();
		$("#comentari-vots-" + id_comentari ).html( resposta );		
		$("#comentari-vots-" + id_comentari ).fadeIn('slow');
	});
}

function comentari_replica( id )
{
	ref = '#' + id + ' ';
	textarea = $('#comentari');
	if (textarea.length == 0 ) return;
	var re = new RegExp(ref);
	var oldtext = textarea.val();
	if (oldtext.match(re)) return;
	if (oldtext.length > 0 && oldtext.charAt(oldtext.length-1) != "\n") oldtext = oldtext + "\n";
	textarea.val(oldtext + ref);
	textarea.get(0).focus();
}

function comprovar( lloc)
{
	var usuari = $('#ipt-'+lloc).val();

	$.post( AJAX, { lloc: lloc, usuari: usuari, accio: 'comprovar' },
	function( resposta )
	{
		if( resposta == 1 )
		{
			$("#ipt-" + lloc ).addClass('comentari');
			$("#ipt-" + lloc ).removeClass('comentari-error');
		}
		else
		{
			$("#ipt-" + lloc ).addClass('comentari-error');
			$("#ipt-" + lloc ).removeClass('comentari');
		}
	});
}



function buildCal_agenda( mes, any, id_blog )
{
	var m = mes;
	var y = any;
		
	$('#calendari').html( '<img src="/img/icones/loading.gif" alt="loader" style="margin: 40px 0px 0px 100px" />' );
	$.getJSON( AJAX, { mes: m, any: y, id_blog: id_blog, accio: 'actes' },
	function( resposta )
	{
		var dies_actes = new Array();
	
		for( var i = 1; i <= 31; i++ )
		{
			dies_actes[i] = false;
		}
	
		if( resposta.dies )
		{
			for(var i = 0; i < resposta.total; i++)
			{
				dies_actes[resposta.dies[i]] = true;
			}
		}
		
		mes_actual = m;
		any_actual = y;
		id_blog_ = id_blog;
	
		var mn=['gener','febrer','mar&#231;','abril','maig','juny','juliol','agost','setembre','octubre','novembre','desembre'];
		var dies=['dl','dt','dc','dj','dv','ds','dg'];
		
		var dim=[31,0,31,30,31,30,31,31,30,31,30,31]; /* dies dels mesos */
		var dim_ant=[31,31,0,31,30,31,30,31,31,30,31,30]; /* dies dels mesos anteriors */
		var dim_seg=[0,31,30,31,30,31,31,30,31,30,31,31]; /* dies dels mesos posteriors */
	
		var oD = new Date(y, m-1, 1);
		oD.od = oD.getDay(); /* dia de la setmana 0 - dg, 6 - ds */
	
		var data_avui = new Date();
		var avui = (y == data_avui.getFullYear() && m == data_avui.getMonth() + 1) ? data_avui.getDate() : 0;
		var setmana_avui = parseInt( (avui-1) / 7 ) + 1; /* la setmana del dia d'avui, més una setmana del mes anterior */
		setmana_actual = setmana_avui;
		
		// dies que té el febrer
		dim[1] = (((oD.getFullYear()%100!=0)&&(oD.getFullYear()%4==0))||(oD.getFullYear()%400==0))?29:28;
		dim_ant[2] = dim[1];
		dim_seg[0] = dim[1];
		
		var bloc = resposta.bloc;
		
		var html = '<table class="calendari_mes"><tr><td>';
		html += '	<a onclick="mes_anterior_agenda();"><img src="img/icones/fletxa_e.png" alt="fletxa esquerra" /></a>';
		html += '</td><td class="desplacament">';
		html += '	<a href="'+resposta.uri_blog+'/agenda/'+ y +'/'+ m +'">'+mn[m-1]+' '+y+'</a>';
		html += '</td><td>';
		html += '	<a onclick="mes_seguent_agenda();"><img src="img/icones/fletxa_d.png" alt="fletxa dreta" /></a>';
		html += '</td></tr></table>';
		
		html += '<table class="calendari_dies" cols="7" cellpadding="3" cellspacing="0">';
		html += '<tr class="cal_cap_dia">';
		
		for( s = 0; s < 7; s++ )
			html += '<td class="">'+dies[s]+'</td>';
		
		html += '</tr><tr class="cal_dies">';
		
		var dia = 1;
		var setmana = 0;
		var classes = '';
		
		/* posa els dies del mes anterior */
		for( i = ( dim_ant[m-1] - 7 - oD.od + 2 ); i <= dim_ant[m-1]; i++ )
		{
			html += '<td></td>';
			if( dia%7 == 0 )
			{
				html += '</tr><tr class="cal_dies">';
				setmana++;
			}
			dia++;
		}
		
		for( i = 1; i <= dim[m-1]; i++ )
		{
			classes = '';
			var x = i;
			
			if( dia%7 == 0 ) classes += 'cal_fest ';
			if( x == avui ) classes += 'cal_avui ';
			
			if( dies_actes[x] == true )
			{
				classes += 'cal_acte ';
				
				html += '<td id="id-'+ x +'" unselectable="on"><a class="'+classes +'" href="'+resposta.uri_blog+'/agenda/'+ y +'/'+ m +'/'+ x +'">' + x + '</a></td>';
			}
			else
				html += '<td unselectable="on"><span class="'+classes+'">' + x + '</span></td>';
	
			if( dia%7 == 0 )
			{
				html += '</tr><tr class="cal_dies">';
				setmana++;
			}
			dia++;
		}
		var ultim_dia = oD.od + dim[m-1]%7;
		
		
		for( i = 1; i < 14 - ultim_dia + 2; i++ )
		{
			html += '<td></td>';
			if( dia%7 == 0 )
			{
				html += '</tr><tr class="cal_dies">';
				setmana++;
			}
			dia++;
		}
		
		html += '</tr></table>';
		
		$('#calendari').html( html );	
	});
}


function mes_anterior_agenda()
{
	if( mes_actual == 1 )
	{
		mes_actual = 12;
		any_actual--;
	}
	else mes_actual--;
	
	buildCal_agenda( mes_actual, any_actual, id_blog_ );
}
function mes_seguent_agenda()
{
	if( mes_actual == 12 )
	{
		mes_actual = 1;
		any_actual++;
	}
	else mes_actual++;
	
	buildCal_agenda( mes_actual, any_actual, id_blog_ );
}

function veure_acte( id_acte )
{
 	if( id_acte )
	{
		$.getJSON( AJAX, { id_acte: id_acte, accio: 'veure_acte' },
		function( resposta )
		{
			$("#contingut-" + id_acte ).html( resposta.contingut );
			$("#veure_acte-" + id_acte ).css( "display", "none" );
			$("#amaga_acte-" + id_acte ).css( "display", "block" );
			$("#contingut-" + id_acte ).css( "display", "block" );
						
			if( GBrowserIsCompatible() && resposta.lat != 0 && resposta.lng != 0 )
			{
				$("#mapat_" + id_acte ).css( "display", "block" );
				mapat = new GMap2(document.getElementById( "mapat_" + id_acte ));
				var geocoder = new GClientGeocoder();
				
				mapat.addControl (new GSmallZoomControl());
				mapat.addControl (new GMapTypeControl());
				
				mapat.enableDoubleClickZoom();
				mapat.enableScrollWheelZoom();
			
				var punt = new GLatLng( resposta.lat , resposta.lng );
				
				mapat.setCenter( punt , 15 );
				marker = new GMarker( punt, {draggable: true}  );
				mapat.addOverlay(marker);
			}
		});
	}
	else
	{
		alert("Error inesperat!");
	}
}

function amaga_acte( id_acte )
{
	$("#veure_acte-" + id_acte ).css( "display", "block" );
	$("#amaga_acte-" + id_acte ).css( "display", "none" );
	$("#contingut-" + id_acte ).css( "display", "none" );
	$("#mapat_" + id_acte ).css( "display", "none" );
}




/* Define Outlook constant for Appointment Item */
var olAppointmentItem = 1;

/* To add other Properties, refer to the Outlook Object Model */
function appt( Subject, Location, Start, ReminderMinutesBeforeStart ){
	this.Subject = Subject;
	this.Location  = Location;
	this.Start  = Start;
	this.ReminderMinutesBeforeStart = ReminderMinutesBeforeStart;
}

function saveAppt( obj )
{
	/* Create the Outlook Object and Appointment Item */
	try{
	out = new ActiveXObject( "Outlook.Application" );
	}
	catch (e) {
	if (e.description){
		alert("Error detectat: " + e.description)
	}else{
		alert("Error detectat: " + e)
	}

	out = new ActiveXObject( "Outlook.Application" );
	}


	/* Create an Appointment Item */
	appt = out.CreateItem( olAppointmentItem );

	/* Transfer the data */
	appt.Subject = obj.Subject;
	appt.Location  = obj.Location;
	appt.Start = obj.Start;
	appt.End   = obj.Start;
	appt.ReminderMinutesBeforeStart = obj.ReminderMinutesBeforeStart;
	
	/* Display the data */
	/* If you want to save instead of viewing it change to appt.Save();*/
	appt.Display();
	
}


function galeria_lateral( id_blog, id_galeria )
{
	var id_galeria_imatge = $("#id_galeria_imatge").val();
	
	$.getJSON( AJAX, { id_blog: id_blog, id_galeria_imatge: id_galeria_imatge, id_galeria: id_galeria, accio: 'galeria_lateral' },
	function( resposta )
	{
	    $("#galeria_imatge img").attr({ src: "/img/310/300/"+ resposta.id_imatge }); //Switch the main image (URL + alt tag)
		
		$("#id_galeria_imatge").val( resposta.id_galeria_imatge );
		$("#galeria_imatge a").attr("href","galeria/"+ resposta.uri +"#"+ resposta.id_galeria_imatge );

		setTimeout( 'galeria_lateral('+ id_blog +','+ id_galeria +')', 5000 );
	});
}
