//////////////////////////////////////////////////////////////////////////////////////////
//CLASE PARA LA CAJA DE LOGIN
//////////////////////////////////////////////////////////////////////////////////////////
var CajaLoginUp = new Class({
	estado: "nologin",
	
	initialize: function(contenedorLogin){
		this.contenedorLogin = $(contenedorLogin);
		this.contenedorLogin.set('tween', {duration: 500});
		this.cajaLoading = new Element("div", {'class': 'loading'});
		this.cajaLoading.set("html","<img src='/images/loadingcw.gif' width=100 height=68>");
		this.cajaLoading.inject($('login'), "after");
		this.cajaLogin  = null;
	},
	expande: function(){
		this.contenedorLogin.tween("height", "225px");
	},
	contrae: function(){
		//this.cajaLogin.set("styles", {'display': 'none'});
		this.contenedorLogin.tween("height", "29px");
		this.estado = "nologin";
	},
	muestraLoading: function(){
		this.cajaLoading.set("styles", {'display': 'block'});
	},
	muestraLogin: function(){
		this.cajaLoading.set("styles", {'display': 'none'});
		this.cajaLogin.set("styles", {'display': 'block', 'opacity': 0});
		this.cajaLogin.fade(1);
		this.estado = "completo";
	},
	ocultaLogin: function(){
		//this.cajaLogin.fade(0);
		//this.cajaLogin.set.delay(500,this, ["styles", {'display': 'none'}]);
		this.cajaLogin.set("styles", {'display': 'none'});
	},
	
	accion: function(){
		if (this.estado=="nologin"){
			this.estado="cargando";
			//lo primero es ver si no tenemos el cajaLogin cargado
			if (!$defined(this.cajaLogin)){
				var esteObjeto = this;
				//es que no tenemos la caja de login cargada
				//la voy a cargar x ajax!
				var nuevoRequest = new Request({
					method: 'get',
					url: '/formularios-ajax/login.php?origen=' + url_origen,
					onRequest: function() { 
						esteObjeto.expande();
						esteObjeto.muestraLoading.delay(500,esteObjeto);
					},
					onSuccess: function(texto, xmlrespuesta){ 
						esteObjeto.cajaLogin = new Element('div', {id: 'cajalogin'});
						esteObjeto.cajaLogin.set('html',texto);
						esteObjeto.cajaLogin.inject($('login'), "after");
						esteObjeto.muestraLogin.delay(500, esteObjeto);
					},
					onFailure: function(){alert('Erro!');}
				}).send();
				
			}else{
				//es que la caja de login ya la tenemos cargada
				this.expande();
				this.muestraLogin.delay(500, this);
			}
		}else{
			if(this.estado =="completo"){
				this.ocultaLogin();
				this.contrae();
			}
		}
	}
});

