var alerta = new Object();
alerta.email = '\n\nRecuerda que ha de ser de la forma : xxxxx@xxx.xxx';
alerta.cif = 'Introduce un CIF/NIF válidos. \n\nRecuerda que el CIF ha de tener la forma : A00000000 \nY el NIF la forma : 00000000A';

var tablaNIF=new Array('T','R','W','A','G','M','Y','F','P','D','X','B','N','J','Z','S','Q','V','H','L','C','K','E','F'); 

var theURLEnviaFormulario = "/servlet/taxiWeb";
var theURLBusquedas = "/servlet/obtenerListados";
var httpEnviaFormulario = getHTTPObject();
var httpEnvia = getHTTPObject();

var httpBuscarVias = getHTTPObject();
var httpBuscarPuntos = getHTTPObject();

//javascript document

function callEnviarFormulario() {
	var creada = false;
	var parametros = "";
	// manual, punto, viaPortal
	// Dirección introducida por via y portal
	if ( document.getElementById('viaPortal').checked == true ) {
		// Si introducimos el resultado por via y portal, tenemos que ver que hay una via seleccionada, y un portal introducido.
		if ( document.getElementById('selectResul').selectedIndex != -1) {
			if ( document.getElementById('portal').value != '' ) {
				parametros += "&via_id=" + document.getElementById('selectResul')[document.getElementById('selectResul').selectedIndex].value;
				parametros += "&direccion="+ document.getElementById('selectResul')[document.getElementById('selectResul').selectedIndex].text;
				parametros += ", " + document.getElementById('portal').value + "&portal=" + document.getElementById('portal').value;								
				creada = true;
			} else {
				alert("Debe introducir un portal.");
				//return false;
			}		
		} else {
			alert("Debe tener una vía seleccionada.");
			//return false;
		}	
	}
	// Dirección introducida por alias
	else if ( document.getElementById('punto').checked == true ) {
		// Si introducimos el resultado por alias, tenemos que ver que hay un alias seleccionado.
		if ( document.getElementById('selectResul').selectedIndex != -1) {
			parametros += "&alias=" + document.getElementById('selectResul')[document.getElementById('selectResul').selectedIndex].text;
			parametros += "&pge_id=" + document.getElementById('selectResul')[document.getElementById('selectResul').selectedIndex].value;
			creada = true;	
		} else {
			alert("Debe tener un punto de interés seleccionado.");
			//return false;
		}		
	}
	// Dirección introducida por manual
	else {
		if ( document.getElementById('direccion').value != '') {
			parametros += "&direccion=" + document.getElementById('direccion').value;
			creada = true;			
		} else {
			alert("Debe introducir un destino.");
		}
	}

	var tipoRegistro = document.getElementById("tipoRegistro").value;
	
	parametros += "&emaildestino=lafuente@treelogic.com";
 	if (tipoRegistro == "registroUsuario") {
	 	parametros += "&nombre=" + document.getElementById("nombre").value;
	 	parametros += "&apellidos=" + document.getElementById("apellidos").value;
 	}
 	else {
	 	parametros += "&nombre=" + document.getElementById("empresa").value;
	 	parametros += "&apellidos=" + document.getElementById("pcontacto").value; 	
 	}
 	
 	parametros += "&nif=" + document.getElementById("CIF").value;
 	parametros += "&localidad=" + document.getElementById("localidad").value;
	
	parametros += "&email=" + document.getElementById("email").value;
	parametros += "&telefono=" + document.getElementById("telefono").value;
	parametros += "&usuario=" + document.getElementById("usuario").value;
	parametros += "&pass=" + document.getElementById("passwd").value;
	if (creada == true) {
		httpEnvia.open("GET", theURLEnviaFormulario + "?method=" + tipoRegistro + parametros , true);
		httpEnvia.onreadystatechange = handleHttpEnvia;
		httpEnvia.send(null);					  
	}
}
function handleHttpEnvia() {
	if (httpEnvia.readyState == 4) {
		if(httpEnvia.status == 200) {
			var res = httpEnvia.responseText; 
			var resXML = httpEnvia.responseXML;
			var aceptado = resXML.getElementsByTagName('registro')[0].getAttribute("ok");
			var tipo =  resXML.getElementsByTagName('registro')[0].getAttribute("tipo");
			if (aceptado.toUpperCase() == "TRUE") {
				document.location = "solicitud_ok.html";
			}
			else {
				document.location = "solicitud_error.html";			
			}
			activarEnvio();
		}
	}
}

