//variables globales
var theURL = "/servlet/gesDireccion";
var theURLEnvia = "/servlet/taxiWeb";
var theURLComprueba = "/servlet/taxiWeb";
var theURLComprueba1 = "/servlet/compruebaSolicitud";
var theURLlistados = "/servlet/obtenerListados";

var httpA = getHTTPObject();
var httpB = getHTTPObject();
var httpC = getHTTPObject();
var httpEnvia = getHTTPObject();
var httpComprueba = getHTTPObject();
var httpListadoAlias = getHTTPObject();
var httpListadoVias = getHTTPObject();

var flag = 1;
var flag2 = 1;

var idpeticionGlobal = '';

var fecha = new Date();
var numeroAleatorioGlobal = fecha.getDay() + fecha.getSeconds() + fecha.getMinutes();

function crearPeticion(id) {
	//alert("IDUsuario: "+ id);
	var cadena;
	cadena = 'IDUsuario: ' + id;
	if (document.getElementById('div_manual').style.display == 'none' || document.getElementById('div_manual').style.display == '') {
		cadena += '\nIntroducción por búsqueda';
		if (document.getElementById('nuevadir_via_select').style.display == 'block') {
			cadena += '\nDirección con via.';
			if (document.getElementById('selectVia').selectedIndex != -1) {
				cadena +='\n\tVia: ' + document.getElementById('selectVia')[document.getElementById('selectVia').selectedIndex].text;
				cadena +='\n\tIdVia: ' + document.getElementById('selectVia')[document.getElementById('selectVia').selectedIndex].value;
				if (document.getElementById('portalInput').value != '') {
					cadena +='\n\tPortal: ' + document.getElementById('portalInput').value;
					cadena +='\n\tLa petición puede ser creada.';
				}
			}
		}
		else if (document.getElementById('nuevadir_alias_select').style.display == 'block') {
			cadena += '\nDirección con alias.';
			if (document.getElementById('selecTalias').selectedIndex != -1) {
				cadena +='\n\tAlias: ' + document.getElementById('selectAlias')[document.getElementById('selectalias').selectedIndex].text;
				cadena +='\n\tPGE_ID: ' + document.getElementById('selectAlias')[document.getElementById('selectalias').selectedIndex].value;
				cadena +='\n\tLa petición puede ser creada.';
			}
		}
	}
	else if (document.getElementById('div_busqueda').style.display == 'none') {
		cadena += '\nIntroducción manual';
		if (document.getElementById('direccionManualInput').value != '') {
			cadena +='\n\tVía: ' + document.getElementById('direccionManualInput').value;
			cadena += '\n\tLa petición puede ser creada.';
		}
	}
	alert(cadena);
	cadena = null;
}

function cambiosViaManual() {
	document.getElementById('dirActual').innerHTML = '<b>Dirección</b>: ' + document.getElementById('direccionManualInput').value;
}

