$(document).ready(function(){
	var hash = window.location.hash;

	if( hash.search("comentari") > 0 && hash.search("comentaris") < 1 )
	{
		tmp = hash.split('-');
		$.getJSON( ARTICLE_AJAX, { id_comentari: tmp[1], accio: 'comentari' },
		function( resposta )
		{
			genera_comentaris( resposta.pagina, resposta.id_article, resposta.lloc, tmp[1] );
		});
	}
});


function enviar_comentari()
{
	var error = false;
	var error_text = '';
	var id_article;
	var nom;
	var tmp;
	var email;
	var comentari;
	var poblacio = "";
	
	var id_article = $("#id_article").val();
	var lloc = $("#lloc").val();
	var color = $("#color").val();
	
	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( $("#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( $("#dni").val() )
	{
		var dni = $("#dni").val();
		
		if( dnicheck( dni ) )
		{
			$("#dni").removeClass("comentari-error");
			$("#dni").addClass("comentari-"+color);
		}
		else
		{
			$("#dni").addClass("comentari-error");
			$("#dni").removeClass("comentari-"+color);
			error_text += "<li>Has de posar un DNI correcte</li>\n";
			error = true;
		}
	}
	else
	{
		$("#dni").addClass("comentari-error");
		$("#dni").removeClass("comentari-"+color);
		error_text += "<li>Has de posar el teu DNI</li>\n";
		error = true;
	}
		
	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-"+color);
			error_text += "<li>El correu electrò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( $("#notifica")[0].checked )
		var notifica = "si";
	else
		var notifica = "no";

 	if( error )
	{
		$("#comentari-error").fadeIn("slow");
		$("#comentari-error").html( '<ul class="error">' + error_text + '</ul>' );
	}
	else
	{
		$.post( ARTICLE_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/loader.gif" alt="loader" style="margin: 100px 0px 100px 250px" />' );
				$.getJSON( ARTICLE_AJAX, { id_article: id_article, lloc: lloc, nom: nom, dni: dni, telefon: telefon, 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;
						
						if( resposta.fb_actiu )
						{
							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-error").hide();
						$("#comentari-enviat").fadeIn("slow");
					}
					else
						window.location.reload()
						//window.location.href = resposta.url_llarga;
				});
			}
		});
	}
}


function genera_comentaris( pagina, id_article, lloc, id_comentari )
{
 	if( pagina && id_article )
	{
		$("#comentaris-cnt").html( '<img src="/img/icones/loader.gif" alt="loader" style="margin: 100px 0px 100px 250px" />' );
		$.post( ARTICLE_AJAX, { id_article: id_article, pagina: pagina, lloc: lloc, id_comentari: id_comentari, accio: 'genera_comentaris' },
		function( resposta )
		{
			$("#comentaris-cnt").html( resposta );
			if( id_comentari )
				window.location.hash = '#comentari-'+id_comentari;
		});
	}
	else
	{
		alert("Error inesperat!");
	}
	
}
function veure_comentari( id_comentari, lloc )
{
 	if( id_comentari )
	{
		$.getJSON( ARTICLE_AJAX, { id_comentari: id_comentari, lloc: lloc, accio: 'veure_comentari' },
		function( resposta )
		{
			$("#comentari-cnt-" + resposta.id_comentari ).html( resposta.text );
		});
	}
	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( ARTICLE_AJAX, { numero: numero, accio: 'limitacio' },
		function()
		{
			genera_comentaris( "1", id_article, lloc, '' );
		});
	}
	else
	{
		alert("Error inesperat!");
	}
}



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( ARTICLE_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( ARTICLE_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();
}


// Variables
var ratings_mouseover_image = new Image();
ratings_mouseover_image.src = "/img/icones/valora_over.png";

// When User Mouse Over Ratings
function valora_actual(lloc, 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_'+lloc+'_'+id_article).html( rating_text );
	$('#valora_text_'+lloc+'_'+id_article).css("display", "inline");
}


// When User Mouse Out Ratings
function valora_off(lloc, 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_'+lloc+'_'+id_article).html( '' );
	$('#valora_text_'+lloc+'_'+id_article).css("display", "inline");
}


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

	$.getJSON( ARTICLE_AJAX, { lloc: lloc, valor: valor, id_article: id_article, accio: 'valorar' },
	function( resposta )
	{
		if( multiple )
		{
			$('#valora_estrelles_'+lloc+'_'+id_article).css("display", "inline")
			$('#valora_loading_'+lloc+'_'+id_article).css("display", "none")
			$('#valora_estrelles_'+lloc+'_'+id_article).html( '' );
		}
		else
		{
			$('#valora_estrelles_'+lloc).css("display", "inline")
			$('#valora_loading_'+lloc).css("display", "none")
			$('#valora_estrelles_'+lloc).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>';

		if( multiple )
			$('#valora_estrelles_'+lloc+'_'+id_article).html( html );
		else
			$('#valora_estrelles_'+lloc).html( html );
		
	});
}


function formulari_article_enviar()
{
	var email = $("#email_e").val();
	var nom = $("#nom_e").val();
	var r_email = $("#r_email").val();
	var r_nom = $("#r_nom").val();
	var comentari = $("#comentari").val();
	var id_article = $("#id_article").val();
	var lloc = $("#lloc").val();

	if( email != '' )
	{
		$.post( ARTICLE_AJAX, { email: email, nom: nom, r_email: r_email, r_nom: r_nom, id_article: id_article, lloc: lloc, comentari: comentari, accio: 'enviar_article' },
		function( resposta )
		{
			$("#popup").fadeOut('slow');
			$("#popup_ok").fadeIn('slow');
			setTimeout('$.prettyPhoto.close()',3000)
		});
	}
}

function formulari_abus_enviar()
{
	var email = $("#email_e").val();
	var nom = $("#nom_e").val();
	var comentari = $("#comentari").val();
	var id_comentari = $("#id_comentari").val();
	var lloc = $("#lloc").val();

	if( email != '' )
	{
		$.post( ARTICLE_AJAX, { email: email, nom: nom, id_comentari: id_comentari, lloc: lloc, comentari: comentari, accio: 'enviar_abus' },
		function( resposta )
		{
			$("#popup").fadeOut('slow');
			$("#popup_ok").fadeIn('slow');
			setTimeout('$.prettyPhoto.close()',3000)
		});
	}
}