function envia(){
	
	if (!(document.getElementById('clausula').checked == true)) {
		alert("Antes de proceder al envío del formulario, debe leer y aceptar la política de protección de datos situada al pie del formulario.");		
		return;
	}	
	//if(!document.getElementById('requerido')){ return; }
	var reqcampos=document.getElementById('requerido').value.split(',');
 	
	for(var i=0;i<reqcampos.length;i++) {
	    var f=document.getElementById(reqcampos[i]);
	    if(!f){continue;}
	    switch(f.type.toLowerCase()) {
	   
			case 'text':				
	        	if (f.value == '' && f.id != 'email'){
	        		alert("Debe rellenar el campo " + f.id + ".");
	        		f.focus();
	        		return false;
	        	}
		        if(f.id=='email' && !cf_isEmailAddr(f.value)){
	        		alert('Verifica que el campo email es correcto.');
		        	f.focus();
	        		return false;		        	
		        }  
		        if (f.id == 'cif') {
		        	if ((cf_isNIF(f.value) && (f.value.toUpperCase() != compruebaNIF())) || (cf_isCIF(f.value) && (compruebaCIF() != true)) || (!cf_isNIF(f.value) && !cf_isCIF(f.value))) {
	        			alert('Verifica que el campo CIF/NIF es correcto.');
	        			f.focus();
	        			return false;
	        		}
		        }	      
				break;
			case 'textarea':
	        	if(f.value==''){
	        		lanza_alert(f);        		
		        	f.focus();
	        		return false;			        	
		        }              
	    	  	break;
		    case 'checkbox':
		        if(!f.checked){
	    	    	lanza_alert(f);  	    	
	        		f.focus();
	        		return false;		        		
		        }              
			      break;
	    	case 'select-one':
	        	if(!f.selectedIndex && f.selectedIndex==0){
		        	lanza_alert(f);	        	
		        	f.focus();
	        		return false;		        	
	    	    }              
		    	break;
			case 'password':
				if(f.value=='') {
					lanza_alert(f);
					f.focus();
	        		return false;					
				}
		        if (document.getElementById('passwd2'))
	        		if (document.getElementById('passwd2').value == ''){
	        			alert("Por favor, repite la contraseña para su confirmación posterior.")
	        			document.getElementById('passwd2').focus();
		        		return false;	        			
	        		}
	        		if (document.getElementById('passwd2').value != f.value){
	        			alert("La contraseña y la repetición de contraseña no coinciden.");
	        			document.getElementById('passwd2').focus();
		        		return false;	        			
	        		}		        	
		    }
		}
	//desactivarEnvio();
	callEnviarFormulario();	
}


function lanza_alert(f){
	var labels = f.form.getElementsByTagName('label');
	for (i=0; i<labels.length ;i++)
	{
		if (labels.item(i).attributes.getNamedItem('for').value== f.id)
			{
				if(labels.item(i).childNodes.item(0).nodeType==3)
						var cp = labels.item(i).childNodes.item(0).nodeValue.split(':'); break;
			}
	}
	var msg = eval("alerta."+f.id);
	if (msg== null) msg='';
	alert('Por favor, verífica que el campo "'+cp[0]+'" es correcto. ' + msg );
}

function cf_isEmailAddr(str) 
	{
		return str.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/);
	}

function cf_isNIF(str) 
	{
		return str.match(/^\d{8}[a-zA-Z]$/);
	}
