$(document).ready(function(){

/* Nascondi i messaggi d'errore e di successo */
if($('.failure').length != 0) { $('.failure').hide(); }
if($('.success').length != 0) { $('.success').hide(); }

/* Invia la chiave di ricerca */
$('#search_push').click(function() { doSearch(); });
$('#search_key').keyup(function(e) { if(e.keyCode == 13) doSearch(); });

// Reindirizzi tutti i link del sito in un'altra pagina
$('.post .text a').each(function() { $(this).attr('target', '_blank'); });

// Riduci tutti i video
$('.post .text object').each(function() {
	var w = $(this).attr('width');
	var h = $(this).attr('height');
	
	// Riduci il video in proporzione
	if(w > 500) {
		h = h * 500 / w; w = 500;	
		$(this).attr('width', w);
		$(this).attr('height', h);
		$(this).children('embed').attr('width', w);
		$(this).children('embed').attr('height', h);
	}
});

/* Invia il form dei commenti */
$('#post_comment_form #send_comment').click(function() {

	$('#post_comment_form #send_comment').text('Salvataggio...');
	$('#post_comment_form #send_comment').attr('disabled', 'true');
	
	/* Nascondi i messaggi d'errore e di successo */
	$('.failure').hide();
	$('.success').hide();
	
	var form_data = $('#post_comment_form').serialize();
	
	/* Invia i campi del form, via POST, allo script di destinazione */
	$.ajax({
		type: "POST",
		url: "/ajax/user_post_comments.php",
		data: form_data,
		dataType: "json",
		success: function(msg){
			
			/* Se esiste la variabile del successo, esegui la funzione di successo */
			if(msg.success != '') {
				$('.success').html(msg.success);
				$('.success').show(100);
				$("#post_comment_form")[0].reset();
				$('#comment_count').text(msg.data.comment_count);
				$('#comment_count_phrase').text(msg.data.comment_count != 1 ? 'commenti' : 'commento');
				var new_comment = $('#comment_hidden').html()
					.replace('%1', msg.data.post_username)
					.replace('%2', msg.data.comment_date)
					.replace('%3', msg.data.post_comment);
				$('#comment_hidden').before(new_comment);
			} else {
			/* Altrimenti esegui la funzione di errore */
				$('.failure').html(msg.failure);
				$('.failure').show(100);
			}
			
			$('#post_comment_form #send_comment').removeAttr('disabled');
			$('#post_comment_form #send_comment').text('Commenta');
		}
	});
	
	return false;
});


})

/* Funzione che invia la chiave di ricerca */
function doSearch() {
	var search_key = $('#search_key').val();
	if(search_key == '') {
		alert('Inserisci una chiave di ricerca valida.');
	} else {
		top.location = '/posts.php/k/'+ search_key.replace(' ', '_');
	}
}

