/**
 * Funciones JavaScript para el formulario de recomendación.
 *
 * @author	Jose Miguel Pérez Ruiz <josemiguel@vexlan.com>
 * @author	(C) 2008 Vexlan Tecnología y Servicios, S.L.
 * @date	06/02/2008
 * @version	0.1 (Beta)
 *
 */

//-----------------------------------------------------------------------------
function vex_InitDocument()
{
	vex_InitForms();
	vex_InitPopups();
}

//-----------------------------------------------------------------------------
function vex_InitForms()
{
	$$("form").each(function(el) {
		// Añadir la clase "hover" en los botones para simular el pseudoselector :hover
		$ES("button", el).addEvent( "mouseover", function() { this.addClass("hover"); } );
		$ES("button", el).addEvent( "mouseout",  function() { this.removeClass("hover"); } );

		// También a los "input" con .class "boton".
		$ES("input.boton", el).addEvent( "mouseover", function() { this.addClass("hover"); } );
		$ES("input.boton", el).addEvent( "mouseout",  function() { this.removeClass("hover"); } );

		$ES("input.txt", el).addEvent( "focus",   function() { activateInput(this); } );
		$ES("input.txt", el).addEvent( "blur",    function() { clearInputs(this.form); } );

		// Evento para saber cuando está enviandose el form y actuar en consecuencia...
		el.addEvent("submit", submitForm);
	});

	var furl = $("form_c1") || $("form_c2");
	if (furl) {
		activateInput(furl);
		furl.focus();
	}
}

//-----------------------------------------------------------------------------
function vex_InitPopups()
{
	$$("a").each(function(el) {
		var __rel = el.rel.split(" ");
		if (__rel.contains("popup")) {
			// Hemos encontrado un enlace con "rel=popup"
			el.addEvent("click", vex_Popup);
			el.title = el.title + " [Abre en ventana aparte]";
		}
	});
}

//-----------------------------------------------------------------------------
function vex_Popup(e)
{
	var event = new Event(e);
	var w = 500;
	var h = 400;

	if (event.target.tagName.toUpperCase() == "A") {
		event.stop();
		var __url = event.target.href;
		var __rel = event.target.rel.split(" ");
		if (__rel.length == 3) {
			w = __rel[1].toInt();
			h = __rel[2].toInt();
		}

		var __str = "resizable=no,toolbar=no,location=no,scrollbars=no,menubar=no,width=" + w + ",height=" + h;
		var __newWin = window.open(__url, "", __str);
		if (__newWin) __newWin.focus();
	}
}


//-----------------------------------------------------------------------------
function activateInput(__inputName)
{
	var io = $(__inputName);

	if (io && io.parentNode && !window.webkit) {
		$(io.parentNode).addClass("glow");
	}
}

//-----------------------------------------------------------------------------
function clearInputs(__form)
{
	var fo = $(__form);

	$ES(".input", fo).each(function(el) {
		el.removeClass("glow");
	});

}

//-----------------------------------------------------------------------------
function getCampo(__inputName)
{
	var io = $(__inputName);
	if (!io) return;

	// Mmmhh... lo siguiente no parece muy ortodoxo... :-)
	return $(io.parentNode.parentNode);
}

//-----------------------------------------------------------------------------
function ponError(__inputName, __errorTxt)
{
	var elem = getCampo(__inputName);

	if (elem && elem.hasClass("campo")) {

		// ¿Este elemento tiene ya un "error"?
		if ($ES(".error", elem).length == 0) {
			// Estamos en un elemento de campo...
			var errorElem = new Element("div", { "class" : "error", "id" : "error_window_of_" + __inputName, "style" : "display:block" });
			new Element("p").setHTML(__errorTxt).inject(errorElem);
			errorElem.inject(elem);
			errorElem.theFX = new Fx.Style(errorElem, "opacity", {duration: 2000} );
			quitaErroresFade.bind(errorElem).delay(4000);
		}
		activateInput(__inputName);
	}
}

//-----------------------------------------------------------------------------
function quitaErroresFade()
{
	if (this.theFX) this.theFX.start(1, 0).chain(function(){ this.element.remove(); });
}


//-----------------------------------------------------------------------------
function compruebaCampo(__inputName, __errorTxt)
{
	var campo = $(__inputName);

	if (campo && !campo.getValue()) {
		ponError(__inputName, __errorTxt);

		alert("Por favor, revisa los campos obligatorios.");

		$(__inputName).focus();
		return true;
	}

	return false;
}

//-----------------------------------------------------------------------------
function compruebaCheck(__inputName)
{
	var campo = $(__inputName);

	if (campo && !campo.checked) {
		alert("Por favor, debes aceptar las condiciones y términos de privacidad.");
		return true;
	}
	return false;
}

//-----------------------------------------------------------------------------
function submitForm(e)
{
	var errores = false;

	var event = new Event(e);
	var todoOk = true;
	if (e.type != "submit") return;

	// Primero paramos el evento. No queremos que el Form haga submit antes
	// de comprobar los datos. Si hay un error de JavaScript, el form se
	// enviará. Esto lo evita.
	event.stop();

	// Comprobación de campos
	if (compruebaCampo("form_c1", "Introduce tu dirección de correo")) return;
	if (compruebaCampo("form_c2", "Introduce la dirección de correo de tu amigo")) return;

	// OK, si llega aquí, está todo correcto.
	this.submit();
}

//=============================================================================
window.addEvent("domready", vex_InitDocument );