function cf_isCIF(str) 
	{
		return str.match(/^[a-zA-Z]\d{8}$/);
	}  


/* Comprobación de NIF y CIF */

function compruebaNIF(){
//devuelve 3 casos:
//'-1' si el nif es erroneo
//una letra para sugerir la letra que corresponde
//el nif completo si es correcto

	//nif=document.formu.cif.value;
	nif=document.getElementById('cif').value;
	
	while (nif.substring(0,1)=='0')
		nif=nif.substring(1);
	
	for (i=0;i<nif.length-1;i++){
		if (nif.charAt(i)<'0' || nif.charAt(i)>'9')
			return '-1';
	}
	
	letra=nif.substring(nif.length-1, nif.length);
	
	if (letra>='0' && letra<='9'){
		numero=nif;
		letra='';
	}
	else
	if ((letra>='a' && letra<='z') || (letra>='A' && letra<='Z')){
		numero=nif.substring(0, nif.length - 1);
		letra=letra.toUpperCase();
	}
	else{
		return '-1';
	}
		
	if (numero.length<5 || numero.length>8)
		return '-1';
		
	if (letra==''){
		letra=tablaNIF[parseInt(numero, 10)%23];
		return letra;
	}
	else{
		if (letra==tablaNIF[parseInt(numero, 10)%23])
			{
				if (numero.length==7) numero = '0'+numero; //nif empieza por 0
				return numero+letra;	//nif correcto
			}
		else
			return tablaNIF[parseInt(numero, 10)%23];
	}
}	