function cambiosViaNombre() {
	document.getElementById('dirActual').innerHTML = '<b>Dirección</b>: ' + document.getElementById('selectVia')[document.getElementById('selectVia').selectedIndex].text;
	document.getElementById('portalInput').disabled = false;
	if (document.getElementById('portalInput').value != '')
		cambiosViaPortal();
}
function cambiosViaPortal() {
	if (document.getElementById('selectVia').selectedIndex != -1)
		document.getElementById('dirActual').innerHTML = '<b>Dirección</b>: ' + document.getElementById('selectVia')[document.getElementById('selectVia').selectedIndex].text;		
	else {
		document.getElementById('dirActual').innerHTML = '<b>Dirección</b>: ';
	}
	if (document.getElementById('portalInput').value != '')
		document.getElementById('dirActual').innerHTML += ' <b>Portal</b>: ' + document.getElementById('portalInput').value;
}
function cambiosAlias() {
	document.getElementById('dirActual').innerHTML = '<b>Dirección</b>: ' + document.getElementById('selectAlias')[document.getElementById('selectAlias').selectedIndex].text;
}
function getCoincidenciasAlias() {
	var obj = document.getElementById('aliasInput');
	document.getElementById('portalInput').disabled = true;
	var url = theURLlistados + "?method=listadoAlias&aliasParcial="+obj.value;
	httpListadoAlias.open("GET",url,true);
	httpListadoAlias.onreadystatechange = handleHttpListadoAlias;
	httpListadoAlias.send(null);
	url = null;
}
function getCoincidenciasVias() {
	var obj = document.getElementById('viaInput');
	var url = theURLlistados + "?method=listadoVias&viaParcial="+obj.value;
	httpListadoVias.open("GET",url,true);
	httpListadoVias.onreadystatechange = handleHttpListadoVias;
	httpListadoVias.send(null);
	url = null;
}
function handleHttpListadoVias() {
	if (httpListadoVias.readyState == 4) {
		if (httpListadoVias.status == 200) {
			var resul = httpListadoVias.responseXML;
			if(resul.documentElement.nodeName!='vacio'){
				document.getElementById('nuevadir_via_select').style.display = 'block';

				if (document.getElementById('cuerpoCaja') != null)		
					document.getElementById('cuerpoCaja').className = 'cuerpoCaja ancha';
				
				document.getElementById('nuevadir_alias_select').style.display = 'none';	
				document.getElementById('selectAlias').length = 0;				
				document.getElementById('aliasInput').value = "";
				var vias = resul.getElementsByTagName('via');		
				var selectVia = document.getElementById('selectVia');
				selectVia.length = 0;
				var optionVia = null;
				var texto = "";
				for (var i=0;i<vias.length;i++) {				
					optionVia = document.createElement('option');
					optionVia.value = vias[i].attributes.getNamedItem('via_id').value;
					texto = document.createTextNode(vias[i].attributes.getNamedItem('via_nombre').value);
					selectVia.appendChild(optionVia);
					optionVia.appendChild(texto);
				}				
				vias = null;
				selectVia = null;
				optionVia = null;
				texto = null;
			}
			resul = null;
		}
	}
}
function handleHttpListadoAlias() {
	if (httpListadoAlias.readyState == 4) {
		if (httpListadoAlias.status == 200) {
			var resul = httpListadoAlias.responseXML;
			if(resul.documentElement.nodeName!='vacio'){
				document.getElementById('nuevadir_alias_select').style.display = 'block';	
				
				if (document.getElementById('cuerpoCaja') != null)				
					document.getElementById('cuerpoCaja').className = 'cuerpoCaja ancha';
				
				document.getElementById('nuevadir_via_select').style.display = 'none';						
				document.getElementById('selectVia').length = 0;				
				document.getElementById('viaInput').value = "";		
				document.getElementById('portalInput').value = "";		
				
				var alias = resul.getElementsByTagName('alias');		
				var selectAlias = document.getElementById('selectAlias');
				selectAlias.length = 0;
				var optionAlias = null;
				var texto = "";
				for (var i=0;i<alias.length;i++) {				
					optionAlias = document.createElement('option');
					optionAlias.value = alias[i].attributes.getNamedItem('pge_id').value;
					texto = document.createTextNode(alias[i].attributes.getNamedItem('pge_alias').value);
					selectAlias.appendChild(optionAlias);
					optionAlias.appendChild(texto);
				}				
				alias = null;
				selectAlias = null;
				opcionAlias = null;
				texto = null;
			}
			resul = null;
		}
	}
}

//functión que inicia cuando se ha enviado un taxi ya
function inicia(){
	document.formu.reset();
	ocultaCapa('enespera');
	var objCapa = document.getElementById('enespera');
	var objCapaE = document.getElementById('estadop');
	//se restaura la capa 'enespera'
		objCapaE.innerHTML = '';
		var objImg = document.createElement('img');
		objImg.src = "/images/procesando.gif";
		objImg.alt = "Su solicitud se está procesando";
		objCapaE.appendChild(objImg);
		var objImg2 = objImg.cloneNode(false);
		objImg2.src = "/images/buscando1.gif";
		objImg2.alt = " ";
		objCapaE.appendChild(objImg2);
		var objImg3 = objImg2.cloneNode(true);
		objImg3.src = "/images/exito1.gif";
		objCapaE.appendChild(objImg3);
	
	ocultaCapa('despeciales');
	muestraCapa('btn_solicitar');
	flag2 = 1;
}

