/* ////////////////////////////////////////////////////////////////////////////
 * Necesita que se haya cargado DOMAssistant.js
 */
/* ///////////////////////////////////////////////////////////////////////////////
 * =Variables
 */
// Contiene por cada campo el tipo de error a chequear con su mensaje asociado
var ERROR_MSG = {
	author : { empty : "Debes indicar un nombre"},
	email : { empty : "Debes indicar un email v\u00e1lido.", novalid : "El formato del email no es correcto." },
	tale : { empty : "Debes subir el archivo que contiene el cuento."}
};

/* ////////////////////////////////////////////////////////////////////////////
 * =Funciones
 */
function isMail(idOrVal) {
	var val = $$(idOrVal).value;
	if(!val) { val = idOrVal; }

	var re = new RegExp ("[a-z_0-9-]+?@[a-z_0-9-]+?\.[a-z]{2,4}$","gi"); // No es perfecto, ni mucho menos...

	return re.test(val);
}
/*
	Devuelve 'true' si el campo no tiene valor y escribe el mensaje de error correspondiente
*/
function checkEmpty(sId) {
	var o = $$(sId);

	if(o && o.value) {
		removeErrorSpan(sId);
		return false;
	}
	else {
		writeErrorSpan(sId,'empty');
		return true;
	}	
}

/**/
function checkMail(sId) {
	var bOk = false;

	if(!checkEmpty(sId)) {
		if(!isMail(sId)) {
			writeErrorSpan(sId,'novalid');
		}
		else {
			bOk = true;
			removeErrorSpan(sId);
		}
	}

	return bOk;
}

function writeErrorSpan(sId, type) {
	var o = $$(sId)
	o.addClass("error");
	var oLabel = $$('lab_'+sId);
	if(oLabel) {
		oLabel.addClass("error");
	}

	if(! $$("err_"+sId)) {
		// Me gustaría saber por qué no funciona: oParent.create("span",{id: "err_"+id, className: "error"}, true, "Mensaje de error");
		var oError = document.createElement("span");
		oError.appendChild(document.createTextNode(ERROR_MSG[sId][type]));
		oError.className = "error";
		oError.id = "err_"+sId;

		$$(sId).parentNode.appendChild(oError);
	}
}

function removeErrorSpan(sId) {
	$$(sId).removeClass("error");
	$$("lab_"+sId).removeClass("error");
	if($$("err_"+sId)) {
		$$("err_"+sId).remove();
	}
}

/*
	Comprobamos el formulario fmuertecito que debe tener:
	Obligatorio: author, email (valido), tale (extensiones a controlar: zip, doc, txt, htm, html, ...)
*/
function checkMuertecito() {
	var sError = "";

	if(checkEmpty('author')) {
		sError += "<li>" + ERROR_MSG['author']['empty'] + "</li>";
	}
	if(!checkMail('email')) {
		sError += "<li>" + ERROR_MSG['email']['empty'] + "</li>";
	}

	if(checkEmpty('tale')) {
		sError += "<li>" + ERROR_MSG['tale']['empty'] + "</li>";
	}

	if(sError) {
		var oErrDiv = $$("errDiv");

		if(oErrDiv) {
			oErrDiv.replaceContent("<p>Se produjeron los siguientes errores, corr\u00e9gelos y vuelve a enviar el formulario:</p><ul>"+sError+"</ul>");
		}
		else {
			var oPrevErr=$(".form_table").first();

			var oErrorNode = document.createElement("div");
			oErrorNode.id = "errDiv";
			oErrorNode.className = "error";
			oErrorNode.innerHTML = "<p>Se produjeron los siguientes errores, corr\u00e9gelos y vuelve a enviar el formulario:</p><ul>"+sError+"</ul>";

			oPrevErr.insertBefore(oErrorNode, $("#main form").first());			
		}

		return false;
	}

	// Tras validar que todo está ok, ponemos el botón a "Enviando..."
	var oSubmitting = document.createElement("p");
	oSubmitting.innerHTML = "<em>Enviando <blink>...</blink></em>";
	oSubmitting.id = "submitting";

	$$("submit").parentNode.appendChild(oSubmitting);

	$$("submit").style.display='none';//remove();

	return true;
}

///////////////////////////////////////////////////////////////////////////////
/*
 * Inicializamos los distintos elementos de /tu-muertecito/
 */
function init() {
	$$('fMuertecito').addEvent("submit", function() {return checkMuertecito();});
	if($$('fMuertecito')) {
		// Añadimos la variable _js = "on" para saber si se le puede devolver por AJAX o no
	}

	$$('author').addEvent("blur", function () {checkEmpty('author')});
	$$('email').addEvent("blur", function () {checkMail('email')});
	$$('tale').addEvent("blur", function () {checkEmpty('tale')});
}

DOMAssistant.DOMReady(init);