function compruebaCIF()
{
	var cif = document.getElementById('cif').value;
	
	if (cif.length != 9){
		alert('Error en el CIF: menos de 9 dígitos');
		return false;
	}
		
	cif = cif.toUpperCase();
		
	var n0 = cif.charAt(0);
	var n1 = cif.charAt(1);
	if (n1<'0' || n1>'9')
	{
		alert('Error en el CIF: el dígito 1 del CIF no es un numero');
		return false;
	}
	
	var n2 = cif.charAt(2);
	if (n2<'0' || n2>'9')
	{
		alert('Error en el CIF: el dígito 2 del CIF no es un numero');
		return false;
	}
	
	var n3 = cif.charAt(3);
	if (n3<'0' || n3>'9')
	{
		alert('Error en el CIF: el dígito 3 del CIF no es un numero');
		return false;
	}
	
	var n4 = cif.charAt(4);
	if (n4<'0' || n4>'9')
	{
		alert('Error en el CIF: el dígito 4 del CIF no es un numero');
		return false;
	}
	
	var n5 = cif.charAt(5);
	if (n5<'0' || n5>'9')
	{
		alert('Error en el CIF: el dígito 5 del CIF no es un numero');
		return false;
	}
		
	var n6 = cif.charAt(6);
	if (n6<'0' || n6>'9')
	{
		alert('Error en el CIF: el dígito 6 del CIF no es un numero');
		return false;
	}
	
	var n7 = cif.charAt(7);
	if (n7<'0' || n7>'9')
	{
		alert('Error en el CIF: el dígito 7 del CIF no es un numero');
		return false;
	}
	
	var n8 = cif.charAt(8);
	
	var caso='desconocido';
	if (n0=='A'||n0=='B'||n0=='C'||n0=='D'||n0=='E'||n0=='F'||n0=='G'||n0=='H')
		caso='controlnumero';
	else
	if (n0=='P'||n0=='Q'||n0=='S'||n0=='K'||n0=='L'||n0=='M'||n0=='N')
		caso='controlletra';
		
	if (caso=='desconocido')
	{
		alert('Error en el CIF: primer dígito incorrecto');
		return false;
	}
	
	if (caso=='controlnumero' && (n8<'0'||n8>'9'))
	{
		alert('Error en el CIF: primer dígito o último incorrectos');
		return false;
	}
	
	if (caso=='controlletra' &&(n8<'A'||n8>'J'))
	{
		alert('Error en el CIF: primer dígito o último incorrectos');
		return false;
	}
		
	var sumapares=parseInt(n2, 10)+parseInt(n4, 10)+parseInt(n6, 10);
	
	var suma_n1=parseInt(n1, 10)*2;
	if (suma_n1>9)
		suma_n1=1+(suma_n1%10);
		
	var suma_n3=parseInt(n3, 10)*2;
	if (suma_n3>9)
		suma_n3=1+(suma_n3%10);
		
	var suma_n5=parseInt(n5, 10)*2;
	if (suma_n5>9)
		suma_n5=1+(suma_n5%10);
		
	var suma_n7=parseInt(n7, 10)*2;
	if (suma_n7>9)
		suma_n7=1+(suma_n7%10);

	var suma = sumapares + suma_n1 + suma_n3 + suma_n5 + suma_n7;
	var control = 10 - (suma % 10);
	control = (control==10 ? 0 : control);
		
	if (caso=='controlnumero')
	{
		if (control != parseInt(n8, 10))
		{
			alert('Error en el CIF: primer dígito o último incorrectos');
			return false;
		}
	}
	else
	if (caso='controlletra')
	{
		if ((control==1 && n8!='A')||(control==2 && n8!='B')||(control==3 && n8!='C')||
			(control==4 && n8!='D')||(control==5 && n8!='E')||(control==6 && n8!='F')||
			(control==7 && n8!='G')||(control==8 && n8!='H')||(control==9 && n8!='I')||
			(control==0 && n8!='J'))
		{
			alert('Error en el CIF: primer dígito o último incorrectos');
			return false;
		}
	}
	return true;	
}
function desactivarEnvio() {
	document.getElementById('imgEnviar').src="../images/btn_enviar_desac.gif";
	document.getElementById('linkEnviar').onclick = null;
}
function activarEnvio() {
	document.getElementById('imgEnviar').src="../images/btn_enviar.gif";
	document.getElementById('linkEnviar').onclick = envia;		
}
// Cambios realizados el 2008 06 04
function mostrarViaPortal() {
	// Deseleccionamos los otros radio buttons.
	document.getElementById('punto').checked = false;
	document.getElementById('manual').checked = false;	
	// Ponemos como etiqueta Vía: al primer input
	document.getElementById('direccionLabel').innerHTML = 'Vía:';
	// Activamos el portal
	document.getElementById('portal').disabled = false;
	document.getElementById('portal').value = '';	
	document.getElementById('portalDiv').disabled = false;	
	// Activamos el botón
	document.getElementById('botonBuscar').disabled = false;
	// Activamos la lista
	document.getElementById('selectResul').disabled = false;
	// Cambiamos el texto de la ayuda
	document.getElementById('ayudaDireccionDiv').innerHTML = 'Introduce los primeros caracteres del nombre de la vía sin incluir el tipo de vía (Calle, avenida, ...).<br/>A continuación pulsa el botón (>>) y selecciona la vía deseada dentro del listado de coincidencias.<br/>Para finalizar debes indicar tu número de portal.';	
	// Limpiamos el listado
	limpiarListado();		
	// Limpiamos la dirección
	limpiarDireccionDestino();	
}
function mostrarPuntoInteres() {
	// Deseleccionamos los otros radio buttons.
	document.getElementById('viaPortal').checked = false;
	document.getElementById('manual').checked = false;	
	// Ponemos como etiqueta Vía: al primer input
	document.getElementById('direccionLabel').innerHTML = 'Punto de interés:';
	// Desactivamos el portal
	document.getElementById('portal').disabled = true;
	document.getElementById('portal').value = '';	
	document.getElementById('portalDiv').disabled = true;	
	// Activamos el botón
	document.getElementById('botonBuscar').disabled = false;
	// Activamos la lista
	document.getElementById('selectResul').disabled = false;	
	// Cambiamos el texto de la ayuda
	document.getElementById('ayudaDireccionDiv').innerHTML = 'Introduce los primeros caracteres del nombre del punto de interés.<br/>A continuación pulsa sobre el botón (>>) y selecciona el punto de recogida que desees dentro del listado de coincidencias.';	
	// Limpiamos el listado
	limpiarListado();
	// Limpiamos la dirección
	limpiarDireccionDestino();							
}
function mostrarManual() {
	// Deseleccionamos los otros radio buttons.
	document.getElementById('punto').checked = false;
	document.getElementById('viaPortal').checked = false;	
	// Ponemos como etiqueta Vía: al primer input
	document.getElementById('direccionLabel').innerHTML = 'Dirección literal:';
	// Desactivamos el portal
	document.getElementById('portal').disabled = true;
	document.getElementById('portal').value = '';
	document.getElementById('portalDiv').disabled = true;	
	// Activamos el botón
	document.getElementById('botonBuscar').disabled = true;
	// Activamos la lista
	document.getElementById('selectResul').disabled = true;	
	// Cambiamos el texto de la ayuda
	document.getElementById('ayudaDireccionDiv').innerHTML = 'Introduce tu dirección de recogida lo más exacta posible.<br/><b>EJ</b>: Calle Asturias esquina Calle Galicia<br/>';
	// Limpiamos el listado
	limpiarListado();					
	// Limpiamos la dirección
	limpiarDireccionDestino();		
}
function cambioViaSelect() {
	var cadena = '<b>Dirección</b>: ' + document.getElementById('selectResul')[document.getElementById('selectResul').selectedIndex].text;
	if (document.getElementById('portal').disabled == false && document.getElementById('portal').value != '') {
		cadena += ' <b>Portal</b>: ' + document.getElementById('portal').value;
	}
	document.getElementById('dirActual').innerHTML = cadena;
}
function cambioPortalInput() {
	if (document.getElementById('selectResul').selectedIndex != -1) {
		cambioViaSelect();
	} else {
		document.getElementById('dirActual').innerHTML = '<b>Portal</b>: ' + document.getElementById('portal').value;
	}	
}
function buscarDireccion() {
	limpiarListado();
	// Si el radio está en puntos geográficos
	if (document.getElementById('punto').checked == true) {
		getBuscarPuntos();
	} else {
		getBuscarVias();
	}		
}
function limpiarListado() {
	var selectVia = document.getElementById('selectResul');
	selectVia.length = 0;	
}
function limpiarDireccionDestino() {
	document.getElementById('dirActual').innerHTML = "";
}
function getBuscarVias() {
	var obj = document.getElementById('direccion');
	var url = theURLBusquedas + "?method=listadoVias&viaParcial="+obj.value;
	httpBuscarVias.open("GET",url,true);
	httpBuscarVias.onreadystatechange = handleHttpBuscarVias;
	httpBuscarVias.send(null);
	url = null;
}
function getBuscarPuntos() {
	var obj = document.getElementById('direccion');
	var url = theURLBusquedas + "?method=listadoAlias&aliasParcial="+obj.value;
	httpBuscarPuntos.open("GET",url,true);
	httpBuscarPuntos.onreadystatechange = handleHttpBuscarAlias;
	httpBuscarPuntos.send(null);
	url = null;
}
function handleHttpBuscarVias() {
	if (httpBuscarVias.readyState == 4) {
		if (httpBuscarVias.status == 200) {
			var resul = httpBuscarVias.responseXML;
			if(resul.documentElement.nodeName!='vacio'){					
				var vias = resul.getElementsByTagName('via');		
				var selectVia = document.getElementById('selectResul');
				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 handleHttpBuscarAlias() {
	if (httpBuscarPuntos.readyState == 4) {
		if (httpBuscarPuntos.status == 200) {
			var resul = httpBuscarPuntos.responseXML;	
			if(resul.documentElement.nodeName!='vacio'){		
				var alias = resul.getElementsByTagName('alias');		
				var selectAlias = document.getElementById('selectResul');
				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;
		}
	}
}
// Fin de cambios realizados el 2008 06 04