//función que borra una dirección de direcciones favoritas
function borradir(obj,id){ //el objeto es una imagen
	flag = 0;
	callBorrar(id,obj);
	flag = 1;	
}

function callBorrar(idpeticion, obj) {
	var idCliente = document.getElementById("idCliente").value;
   	httpB.open("GET", theURLEnvia + "?method=borrarDir&idDireccion="+idpeticion+"&idCliente="+idCliente, true);
	httpB.onreadystatechange = function(){ 
		if (httpB.readyState == 4) {
			res = httpB.responseText; 
			if(res.indexOf('OK') != -1){
				var objLI = obj.parentNode;
				var objUL = objLI.parentNode;
				objUL.removeChild(objLI);
			}
			else if (res.indexOf('ERR1') != -1) {
				alert("No se ha podido elminar la dirección con éxito.");
			}
			else if (res.indexOf('ERR2') != -1) {
				alert("No se puede borrar la dirección. Al menos debe poseerse una.");			
			}
			else 
				alert("Ha habido un error de conexión con la aplicación. Vuelva a intentarlo en unos segundos.");
		}
	};
	httpB.send(null);					  
}

//función que añade una nueva dirección al listado de direcciones favoritas
function anyadirDireccion(idClien) {
	var creada = false;
	var parametros = "";
	var texto_mostrar = "";
	if (document.getElementById('div_manual').style.display == 'none' || document.getElementById('div_manual').style.display == '') {
		if (document.getElementById('nuevadir_via_select').style.display == 'block') {
			if (document.getElementById('selectVia').selectedIndex != -1) {
				parametros += "&via_id=" + document.getElementById('selectVia')[document.getElementById('selectVia').selectedIndex].value;
				parametros += "&direccion="+ document.getElementById('selectVia')[document.getElementById('selectVia').selectedIndex].text;
				if (document.getElementById('portalInput').value != '') {
					parametros += ", " + document.getElementById('portalInput').value + "&portal=" + document.getElementById('portalInput').value;
					texto_mostrar = document.getElementById('selectVia')[document.getElementById('selectVia').selectedIndex].text;
					texto_mostrar += ", " + document.getElementById('portalInput').value;
					creada = true;
				}
			}
		}
		else if (document.getElementById('nuevadir_alias_select').style.display == 'block') {
			if (document.getElementById('selecTalias').selectedIndex != -1) {
				parametros += "&alias=" + document.getElementById('selectAlias')[document.getElementById('selectalias').selectedIndex].text;
				parametros += "&pge_id=" + document.getElementById('selectAlias')[document.getElementById('selectalias').selectedIndex].value;
				texto_mostrar = document.getElementById('selectAlias')[document.getElementById('selectalias').selectedIndex].text;
				creada = true;
			}
		}
	}
	else if (document.getElementById('div_busqueda').style.display == 'none') {
		if (document.getElementById('direccionManualInput').value != '') {
			parametros += "&direccion=" + document.getElementById('direccionManualInput').value;
			texto_mostrar = document.getElementById('direccionManualInput').value;
			creada = true;
		}
	}
	if (creada == true) {
		callAnyadir(parametros,idClien,texto_mostrar);
	}
	else {
		alert("Introduzca los datos corretamente.");
	}	
}
function callAnyadir(parametros,idcliente,texto) {
   	httpA.open("GET", theURLEnvia + "?method=nuevaDir" + parametros + "&idCliente=" + idcliente, true);
	httpA.onreadystatechange = 
		function(){ 
			if (httpA.readyState == 4) {
				res = httpA.responseText; 
	  			if(res.indexOf('OK')!=-1){
					var objHijo = document.getElementById("listaDirecciones").lastChild;
					
					var objUL = document.getElementById("listaDirecciones");
					var objLI = document.createElement('li');
					var objA = document.createElement('a');
					var objImg = document.createElement('img');
					var id = res.substring(res.indexOf('#')+2,res.lastIndexOf('#'));
					var pgeId = res.substring(res.lastIndexOf('#')+1,res.length);				
					 
					objImg.src = "/images/ico_eliminar.gif";
					objImg.alt = "borrar dirección";
					objImg.onclick = function () { borradir(objImg,id) }
					if (pgeId != "-1") {
						objA.appendChild(document.createTextNode(texto));
						objA.href= "#";
						objA.onclick = function() { cambiadir(objA,id,idcliente);return false; }
						objA.onkeypress = function() { cambiadir(objA,id,idcliente);return false; } 
						objLI.appendChild(objA);
					}
					else {
						objLI.appendChild(document.createTextNode(texto));
					}
					objLI.appendChild(objImg);
					objUL.insertBefore(objLI,objHijo);							 
				}
				else alert("Ha habido un error de conexión con la aplicación. Vuelva a intentarlo en unos segundos");
			}
		};
	httpA.send(null);					  
}