window.addEvent('domready', function(){
	LoginPrincipal = new CajaLoginUp("cajaverde");
	if($defined($('enlacelogin'))){
		$('enlacelogin').addEvent('click', function(evento){
			LoginPrincipal.accion();
		});
	}
});
//////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////
//MENÚ DE OPCIONES HORIZONTAL DE CABECERA
////////////////////////////////////////////////////////////////////////
//CONFIGURACIÓN DEL MENÚ
opcionesPrincipales = [
	["Home","/"],
	["Monotem&aacute;ticos", "/monotematicos/"],
	["Se&ccedil;&otilde;es", "/secoes/"],
	["Comunidade", "/comunidade/"]
];
opcionesSecundarias = [
	[[],[]],
	[["Desde 0", "HTML", "CSS", "Javascript", "ASP", "PHP", "Webdesign","Divulga&ccedil;&atilde;o de sites"],["/desde_0/", "/html/","/css/", "/javascript/", "/asp/", "/php/","/web-design/","/divulgacao-web"]],
	[["Manuais", "Programas", "FAQS", "Diret&oacute;rio", "Colabore"],["/manuais/","/programas/", "/faq/", "/diretorio/", "/contribue/"]],
	[["Suas P&aacute;ginas ","Boletim de Novidades", "Cadastrar-se", "Enquete","Comentários", "Cursos Online"],["http://criarweb.websitealbum.com/", "/boletim/", "/comunidade/cadastrar-se/", "/questionario/","/comentarios", "http://www.treinaweb.com.br/parceiro/criarweb"]]
];
desplazamientosSubmenu = [0,0,0,0];
classOpcionesPrincipales = ["navupconfondo","navupconfondo","navupconfondo","navupconfondo","navupsinfondo"]
////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////
//CLASE DE OPCIONES PRINCIPALES DEL NAVEGADOR
var OpcionPrincipal = new Class({
	initialize: function(texto, url, indice, navegadorDondeEstoy, claseEspecial){
		this.texto = texto;
		this.url = url;
		this.indice = indice;
		this.navegadorDondeEstoy = navegadorDondeEstoy;
		this.claseEspecial = claseEspecial;
		this.enlace = new Element("a", {href: this.url});
		this.enlace.set("html",this.texto); 
		this.enlace.addEvent("mouseenter",function(){
			this.navegadorDondeEstoy.ocultaSubmenus();
			this.navegadorDondeEstoy.muestraSubmenu(this.indice);
		}.bind(this));
		this.enlace.addEvent("mouseleave",function(){
			this.navegadorDondeEstoy.ocultaSubmenuRetardo(this.indice);
		}.bind(this));
	},
	
	dameCodigo: function(){
		return "<li class='" + this.claseEspecial + "'><a href='" + this.url + "'>" + this.texto + "</a></li>";
	},
	dameEnlace: function(){
		return this.enlace;
	},
	
	dameElementoLista: function(){
		var elementoLista = new Element("li",{'class': this.claseEspecial});
		this.enlace.inject(elementoLista);
		return elementoLista;
	}
});
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
//CLASE DE UNA ÚNICA OPCIÓN SECUNDARIA
var OpcionSecundaria = new Class({
	initialize: function(texto, url){
		this.texto = texto;
		this.url = url;
	},
	
	dameCodigo: function(){
		return "<div class='opcionessubnavegador'><a href='" + this.url + "'>" + this.texto + "</a></div>";
	}
});
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
//CLASE DE UN GRUPO DE OPCIONES SECUNDARIAS
var SubNavegador = new Class({
	initialize: function(arrayComponentes,indice, navegadorPresente, desplazamientoSubmenu){
		this.navegadorDondeEstoy = navegadorPresente;
		this.indice = indice;
		this.desplazamientoSubmenu = desplazamientoSubmenu;
		this.elementos = new Array();
		var i
		for (i=0; i<arrayComponentes[0].length; i++){
			this.elementos.include(new OpcionSecundaria(arrayComponentes[0][i], arrayComponentes[1][i]));
		}
		
		this.elementoGenerado  = new Element('div', {
			id: 'subnavegador' + this.indice, 'class': 'subnavegador'
		});
		//meto los eventos para los div donde están los subnavegadores
		this.elementoGenerado.addEvent("mouseenter", function(){
			this.navegadorDondeEstoy.anulaRetardo();
		}.bind(this));
		this.elementoGenerado.addEvent("mouseleave", function(){
			this.navegadorDondeEstoy.ocultaSubmenuRetardo(this.indice);
		}.bind(this));
		
		var navegador = "";
		this.elementos.each(function (item, index){
			navegador += item.dameCodigo();
		});
		
		this.elementoGenerado.set("html",navegador);
	},
	
	ocultate: function(){
		this.elementoGenerado.setStyle("display", "none");
		this.navegadorDondeEstoy.opcionesPrincipales[this.indice].enlace.set("styles", {"color": "#d46710", "background-color": "transparent", "border": "0px"});
	},
	
	muestrate: function(){
		this.elementoGenerado.setStyle("display", "block");
	},
	
	dameElemento: function(){
		return this.elementoGenerado;
	},
	
	recolocate: function(posicionEnlace, sizeEnlace){
		this.elementoGenerado.setStyle("top", posicionEnlace.y + sizeEnlace.y);
		this.elementoGenerado.setStyle("left", posicionEnlace.x - this.desplazamientoSubmenu);
	}
});
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
//CLASE NAVEGADOR
var Navegador = new Class({
	retardo: null,
	
	initialize: function(Principales, secundarias, desplazamientosSubmenu, estilosEspacilesPrincipales){
		this.opcionesPrincipales = new Array();
		this.opcionesSecundarias = new Array();
		var i
		for (i=0; i<Principales.length; i++){
			this.opcionesPrincipales.include(new OpcionPrincipal(Principales[i][0], Principales[i][1], i, this, estilosEspacilesPrincipales[i]));
			this.opcionesSecundarias.include(new SubNavegador(secundarias[i],i, this, desplazamientosSubmenu[i]));
		}
	},
	anulaRetardo: function(){
		$clear(this.retardo);
	},
	
	ocultaSubmenus: function(){
		this.opcionesSecundarias.each(function(item, index){
			item.ocultate();
		});
	},
	ocultaSubmenuRetardo: function(indiceOcultar){
		//alert ("oculto " + indiceOcultar)
		this.retardo = this.opcionesSecundarias[indiceOcultar].ocultate.delay(1000,this.opcionesSecundarias[indiceOcultar]);
	},
	
	muestraSubmenu: function (indiceSubmenu){
		this.anulaRetardo();
		this.opcionesSecundarias[indiceSubmenu].muestrate();
		this.opcionesPrincipales[indiceSubmenu].enlace.set("styles", {"color": "#ffffff", "background-color": "#d46710", "border": "1px solid #d7d7d7"});
	},
	
	recolocaSubnavegadores: function(){
		for (i=0; i<this.opcionesPrincipales.length; i++){
			//alert (i + " " + this.opcionesPrincipales[i].enlace.getPosition().x);
			this.opcionesSecundarias[i].recolocate(this.opcionesPrincipales[i].enlace.getPosition(), this.opcionesPrincipales[i].enlace.getSize());
		}
	},
	
	escribete: function(lugar){
		
		//lugar donde voy a insertarlo todo
		var lugar_impresion = $(lugar);
		
		//genero opciones principales
		var listaElementos = new Element ("ul");
		
		this.opcionesPrincipales.each(function (item, index){
			item.dameElementoLista().inject(listaElementos);
		});
		listaElementos.inject(lugar_impresion);
		
		//genero recuadros con las opciones secundarias
		var elementoSecundario;
		this.opcionesSecundarias.each(function (item, index){
			elementoSecundario = item.dameElemento();
			elementoSecundario.inject(lugar_impresion, 'after');
		});
		
		//posiciono las opciones secundarias
		this.recolocaSubnavegadores.delay(100, this);
	}
}); 
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
//CLASE PARA ENVIAR UN FORMULARIO Y MOSTRAR ERRORES DE VALIDACIÓN
//Se utiliza por ejempo en el registro
//requiere 
/////formulario (el id del form), 
/////mostrarError (la capa donde se mostrarán los errores, 
/////mostrarCorrecto (la capa donde se mostrará que es correcto), 
/////botonEnvio (el id del botón de sumbit)
/////cargandoformulario (la capa donde se muestra que el formulario está cargando, hasta que se inicializa el formulario ajax
/////
/////tiene un método mantenerFormulario(), que recibe un boleano, para decir si ese formulario se mantiene o no visible en la página después de que haya sido recibido y procesado correctamente.
////////////////////////////////////////////////////////////////////////
var FormularioAjax = new Class({
	initialize: function(formulario, mostrarError, mostrarCorrecto, botonEnvio, cargandoformulario){
		this.formulario = $(formulario);
		this.formulario.capaError = $(mostrarError);
		this.formulario.capaCorrecto = $(mostrarCorrecto);
		$(cargandoformulario).set("styles", {"display": "none"});
		this.formulario.botonEnvio = $(botonEnvio);
		this.formulario.botonEnvio.set("styles", {"display": "block"});
		this.formulario.cajaLoading = null;
		this.formulario.mantenFormulario=false;
		//defino el evento submit
		this.formulario.addEvent('submit', function(e){
			e.stop();
			this.capaError.empty();
			if (this.mantenFormulario){
				this.capaCorrecto.empty();
			}
			this.cajaLoading = new Element("div");
			this.cajaLoading.set("html","<img src='/images/loadingcw.gif' width=100 height=68>");
			this.botonEnvio.set("styles", {"display": "none"});
			this.cajaLoading.inject(this.botonEnvio,"after");
			this.set('send', {
				onComplete: function(response) { 
					//alert(response);
					var respuesta = JSON.decode.attempt(response);
					if (respuesta) {
						if (respuesta.valido != "1") {
							//error en el formulario
							this.cajaLoading.destroy();
							this.botonEnvio.set("styles", {"display": "block"});
							this.capaError.set("html", respuesta.mensaje);
						}else {
							//formulario correcto
							this.cajaLoading.destroy();
							this.capaCorrecto.set("html", respuesta.mensaje);
							if (this.mantenFormulario){
								this.botonEnvio.set("styles", {"display": "block"});
							}
	            		}
	          		}else{
						this.cajaLoading.destroy();
						this.botonEnvio.set("styles", {"display": "block"});
						this.capaError.set("html", "Recebemos dados de resposta incorretos. \nComprove seu formulário, tente mais tarde ou entre em contato conosco para informar o erro.");
						this.capaError.set("html", response);
					}
				}.bind(this)
			});
			//Send the form.
			this.send();
		});
	},
	mantenerFormulario: function(boleanoMantener){
		this.formulario.mantenFormulario=boleanoMantener;
	}
});
////////////////////////////////////////////////////////////////////////

