$(document).ready(function(){
	$("#invia_gb").click(function(){
	
	//Recuperiamo tutte le variabili
		var valid = '';
		var autore = $("#autore").val();
        var commento = $("#commento").val();
        var lg = $("#lg").val();

        var commento1 = trim(commento);
        var autore1 = trim(autore);

        var commento2 = commento1.replace(/[\']/g,"`");
        var autore2 = autore1.replace(/[\']/g,"`");

	//Eseguiamo una serie di controlli
		if (autore1.length<1) {

            if (lg.length<1) {

                valid += '<p class="prgf">Inserisci l\'autore!</p>';

            } else {

                valid += '<p class="prgf">Please insert any author!</p>';

            }
		}
        if (commento1.length<1) {

            if (lg.length<1) {

                valid += '<p class="prgf">Inserisci il tuo commento!</p>';

            } else {

                valid += '<p class="prgf">Please insert your comment!</p>';

            }

		}
	//Se i controlli non vengono superati, appare il messaggio di errore.
		if (valid!='') {
			$("#risposta_gb").fadeIn("slow");

            if (lg.length<1) {

                $("#risposta_gb").html("<p class='prgf'><b>ATTENZIONE!</b></p>"+valid);

            } else {

                $("#risposta_gb").html("<p class='prgf'><b>ATTENTION!</b></p>"+valid);

            }

			$("#risposta_gb").css("background-color","#ffc0c0");
		}
		//Se i controlli vengono superati, compare un messaggio di invio in corso
		else {
			var datastr ='autore=' + autore2 + '&commento=' + commento2;
			$("#risposta_gb").css("display", "block");
			$("#risposta_gb").css("background-color","#FFFFA0");

            if (lg.length<1) {

                $("#risposta_gb").html("<p class='prgf'>Invio del commento in corso...</p>");

            } else {

                $("#risposta_gb").html("<p class='prgf'>Send your comment...</p>");

            }

			$("#risposta_gb").fadeIn("slow");
			setTimeout("send('"+datastr+"')",2000);
		}
		return false;
	});
});

function send(datastr){
	$.ajax({	
		type: "POST",
		url: "guestbook.php",
		data: datastr,
		cache: false,
		success: function(html){
		$("#risposta_gb").fadeIn("slow");
		$("#risposta_gb").html(html);
		$("#risposta_gb").css("background-color","#e1ffc0");
		setTimeout('$("#risposta_gb").fadeOut("slow")',6000);
	}
	});
}

function trim(stringa){
    while (stringa.substring(0,1) == ' '){
        stringa = stringa.substring(1, stringa.length);
    }
    while (stringa.substring(stringa.length-1, stringa.length) == ' '){
        stringa = stringa.substring(0,stringa.length-1);
    }
    return stringa;
}

