// JavaScript Document

var Presupuesto = function(nombreContenedor,nombreCuadro){
	var oClase = this;
	this.req = new Request(oClase);
	var dirImagenes = "img/";
	
	var contenedor = document.getElementById(nombreContenedor);
	var cuadro = document.getElementById(nombreCuadro);
	var btnEnviar = document.getElementById("botonEnviar");
	var btnBorrar = document.getElementById("botonBorrar");
	var btnSi = document.getElementById("btnSi");
	var btnNo = document.getElementById("btnNo");
	var nombre = document.getElementById("nombre");
	var empresa = document.getElementById("empresa");
	var direccion = document.getElementById("direccion");
	var telefono = document.getElementById("telefono");
	var email = document.getElementById("email");
	var blockeador = document.getElementById("blockeador");
	var dFijos = document.getElementById("detallesFijos");
	var dVariables = document.getElementById("detallesVariables");
	var aceptarOpc = document.getElementById("aceptarOpcion");
	var cancelarOpc = document.getElementById("cancelarOpcion");
	var cantidad = document.getElementById("cantidad");
	var ancho = document.getElementById("ancho");
	var alto = document.getElementById("alto");
	var comentario = document.getElementById("comentario");
	var bPres = document.getElementById("botonesPres");
	var nuevaTela = document.getElementById("nuevaTela");
	var cTipos = document.getElementById("contenedorTipos");
	var cTipo = document.getElementById("contenedorTipo");
	var enviando = document.getElementById("enviandoPresupuesto");
	var exito = document.getElementById("exitoPresupuesto");
	var fallo = document.getElementById("falloPresupuesto");
	var cerrar = document.getElementById("cerrarPresupuesto");
	var pregunta = document.getElementById("contMensajePregunta");
	var mensajeOpcion = document.getElementById("contMensajeOpcion");
	var aceptarMensaje = document.getElementById("btnAceptar");
	var textoMensajeExito = document.getElementById("textoMensajeExito");

	var totalErrores = 0;
	var indiceActual = -1;
	var nombreActual = "";
	var accion = "";
	var objetoActual = false;
	var objetoEdicion = false;
	var lineaInicial = false;
	var Lineas = new Array();

	if(Nav.esIE || Nav.esIE7) blockeador.style.filter = 'alpha(opacity=45)';
	else blockeador.style.MozOpacity = ".45";

	//OPCIONES
	var aceptarOpcion = function(){
		totalErrores = 0;
		cantidad.onblur();
		ancho.onblur();
		alto.onblur();
		if(totalErrores == 0){
			if(accion != "editar"){
				oClase.agregarLinea(nombreActual,alto.value,ancho.value,cantidad.value,indiceActual);
				textoMensajeExito.innerHTML = "La cortina se agregó con éxito.";
			}
			else{
				oClase.cargarEdicion();
				textoMensajeExito.innerHTML = "La cortina se modificó con éxito.";
			}
			iniciarCamposOpciones();
			oClase.centrarContenido(cuadro);
			oMens.mover();
		}
		
	}
	this.cargarEdicion = function(){
		objetoEdicion.td2.innerHTML = ancho.value+" x "+alto.value+" Mts";
		objetoEdicion.td3.innerHTML = cantidad.value;
		objetoEdicion.td4.innerHTML = valoresTabla(objetoEdicion.indiceOpciones);
		objetoEdicion.ancho = ancho.value;
		objetoEdicion.alto = alto.value;
		objetoEdicion.cantidad = cantidad.value;
		objetoEdicion.comentario = comentario.value;
		objetoEdicion.valores = devolverValor(objetoEdicion.indiceOpciones);
	}	
	this.mostrarOpciones = function(indice,objeto){
		dVariables.style.display = "block";
		dFijos.style.display = "block";
		if(indiceActual > 0){
			aPres[indiceActual]['contenedor'].style.display = "none";
			objetoActual.className = "tDera";
		}
		indiceActual = indice;
		nombreActual = objeto.innerHTML;
		objetoActual = objeto;
		objeto.className = "tDeraOn";
		bPres.style.display = "block";
		aPres[indice]['contenedor'].style.display = "inline";
		oClase.centrarContenido(cuadro);
	}	
	var iniciarCamposOpciones = function(){
		cantidad.value = "";
		ancho.value = "";
		alto.value = "";
		comentario.value = "";
		ocultarError(cantidad);
		ocultarError(ancho);
		ocultarError(alto);
		nombreActual = "";
		
		if(indiceActual > 0){
			if(objetoActual)objetoActual.className = "tDera";
			aPres[indiceActual].contenedor.style.display = "none";
			bPres.style.display = "none";
			dFijos.style.display = "none";
		}
		objetoActual = false;
		objetoEdicion = false;
		accion = "";
		cTipos.style.display = "inline";
		cTipo.style.display = "none";
		indiceActual = -1;
	}
	this.valoresEnviar = function(){
		var val = "";
		var indices = Lineas.length;
		val+= "indices|=|"+indices+"|&|";
		for(i=0;i<Lineas.length;i++){
			val+= 'producto'+i+"|=|"+Lineas[i].producto+"|&|";
			val+= 'ancho'+i+"|=|"+Lineas[i].ancho+"|&|";
			val+= 'alto'+i+"|=|"+Lineas[i].alto+"|&|";
			val+= 'cantidad'+i+"|=|"+Lineas[i].cantidad+"|&|";
			val+= 'comentario'+i+"|=|"+Lineas[i].comentario+"|&|";			
			val += "posiciones"+i+"|=|"+Lineas[i].valores.valores.length+"|&|";
			for(j=0;j<Lineas[i].valores.valores.length;j++){
				switch(Lineas[i].valores.valores[j].tipo){
					case "Opcion Simple":
						val+= 'valor'+i+"-"+j+"|=|"+aPres[Lineas[i].valores.valores[j].indice][Lineas[i].valores.valores[j].posicion].nombre+"|!-!|"+Lineas[i].valores.valores[j].opcion.value+"|&|";
					break;
				}
			}
		}
		return val;
	}		
	var crearTh = function(texto,alineacion){
		var th = document.createElement("th");
		th.innerHTML = texto;
		th.align = alineacion;
		return th;
	}
	var crearTd = function(texto,alineacion){
		var td = document.createElement("td");
		td.innerHTML = texto;
		td.align = alineacion;
		return td;
	}
	this.iniciarTabla = function(){
		var tabla = document.createElement("table");
		var tbody = document.createElement("tbody");
		tabla.appendChild(tbody);
		tabla.className = "tablaPresupuesto";
		var colgroup1 = document.createElement("colgroup");
		var colgroup2 = document.createElement("colgroup");
		var colgroup3 = document.createElement("colgroup");
		var colgroup4 = document.createElement("colgroup");		
		var colgroup5 = document.createElement("colgroup");
		
		
		tbody.appendChild(colgroup1);
		tbody.appendChild(colgroup2);
		tbody.appendChild(colgroup3);
		tbody.appendChild(colgroup4);
		tbody.appendChild(colgroup5);		
	
		var th1 = crearTh("Producto","center");
		var th2 = crearTh("Medida","center");
		var th3 = crearTh("Cantidad","center");
		var th4 = crearTh("Detalle","center");
		var th5 = crearTh("&nbsp;","center");		
		var tr = document.createElement("tr");
		tr.appendChild(th1);
		tr.appendChild(th2);
		tr.appendChild(th3);
		tr.appendChild(th4);
		tr.appendChild(th5);		
		tbody.appendChild(tr);

		contenedor.appendChild(tabla);
		contenedor.style.display = "none";
		var ini = crearLineaInicial();
		tbody.appendChild(ini);
		this.tabla = tabla;
		this.tbody = tbody;
		
		th1.width = 235;
		th2.width = 75;
		th3.width = 55;
		th4.width = 170;
		th5.width = 45;
		colgroup1.width = 235;
		colgroup2.width = 75;
		colgroup3.width = 55;
		colgroup4.width = 170;
		colgroup5.width = 45;
		

	}
	var crearLineaInicial = function(){
		var trIn = document.createElement("tr");
		var td1 = document.createElement("td");
		td1.innerHTML = "Seleccione una cortina.";
		trIn.appendChild(td1);
		var td2 = document.createElement("td");
		td2.innerHTML = "&nbsp;";
		trIn.appendChild(td2);

		var td3 = document.createElement("td");
		td3.innerHTML = "&nbsp;";
		trIn.appendChild(td3);

		var td4 = document.createElement("td");
		td4.innerHTML = "&nbsp;";
		trIn.appendChild(td4);

		var td5 = document.createElement("td");
		td5.innerHTML = "&nbsp;";
		trIn.appendChild(td5);
		lineaInicial = trIn;
		return trIn;
	}
	this.agregarLinea = function(producto,alto,ancho,cantidad,indiceOpciones){
		
		if(lineaInicial){
			lineaInicial.parentNode.removeChild(lineaInicial);
			lineaInicial = false;
		}
		var ob = new Object();
		var tr = document.createElement("tr");
		ob.td1 = crearTd("Cortina: "+producto,"left");
		ob.td2 = crearTd(ancho+" x "+alto+" Mts","right");
		ob.td3 = crearTd(cantidad,"right");
		ob.td4 = crearTd(valoresTabla(indiceOpciones),"left");
		ob.td5 = crearTd("","center");


		ob.td5.innerHTML = '<img src="img/editarMini.gif" onmouseover="oToolTip.mostrar(event,\'Modificar\')" onmouseout="oToolTip.ocultar()">';
		ob.td5.innerHTML += '<img src="img/quitarMini.gif" onmouseover="oToolTip.mostrar(event,\'Quitar\')" onmouseout="oToolTip.ocultar()">';		

		var editar = ob.td5.childNodes[0];
		editar.style.margin = "0px";
		editar.style.marginRight = "2px";

		var quitar = ob.td5.childNodes[1];
		quitar.style.margin = "0px";
		quitar.style.marginLeft = "0px";

		
	
		AddEvent(editar, "click", function(){editarLinea(ob)});
		AddEvent(quitar, "click", function(){confirmarEliminar(ob)});

		tr.appendChild(ob.td1);
		tr.appendChild(ob.td2);
		tr.appendChild(ob.td3);
		tr.appendChild(ob.td4);
		tr.appendChild(ob.td5);
		ob.td5.width = 45;
		ob.producto = producto;
		ob.alto = alto;
		ob.ancho = ancho;
		ob.cantidad = cantidad;
		ob.comentario = comentario.value;
		ob.linea = tr;
		ob.indice = Lineas.length;
		ob.indiceOpciones = indiceOpciones;
		ob.valores = devolverValor(indiceOpciones);
		Lineas[Lineas.length] = ob;
		this.tbody.appendChild(tr);
		contenedor.style.display = "block";
	}
	var devolverValor = function(indice){
		var ob = new Object();
		ob.valores = new Array();
		for(i=0;i<aPres[indice].length;i++){
			switch(aPres[indice][i].tipo){
				case "Opcion Simple":
					for(j=0;j<aPres[indice][i].opciones.length;j++){
						if(aPres[indice][i].opciones[j].checked){
							ob.valores[ob.valores.length] = new Object();
							ob.valores[ob.valores.length-1].tipo = "Opcion Simple";
							ob.valores[ob.valores.length-1].opcion = aPres[indice][i].opciones[j];
							ob.valores[ob.valores.length-1].indice = indice;
							ob.valores[ob.valores.length-1].posicion = i;							
							break;
						}
					}
				break;
			}
		}
		return ob;
	}
	var valoresTabla = function(indice){
		var dev = "";
		for(i=0;i<aPres[indice].length;i++){
			switch(aPres[indice][i].tipo){
				case "Opcion Simple":
					for(j=0;j<aPres[indice][i].opciones.length;j++){
						if(aPres[indice][i].opciones[j].checked){
							dev += "<b>"+aPres[indice][i].nombre+": </b>"+aPres[indice][i].opciones[j].value;
							break;
						}
					}
				break;
			}
		}
		return dev;		
	}
	var quitarLinea = function(){
		var objeto = oClase.objetoBorrar;
		if(objeto){
			objeto.linea.parentNode.removeChild(objeto.linea);
			var temp = new Array();
			for(i=0;i<objeto.indice;i++){
				temp[i] = Lineas[i];	
			}
			for(i=objeto.indice;i<Lineas.length-1;i++){
				temp[i] = Lineas[i+1];
				temp[i].indice = i;
			}
			Lineas = temp;
			if(Lineas.length == 0){
				contenedor.style.display = "none";
			}
			oClase.objetoBorrar = false;
			ocultarContenido(pregunta);
			mostrarBlockeador();
		}
	}
	var editarLinea = function(objeto){
		cantidad.value = objeto.cantidad;
		ancho.value = objeto.ancho;
		alto.value = objeto.alto;
		comentario.value = objeto.comentario;
		for(i=0;i<objeto.valores.valores.length;i++){
			switch(objeto.valores.valores[i].tipo){
				case "Opcion Simple":
					objeto.valores.valores[i].opcion.checked = true;
				break;
			}
		}
		objetoEdicion = objeto;
		indiceActual = objeto.indiceOpciones;
		accion = "editar";
		cTipos.style.display = "none";
		cTipo.style.display = "inline";
		cTipo.innerHTML = objeto.producto;
		dFijos.style.display = "block";
		bPres.style.display = "block";
		aPres[objeto.indiceOpciones].contenedor.style.display = "block";
		oClase.mostrarCuadro();
		
	}
	var confirmarEliminar = function(objeto){
		oClase.objetoBorrar = objeto;
		oClase.centrarContenido(pregunta);
		pregunta.style.visibility = "visible";
		mostrarBlockeador(true);
	}
	var cancelarEliminar = function(){
		oClase.objetoBorrar = false;
		ocultarContenido(pregunta);
		mostrarBlockeador();
	}

	//PRESUPUESTO
	
	this.mostrarCuadro = function(){
		cuadro.style.visibility = "visible";
		cuadro.style.zIndex = "2100";
		mostrarBlockeador(true);	
		oClase.centrarContenido(cuadro);
		oMens.ubicar(cuadro);
	}
	this.enviarPresupuesto = function(){
		totalErrores = 0;
		nombre.onblur();
		email.onblur();
		if(totalErrores == 0){
			if(Lineas.length > 0){
				oClase.centrarContenido(enviando);
				enviando.style.visibility = "visible";
				mostrarBlockeador(true);
				var v = "nombre|=|"+nombre.value+"|&|email|=|"+email.value+"|&|direccion|=|"+direccion.value+"|&|telefono|=|"+telefono.value+"|&|empresa|=|"+empresa.value+"|&|";
				v += oClase.valoresEnviar();
				oClase.req.pedir("xmlHttpRequest/presupuesto.php",v);
			}
			else{
				oClase.centrarContenido(mensajeOpcion);
				mensajeOpcion.style.visibility = "visible";
				mostrarBlockeador(true);								
			}
		}
		
	}
	var ocultarCuadro = function(){
		mostrarBlockeador();	
		cuadro.style.visibility = "hidden";
		cuadro.style.top = "-1000px";
		iniciarCamposOpciones();
	}
	var crearError = function(campo,mensaje,expresion,ubicacion){
		var contenido = document.createElement("div");
		contenido.className = "contenidoErrorPresupuesto";
		campo.className = "inputPres";
		var mens = document.createElement("mensaje");
		mens.innerHTML = mensaje;
		mens.className = "mensajeErrorPresupuesto";

		if(!ubicacion){
			var flecha = document.createElement("img");
			flecha.src = dirImagenes+"redArrow.gif";
			contenido.appendChild(flecha);
			contenido.appendChild(mens);
			campo.parentNode.appendChild(contenido);
			contenido.style.width = "280px";
		}
		else{
			var flecha = document.createElement("img");
			flecha.src = dirImagenes+"redArrowDer.gif";
			contenido.appendChild(mens);
			contenido.appendChild(flecha);
			campo.parentNode.insertBefore(contenido,campo);
			mens.style.marginLeft = "0px";
			mens.style.marginRight = "3px";
			contenido.style.display = "block";
			contenido.style.left = (contenido.offsetLeft - contenido.offsetWidth)+"px";
			contenido.style.display = "none";			
			contenido.style.width = "151px";
		}

		campo.contenido = contenido;
		campo.expresion = expresion;
		campo.onblur = function(){
			if(!campo.expresion.test(campo.value.toLowerCase()))mostrarError(campo);
			else ocultarError(campo);
		}
	}
	var crearErrores = function(){
		crearError(nombre,'Ingrese su nombre',ER_STR,true);
		crearError(email,'Email incorrecto',ER_EMAIL,true);
		crearError(cantidad,'Debe ingresar la cantidad',ER_NATURAL_NOCERO);
		crearError(ancho,'Ancho incorrecto',ER_DECIMAL);
		crearError(alto,'Alto incorrecto',ER_DECIMAL);		
	}
	var mostrarError = function(campo){
		totalErrores++;
		campo.contenido.style.display = "inline";
		campo.className = "inputErrorPres";
	}
	var ocultarError = function(campo){
		campo.contenido.style.display = "none";
		campo.className = 'inputPres';
	}
	var mostrarBlockeador = function(valor){
		if(valor){
			var scrn = getBodyDims();
			var pant = getBodyWHAvaible();
			var dim = getWindowDims();
			var pos = getScrollPos();
			blockeador.style.display = "block";
			if(Nav.esIE || Nav.esIE7)blockeador.style.height = (pant.h)+"px";
			else blockeador.style.height = (dim.h)+"px";
			blockeador.style.width = scrn.w+"px";
		}
		else blockeador.style.display = "none";
	}
	this.centrarContenido = function(objeto){
		var pos = getScrollPos();
		var scrn = getBodyWHAvaible();
		var dim = getBodyDims();
		objeto.style.top = (Math.round((scrn.h - objeto.offsetHeight)/2)+pos.y)+"px";
		objeto.style.left = (Math.round((scrn.w - objeto.offsetWidth)/2)+pos.x)+"px";
	}
	var ocultarContenido = function(objeto){
		objeto.style.visibility = "hidden";
		objeto.style.top = "-2000px";
		mostrarBlockeador();
	}
	this.limpiarCampos = function(){
		nombre.value = "";
		empresa.value = "";
		direccion.value = "";
		telefono.value = "";
		email.value = "";
		ocultarError(nombre);
		ocultarError(email);
	}

	//MENSAJE
	
	var Mensaje = function(nombreCont){
		var contMensaje = document.getElementById(nombreCont);
		var velocidad = 5;
		var aceleracion = 50;
		var oCl = this;
		this.altoInicial = 0;
		var iniciado = 0;
		this.ubicar = function(objeto){
			/*var alto = (objeto.offsetTop+objeto.offsetHeight)-contMensaje.offsetHeight;
			oCl.altoInicial = alto;
			contMensaje.style.top = alto+"px";
			contMensaje.style.left = objeto.offsetLeft+"px";*/
		}
		this.mover = function(){
			if(iniciado == 0){
				this.moverAbajo();
				iniciado = 1;
			}
		}
		this.moverAbajo = function(){
			var marg = (parseInt(contMensaje.style.marginTop.replace("px",""))+velocidad);
			if(marg <= 0){
				contMensaje.style.marginTop = marg+"px"
				setTimeout(function(){oCl.moverAbajo()},aceleracion);
			}
			else{
				contMensaje.style.marginTop = 0+"px"
				setTimeout(function(){oCl.moverArriba()},2000);
			}
		}
		this.moverArriba = function(){
			var marg = (parseInt(contMensaje.style.marginTop.replace("px",""))-velocidad);
			if(marg >= (-(contMensaje.offsetHeight))){
				contMensaje.style.marginTop = marg+"px"
				setTimeout(function(){oCl.moverArriba()},aceleracion);
			}
			else{
				contMensaje.style.marginTop = (-(contMensaje.offsetHeight))+"px";
				iniciado =0;
			}
		}
		contMensaje.style.marginTop = (-(contMensaje.offsetHeight))+"px";
	}
	var oMens = new Mensaje("mensajeExito");

	AddEvent(aceptarOpc, "click", aceptarOpcion);
	AddEvent(cancelarOpc, "click", ocultarCuadro);
	AddEvent(nuevaTela, "click", oClase.mostrarCuadro);	
	AddEvent(btnEnviar, "click", oClase.enviarPresupuesto);
	AddEvent(btnBorrar, "click", oClase.limpiarCampos);
	AddEvent(btnSi, "click", quitarLinea);
	AddEvent(btnNo, "click", cancelarEliminar);
	AddEvent(aceptarMensaje, "click", function(){ocultarContenido(mensajeOpcion)});	

	AddEvent(exito, "click", function(){ocultarContenido(exito)});
	AddEvent(fallo, "click", function(){ocultarContenido(fallo)});	
	AddEvent(btnBorrar, "click", oClase.limpiarCampos);
	AddEvent(cerrar, "click", ocultarCuadro);	
	this.onRequestLoad = function(){
		var nodo = this.req.respuestaXML;
		if(!nodo){
			alert(this.req.respuestaHTML);	
			return false;
		}
		if(nodo.getAttribute("exito") == ""){
			this.centrarContenido(fallo);
			fallo.style.visibility = "visible";
		}
		else{
			this.centrarContenido(exito);
			exito.style.visibility = "visible";
			this.limpiarCampos();
			contenedor.innerHTML = "";
			this.iniciarTabla();
			Lineas = new Array();
		}
		enviando.style.visibility = "hidden";
		enviando.style.top = "-1000px";

	}
	crearErrores();
	this.iniciarTabla();
}