//función que cambia la dirección a la que se enviará el taxi tras seleccionar una dirección de la lista
function cambiadir(obj,id,idcliente){ //el objeto es un enlace
	flag = 0;
	callCambiar(id,obj,idcliente);
	flag = 1;		
}	

function callCambiar(idpeticion, obj,idcliente) {
   	httpC.open("GET", theURL + "?accion=actualizar&id=" + idpeticion + "&idcliente=" + idcliente, true);
	  httpC.onreadystatechange = 
	  			function(){ 
	  				if (httpC.readyState == 4) {
	  					res = httpC.responseText; 
	  					
	  					if(res.toLowerCase() =='ok'){
								var objDir = document.getElementById('direccion');
								objDir.innerHTML = obj.firstChild.nodeValue;
								ocultaCapa('dcha');
								document.getElementById('m_dir').style.visibility = "visible";
								iddireccionGlobal = idpeticion;
							}
							else alert("Ha habido un error de conexión con la aplicación. Vuelva a intentarlo en unos segundos");
						}
	  			};
	  httpC.send(null);					  
}

//función que muestra la lista de direcciones 
function muestraFavoritos(obj){ //el objeto es una imagen
	muestraCapa('dcha');
	//document.getElementById('dcha').style.display = "block";	
	obj.style.visibility = "hidden";
}

//función que muestra la ayuda de mis direcciones 
function muestraCapa(capa,obj){
	document.getElementById(capa).style.display = "block"
	document.getElementById(capa).style.visibility = "visible"
	if (obj){
		obj.onclick = function(){ ocultaCapa(capa,obj);return false }
		obj.onkeypress = function(){ ocultaCapa(capa,obj);return false }
	}	
}
function ocultaCapa(capa,obj){
	document.getElementById(capa).style.display = "none"
	document.getElementById(capa).style.visibility = "hidden"
	if (obj){
		obj.onclick = function(){ muestraCapa(capa,obj);return false }
		obj.onkeypress = function(){ muestraCapa(capa,obj);return false }
	}
}

//funciones Ajax
function getHTTPObject() {
	var xmlhttp;
	try {
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	   try {
	      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	   } catch (E) {
	      xmlhttp = false;
	   }
	}
	
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
	  try {
	    xmlhttp = new XMLHttpRequest();
	  } catch (e) {
	    xmlhttp = false;
	  }
	}
	
	return xmlhttp;
}

// función para enviar
function enviar (idpeticion){
	dir = document.getElementById('direccion');
	circunstancias = reuneCircunstancias();
	circunstanciasT = reuneCircunstancias('texto');
	var c = confirm("Se va a proceder al envio de un taxi a la dirección:\n"+ dir.innerHTML);
	if (c){
		flag = 0;
		callEnviar(idpeticion,circunstancias);
		flag = 1;
	}else 
		return;
}