var FormularioEncuesta = new Class({
	initialize: function(formulario, capaformulario, cargandoformulario, botonEnvio, tituloEncuesta){
		
		this.formulario = $(formulario);
		this.formulario.capaformulario = $(capaformulario);
		$(cargandoformulario).set("styles", {"display": "none"});
		this.formulario.botonEnvio = $(botonEnvio);
		this.formulario.botonEnvio.set("styles", {"display": "block"});
		this.formulario.tituloEncuesta=tituloEncuesta;
		this.formulario.cajaLoading=null;
		
		//defino el evento submit
		this.formulario.addEvent('submit', function(e){
			e.stop();
			this.cajaLoading = new Element("div", {'id': 'loadingencuesta'});
			this.cajaLoading.set("html","<img src='/images/loadingcw.gif' width=100 height=68>");
			//this.botonEnvio.set("styles", {"display": "none"});
			this.cajaLoading.replaces(this.botonEnvio);
			this.set('send', {
				onComplete: function(response) { 
					this.capaformulario.set("html","<p>Muito obrigado por votar!</p><div class=fuente8 style='line-height: 140%; font-weight: bold;'>&gt; <a href='javascript:void(0)' id='volverver'>ver o resultado da enquete</a><br>&gt; <a href='/questionario'>ver outras enquetes</a></div><p>");
					$('volverver').addEvent("click", function(){
						var popopEstadisticas = new MiPopup(this.cajaImagenResult.get("html") ,600,220, this.tituloEncuesta)
					}.bind(this));
					//this.capaimgresult = new Element("div", {'id': 'capaimgresult'});
					var imagenresultado = new Asset.image(response, {'id': 'imagenresultado', 'title': 'Resultado de la encuesta', 'onload': function(img){
							this.cajaImagenResult = new Element("div", {'id': 'capaimgresult'});
							//cajaImagenResult.inject(window.document.html,'top');
							//this.cajaImagenResult.inject(document.body);
							img.inject(this.cajaImagenResult);
							var popopEstadisticas = new MiPopup(this.cajaImagenResult.get("html") ,600,220, this.tituloEncuesta)
						}.bind(this)
					});
				}.bind(this)
			});
			//Send the form.
			//alert("envio form");
			this.send();
		});
	}
});




