var AJAX = '/ajax/ajax.php';
var GALERIA_AJAX = '/ajax/galeria.php';
var AGENDA_AJAX = '/ajax/agenda.php';

//if( location.href.match(/#(c-\d+)$/) )
//{
//	$("#"+RegExp.$1+">:first").css("border-style","double").css("border-width","3px")
//}


function avis_legal()
{
	if( $("#avis_legal").is(":hidden") )
		$("#avis_legal").fadeIn('slow');
	else
		$("#avis_legal").fadeOut('slow');
}

function les_noticies( lloc ) {

	if( lloc == 'comentaris' )
	{
		$("#mes_comentat").slideDown();
		$("#mes_llegit").slideUp();
		
		$("#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");
	}
	else
	{
		$("#mes_comentat").slideUp();
		$("#mes_llegit").slideDown();
		
		$("#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");
	}
}

function votar()
{
	var enq = $("input[@name='enq']:checked").attr("value");
  	if( enq )
	{
		$.getJSON( AJAX, { id_enquesta_opcio: enq, accio: 'votar' },
		function( resposta )
		{
			var vots = 0;
			vots = parseInt( vots );
				
 			$('#enquesta-opcions').fadeOut("slow", function()
 			{
				$(this).empty();

				for(var i = 0; i < resposta.opcions.length; i++)
				{
					tmp = parseInt( resposta.opcions[i].vots );
					vots = tmp + vots;
					afegeixOpcio(resposta.opcions[i].id_element, resposta.opcions[i].titol, resposta.opcions[i].width1, resposta.opcions[i].percentatge, enq, i);
				}

				html = '<div class="lila"><img src="img/icones/vots.png" alt="Vots" /> <span id="enquesta-vots">'+ vots +'</span> vots&nbsp;&nbsp;<a href="enquesta/'+ resposta.uri  +'#comentaris"><img src="img/icones/comentari.png" alt="Comentaris" /> '+ resposta.comentaris +'</a></div></div>';

				$('#enquesta-opcions').append( html );
				$('#enquesta-opcions').fadeIn("slow",function(){animateResults();});
			});
		});
	}
	else
	{
		alert("Has de seleccionar una opció!");
		return false;
	}
}

function afegeixOpcio(id, titol, width1, percentatge, enq, i)
{
	var html = '';

	if( id == enq )
		html += '<label for="enq_opt'+id+'"><strong>'+titol+'</strong></label><br />\n';
	else
		html += '<label for="enq_opt'+id+'">'+titol+'</label><br />\n';
		
	html += '	<div class="enq_barra" style="width: 0%;"></div>\n';
	html +=	'	<div class="enq_percent">'+percentatge+'%</div>\n';
	html +=	'<br class="p" /><br />\n';

	$('#enquesta-opcions').append( html );
}

function animateResults()
{
  $("#enquesta-opcions div.enq_barra").each(function()
  {
      var percentage = $(this).next().text();
      $(this).css({width: "0%"}).animate({width: percentage}, 'slow');
  });
}


function inscriure( accio )
{

	var email = $("#email_titulars").val();
	var nom = $("#nom_titulars").val();
         
	if( accio == 'alta' )
		accio = 'inscriure_alta';
	else
		accio = 'inscriure_baixa';
		
	if( email )
	{
		if( !echeck( email ) )
		{
			alert("El correu electrònic que has posat és incorrecte");
			return false;
		}
		
		if( accio == 'alta' ) accio = 'inscriure_alta';

		if( accio == 'baixa' ) accio = 'inscriure_baixa';

				
		$.getJSON( AJAX, { email: email, nom: nom, accio: accio },
		function( resposta )
		{
			if( resposta.exit == 'true' ) $("#inscriure-formulari").empty();
			$("#inscriure-text").html( resposta.text );
		});
	}
	else
	{
		alert("Falta posar la teva adreça electrònica");
		return false;
	}
}