function callEnviar(idpeticion,circunstancias) {
   	httpEnvia.open("GET", theURLEnvia + "?method=crearPeticion&idCliente=" + idpeticion +"&iddireccion="+ iddireccionGlobal + "&circunstancias=" + circunstancias + "&param=" + numeroAleatorioGlobal , true);
	  httpEnvia.onreadystatechange = 
	  			function(){ 
	  				if (httpEnvia.readyState == 4) {
	  					res = httpEnvia.responseText; 
	  					//alert(res);
	  					if(res.toLowerCase().indexOf('ok')!=-1){
								ocultaCapa('btn_solicitar');
								muestraCapa('enespera');
								idpeticionGlobal = res.substring(res.indexOf('##')+2,res.length);
								setTimeout('comprueba()',5000)//5 segundos;
							}
							else alert("Ha habido un error de conexión con la aplicación. Vuelva a intentarlo en unos segundos.");
						}
	  			};
	  httpEnvia.send(null);					  
}

//RECOGE LAS CIRCUNSTANCIAS ESPECIALES SELECCIONADAS
function reuneCircunstancias(param){
	var circ = '';
	var aInputs = document.getElementById('circ').getElementsByTagName('input');
	for( i=0; i< aInputs.length; i++){
		if (aInputs[i].name.indexOf('cespeciales')!=-1){
			if (aInputs[i].checked){
				if (param)
					circ += aInputs[i].nextSibling.nodeValue + ', ';
				else
					circ += aInputs[i].name.substring(11,aInputs[i].name.length) + '|';
			}
		}
	}
	return circ;
}

//COMPRUEBA EL ESTADO DE LA PETICIÓN
function comprueba() {
				  //if (flag && flag2) {
					if (flag2) {				  
						httpComprueba.open("GET",theURLComprueba +"?idsolicitud="+ idpeticionGlobal + "&method=obtenerEstadoPeticion&param=" + numeroAleatorioGlobal , true);
						httpComprueba.onreadystatechange = callComprueba;
						httpComprueba.send(null);
						setTimeout('comprueba()',5000)//5 segundos
				  }				  
			}
			
function callComprueba(){ 
					var img1 = document.getElementById('estadop').childNodes[0]
					var img2 = document.getElementById('estadop').childNodes[1]
					var img3 = document.getElementById('estadop').childNodes[2]
					
					if (httpComprueba.readyState == 4) {
						res = httpComprueba.responseText; 
						numeroAleatorioGlobal = res.split('||')[1];
						if(res.toLowerCase().indexOf('ok')!=-1){
							var Ares = res.split('||')[0].split('##');
							if (Ares[1]==1){
									if ( Ares.length==2){
										img1.src = "/images/procesando2.gif";
										img1.alt = "Su solicitud se está procesando";
										img2.src = "/images/buscando2.gif";
										img2.alt = "Buscando el taxi más proximo";
									}
									else {
										flag2=0;
										img2.src = "/images/buscando3.gif";
										img2.alt = "Buscando el taxi más proximo";
										img3.src = "/images/exito2.gif";
										img3.alt = "Solicitud completada con éxito";
										var objStrong = document.createElement('strong');
										var objBR = document.createElement('br');
										document.getElementById('estadop').appendChild(objBR);
										var objBR = document.createElement('br');
										document.getElementById('estadop').appendChild(objBR);
										document.getElementById('estadop').appendChild(document.createTextNode("El "));
										objStrong.appendChild(document.createTextNode("taxi nº " + Ares[2] + " "));
										document.getElementById('estadop').appendChild(objStrong);
										document.getElementById('estadop').appendChild(document.createTextNode("pasará a recogerle por la dirección indicada."));
										var objBR = document.createElement('br');
 										document.getElementById('estadop').appendChild(objBR);
										var objBR = document.createElement('br');
 										document.getElementById('estadop').appendChild(objBR);
 							
										var objA = document.createElement('a');
										objA.href="#";
										objA.onclick = function() { inicia();return false } 
										objA.onkeypress= function() { inicia();return false }
										objA.appendChild(document.createTextNode('solicitar otro taxi'));

										var objA2 = document.createElement('a');
										objA2.href="#";
										objA2.onclick = function() { document.location.href="/index.html"; } 
										objA2.onkeypress= function() { document.location.href="/index.html"; }
										objA2.className = "ulti";
										objA2.appendChild(document.createTextNode('salir del servicio'));
										
										document.getElementById('estadop').appendChild(objA);
										document.getElementById('estadop').appendChild(objA2);
									}	
							}		
						}
						else if (res.toLowerCase().indexOf('cancela')!=-1){
										flag2=0;
										var objDIV = document.getElementById('estadop');
										img1.style.display = "none";
										img2.style.display = "none";
										img3.style.display = "none";
										var objStrong = document.createElement('strong');
										objStrong.appendChild(document.createTextNode("Su solicitud ha sido cancelada debido a problemas técnicos."));
										objDIV.appendChild(objStrong);
										var objBR = document.createElement('br');
 										var objBR = document.createElement('br');
 										objDIV.appendChild(objBR);
 										objDIV.appendChild(document.createTextNode('si lo desea puede '));
 										var objA = document.createElement('a');
										objA.href="#";
										objA.onclick = function() { inicia();return false } 
										objA.onkeypress= function() { inicia();return false }
										objA.appendChild(document.createTextNode('solicitar otro taxi'));
										
										objDIV.appendChild(objA);
									}
							 		else alert("Ha habido un error de conexión con la aplicación. Vuelva a intentarlo en unos segundos");
				}
	}					