var MiPopup = new Class({
	initialize: function(miHtml,ancho,alto,titulo){
		this.titulo=titulo;
		this.tamanoBody = window.getScrollSize();
		this.posScroll = window.getScroll();
		this.espacioDisponibleVentana = window.getSize();
		this.capaSombra = new Element("div", {'id': 'capasombra', 'style': 'width: ' + this.tamanoBody.x + 'px; height: ' + this.tamanoBody.y + 'px; ' });
		this.capaSombra.inject(document.body);
		var myFx = new Fx.Tween(this.capaSombra,{'duration': 300});
		myFx.start('opacity',0,0.8);
		
		this.contenido = new Element("div", {'id': 'contenidopopup'});
		this.contenido.set('html', miHtml);
		var titulo = new Element("div", {'id': 'titulopopup'});
		titulo.set('html', this.titulo);
		var cerrar = new Element("div", {'id': 'cerrarpopup'});
		cerrar.addEvent('click', function(){
			this.cerrar();
		}.bind(this));
		cerrar.inject(titulo,'top');
		titulo.inject(this.contenido,'top');
				
		this.capaPopup = new Element("div", {'id': 'capapopup', 'style': 'margin-left:-' + ancho/2 +'px; top:' + (this.posScroll.y + (this.espacioDisponibleVentana.y/2) - (alto/2)-15) +'px'});
		this.capaPopup.inject(this.capaSombra,'after');
		
		var myFx2 = new Fx.Tween(this.capaPopup,{'duration': 700});
		myFx2.start('width',4,ancho);
		myFx2.addEvent('complete', function(){
			var myFx3 = new Fx.Tween(this.capaPopup,{'duration': 700});
			myFx3.start('height',4,alto+30);
			myFx3.addEvent('complete', function(){
				this.contenido.inject(this.capaPopup);
				this.contenido.setStyle('opacity', 0);
				this.contenido.setStyle('display', 'block');
				var myFx4 = new Fx.Tween(this.contenido,{'duration': 600});
				myFx4.start('opacity',0,1);
			}.bind(this));
		}.bind(this));
		
		this.capaSombra.addEvent('click', function(){
				this.cerrar();
			}.bind(this)
		);
	},
	
	cerrar: function(){
		var myFx = new Fx.Tween(this.capaPopup,{'duration': 500});
		myFx.start('opacity',1,0);
		myFx.addEvent('complete', function(){
			var myFx2 = new Fx.Tween(this.capaSombra,{'duration': 500});
			myFx2.start('opacity',0.8,0);
			myFx.addEvent('complete', function(){
				this.capaSombra.destroy();
				this.capaPopup.destroy();
			}.bind(this));
		}.bind(this));
	}
});

window.addEvent('domready', function(){
	miNavegador = new Navegador(opcionesPrincipales, opcionesSecundarias, desplazamientosSubmenu, classOpcionesPrincipales);
	miNavegador.escribete("navprincipal");
});
window.addEvent('resize', function(){
	miNavegador.recolocaSubnavegadores();
});