function comprovaCamp ( id_camp, color )
{

	if( $("#"+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 comprovaMail ( id_camp, color )
{
	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 notifica = '';

	if( $("#email").val() ) return false;

	$("#comentari-error").html();
	$("#comentari-error").hide();
	var id_article = $("#id_article").val();
	var lloc = $("#lloc").val();
	var color = $("#color").val();

	if( $('#notifica').is(':checked') )
		notifica = 'si';
	else
		notifica = 'no';

	if( $("#facebook_uid").val() )
	{
		var facebook_uid = $("#facebook_uid").val();
		var facebook_foto = $("#facebook_foto").val();
	}
	
	if( $("#nom").val() )
	{
		$("#nom").removeClass("comentari-error");
		$("#nom").addClass("comentari-"+color);
		var nom = $("#nom").val();
	}
	else if( !facebook_uid )
	{
		$("#nom").addClass("comentari-error");
		$("#nom").removeClass("comentari-"+color);
		error_text += "<li>Has de posar el teu nom</li>\n";
		error = true;
	}

	if( $("#poblacio").val() )
		var poblacio = $("#poblacio").val();
		
	if( $("#ae").val() )
		var ae = $("#ae").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-"+color);
	//		error_text += "<li>El correu elctrònic que has posat és erroni</li>\n";
	//		error = true;
	//	}
	//}
	//else
	//{
	//	$("#ae").addClass("comentari-error");
	//	$("#ae").removeClass("comentari-"+color);
	//	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-"+color);
		error_text += "<li>Has d'escriure un comentari</li>\n";
		error = true;
	}

	
 	if( error )
	{
		$("#comentari-error").fadeIn("slow");
		$("#comentari-error").html( '<ul class="error">' + error_text + '</ul>' );
	}
	else
	{
		$.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, facebook_uid: facebook_uid, facebook_foto: facebook_foto, lloc: lloc, nom: nom, poblacio: poblacio, email: ae, comentari: comentari, notifica: notifica, accio: 'enviar_comentari' },
				function( resposta )
				{
					$("#comentari-error").show();
					$("#comentari-formulari").fadeOut("slow");
					
					if( !resposta.recarregar )
					{
						var message = resposta.comentari;
						var attachment = {
								'name': resposta.titol,
								'href': resposta.url,
								'caption': resposta.subtitol,
								'media': [{
									'type': 'image',
									'src': resposta.imatge,
									'href': resposta.url
									}] };
						var action_links = [{'text':resposta.titol, 'href':resposta.url}];
						FB.Connect.streamPublish(message, attachment, action_links);
						
						$("#comentari-enviat").fadeIn("slow");
					}
					else
						window.location.reload()
						//window.location.href = resposta.url_llarga;
				});
			}
		});
	}
}


function genera_comentaris( pagina, id_article, lloc )
{
 	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, lloc: lloc, accio: 'genera_comentaris' },
		function( resposta )
		{
			$("#comentaris-cnt").html( resposta );
		});
	}
	else
	{
		alert("Error");
	}
}

function veure_comentari( id_comentari, lloc )
{
 	if( id_comentari )
	{
		$.getJSON( AJAX, { id_comentari: id_comentari, lloc: lloc, accio: 'veure_comentari' },
		function( resposta )
		{
			$("#comentari-cnt-" + resposta.id_comentari ).html( resposta.text );
		});
	}
	else
	{
		alert("Error");
	}
}

function limitacio( numero, id_article, lloc )
{
 	if( numero && id_article && lloc )
	{
		$("#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, lloc );
		});
	}
	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 comparteix( url )
{
	if ($("#comparteix").length === 0) {
		var html = '<a href="http://latafanera.cat/submit.php?url=' + url + '" title="Envia a La Tafanera" target="_blank"><img src="img/icones/tafanera.png" alt="La Tafanera" /></a> ';
		html += '<a href="http://www.facebook.com/share.php?u=' + url + '" title="Comparteix a Facebook" target="_blank"><img src="img/icones/facebook.png" alt="Facebook" /></a> ';
		html += '<a href="http://www.google.com/bookmarks/mark?op=edit&bkmk=' + url + '" title="Comparteix a Google" target="_blank"><img src="img/icones/google.png" alt="Google" /></a> ';
		html += '<a href="http://twitter.com/home?status=' + url + '" title="Comparteix a Twitter" target="_blank"><img src="img/icones/twitter.png" alt="Twitter" /></a> ';
		html += '<a href="http://www.google.com/reader/link?url=' + url + '" title="Envia a Google Buzz" target="_blank"><img src="img/icones/buzz.png" alt="google buzz" /></a> ';
		
		if( $(".llegenda_dreta") )
			$(".llegenda_dreta").append('<span id="comparteix">'+ html +'</span>');
		if( $(".llegenda_dret") )
			$(".llegenda_dret").append('<span id="comparteix">'+ html +'</span>');
		
		$("#comparteix").fadeIn("slow");
	}
}


function cerca_avancada()
{
	$('#cerca_avancada').show();
}