function verBusquedaDiv() {	
	if (document.getElementById('cabeceraCuadro') != null)		
		document.getElementById('cabeceraCuadro').style.background = "URL('../images/formulario/cabecera.jpg')";	
	else
		document.getElementById('ayuda').innerHTML = "Por favor, introduce el comienzo del nombre de la <b>vía</b> o <b>punto de interés</b> y pulsa sobre >> para seleccionar el nombre exacto.<br/>En caso de no existir, pulsa sobre <b>introducción manual</b>.";		
	if (document.getElementById('cuerpoCaja') != null)		
		document.getElementById('cuerpoCaja').className = 'cuerpoCaja';
	var div1 = document.getElementById('div_busqueda');
	var div2 = document.getElementById('div_manual');
	var etiqueta = document.getElementById('tipoDirLink');

	document.getElementById('nuevadir_alias_select').style.display = 'none';	
	document.getElementById('nuevadir_via_select').style.display = 'none';
	document.getElementById('dirActual').innerHTML = '<b>Dirección</b>: '
	
	var selectVia = document.getElementById('selectVia');
	selectVia.length = 0;
	document.getElementById('portalInput').value = '';
	document.getElementById('viaInput').value = '';
	document.getElementById('aliasInput').value ='';
	var selectAlias = document.getElementById('selectAlias');
	selectAlias.length = 0;	



	etiqueta.innerHTML = 'Introducción manual';
	etiqueta.onclick = verManualDiv;
	
	div1.style.display='block';
	div2.style.display='none';
	div1 = null;
	div2 = null;
}

function verManualDiv() {
	if (document.getElementById('cabeceraCuadro') != null)		
		document.getElementById('cabeceraCuadro').style.background = "URL('../images/formulario/cabecera2.jpg')";	
	else
		document.getElementById('ayuda').innerHTML = "Por favor, introduce tu dirección lo más exacta posible y a continuación pulsa sobre el botón <b>añadir</b>. Recibirás por correo electrónico la activación de tu nueva dirección.<br/>Si deseas que busquemos tu dirección, pulsa sobre <b>introducción por búsqueda</b>.";
	if (document.getElementById('cuerpoCaja') != null)				
		document.getElementById('cuerpoCaja').className = 'cuerpoCaja';	
	document.getElementById('portalInput').disabled = true;
	var div1 = document.getElementById('div_busqueda');
	var div2 = document.getElementById('div_manual');
	var etiqueta = document.getElementById('tipoDirLink');
	document.getElementById('dirActual').innerHTML = '<b>Dirección</b>: '	
	etiqueta.innerHTML = 'Introducción por búsqueda';
	etiqueta.onclick = verBusquedaDiv;
	div1.style.display='none';
	div2.style.display='block';
	div1 = null;
	div2 = null;
}
function eliminarTexto(obj) {
		obj.value ="";
		obj.className = null;
}