$(document).ready(f_init);

var nCur = 0;
var nMax = -1;
var aMsg = {};

function f_init() {
	$("#msgs div").each(function (a, b) {
		nMax++;
		aMsg[a] = $(b).position().top;
	});
	$("#up").click(function () { nCur = Math.max(0,    nCur-1); f_refresh() });
	$("#dn").click(function () { nCur = Math.min(nMax, nCur+1); f_refresh() });
	$("#submit").click(f_submit);
	f_refresh();
}

function f_refresh() {
	$("#up").css("display", nCur>0    ? "block" : "none");
	$("#dn").css("display", nCur<nMax ? "block" : "none");
	$("#msgs").animate({
		top: -aMsg[nCur]
	});
}

function f_submit() {
	var sNombre = $("#nombre").val();
	var sTexto  = $("#texto").val();
	$("#msgs"  ).animate({ top: 0 });
	$("#submit").css(    { display: "none" });
	$("#form"  ).animate({ opacity: 0.25 });
	jQuery.get("modelos/tablon-comentarios-insertar.php", {
		n: sNombre,
		t: sTexto
	}, function (resp) {
		if(resp=="KO") {
			alert("Tu comentario será revisado antes de aparecer publicado.");
		} else {
			$("#msgs div:eq(0)").before(resp);
			var plus = $("#msgs div:eq(0)").height();
			for(k in aMsg) {
				k = parseInt(k);
				aMsg[k+1] = aMsg[k]+plus;
			}
			aMsg[0] = 0;
			$("#msgs div").each(function (a, b) {
				if(a==0) {
					$(b).slideDown(1000);
				} else {
					$(b).animate({ top: aMsg[a] }, 1000);
				}
			});
		}
	});
}