var AJAX = '/ajax/ajax.php';

function les_noticies( lloc )
{
	if( lloc == 'ultimes' )
	{
		$("#mes_llegits").hide();
		$("#votades").hide();
		$("#mes_comentats").hide();
		$("#ultimes").fadeIn('slow');

		$("#noticies_tag").removeClass("fons_noticies_tag_actiu");
		$("#noticies_tag").addClass("fons_noticies_tag_inactiu");
		$("#comentaris_tag").removeClass("fons_noticies_tag_actiu");
		$("#comentaris_tag").addClass("fons_noticies_tag_inactiu");
		$("#ultimes_tag").removeClass("fons_noticies_tag_inactiu");
		$("#ultimes_tag").addClass("fons_noticies_tag_actiu");
		$("#votades_tag").removeClass("fons_noticies_tag_actiu");
		$("#votades_tag").addClass("fons_noticies_tag_inactiu");
	}
	else if( lloc == 'llegides' )
	{
		$("#ultimes").hide();
		$("#votades").hide();
		$("#mes_comentats").hide();
		$("#mes_llegits").fadeIn('slow');

		$("#noticies_tag").removeClass("fons_noticies_tag_inactiu");
		$("#noticies_tag").addClass("fons_noticies_tag_actiu");
		$("#comentaris_tag").removeClass("fons_noticies_tag_actiu");
		$("#comentaris_tag").addClass("fons_noticies_tag_inactiu");
		$("#ultimes_tag").removeClass("fons_noticies_tag_actiu");
		$("#ultimes_tag").addClass("fons_noticies_tag_inactiu");
		$("#votades_tag").removeClass("fons_noticies_tag_actiu");
		$("#votades_tag").addClass("fons_noticies_tag_inactiu");
	}
	else if( lloc == 'votades' )
	{
		$("#ultimes").hide();
		$("#mes_llegits").hide();
		$("#votades").fadeIn('slow');
		$("#mes_comentats").hide();

		$("#noticies_tag").removeClass("fons_noticies_tag_actiu");
		$("#noticies_tag").addClass("fons_noticies_tag_inactiu");
		$("#comentaris_tag").removeClass("fons_noticies_tag_actiu");
		$("#comentaris_tag").addClass("fons_noticies_tag_inactiu");
		$("#ultimes_tag").removeClass("fons_noticies_tag_actiu");
		$("#ultimes_tag").addClass("fons_noticies_tag_inactiu");
		$("#votades_tag").removeClass("fons_noticies_tag_inactiu");
		$("#votades_tag").addClass("fons_noticies_tag_actiu");
	}
	else if( lloc == 'comentaris' )
	{
		$("#ultimes").hide();
		$("#mes_llegits").hide();
		$("#votades").hide();
		$("#mes_comentats").fadeIn('slow');
		
		$("#comentaris_tag").removeClass("fons_noticies_tag_inactiu");
		$("#comentaris_tag").addClass("fons_noticies_tag_actiu");
		$("#noticies_tag").removeClass("fons_noticies_tag_actiu");
		$("#noticies_tag").addClass("fons_noticies_tag_inactiu");
		$("#ultimes_tag").removeClass("fons_noticies_tag_actiu");
		$("#ultimes_tag").addClass("fons_noticies_tag_inactiu");
		$("#votades_tag").removeClass("fons_noticies_tag_actiu");
		$("#votades_tag").addClass("fons_noticies_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, i);
				}

				html = '<img src="img/icones/vots.gif" alt="Vots" /> <span id="enquesta-vots">'+ vots +'</span> vots&nbsp;&nbsp;<a href="enquesta/'+ resposta.uri  +'#comentaris"><img src="img/icones/comentari_lila.gif" alt="Comentaris" /> <span class="text_enquesta">'+ resposta.comentaris +'</span></a></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, i)
{
	var html = '';

	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()
{
	var email = $('#email-titulars').val();

 	if( email )
	{
		if( !echeck( email ) )
		{
			alert("El correu electrònic que has posat és incorrecte");
			return false;
		}
		
		var alta = $('#acc_alta:checked').val();
		var baixa = $('#acc_baixa:checked').val();
		
		if( !alta && !baixa )
		{
			alert("Has de triar alguna opció");
			return false;
		}
		else if( alta )
		{
			var accio = 'inscriure_alta';
		}
		else if( baixa )
		{
			var accio = 'inscriure_baixa';
		}
		
		$.getJSON( AJAX, { email: email, accio: accio },
		function( resposta )
		{
			if( resposta.exit == 'true' ) $("#inscriure-formulari").empty();
			
			$("#inscriure-text").html( resposta.text );
		});
	}
	else
	{
		alert("Falta posar el teu correu electrònic");
		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 nom;
	var nick = '';
	var dni = '';
	var telefon;
	var tmp;
	var email;
	var comentari;
	var poblacio = "";
	var notifica;
	
	var id_article = $("#id_article").val();
	var lloc = $("#lloc").val();
	var color = $("#color").val();

	if( $("input[@name='notifica']:checked").attr("value") )
		notifica = 'si';
	else
		notifica = 'no';
		
	if( $("#email").val() ) return false;
	
	if( $("#nom").val() )
	{
		$("#nom").removeClass("comentari-error");
		$("#nom").addClass("comentari-"+color);
		var nom = $("#nom").val();
	}
	else
	{
		$("#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( $("#nick").val() )
		var nick = $("#nick").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( $("#telefon").val() )
	{
		var telefon = $("#telefon").val();
		
		if( telefon.length == 9 )
		{
			$("#telefon").removeClass("comentari-error");
			$("#telefon").addClass("comentari-"+color);
		}
		else
		{
			$("#telefon").addClass("comentari-error");
			$("#telefon").removeClass("comentari-"+color);
			error_text += "<li>Has de posar un telèfon correcte</li>\n";
			error = true;
		}
	}
	else
	{
		$("#telefon").addClass("comentari-error");
		$("#telefon").removeClass("comentari-"+color);
		error_text += "<li>Has de posar el teu telèfon</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-formulari").html( '<img src="/img/icones/loader.gif" alt="loader" style="margin: 100px 0px 100px 250px" />' );
		$.post( AJAX, { id_article: id_article, lloc: lloc, nick: nick, nom: nom, dni: dni, telefon: telefon, poblacio: poblacio, email: ae, comentari: comentari, notifica: notifica, accio: 'enviar_comentari' },
		function( resposta )
		{
			$("#comentari-error").css("display", "")
			$("#comentari-formulari").fadeOut("slow");
			$("#comentari-enviat").fadeIn("slow");
		});
	}
	else
	{
		$("#comentari-error").fadeIn("slow");
		$("#comentari-error").html( "<ul>" + error_text + "</ul>");
	}
}

function dnicheck( dni )
{
	numero = dni.substr(0,dni.length-1);
	let = dni.substr(dni.length-1,1);
	numero = numero % 23;
	letra='TRWAGMYFPDXBNJZSQVHLCKET';
	letra=letra.substring(numero,numero+1);
	if ( letra!=let )
	{
		letra='trwagmyfpdxbnjzsqvhlcket';
		letra=letra.substring(numero,numero+1);
		if ( letra!=let )
			return false;
		else
			return true;
	}
	else
		return true;
}

function genera_comentaris( pagina, id_article, lloc )
{
 	if( pagina && id_article )
	{
		$("#comentaris-cnt").html( '<img src="/img/icones/loader.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 );
			window.location.hash = "comentaris";
		});
	}
	else
	{
		alert("Error inesperat!");
	}
	
}
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 );
			$("#comentari-cnt-" + resposta.id_comentari ).removeClass( "text_vermell" );
		});
	}
	else
	{
		alert("Error inesperat!");
	}
}
function limitacio( numero, id_article, lloc )
{
 	if( numero && id_article && lloc )
	{
		$("#comentaris-cnt").html( '<img src="/img/icones/loader.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 inesperat!");
	}
}


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;
}




// 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, titol, tinyurl )
{
	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://technorati.com/search/' + url + '" title="Cerca a Technorati" target="_blank"><img src="img/icones/technorati.png" alt="Technorati" /></a> ';
		html += '<a href="http://del.icio.us/post?url=' + url + '" title="Envia a Delicious" target="_blank"><img src="img/icones/delicious.png" alt="Delicious" /></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=@sentmenat Llegint \''+ titol +'\' '+ tinyurl +'" title="Comparteix al Twitter!" target="_blank"><img src="img/icones/twitter.png" alt="Twitter" /></a>';
		$(".llegenda_d").append('<span id="comparteix">'+ html +'</span>');
		$("#comparteix").fadeIn("slow");
	}
}


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');
	});
}

