/////////////////////////////////////////////////////////////////////////////////////////////////
//Funciones para la validación de datos dinamicos
/////////////////////////////////////////////////////////////////////////////////////////////////
var vlsUsuario=new Array();

function AmpliacionRegistro(campo, obligatorio, tipo, mensaje, validar) {
	this.campo=campo;
	this.tipo=tipo.toUpperCase();
	this.obligatorio=obligatorio;
	this.mensaje=mensaje;
	this.validar=validar;
}

function anyadirCampoRegistro(campo, tipo, obligatorio, mensaje, validar){
	if (vlsUsuario){
		vlsUsuario[campo]=new AmpliacionRegistro(campo, obligatorio, tipo, mensaje, validar);
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////
//Funciones para la validación de datos del formulario
/////////////////////////////////////////////////////////////////////////////////////////////////
function esDatoNoValido(nombre, valor){
	var error=false;
	var cObj, fObj;

	if (vlsUsuario[nombre]){
		cObj = vlsUsuario[nombre];
		if (cObj.obligatorio){
			 if (cObj.validar){
				error=eval("!" + cObj.validar + "('" + valor + "')");
			} else {
				 if (cObj.tipo=='TEXT' || cObj.tipo=='HIDDEN'){
					valor=Trim(valor);
					if(valor.length==0) {
						error=true;
					}
				} else if (cObj.tipo.length>4 && (cObj.tipo.substr(0,5)=="CHECK" || cObj.tipo.substr(0,5)=="RADIO")){
					fObj=document.getElementById(cObj.campo);
					if (!fObj.checked){
						error=true;
					}
				} else if (cObj.tipo.length>5 && cObj.tipo.substr(0,6)=="SELECT"){
					fObj=document.getElementById(cObj.campo);
					if (fObj.selectedIndex==0) {
						error=true;
					}
				}
			}
		}
	}

	return error;
}

function obtenerTextosCombos(){
	if (Elements.usu_codpais.selectedIndex>0){
		Elements.txt_pais.value=Elements.usu_codpais.options[Elements.usu_codpais.selectedIndex].text;
	}
	if (Elements.usu_codespecialidad.selectedIndex>0){
		Elements.txt_especialidad.value=Elements.usu_codespecialidad.options[Elements.usu_codespecialidad.selectedIndex].text;
	}
	if (Elements.usu_codprovestado && Elements.usu_codprovestado.selectedIndex>0){
		Elements.txt_provincia.value=Elements.usu_codprovestado.options[Elements.usu_codprovestado.selectedIndex].text;
	}

	if (Elements.usu_codpoblacion && Elements.usu_codpoblacion.selectedIndex>0 && Elements.txt_localidad){
		Elements.txt_localidad.value=Elements.usu_codpoblacion.options[Elements.usu_codpoblacion.selectedIndex].text;
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////
//Funciones para la carga de combos en el formulario de registro (especialidades, provincias, poblaciones)
/////////////////////////////////////////////////////////////////////////////////////////////////
function verEspecialidades(obj, box, esp){

	limpiarCombo(box);

	if (obj.value=="ME"){
		mostrarCapa('selespecialidad', 'block');
		cargarBox(box, 'op=esp&perfil=1');
		seleccionarCombo(box, esp);
	} else if (obj.value=="VE"){
		mostrarCapa('selespecialidad', 'block');
		cargarBox(box, 'op=esp&perfil=3');
		seleccionarCombo(box, esp);
	} else {
		mostrarCapa('selespecialidad', 'none');
	}

	actualizarSeleccionadoCSS(box);
}

function verProvincias(boxPais, boxProv, boxPob, prov){
	var pais=getSeleccionado(boxPais)

	limpiarCombo(boxProv);
	limpiarCombo(boxPob);

	if (pais != "0"){
		cargarBox(boxProv, 'op=prv&pais='+pais);

		if (document.getElementById(boxProv).options.length>1){
			seleccionarCombo(boxProv, prov);

			mostrarCapa('selprovincia', 'block');
			mostrarCapa('selpoblacion', 'block');
			mostrarCapa('selciudad', 'none');
			//posicionarCapa('restodatos', '0');

		} else {
			mostrarCapa('selprovincia', 'none');
			mostrarCapa('selpoblacion', 'none');
			mostrarCapa('selciudad', 'block');
			//posicionarCapa('selciudad', '-248');
			//posicionarCapa('restodatos', '-40');
		}
	} else {
		mostrarCapa('selprovincia', 'block');
		mostrarCapa('selpoblacion', 'block');
		mostrarCapa('selciudad', 'none');
		//posicionarCapa('restodatos', '0');
	}
	
	actualizarSeleccionadoCSS(boxProv);
	actualizarSeleccionadoCSS(boxPob);
}

function verPoblaciones(boxPais, boxProv, boxPob, ciudad){
	var pais=getSeleccionado(boxPais);
	var prov=getSeleccionado(boxProv);

	limpiarCombo(boxPob);
	document.getElementById('usu_ciudad').value="";

	if (pais != "0" && prov != "0"){
		cargarBox(boxPob, 'op=pob&pais='+pais+'&provincia='+prov);
		if (document.getElementById(boxPob).options.length>1){
			seleccionarCombo(boxPob, ciudad);

			mostrarCapa('selpoblacion', 'block');
			mostrarCapa('selciudad', 'none');
		} else {
			mostrarCapa('selpoblacion', 'none');
			mostrarCapa('selciudad', 'block');
			//posicionarCapa('selciudad', '-208');

			if (ciudad) document.getElementById('usu_ciudad').value=ciudad;
		}
	} else {
		if (pais != "0" && document.getElementById(boxProv).options.length==1){
			mostrarCapa('selpoblacion', 'none');
			mostrarCapa('selciudad', 'block');
			if (ciudad) document.getElementById('usu_ciudad').value=ciudad;
		} else {
			mostrarCapa('selpoblacion', 'block');
			mostrarCapa('selciudad', 'none');			
		}
	}
	actualizarSeleccionadoCSS(boxPob);
}

function actualizarCiudad(boxPais, boxProv, boxPob, prov, pob, ciudad){
	verProvincias(boxPais, boxProv, boxPob, prov);

	var dato=ciudad.replace(/#/g, "'"); 
	if (prov!="0" && pob!="0") {
		dato=pob;
	}
	verPoblaciones(boxPais, boxProv, boxPob, dato);
}


/////////////////////////////////////////////////////////////////////////////////////////////////
//Funciones para la utilización de AJAX
/////////////////////////////////////////////////////////////////////////////////////////////////
// Este fichero define las acciones necesarias sobre el objeto HTTPREQUEST para peticions "AJAX" a un servidor.
// Las variables siguientes definen estados y carcterísticas de las peticiones realizadas.

var listaBoxAjax;

function cargarBox(lista, params) {
    peticion = new peticionAJAX (
    {
        url: '/EsteveFront/RegistroServlet',
        lista: lista,
        parametros: params
    });
}

// Esta función inicia el proceso de petición creando el objeto httpRequest.
function peticionAJAX () {
  	var peticionHTTP;
  	var propiedades = arguments [0];

	if(window.XMLHttpRequest) {  // Navegadores que siguen los estándares
		peticionHTTP = new XMLHttpRequest();
	} else if(window.ActiveXObject) {  // Navegadores obsoletos
	  	peticionHTTP = new ActiveXObject("Microsoft.XMLHTTP");
	}

	peticionHTTP.open ("GET", propiedades.url + '?' + propiedades.parametros + '&random=' + Math.random (), false);
	//Si la funciona es asincrona se tendrá que poner esta linea.
	//peticionHTTP.onreadystatechange=recogerPeticionAJAX;
	peticionHTTP.setRequestHeader("Content-Type", "Application/XML; charset=ISO-8859-1");
	peticionHTTP.send(null);	
	recogerPeticionAJAX(peticionHTTP, propiedades.lista);
}

function recogerPeticionAJAX(peticionHTTP, box) {
	//Si es asincrono tenemos que controlar el estado de la peticion.
	//if(peticionHTTP.readyState==4){
		if(peticionHTTP.status==200 || peticionHTTP.status==0){
			//Obtenemos el resultado y recorremos el XML
			var nodes = peticionHTTP.responseXML.getElementsByTagName('option');

			//recorremos los nodos
			for(i=0;i<nodes.length;i++){
				clave = nodes[i].getElementsByTagName('clave')[0].firstChild.nodeValue;
				titulo = nodes[i].getElementsByTagName('titulo')[0].firstChild.nodeValue;
				creaOpcion(titulo, clave, box);
			}
		}
	//}
}

/////////////////////////////////////////////////////////////////////////////////////////////////
//Funciones de ayuda
/////////////////////////////////////////////////////////////////////////////////////////////////
function creaOpcion(txt, valor, box){
	var objSel = null;
	objSel = document.getElementById(box);
	if (objSel) {
		objSel.options[objSel.length]=new Option(txt, valor);
	}
}

function borrarSelect(box){
	var objSel = document.getElementById(box);
	if (objSel) {
		for(i=objSel.length;i>=0;i--){
			objSel[i] = null;
		}
	}
}

function actualizarCombo(box, params){
	//vaciamos el combo
	limpiarCombo(box);

	//cargamos las provincias del pais
	cargarBox(box, params);
}

function limpiarCombo(box){
	//borramos el combo
	borrarSelect(box);
	primeraOpcion(box);
}

function getSeleccionado(box){
	var obj, valor="";
	if (document.getElementById(box)) {
		obj = document.getElementById(box);
		valor = obj.options[obj.selectedIndex].value;
	}
	return valor;
}

function mostrarCapa(capa, estado){
	if (document.getElementById(capa)) document.getElementById(capa).style.display=estado;
}

function posicionarCapa(capa, c1){
	if (document.getElementById(capa)) document.getElementById(capa).style.top=c1+ "px";
}

function seleccionarCombo(box, clave){
	var objSel = document.getElementById(box);
	var fin=false;
	var k=0;

	if (clave) {
		while(!fin && objSel.length>k){
			if (objSel[k].value==clave){
				objSel.selectedIndex=k;
				fin=true;
			}
			k++;
		}
	}
}

function actualizarSeleccionadoCSS(box){
	var objSel = document.getElementById(box);
	if (document.getElementById("select" + box)){
		document.getElementById("select" + box).childNodes[0].nodeValue = objSel.options[objSel.selectedIndex].text;
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////
//Funciones registro ampliacion
/////////////////////////////////////////////////////////////////////////////////////////////////
function datosDinamicosInscripcion(){
	//limpiamos los campo hidden de la ampliacion
	vaciarCamposRegAmpliado();

	//obtenemos valores multiseleccion
	camposRegAmpliadoMultiseleccion();

	//validamos los campos de la ampliacion
	return validarCamposRegAmpliado();
}

function vaciarCamposRegAmpliado(){
	var cObj, clave;

	//limpiamos los campo hidden de la ampliacion
	if (vlsUsuario){
		for (clave in vlsUsuario){
			if (clave.length>5 && clave.substr(0,5)=="IXV##"){
				cObj=vlsUsuario[clave];
				if (cObj.tipo.toUpperCase()=="HIDDEN"){
					if (document.getElementById(clave)){
						document.getElementById(clave).value="";
					}
				}
			}
		}
	}
}

function camposRegAmpliadoMultiseleccion(){
	var i;
	var sNom="",sTipo="",sValor="";

	for (i=0;i<Elements.elements.length;i++){
		sNom=Elements.elements[i].name;
		sTipo=Elements.elements[i].type.toUpperCase();

		if (sNom.length>5 && sNom.substr(0,5)=="IXV##" && sTipo.length>4 && (sTipo.substr(0,5)=="CHECK" || sTipo.substr(0,5)=="RADIO")){
			if (Elements.elements[i].checked){
				sNom=sNom.substr(0,sNom.lastIndexOf('##'));
				if (document.getElementById(sNom)){
					sValor = document.getElementById(sNom).value;
					if (sValor.length>0){
						sValor+=',';
					}
					sValor+=Elements.elements[i].value;
					document.getElementById(sNom).value=sValor;
				}
			}
		}
	}
}

function validarCamposRegAmpliado(){
	var valido=true;
	var cObj, clave, valor="";

	for (clave in vlsUsuario){
		if (valido && clave.length>5 && clave.substr(0,5)=="IXV##"){
			cObj=vlsUsuario[clave];

			if (document.getElementById(clave)){
				valor=Trim(document.getElementById(clave).value);
			}

			if (cObj.obligatorio){
				if (cObj.validar){
					valido=eval(cObj.validar + "('" + valor + "')");
				} else {
					if (cObj.tipo.toUpperCase()=='TEXT' || cObj.tipo.toUpperCase()=="HIDDEN"){
						if(valor.length==0) {
							valido=false;
						}
					} else if (cObj.tipo.toUpperCase()=="SELECT"){
						if (document.getElementById(clave).selectedIndex==0) {
							valido=false;
						}
					}
				}
			}

			if(!valido){
				alert(cObj.mensaje);
			}
		}
	}

	return valido;
}


