//var peticion = null;
	

	//var servidor ="http://localhost:8080/RIER";
	var servidor ="http://www.rier.es";


	function mostrarA (mensaje) {
		alert(mensaje);
		return false;
		}

	function muestraPaises(peticion) {
		if (peticion.readyState == 4) {//Completado
			if (peticion.status == 200) {//Estado OK
				var lista = document.getElementById("pais");
				var listaProvincia = document.getElementById("provincia");
				var listaMunicipio = document.getElementById("municipio");
				var documento_xml = peticion.responseXML;
				var paises = documento_xml.getElementsByTagName("paises")[0];
				var losPaises = paises.getElementsByTagName("pais");

			//	listaProvincia.options[0] = new Option("Seleccione una provincia", -1);
			//	listaMunicipio.options[0] = new Option("Seleccione una localidad", -1);
				for(i=0; i < losPaises.length; i++) {
					var codigo =losPaises[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
					var nombre =losPaises[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
					lista.options[i+1] = new Option(nombre, codigo);
				}
			}

		}
	}
	
	function cargarListaPaises(){
		var peticion = inicializa_xhr();
		if(peticion) {
			peticion.open("GET", servidor + "/ajax.html?opcion=1&nocache="+Math.random(), true);
// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//			y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada
			peticion.onreadystatechange = function (){muestraPaises(peticion);};
			peticion.send(null);
		}
		document.getElementById("pais").onchange = cargaProvincias;
		document.getElementById("provincia").onchange = cargaMunicipios;
	}
	
	function cargaProvincias() {
		var lista = document.getElementById("pais");
		var pais = lista.options[lista.selectedIndex].value;
		if(!isNaN(pais)) {
			var peticion = inicializa_xhr();
			if (peticion) {
				peticion.onreadystatechange = function(){muestraProvincias(peticion);};
				peticion.open("POST", servidor + "/ajax.html?opcion=2&nocache=" + Math.random() ,true);
// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//				y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada
				peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				peticion.send("pais=" + encodeURIComponent(pais));
			}
			}
		}

	
	function muestraProvincias(peticion) {
		if (peticion.readyState == 4) {//Completado
			if (peticion.status == 200) {//Estado OK
				var lista = document.getElementById("provincia");
				var documento_xml = peticion.responseXML;
				var provincias = documento_xml.getElementsByTagName("provincias")[0];
				var lasProvincias = provincias.getElementsByTagName("provincia");

				//Borrar los elementos anteriores
				lista.options.length = 1;

				//lista.options[0] = new Option("Seleccione una provincia",-1);
				for(i=0; i < lasProvincias.length; i++) {
					var codigo = lasProvincias[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
					var nombre = lasProvincias[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
					lista.options[i+1] = new Option(nombre, codigo);
				}

				//Vaciamos los municipios
				var municipio = document.getElementById("municipio");
				municipio.options.length = 1;
			}
		}
	}

	function cargaMunicipios() {
		var lista = document.getElementById("provincia");
		var provincia = lista.options[lista.selectedIndex].value;
		if(!isNaN(provincia)) {
			var peticion = inicializa_xhr();
			if (peticion) {
				peticion.onreadystatechange = function(){muestraMunicipios(peticion);};
				peticion.open("POST", servidor + "/ajax.html?opcion=3&nocache=" + Math.random() ,true);
	// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//				y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada			
				peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				peticion.send("provincia=" + provincia);
			}
			}
		}

		function muestraMunicipios(peticion) {
			if (peticion.readyState == 4) {
				if (peticion.status == 200) {
					var lista = document.getElementById("municipio");
					var documento_xml = peticion.responseXML;
					var municipios = documento_xml.getElementsByTagName("municipios")[0];
					var losMunicipios = municipios.getElementsByTagName("municipio");
					// Borrar elementos anteriores
					lista.options.length = 1;
					// Se utiliza el método de crear elementos Option() y añadirlos a la lista
					
					for(i=0; i<losMunicipios.length; i++) {
						var codigo = losMunicipios[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
						var nombre = losMunicipios[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
						lista.options[i+1] = new Option(nombre, codigo);
					}
				}
			}
		}

		function inicializar(){
			var peticion = inicializa_xhr();
			if(peticion) {
				
				peticion.open("GET", servidor + "/ajax.html?opcion=1&nocache="+Math.random(), true);
//				peticion.onreadystatechange = muestraPaises;
// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//	y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada
				peticion.onreadystatechange = function(){muestraPaises(peticion);};
				peticion.send(null);
			}
			document.getElementById("pais").onchange = cargaProvincias;
			document.getElementById("provincia").onchange = cargaMunicipios;
		
	}
		
		//FUNCIONES PARA GARGAR PAISES SELECCIONANDO UNO CONCRETO PASADO SU ID
		
		function cargaPaisesId(pais){
			var peticion = inicializa_xhr();
			
			if(peticion) {
			
				peticion.open("GET", servidor + "/ajax.html?opcion=1&nocache="+Math.random(), true);
	// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//				y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada
				peticion.onreadystatechange = function (){muestraPaisesId(peticion,pais);};
				peticion.send(null);
			}
			document.getElementById("pais").onchange = cargaProvincias;
			document.getElementById("provincia").onchange = cargaMunicipios;
		}
		
		function muestraPaisesId(peticion, value) {
			if (peticion.readyState == 4) {//Completado
				if (peticion.status == 200) {//Estado OK
					var lista = document.getElementById("pais");
					var listaProvincia = document.getElementById("provincia");
					var listaMunicipio = document.getElementById("municipio");
					var documento_xml = peticion.responseXML;
					var paises = documento_xml.getElementsByTagName("paises")[0];
					var losPaises = paises.getElementsByTagName("pais");

//					listaProvincia.options[0] = new Option("Seleccione una provincia", -1);
//					listaMunicipio.options[0] = new Option("Seleccione una localidad", -1);
					for(i=0; i < losPaises.length; i++) {
						var codigo =losPaises[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
						var nombre =losPaises[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
						if (codigo == value)
							lista.options[i+1] = new Option(nombre, codigo, "","selected");
						else
							lista.options[i+1] = new Option(nombre, codigo);
					}
				}

			}
		}

		function cargaProvinciasId(idPais,idProvincia) {
			var pais = idPais;
			if(!isNaN(pais)) {
				var peticion = inicializa_xhr();
				if (peticion) {
					peticion.onreadystatechange = function(){muestraProvinciasId(peticion,idProvincia);};
					peticion.open("POST", servidor + "/ajax.html?opcion=2&nocache=" + Math.random() ,true);
	// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//					y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada
					peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
					peticion.send("pais=" + encodeURIComponent(pais));
				}
			}
		}

		function muestraProvinciasId(peticion, value) {
			if (peticion.readyState == 4) {//Completado
				if (peticion.status == 200) {//Estado OK
					var lista = document.getElementById("provincia");
					var documento_xml = peticion.responseXML;
					var provincias = documento_xml.getElementsByTagName("provincias")[0];
					var lasProvincias = provincias.getElementsByTagName("provincia");

					//Borrar los elementos anteriores
					lista.options.length = 1;

				//	lista.options[0] = new Option("Seleccione una provincia",-1);
					for(i=0; i < lasProvincias.length; i++) {
						var codigo = lasProvincias[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
						var nombre = lasProvincias[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
						if (codigo == value)
							lista.options[i+1] = new Option(nombre, codigo, "", "selected");
						else
							lista.options[i+1] = new Option(nombre, codigo);
					}

					//Vaciamos los municipios
	/*				var municipio = document.getElementById("municipio");
					municipio.options.length = 0;
					municipio.options[0] = new Option("Seleccione una localidad",-1);*/
				}
			}
		}

		function cargaMunicipiosId(idProvincia, idMunicipio) {
			var lista = document.getElementById("provincia");
			var provincia = idProvincia;
			if(!isNaN(provincia)) {
				var peticion = inicializa_xhr();
				if (peticion) {
					peticion.onreadystatechange = function(){muestraMunicipiosId(peticion, idMunicipio);};
					peticion.open("POST", servidor + "/ajax.html?opcion=3&nocache=" + Math.random() ,true);
		// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//					y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada			
					peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
					peticion.send("provincia=" + provincia);
				}
				}
			}

		function muestraMunicipiosId(peticion, value) {
			if (peticion.readyState == 4) {
				if (peticion.status == 200) {
					var lista = document.getElementById("municipio");
					var documento_xml = peticion.responseXML;
					var municipios = documento_xml.getElementsByTagName("municipios")[0];
					var losMunicipios = municipios.getElementsByTagName("municipio");
					// Borrar elementos anteriores
					lista.options.length = 1;
					// Se utiliza el método de crear elementos Option() y añadirlos a la lista
				
					for(i=0; i<losMunicipios.length; i++) {
						var codigo = losMunicipios[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
						var nombre = losMunicipios[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
						if (codigo == value)
							lista.options[i+1] = new Option(nombre, codigo, "", "selected");
						else
							lista.options[i+1] = new Option(nombre, codigo);
					}
				}
			}
		}
		
		
		function cargaPaisesIdIdioma(pais, provincia, municipio,comboIdioma){
			var peticion = inicializa_xhr();
			
			var miPais = document.getElementById('pais');
			var miProvincia = document.getElementById('provincia');
			var miMunicipio = document.getElementById('municipio');
			var idIdioma = comboIdioma.options[comboIdioma.selectedIndex].value;
			if(peticion){ 
				if ((miPais != null) && (miProvincia != null) && (miMunicipio != null)) {
					peticion.open("GET", servidor + "/ajax.html?opcion=1&idIdioma=" + idIdioma + "&nocache="+Math.random(), true);
		// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
		//			y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada
					peticion.onreadystatechange = function (){muestraPaisesId(peticion,miPais.options[miPais.selectedIndex].value);};
					peticion.send(null);
				}
			}
			document.getElementById("pais").onchange = cargaProvincias;
			document.getElementById("provincia").onchange = cargaMunicipios;
			document.selectedIndex = document.getElementById("pais").options[document.getElementById("pais").selectedIndex].value;
			/*cargaProvinciasIdIdioma (document.getElementById("pais").options[document.getElementById("pais").selectedIndex].value, idIdioma);
			cargaMunicipiosIdIdioma (document.getElementById("provincia").options[document.getElementById("provincia").selectedIndex].value, idIdioma);*/
		}

		function cargaProvinciasIdIdioma(idPais,idProvincia,idIdioma) {
			var pais = idPais;
			if(!isNaN(pais)) {
				var peticion = inicializa_xhr();
				if (peticion) {
					peticion.onreadystatechange = function(){muestraProvinciasId(peticion,idProvincia);};
					peticion.open("POST", servidor + "/ajax.html?opcion=2&nocache=" + Math.random() ,true);
	// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
	//					y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada
					peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
					peticion.send("pais=" + encodeURIComponent(pais) + "&idIdioma=" + idIdioma);
				}
				}
		}
		
		function cargaMunicipiosIdIdioma(idProvincia, idMunicipio, idIdioma) {
			var lista = document.getElementById("provincia");
			var provincia = idProvincia;
			if(!isNaN(provincia)) {
				var peticion = inicializa_xhr();
				if (peticion) {
					peticion.onreadystatechange = function(){muestraMunicipiosId(peticion, idMunicipio);};
					peticion.open("POST", servidor + "/ajax.html?opcion=3&nocache=" + Math.random() ,true);
		// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//					y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada			
					peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
					peticion.send("provincia=" + provincia + "&idIdioma=" + idIdioma);
				}
				}
			}
		

//FUNCIONES PARA CARGAR CATEGORÍAS
		
		function cargaCategoria(tipoContenido){
			var peticion = inicializa_xhr();
			if (peticion) {
				peticion.open ("GET", servidor + "/ajax.html?opcion=4&tipoContenido=" + tipoContenido +"&nocache="+Math.random(), true);
				peticion.onreadystatechange = function (){muestraCategorias(peticion);};
				peticion.send(null);
			}
		}
		
		function muestraCategorias(peticion) {
			if (peticion.readyState == 4) {//Completado
				if (peticion.status == 200) {//Estado OK
					var lista = document.getElementById("categoria");
					var documento_xml = peticion.responseXML;
					var categorias = documento_xml.getElementsByTagName("categorias")[0];
					var lasCategorias = categorias.getElementsByTagName("categoria");

					
					for(i=0; i < lasCategorias.length; i++) {
						var codigo =lasCategorias[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
						var nombre =lasCategorias[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
						lista.options[i+1] = new Option(nombre, codigo);
					}
				}

			}
		}
		
		function cargaCategoriaId(tipoContenido, idCategoria){
			
			var peticion = inicializa_xhr();
			if (peticion) {
				peticion.open ("GET", servidor + "/ajax.html?opcion=4&tipoContenido=" + tipoContenido +"&nocache="+Math.random(), true);
				peticion.onreadystatechange = function (){muestraCategoriasId(peticion, idCategoria);};
				peticion.send(null);
			}
		}
		
		
		function muestraCategoriasId(peticion, idCategoria) {
			if (peticion.readyState == 4) {//Completado
				if (peticion.status == 200) {//Estado OK
					var lista = document.getElementById("categoria");
					var documento_xml = peticion.responseXML;
					var categorias = documento_xml.getElementsByTagName("categorias")[0];
					var lasCategorias = categorias.getElementsByTagName("categoria");

					
					for(i=0; i < lasCategorias.length; i++) {
						var codigo =lasCategorias[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
						var nombre =lasCategorias[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
						if (codigo == idCategoria)
							lista.options[i+1] = new Option(nombre, codigo, "", "selected");
						else
							lista.options[i+1] = new Option(nombre, codigo);
					}
				}

			}
		}
		
		
		function cargaCategoriaPorIndex(tipoContenido, comboCategoria, comboIdioma){
			//Esta función recibe como parámetro 2 combo. De este tenemos que obtener el elemento seleccionado
			//y el idioma
			if(document.getElementById(comboCategoria)!= null)
			{
				var indiceSeleccionado=document.getElementById(comboCategoria).selectedIndex;
				if (comboIdioma!=null){
					cargaCategoriaIndex(tipoContenido, indiceSeleccionado, comboIdioma[comboIdioma.selectedIndex].value);
				}
			}
		}
		
		function cargaCategoriaIndex(tipoContenido, idASeleccionar, idIdioma){
			
			var peticion = inicializa_xhr();
			if (peticion) {
				peticion.open ("GET", servidor + "/ajax.html?opcion=5&tipoContenido=" + tipoContenido + "&idIdioma=" + idIdioma + "&nocache="+Math.random(), true);
				peticion.onreadystatechange = function (){muestraCategoriasIndex(peticion, tipoContenido, idASeleccionar);};
				peticion.send(null);
			}
		}
		
		function muestraCategoriasIndex(peticion, idCategoria, idASeleccionar) {
			if (peticion.readyState == 4) {//Completado
				if (peticion.status == 200) {//Estado OK
					var lista = document.getElementById("categoria");
					// Borrar elementos anteriores
					lista.options.length = 1; 
					var documento_xml = peticion.responseXML;
					var categorias = documento_xml.getElementsByTagName("categorias")[0];
					var lasCategorias = categorias.getElementsByTagName("categoria");

					
					for(i=0; i < lasCategorias.length; i++) {
						var codigo =lasCategorias[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
						var nombre =lasCategorias[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
						lista.options[i+1] = new Option(nombre, codigo);
					}
					lista.selectedIndex=idASeleccionar;
				}

			}
		}

		
//FUNCIONES DE GRUPOS Y USUARIOS
		
	function cargaGruposC(comboGrupos){
		var peticion = inicializa_xhr();
		
		if (peticion){
			peticion.open("GET", servidor + "/ajax.html?opcion=6&idIdioma=1&nocache="+Math.random(), true);
			peticion.onreadystatechange = function (){muestraGrupos(peticion, comboGrupos);};
			peticion.send(null);
			
		}
		if (document.getElementById("usuarios"))
			document.getElementById("grupo").onchange =cargaUsuarios;
			
	}
	
	function cargaGruposId(comboGrupos, idGrupo){
		var peticion = inicializa_xhr();
		if (peticion){
			peticion.open("GET", servidor + "/ajax.html?opcion=6&idIdioma=1&nocache="+Math.random(), true);
			peticion.onreadystatechange = function (){muestraGruposId(peticion, comboGrupos, idGrupo);};
			peticion.send(null);
			
		}
		
	}
	
	function muestraGrupos(peticion, comboGrupos){
		if (peticion.readyState == 4) {//Completado
			if (peticion.status == 200) {//Estado OK
				var lista = document.getElementById(comboGrupos);
				var documento_xml = peticion.responseXML;
				var gruposTipo = documento_xml.getElementsByTagName("gruposTipo")[0];
				var lasColecciones = gruposTipo.getElementsByTagName("coleccion");

				var grupoAnterior="";  
				var grupo;  
				var opcion;
				for(i=0; i < lasColecciones.length; i++) {
				  
					var tipoGrupo = lasColecciones[i].getElementsByTagName("tipoGrupo")[0].firstChild.nodeValue;
					if (grupoAnterior != tipoGrupo){
						grupo = document.createElement('OPTGROUP');
						grupo.label = tipoGrupo;
						grupoAnterior = tipoGrupo;
						lista.appendChild(grupo);
					}
					
					var losGrupos = lasColecciones[i].getElementsByTagName("grupos")[0].getElementsByTagName("grupo");
					for (k=0; k < losGrupos.length; k++ ){
					  var codigo =losGrupos[k].getElementsByTagName("codigo")[0].firstChild.nodeValue;
					  var nombre =losGrupos[k].getElementsByTagName("nombre")[0].firstChild.nodeValue;
					  
					  opcion = document.createElement('OPTION');
					  opcion.setAttribute("value",codigo);
					  opcion.setAttribute("title", nombre);
					  opcion.innerHTML = nombre;
					  lista.appendChild(opcion);
					}
				}
			}

		}
	}
	
	function muestraGruposId(peticion, comboGrupos, idGrupo){
		if (peticion.readyState == 4) {//Completado
			if (peticion.status == 200) {//Estado OK
				var lista = document.getElementById(comboGrupos);
				var documento_xml = peticion.responseXML;
				var gruposTipo = documento_xml.getElementsByTagName("gruposTipo")[0];
				var lasColecciones = gruposTipo.getElementsByTagName("coleccion");

				var grupoAnterior="";  
				var grupo;  
				var opcion;
				for(i=0; i < lasColecciones.length; i++) {
				  
					var tipoGrupo = lasColecciones[i].getElementsByTagName("tipoGrupo")[0].firstChild.nodeValue;
					if (grupoAnterior != tipoGrupo){
						grupo = document.createElement('OPTGROUP');
						grupo.label = tipoGrupo;
						grupoAnterior = tipoGrupo;
						lista.appendChild(grupo);
					}
					
					var losGrupos = lasColecciones[i].getElementsByTagName("grupos")[0].getElementsByTagName("grupo");
					for (k=0; k < losGrupos.length; k++ ){
					  var codigo =losGrupos[k].getElementsByTagName("codigo")[0].firstChild.nodeValue;
					  var nombre =losGrupos[k].getElementsByTagName("nombre")[0].firstChild.nodeValue;
					  
					  opcion = document.createElement('OPTION');
					  opcion.setAttribute("value",codigo);
					  opcion.setAttribute("title", nombre);
					  if (codigo == idGrupo){
						  opcion.setAttribute("selected", "selected");
						  //El siguiente código es para que se envíe un código de grupo al dar de alta un usuario por parte de un responsable de grupo 
						  //ya que el campo grupo en este caso está desactivado y no se envía en el formulario.
						  if (document.getElementById("grupoDestino") != null){
								document.getElementById("grupoDestino").value = codigo;
							}
					  }
					  opcion.innerHTML = nombre;
					  lista.appendChild(opcion);
					}
				}
			}
		}
	}
	
	
	function cargaUsuarios(){
		var lista = document.getElementById("grupo");
		var grupo = lista.options[lista.selectedIndex].value;
		if(!isNaN(grupo)) {
			var peticion = inicializa_xhr();
			if (peticion) {
				peticion.onreadystatechange = function(){muestraUsuarios(peticion);};
				peticion.open("POST", servidor + "/ajax.html?opcion=9&nocache=" + Math.random(), true);
// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//				y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada
				peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				peticion.send("grupo=" + encodeURIComponent(grupo));
			}
		}
		
		//Si estamos en una página en la que se tengan que mostrar los datos del usuario
		if ((document.getElementById("usuarios") != null) && ((document.getElementById("responsable")!= null) || (document.getElementById("nombre")!= null))){
			//cargaDatosUsuario();
			document.getElementById("usuarios").onchange = cargaDatosUsuario;
		}
		if (document.getElementById("grupoDestino") != null){
			document.getElementById("grupoDestino").selectedIndex = lista.selectedIndex;
		}
			
	}
	
	function cargaUsuariosGrupo(idGrupo){
		if(!isNaN(idGrupo)) {
			var peticion = inicializa_xhr();
			if (peticion) {
				peticion.onreadystatechange = function(){muestraUsuarios(peticion);};
				peticion.open("POST", servidor + "/ajax.html?opcion=9&nocache=" + Math.random(), true);
// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//				y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada
				peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				peticion.send("grupo=" + encodeURIComponent(idGrupo));
			}
		}
		
		if (document.getElementById("usuarios") != null){
			document.getElementById("usuarios").onchange = cargaDatosUsuario;
		}
			
	}

	function muestraUsuarios(peticion) {
		if (peticion.readyState == 4) {//Completado
			if (peticion.status == 200) {//Estado OK
				var lista = document.getElementById("usuarios");
				var documento_xml = peticion.responseXML;
				var usuarios = documento_xml.getElementsByTagName("usuarios")[0];
				var losUsuarios = usuarios.getElementsByTagName("usuario");
				lista.options.length = 0;
				
				for(i=0; i < losUsuarios.length; i++) {
					var codigo =losUsuarios[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
					var nombre =losUsuarios[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
					lista.options[i] = new Option(nombre, codigo);
				}
				
					lista.options.selectedIndex = 0;
				//Si estamos en una pantalla que muestre los datos del usuario
			if ((document.getElementById("responsable")!= null) ||(document.getElementById("nombre")!= null))
					cargaDatosUsuario();
				
			}
			
		}
	}
	
	function cargaDatosUsuario(){
			
		var lista = document.getElementById("usuarios");
		var idUsuario = 0;
		if (lista != null){
			idUsuario = lista.options[lista.selectedIndex].value;
			if (!isNaN(idUsuario)){
				var peticion = inicializa_xhr();
				if (peticion){
					peticion.open("POST", servidor + "/ajax.html?opcion=10&nocache=" + Math.random() ,true);
					peticion.onreadystatechange = function(){muestraDatosUsuario(peticion);};
					
					// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//					y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada
					peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
					peticion.send("idUsuario=" + encodeURIComponent(idUsuario));
				}
			}
		}
	}
	
	function cargaDatosUsuarioId(idUsuario){
		//Primero cargamos los perfiles disponibles y a continuación se rellenan los datos
			if (!isNaN(idUsuario)){
				var peticion = inicializa_xhr();
				if (peticion){
					
					peticion.open("POST", servidor + "/ajax.html?opcion=11&nocache=" + Math.random() , true);
					peticion.onreadystatechange = function(){muestraDatosUsuarioId(peticion);};
					
					// Para poder pasar la petición como parámetro, en vez de utilizar una variable peticion global 
//					y ".onreadystatechange = referencia a función" usamos una variable local y hacemos la siguiente llamada
					peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
					peticion.send("idUsuario=" + encodeURIComponent(idUsuario));
				}
			}
		
	}

	
	function muestraDatosUsuario(peticion) {
		
		if (peticion.readyState == 4) {//Completado
			if (peticion.status == 200) {//Estado OK
				var documento_xml = peticion.responseXML;
				var usuario = documento_xml.getElementsByTagName("usuario")[0];
	
				//Rellenamos los campos con los valores del usuario seleccionado
				
					if (document.getElementById("tratamiento")){
						var tratamiento = usuario.getElementsByTagName("tratamiento")[0].firstChild.nodeValue;
					var listaTratamiento = document.getElementById("tratamiento");
						listaTratamiento.options[0].selected = true;
					for (i=0; i < listaTratamiento.length; i++){
						var listaTratamientoValor = listaTratamiento.options[i].value;
						if (tratamiento == listaTratamientoValor)
							listaTratamiento.options[i].selected = true;
					}
				}
				if (document.getElementById("nombre")!= null)
					document.getElementById("nombre").value = usuario.getElementsByTagName("nombre")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("nombre")[0].firstChild.nodeValue:"";
				if (document.getElementById("primerApellido")!= null)
					document.getElementById("primerApellido").value = usuario.getElementsByTagName("apellido1")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("apellido1")[0].firstChild.nodeValue:"";
				if (document.getElementById("segundoApellido")!= null)
					document.getElementById("segundoApellido").value = usuario.getElementsByTagName("apellido2")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("apellido2")[0].firstChild.nodeValue:"";
				if (document.getElementById("usuario")!= null)
					document.getElementById("usuario").value = usuario.getElementsByTagName("login")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("login")[0].firstChild.nodeValue:"";
				if (document.getElementById("perfil")!= null){
					var perfil = usuario.getElementsByTagName("perfilesUsuario")[0];
					var losPerfiles = perfil.getElementsByTagName("perfilUsuario");
					var listaPerfiles = document.getElementById("perfil");
					deseleccionarList(listaPerfiles);
					for (i=0; i<losPerfiles.length; i++){
						var codigo =losPerfiles[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
						var j = 0;
						var enc = false;
						do{
						  if (listaPerfiles.options[j].value == codigo){
							listaPerfiles.options[j].selected = true;
							enc = true;
						  }
						  j++;
						}while ((j<listaPerfiles.length) && (!enc));
					}
				}
				if (document.getElementById("responsable")!= null){
					document.getElementById("responsable").checked = false;
					var respons = usuario.getElementsByTagName("responsable")[0].firstChild.nodeValue;
					if (respons == "true"){
						checkear("responsable");
						desactivarElemento("responsable");
						document.getElementById("responsable").title = "No se puede dejar un grupo sin grupo";
						if (document.getElementById("grupoDestino") != null){
							desactivarElemento("grupoDestino");
							//document.getElementById("grupoDestino").disabled = true;
							document.getElementById("grupoDestino").title = "No se puede modificar el destino del responsable de grupo";
						}
					}
					else{
						//Si lo que estamos haciendo es eliminar un ususario no dejamos modificar el checkbox de responsable
						if (document.getElementById("eliminar") != null)
							desactivarElemento("reponsable");
						else{
							activarDisabled("responsable");
							document.getElementById("responsable").title = "";
							if (document.getElementById("grupoDestino") != null){
								activarDisabled("grupoDestino");
								document.getElementById("grupoDestino").title = "";
							}
						}
					}
				}
				if (document.getElementById("email")!= null)
					document.getElementById("email").value = usuario.getElementsByTagName("email")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("email")[0].firstChild.nodeValue:"";
				if (document.getElementById("confirmarEmail")!= null)	
					document.getElementById("confirmarEmail").value = usuario.getElementsByTagName("email")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("email")[0].firstChild.nodeValue:"";
				if (document.getElementById("puesto")!= null)
					document.getElementById("puesto").value = usuario.getElementsByTagName("puesto")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("puesto")[0].firstChild.nodeValue:"";
				if (document.getElementById("telefono")!= null)
					document.getElementById("telefono").value = usuario.getElementsByTagName("telefono")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("telefono")[0].firstChild.nodeValue:"";
				if (document.getElementById("telefonoMovil")!= null)
					document.getElementById("telefonoMovil").value = usuario.getElementsByTagName("telefonoMovil")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("telefonoMovil")[0].firstChild.nodeValue:"";
				if (document.getElementById("fax")!= null)
					document.getElementById("fax").value = usuario.getElementsByTagName("fax")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("fax")[0].firstChild.nodeValue:"";
				if (document.getElementById("firma")!= null)
					document.getElementById("firma").value = usuario.getElementsByTagName("firma")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("firma")[0].firstChild.nodeValue:"";
			}
		}
	}
	
	function muestraDatosUsuarioId(peticion) {
		if (peticion.readyState == 4) {//Completado
			if (peticion.status == 200) {//Estado OK
				
				var documento_xml = peticion.responseXML;
				var lista = document.getElementById("perfil");
				var datosUsuario = documento_xml.getElementsByTagName("datosUsuario")[0];
				var perfilesNivel = datosUsuario.getElementsByTagName("perfiles")
				var losPerfilesPorNivel = perfilesNivel[0].getElementsByTagName("perfil");
				//Rellenamos los campos con los valores de los perfiles
				//Borrar los elementos anteriores
				lista.options.length = 0;
				for(i=0; i < losPerfilesPorNivel.length; i++) {
					var codigo =losPerfilesPorNivel[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
					var nombre =losPerfilesPorNivel[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
					lista.options[i] = new Option(nombre, codigo);
				}
				
				var usuario = datosUsuario.getElementsByTagName("usuario")[0];

				//Rellenamos los campos con los valores del usuario seleccionado
				
				var tratamiento = usuario.getElementsByTagName("tratamiento")[0].firstChild.nodeValue;
				var listaTratamiento = document.getElementById("tratamiento");
				listaTratamiento.options[0].selected = true;
				for (i=0; i < listaTratamiento.length; i++){
					var listaTratamientoValor = listaTratamiento.options[i].value;
					if (tratamiento == listaTratamientoValor)
						listaTratamiento.options[i].selected = true;
				}
				if (document.getElementById("nombre")!= null)
					document.getElementById("nombre").value = usuario.getElementsByTagName("nombre")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("nombre")[0].firstChild.nodeValue:"";
				if (document.getElementById("primerApellido")!= null)
					document.getElementById("primerApellido").value = usuario.getElementsByTagName("apellido1")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("apellido1")[0].firstChild.nodeValue:"";
				if (document.getElementById("segundoApellido")!= null)
					document.getElementById("segundoApellido").value = usuario.getElementsByTagName("apellido2")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("apellido2")[0].firstChild.nodeValue:"";
				if (document.getElementById("usuario")!= null)
					document.getElementById("usuario").value = usuario.getElementsByTagName("login")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("login")[0].firstChild.nodeValue:"";
				if (document.getElementById("perfil")!= null){
					var perfil = usuario.getElementsByTagName("perfilesUsuario")[0];
					var losPerfiles = perfil.getElementsByTagName("perfilUsuario");
					var listaPerfiles = document.getElementById("perfil");
					deseleccionarList(listaPerfiles);
					for (i=0; i<losPerfiles.length; i++){
						codigo =losPerfiles[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
						var j = 0;
						var enc = false;
						do{
						  if (listaPerfiles.options[j].value == codigo){
							listaPerfiles.options[j].selected = true;
							enc = true;
						  }
						  j++;
						}while ((j<listaPerfiles.length) && (!enc))
					}
				}
				if (document.getElementById("responsable")!= null){
					document.getElementById("responsable").checked = false;
					document.getElementById("responsable").checked = usuario.getElementsByTagName("responsable")[0].firstChild.nodeValue == "true"?true:false;
				}
				if (document.getElementById("email")!= null)
					document.getElementById("email").value = usuario.getElementsByTagName("email")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("email")[0].firstChild.nodeValue:"";
				if (document.getElementById("confirmarEmail")!= null)	
					document.getElementById("confirmarEmail").value = usuario.getElementsByTagName("email")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("email")[0].firstChild.nodeValue:"";
				if (document.getElementById("puesto")!= null)
					document.getElementById("puesto").value = usuario.getElementsByTagName("puesto")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("puesto")[0].firstChild.nodeValue:"";
				if (document.getElementById("telefono")!= null)
					document.getElementById("telefono").value = usuario.getElementsByTagName("telefono")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("telefono")[0].firstChild.nodeValue:"";
				if (document.getElementById("telefonoMovil")!= null)
					document.getElementById("telefonoMovil").value = usuario.getElementsByTagName("telefonoMovil")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("telefonoMovil")[0].firstChild.nodeValue:"";
				if (document.getElementById("fax")!= null)
					document.getElementById("fax").value = usuario.getElementsByTagName("fax")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("fax")[0].firstChild.nodeValue:"";
				if (document.getElementById("firma")!= null)
					document.getElementById("firma").value = usuario.getElementsByTagName("firma")[0].firstChild.nodeValue != "null"?usuario.getElementsByTagName("firma")[0].firstChild.nodeValue:"";
			}
		}
	}
	
	function deseleccionarList(lista){
		for (i=0; i<lista.length; i++)
			lista.options[i].selected = false;
	}
	
	/**/
	function cargaPerfiles(comboPerfiles){
		var peticion = inicializa_xhr();
		if (peticion){
			peticion.open("GET", servidor + "/ajax.html?opcion=7&nocache="+Math.random(), true);
			peticion.onreadystatechange = function (){muestraPerfiles(peticion, comboPerfiles);};
			peticion.send(null);
		}
	}
	
	function muestraPerfiles(peticion, comboPerfiles) {
		if (peticion.readyState == 4) {//Completado
			if (peticion.status == 200) {//Estado OK
				var lista = document.getElementById(comboPerfiles);
				var documento_xml = peticion.responseXML;
				var perfiles = documento_xml.getElementsByTagName("perfiles")[0];
				var losPerfiles = perfiles.getElementsByTagName("perfil");
				//Borrar los elementos anteriores
				lista.options.length = 0;
				for(i=0; i < losPerfiles.length; i++) {
					var codigo =losPerfiles[i].getElementsByTagName("codigo")[0].firstChild.nodeValue;
					var nombre =losPerfiles[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
					lista.options[i] = new Option(nombre, codigo);
				}
			}

		}
	}
	
	function compruebaDisponibilidad(peticion, login){
		if (peticion.readyState == 4) { //Completado
			if (peticion.status == 200) { //Estado OK
				var lista = login;
				
				var documento_xml = peticion.responseXML;
				var datosUsuarios = documento_xml.getElementsByTagName("datosUsuarios")[0];
				//var usuarios = documento_xml.getElementsByTagName("usuarios")[0];
				var usuarios = datosUsuarios.getElementsByTagName("usuarios")[0];
				if (usuarios != null){
					var losUsuarios = usuarios.getElementsByTagName("usuario");
					var usuarioConectado = documento_xml.getElementsByTagName("usuarioConectado")[0];
					var loginConectado = usuarioConectado.getElementsByTagName("loginConectado")[0].firstChild.nodeValue;
					
					var enc = false;
					var i=0;
					var nombre;
					//El login del usuario conectado sí tiene que acepatarse, de otra forma si se modificase el login no se podría volver a poner el original
					if (lista.value.toLowerCase() != loginConectado.toLowerCase()){
						while ((i<losUsuarios.length) && (!enc)){
							nombre = losUsuarios[i].getElementsByTagName("nombre")[0].firstChild.nodeValue;
							if (lista.value == nombre)
								enc = true;
							i++;
						}
					}
				}
				var divMensaje = login.id + "Error";
				var spanUsuario = login.id + "SpanError";
				if (enc){
					document.getElementById(spanUsuario).innerHTML = nombre + " ";
					document.getElementById(divMensaje).style.display="block";
					login.focus();
				}
				else{
					document.getElementById(spanUsuario).innerHTML="";
					document.getElementById(divMensaje).style.display="none";
				}
					
					
			}
		}
	}
	
	function comprobarDisponibilidad(login){
		var peticion = inicializa_xhr();
		var loginUsuario = login.value;
		if (peticion){
			peticion.open("GET", servidor + "/ajax.html?opcion=8&loginUsuario=" + loginUsuario + "&nocache="+Math.random(), true);
			peticion.onreadystatechange = function(){compruebaDisponibilidad(peticion, login);};
			peticion.send(null);
		}
	}
	
	
	function comprobarAnteriorContrasenya(contrasenya){
		var peticion = inicializa_xhr();
		var contrasenyaAnterior = contrasenya.value;
		if (peticion){
			peticion.open("POST", servidor + "/ajax.html?opcion=12&nocache="+Math.random(), true);
			peticion.onreadystatechange = function(){compruebaAnteriorContrasenya(peticion, contrasenya);};
			peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			peticion.send("pass=" + encodeURIComponent(contrasenyaAnterior));
		}
	}
	
	function compruebaAnteriorContrasenya(peticion, contrasenya){
		if (peticion.readyState == 4) { //Completado
			if (peticion.status == 200) { //Estado OK
				
				var documento_xml = peticion.responseXML;
				var passwords = documento_xml.getElementsByTagName("contrasenyas")[0];
				var losPasswords = passwords.getElementsByTagName("contrasenya");
				
				var enc = false;
				var i=0;
				var valor;
				while ((i<losPasswords.length) && (!enc)){
					valor = losPasswords[i].getElementsByTagName("valor")[0].firstChild.nodeValue;
					if (valor == "true")
						enc = true;
					i++;
				}
				var divMensaje = contrasenya.id + "Error";
				var spanPassword = contrasenya.id + "SpanError";
				if (!enc){
					
					document.getElementById(divMensaje).style.display="block";
					contrasenya.value="";
					contrasenya.focus();
				}
				else{
					document.getElementById(spanPassword).innerHTML="";
					document.getElementById(divMensaje).style.display="none";
				}
					
					
			}
		}
	}
	
	
	
	function inicializa_xhr() {
		if (window.XMLHttpRequest) {
			return new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			try{
				return new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (e){
				try {
					return new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (e){
					
				}
			}
				
			}
	}




