/**
 * Funciones JavaScript para el formulario de petición de informes.
 *
 * @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)  :-) Hey! Es Web 2.0...
 *
 */

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

	new SmoothScroll();
}

//-----------------------------------------------------------------------------
function getUpdate(type, pr1, pr2, swf)
{
	if (type == "state") {
		if (pr1 == 2) {
			abreVideo();
		}
		if (pr1 == 0) {
			cierraVideo();
		}
	}
}

//-----------------------------------------------------------------------------
function thisMovie(swf)
{
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[swf];
	} else {
		return document[swf];
	}
}

//-----------------------------------------------------------------------------
function vex_InitVideo()
{
	claimDes   = $("claim-desarrollo");
	claimBack  = $("claim-videoback");
	claimDiv   = $("claim");
	claimThumb = $("claim-videothumb");
	claimClose = $("claim-videoclose");

	videoSetup = false;
	videoOpen  = false;
	if (claimDes && claimBack && claimDiv) {
		claimDes.fx  = new Fx.Style("claim-desarrollo", "opacity", { duration: 1000 });
		claimBack.fx = new Fx.Style("claim-videoback", "opacity", { duration: 1000 });
		claimClose.fx  = new Fx.Style("claim-videoclose", "opacity", { duration: 1000 });

		claimDiv.fx  = new Fx.Style("claim", "height",
			{	duration: 1000,
				transition: Fx.Transitions.Sine.easeInOut,
				onComplete: function(){
/*					if (!videoOpen && window.ie) $ES("form").each(function(el){ el.setStyle("visibility", "visible") }); */
					if (!videoOpen) claimBack.fx.start(0, 1);
					if (videoOpen) 	claimClose.fx.start(0, 1);
				}
			});
		claimThumb.fxHeight = new Fx.Style("claim-videothumb", "height", { duration: 1000, transition: Fx.Transitions.Sine.easeInOut });
		claimThumb.fxWidth  = new Fx.Style("claim-videothumb", "width",  { duration: 1000, transition: Fx.Transitions.Sine.easeInOut });
		claimThumb.fxPos    = new Fx.Style("claim-videothumb", "right",  { duration: 1000, transition: Fx.Transitions.Sine.easeInOut });
		videoSetup = true;

		$("vclose").addEvent("click", function(){ cierraVideo(); });
	}

	var so = new SWFObject('/pub/video/flvplayer.swf','mpl','100%','100%','8');
	so.addParam('allowscriptaccess','always');
	so.addParam('allowfullscreen','true');

	so.addVariable('width','320');
	so.addVariable('height','240');
	so.addVariable('displayheight', '240');

	so.addVariable('backcolor', '#000000');
	so.addVariable('frontcolor', '#FFFFFF');
	so.addVariable('lightcolor', '#000000');
	so.addVariable('screencolor', '#333333');

	so.addVariable('file','/pub/video/video_informe.flv');
	so.addVariable('image', 'img/thumb-video-ok.jpg');
	so.addVariable('showicons', 'false');
	so.addVariable('overstretch', 'true');
	so.addVariable('enablejs', 'true');
	so.write('claim-videothumb');
}


//-----------------------------------------------------------------------------
function abreVideo()
{
	if (!videoSetup || videoOpen) return;

	claimDes.fx.start(1, 0);
//	claimBack.fx.start(1, 0);
	claimBack.fx.set(0);
	claimDiv.fx.start(300, 530);
	claimThumb.fxWidth.start(320, 640);
	claimThumb.fxHeight.start(240, 480);
	claimThumb.fxPos.start(20, 120);

	if (window.ie) $ES("form").each(function(el){ el.setStyle("visibility", "hidden") });
	videoOpen  = true;
}

//-----------------------------------------------------------------------------
function cierraVideo()
{
	if (!videoSetup || !videoOpen) return;

	videoOpen  = false;

	thisMovie("mpl").sendEvent("stop");

	claimDes.fx.start(0, 1);
//	claimBack.fx.start(0, 1);
	claimClose.fx.start(1, 0);
	claimDiv.fx.start(530, 300);
	claimThumb.fxWidth.start(640, 320);
	claimThumb.fxHeight.start(480, 240);
	claimThumb.fxPos.start(120, 20);
}


//-----------------------------------------------------------------------------
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); } );
//		$ES("input.txt", el).addEvent( "keydown", function(e) { keyEvent(this, e); } );

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

	var furl = $("form_url");
	var femp = $("form_empresa");

	if (furl && (furl.value.length == 0)) {
		activateInput(furl);
//		furl.focus();
	} else if (femp) {
		activateInput(femp);
		femp.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 keyEvent(__input, __event)
{
	if (!__event || __event.type != "keydown") return;

	var eo = new Event(__event);

	if (eo.code == 13) {
		// Mmmmhhh.... Manualmente avanzamos... not good... :-)
		switch (__input.id) {
			case "form_url":		$("form_empresa").focus(); break;
			case "form_empresa":	$("form_crit1").focus(); break;
			case "form_crit1":		$("form_crit2").focus(); break;
			case "form_crit2":		$("form_crit3").focus(); break;
			case "form_crit3":		$("form_comp1").focus(); break;
			case "form_comp1":		$("form_comp2").focus(); break;
			case "form_comp2":		$("form_correo").focus(); break;
			case "form_correo":		$("form_nombre").focus(); break;
			case "form_nombre":		$("form_telefono").focus(); break;
			case "form_telefono":	submitForm.bind($("solicitud_informe"))(); break;
		}
		eo.stop();
	}
}


//-----------------------------------------------------------------------------
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")) {
//		quitaError(__inputName);

		// ¿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 quitaError(__inputName)
{
	var elem = getCampo(__inputName);

	// OK, tenemos el campo... ahora cogemos los campos con class "error"
	if (elem && elem.hasClass("campo")) {
		$ES(".error", elem).each(function(el){ el.remove(); });
	}
}

//-----------------------------------------------------------------------------
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;
	}

//	quitaError(__inputName);
	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();

	// La URL de la web
	if (compruebaCampo("form_url", "Introduce la dirección de tu Web")) return;
	if (compruebaCampo("form_crit1", "Introduce almenos un criterio")) return;
	if (compruebaCampo("form_correo", "Introduce tu correo electrónico")) return;
	if (compruebaCampo("form_nombre", "Introduce tu nombre")) return;
	if (compruebaCampo("form_telefono", "Introduce tu teléfono de contacto")) return;

	// Ahora comprobamos que haya leido el compromiso de confidencialidad.
	if (compruebaCheck("form_confirma")) return;

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

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