function entre_data()
{
	document.cercador.dia_inici.disabled = !document.cercador.dia_inici.disabled;
	document.cercador.mes_inici.disabled = !document.cercador.mes_inici.disabled;
	document.cercador.any_inici.disabled = !document.cercador.any_inici.disabled;
	document.cercador.dia_fi.disabled = !document.cercador.dia_fi.disabled;
	document.cercador.mes_fi.disabled = !document.cercador.mes_fi.disabled;
	document.cercador.any_fi.disabled = !document.cercador.any_fi.disabled;
}



function actualitzar_usuari()
{
	$('#div-facebook').html( "<fb:profile-pic uid='loggedinuser' facebook-logo='true'></fb:profile-pic>"
	+ "<br />Benvingut/da, <fb:name uid='loggedinuser' useyou='false'></fb:name>. T'has identificat/da amb el teu compte de Facebook. "
	+ "<a href=\"#\" onclick=\"FB.Connect.logout(function() { window.location.reload(); netejar_usuari(); }); 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 netejar_usuari ()
{
	$('#facebook_foto').val('');
	$('#nom').val('');
	$('#poblacio').val('');
	$('#ae').val('');
	$('#facebook_uid').val('');
}

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 selecciona_municipi()
{
	var id_comarca = $('#ipt-comarca').val();

	$('#div-municipi').html('<img src="img/icones/loading.gif" alt="loader" />');
	
	$.post( AJAX, { id_comarca: id_comarca, accio: 'selecciona_municipi' },
	function( resposta )
	{
		$('#div-municipi').html( resposta );
	});
}

function selecciona_comarca()
{
	var id_zona = $('#ipt-zona').val();

	$('#div-comarca').html('<img src="imatges/loading_gros.gif" alt="loader" />');
	
	$.post( AJAX, { id_zona: id_zona, accio: 'selecciona_comarca' },
	function( resposta )
	{
		$('#div-comarca').html( resposta );
		$('#div-municipi').html( '' );
	});
}


// 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, id_article, rating_text)
{
	for(i = 1; i <= rating; i++)
		document.images['valora_' + id_article + '_' + 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(id_article, rating_score, insert_half)
{
	for(i = 1; i <= 5; i++)
	{
		if(i <= rating_score)
			document.images['valora_' + id_article + '_' + i].src = 'img/icones/valora_on.png';
		else if(i == insert_half)
			document.images['valora_' + id_article + '_' + i].src = 'img/icones/valora_meitat.png';
		else
			document.images['valora_' + id_article + '_' + i].src = 'img/icones/valora_off.png';
	}
	
	$('#valora_text').html( '' );
	$('#valora_text').css("display", "inline");
}


function valora_article( lloc, id_article, valor, multiple )
{
	if( multiple )
	{
		$('#valora_estrelles_'+id_article).css("display", "none");
		$('#valora_loading_'+id_article).css("display", "inline");
	}
	else
	{
		$('#valora_estrelles').css("display", "none");
		$('#valora_loading').css("display", "inline");		
	}

	$.getJSON( AJAX, { lloc: lloc, valor: valor, id_article: id_article, accio: 'valorar' },
	function( resposta )
	{
		if( multiple )
		{
			$('#valora_estrelles_'+id_article).css("display", "inline")
			$('#valora_loading_'+id_article).css("display", "none")
			$('#valora_estrelles_'+id_article).html( '' );
		}
		else
		{
			$('#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 += ' <br />hi ha <span>1</span> vot';
		else
			html += ' <br />hi ha <span>'+ resposta.vots +'</span> vots';
		
		if( multiple )
			$('#valora_estrelles_'+id_article).html( html );
		else
			$('#valora_estrelles').html( html );
		
	});
}



function galeria_lateral( id_galeria )
{
	var id_galeria_imatge = $("#id_galeria_imatge").val();
	
	$.getJSON( GALERIA_AJAX, { id_galeria_imatge: id_galeria_imatge, id_galeria: id_galeria, accio: 'galeria_lateral' },
	function( resposta )
	{
	    $("#galeria_imatge img").attr({ src: "/img/220/220/"+ 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_galeria +')', 5000 );
	});
}


function agenda_lateral( id_agenda )
{
	$('#destacat').html('<img src="img/icones/loading.gif" alt="loader" />');
	$.post( AGENDA_AJAX, { id_agenda: id_agenda, accio: 'agenda_lateral' },
	function( resposta )
	{
		$("#destacat").hide();
	    $("#destacat").html( resposta );
		$("#destacat").fadeIn('slow');
		setTimeout( 'agenda_lateral('+ id_agenda +')', 5000 );
	});
}
