	/*
	 * Variables globales
	 */
	var map;
	var ruta;

	/*
	 * Funcion para iniciar elementos como el mapa.
	 */
	function menuGeneral() {
		document.getElementById("menu-opciones").innerHTML=
			"<ul>"
				+"<li class='primero'><label onclick='buscarRutas()'>Buscador de rutas</label></li>"
				+"<li><label onclick='enConstruccion();'>Zona Grupos</label></li>"
				+"<li><label onclick='enConstruccion();'>Foro</a></li>"
				+"<li><label onclick='enConstruccion();'>Miscelaneas</label></li>"
				+"<li><label onclick='enConstruccion();'>Ayuda</label></li>"
			+"</ul>";
	}

	/*
	 * Funcion para iniciar elementos como el mapa.
	 */
	function enConstruccion() {
	document.getElementById("central").innerHTML=
			"<div id='construccion'>"
			+"</div>";
	}



	/*
	 * Funcion para iniciar elementos como el mapa.
	 */
	function iniciarMapa(str) {
		if (GBrowserIsCompatible()){

			document.getElementById(str).innerHTML=
			"<div id='buscador-rutas'>"
				+"<div>"
					+"<div id='tusRutas-pestanas'>"
						+"<div class='tusRutas-pestana-select-dcha' id='pestana-0' onclick='pestanaActivada(0);'>mapa</div>"
						+"<div class='tusRutas-pestana-select-no' 	id='pestana-1' onclick='pestanaActivada(1);'>perfil</div>"
						+"<div class='tusRutas-pestana-select-no' 	id='pestana-2' onclick='pestanaActivada(2);'>datos</div>"
						+"<div class='tusRutas-pestana-select-no' 	id='pestana-3' onclick='pestanaActivada(3);'>descargar</div>"
					+"</div>"
					+"<div id='grafico-pestana-0' class='resultado-busquedas-grafico'></div>"
					+"<div id='grafico-pestana-1' class='resultado-busquedas-grafico'></div>"
					+"<div id='grafico-pestana-2' class='resultado-busquedas-grafico'></div>"
					+"<div id='grafico-pestana-3' class='resultado-busquedas-grafico'></div>"
				+"</div>"
			+"</div>";

			addMapaBusqueda();
			document.getElementById("grafico-pestana-1").innerHTML="<div id='grafico-pestana-1-resize' style='background: url(./imagenes/graficas/"+ruta+".png);'></div>";
			completarPestanaDatos(ruta,'2');
			document.getElementById("grafico-pestana-3").innerHTML="<div id='grafico-pestana-3-resize' style='background: url(./imagenes/enConstruccion2.gif);'></div>";
			pestanaActivada(0);
		}
	}

	/*
	 * Funcion para iniciar la pagina con una ruta aleatoria visualizandose
	 */
	function iniciarMapaRandom(str) {
		var xmlHttpReq = false;
		var self = this;

		if (window.XMLHttpRequest){ // Mozilla/Safari
		  self.xmlHttpReq = new XMLHttpRequest();
		}else if (window.ActiveXObject){ // IE
		  self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}

		var txt= "./phps/buscarRutaAleatoria.php";

		self.xmlHttpReq.open('GET',txt, true);
		self.xmlHttpReq.onreadystatechange = function() {
			if (self.xmlHttpReq.readyState == 4) {
				var n=self.xmlHttpReq.responseText.split("~~");
				ruta=n[0];
				iniciarMapa(str);
				mostrarRuta(ruta,true);
			}
		}
		self.xmlHttpReq.send(null);
	}

	/*
	 * Funcion para mostrar una de las rutas de la tabla de clasificaciones
	 */
	function mostrarRutaClasificaciones(str) {
		ruta=str;
		iniciarMapa("central");
		mostrarRuta(str,true);
	}

	/*
	 * Funcion para llamar al mapa de la pagina inicial sin pasarle parametros.
	 * Este mapa estará dentro del div CENTRAL
	 */
	function llamarMapa(){
		iniciarMapa("central");
	}

	/*
	 * Funcion que realiza la petición de una ruta al servidor y este devuelve la colección de puntos que la forman.
	 */
	function mostrarRuta(id,b){
		ruta=id;
		var xmlHttpReq = false;
		var self = this;

		if (window.XMLHttpRequest){ // Mozilla/Safari
		  self.xmlHttpReq = new XMLHttpRequest();
		}else if (window.ActiveXObject){ // IE
		  self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}

		var txt= "./phps/linestring.php?id="+id;

		self.xmlHttpReq.open('GET',txt, true);
		self.xmlHttpReq.onreadystatechange = function() {
			if (self.xmlHttpReq.readyState == 4) {
		    crearPolyline(self.xmlHttpReq.responseText,b);
			}
		}
		self.xmlHttpReq.send(null);
	}

	/*
	 * Funcion que recibe un String con los puntos que forman la ruta y crea una GPolyline para anadirla al mapa.
	 * El String de entrada contiene las X y las Y de cada punto separadas por un espacio y la separacion entre
	 * puntos se realiza mediante ",".
	 */
	function crearPolyline(str,b){
		if(b==true){
			iniciarMapa("central");
		}else{
			iniciarMapa("div-pestanas");

		}

		var posiciones = Array();
		var array_coma = Array();
		var array_espacio = Array();

		array_coma = str.split(',');

		for (pos in array_coma) {
			var s = array_coma[pos];
			as = s.split(' ');
			posiciones.push(new GLatLng(as[0],as[1]));		
		}

		var polylineEncoder = new PolylineEncoder();
		var polyline = polylineEncoder.dpEncodeToGPolyline(posiciones);

		//var polyline = new GPolyline(posiciones, "#ff0000", 2); //Creamos la polyline mediante el array de puntos
		map.addOverlay(polyline); //anadimos la polyline al mapa
		var bounds = polyline.getBounds();	
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	}

	/*
	 * Funcion que verifica el estado del usuario y carga el formulario o menu de acuerdo a su situacion.
	 * Para ell verificaremos los atributos de la 
	 */
	function formUsuario(){
		var usr=getCookie('usuario');
		if (usr!=null && usr!=""){
			formUsuarioRegistrado();
		}else{
			formUsuarioInicial();
		}
	}

	/*
	 * Funcion para modificar el contenido del div del usuario.
	 * En el cambiaremos los inputs de nombre y password por enlaces unicamente disponibles para usuarios registrados
	 * y logados en nuestra aplicaion.
	 */
	function formUsuarioRegistrado(){
		var nombre=getCookie('usuario').toUpperCase();
		document.getElementById("menu-usuario").innerHTML=
		"<div id=\"registrado\">"
			+"<label style=\"cursor: default\"class=\"titulo\">"+nombre+"</label>"
			+"<table id=\"tabla-usuario\">"
				+"<tr><td><label onclick=\"addRuta()\">A&ntilde;adir ruta</label></td></tr>"
				+"<tr><td><label onclick=\"tusRutas()\">Tus rutas</label></td></tr>"
				+"<tr><td><label onclick=\"evolucion()\">Evolucion</label></td></tr>"
				+"<tr><td><label onclick=\"verPerfil()\">Modificar perfil</label></td></tr>"
				+"<tr><td><label style=\"cursor: pointer\" onclick=\"eliminarCookie()\">Salir</label></td></tr>"
			+"</table>"
		+"</div>";
	}

	/*
	 * Funcion para volver al formulario inicial de usuario.
	 */
	function formUsuarioInicial(){
		document.getElementById("menu-usuario").innerHTML=		
		"<form name=\"formValidarUsuario\" id=\"formulario1\">"
			+"<table>"	
				+"<tr><td><label>Usuario:</label></td></tr>"
				+"<tr><td><input type=\"text\" name=\"nombre\" maxlength='30'/></td></tr>"
				+"<tr><td><label>Contrase&ntilde;a:</label></td></tr>"
				+"<tr><td><input type=\"password\" name=\"pass\" maxlength='20'/></td></tr>"
				+"<tr><td><input type=\"button\" class=\"boton\" value=\"Entrar\" onclick=\"validarUsuario()\"/></td></tr>"
				+"<tr><td><div><label name=\"error\" id=\"error\" class=\"error\">&nbsp;</label></div></td></tr>"
				+"<tr><td><label style=\"cursor: pointer;\" onclick=\"recordarPassword()\">Recordar contrase&ntilde;a</label></td></tr>"
				+"<tr><td><label style=\"cursor: pointer;\" onclick=\"registrar()\">Registrarse</label></td></tr>"
			+"</table>"
		+"</form>";
	}

	/*
	 * Funcion que verifica los campos usuario y contrasena del formulario de usuario y se realiza la validacion de 
	 * estos en la Base de Datos
	 */
	function validarUsuario(){
	
		var nom = document.formValidarUsuario.nombre.value;
		var pwd =  document.formValidarUsuario.pass.value;

		document.formValidarUsuario.nombre.style.backgroundColor="#FFFFFF";
		document.formValidarUsuario.pass.style.backgroundColor="#FFFFFF";

		if(nom.length==0){
			document.formValidarUsuario.nombre.style.backgroundColor="#CCFF00";
			document.getElementById("error").innerHTML="nombre vacio";
		}else if(pwd.length==0){
			document.getElementById("error").innerHTML="contrase&ntilde;a vac&iacute;a";
			document.formValidarUsuario.pass.style.backgroundColor="#CCFF00";
		}else if(!(validarInput(nom))){
			document.getElementById("error").innerHTML="s&oacute;lo alfanum&eacute;ricos y guiones";
			document.formValidarUsuario.nombre.style.backgroundColor="#CCFF00";
		}else if(!(validarInput(pwd))){
			document.getElementById("error").innerHTML="s&oacute;lo alfanum&eacute;ricos y guiones";
			document.formValidarUsuario.pass.style.backgroundColor="#CCFF00";
		}else{
	
			var xmlHttpReq = false;
			var self = this;

			if (window.XMLHttpRequest){ // Mozilla/Safari	
				self.xmlHttpReq = new XMLHttpRequest();
			}else if (window.ActiveXObject){ // IE	
				self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			}

			var txt= "./phps/verificarUsuario.php?nombre="+nom+"&pass="+pwd;		

			self.xmlHttpReq.open('GET',txt, true);
			self.xmlHttpReq.onreadystatechange = function() {
				if (self.xmlHttpReq.readyState == 4) {
					if(self.xmlHttpReq.responseText==-1){
						document.formValidarUsuario.nombre.style.backgroundColor="#CCFF00";
						document.getElementById("error").innerHTML="Usuario desconocido";
					}else if(self.xmlHttpReq.responseText==-2){
						document.formValidarUsuario.pass.style.backgroundColor="#CCFF00";
						document.getElementById("error").innerHTML="Contrasena incorrecta";
					}else if(self.xmlHttpReq.responseText==1){
						setCookie('usuario',nom,365);
						document.formValidarUsuario.nombre.style.backgroundColor="#FFFFFF";
						document.formValidarUsuario.pass.style.backgroundColor="#FFFFFF";
						formUsuarioRegistrado();
					}else{
						alert("ERROR: Ponte en contacto con el administrador");		 
					}   
				}
			}
			self.xmlHttpReq.send(null);
		}
	}

	/*
	 * Funcion que nos devuelve el nombre de usuario registrado y almacenado en la cookie
	 */
	function getCookie(c_name){
		if (document.cookie.length>0){
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1){ 
				c_start=c_start + c_name.length+1; 
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
					return unescape(document.cookie.substring(c_start,c_end));
			} 
		}
		return "";
	}

	/*
	 * Funcion para modificar los campos propios de la cookie
 	 */
	function setCookie(c_name,value,expiredays){
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
	}

	/*
	 * Funcion que nos elimina la cookie.
	 * Esta funcion es llamada en casos como el de salir en el menu de usuario
	 */
	function eliminarCookie() {
		setCookie('usuario',"","");
		var usr=getCookie('usuario');
		if (!(usr!=null && usr!="")){
			formUsuario();
		}
	}

	/*
	 * Funcion que crea el formulario para el recordatorio de la contrasena
	 */
	function recordarPassword(){
		document.getElementById("central").innerHTML=
			"<div id=\"form-recordar-password\">"
				+"<table>"
					+"<tr><td colspan=\"2\" align=\"center\"><label id=\"titulo2\">Recordar Contrase&ntilde;a</label></td></tr>"
					+"<tr><td colspan=\"2\" align=\"center\"><label>&nbsp;</label></td></tr>"
					+"<tr>"
						+"<td><label>Nombre: </label></td>"
						+"<td><input id=\"nombreRP\" maxlength='30'></input></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>e-mail: </label></td>"
						+"<td><input id=\"mailRP\" maxlength='200'></input></td>"
					+"</tr>"
				+"</table>"
				+"<div>"
					+"<table style='width:300px'>"
						+"<tr>"
							+"<td style='float:right'><label style='color:#CF0' class='error2' id='error3'>&nbsp;</label></td>"
						+"<tr>"
					+"</table>"
				+"</div>"
				+"<div style='width:220px;float:right'>"
					+"<table>"
						+"<tr>"
							+"<td><input style='width:60px' type=\"button\" class=\"boton\" value=\"Borrar\" onclick=\"recordarPassword()\"/></td>"
							+"<td><label>&nbsp;</label></td>"
							+"<td><input style='width:60px'type=\"button\" class=\"boton\" value=\"Enviar\" onclick=\"validarRecordarPassword()\"/></td>"
						+"</tr>"
					+"</table>"
				+"</div>"
			+"</div>";
	}

	/*
	 * Funcion que verifica los campos del formulario de recordarPassword
	 */
	function validarRecordarPassword(){

		var nom = document.getElementById("nombreRP").value;
		var mail =  document.getElementById("mailRP").value;
		
		document.getElementById("nombreRP").style.backgroundColor="#FFFFFF";
		document.getElementById("mailRP").style.backgroundColor="#FFFFFF";

		if(nom.length==0){
			document.getElementById("nombreRP").style.backgroundColor="#CCFF00";
			document.getElementById("error3").innerHTML="nombre vacio";
		}else if(mail.length==0){
			document.getElementById("error3").innerHTML="e-mail vacio";
			document.getElementById("mailRP").style.backgroundColor="#CCFF00";
		}else if(!(validarInput(nom))){
			document.getElementById("error3").innerHTML="s&oacute;lo caracteres alfanum&eacute;ricos y guiones";
			document.getElementById("nombreRP").style.backgroundColor="#CCFF00";
		}else if(validarMail(document.getElementById("form-login-mail").value)==-1){
			document.getElementById("error2").innerHTML="formato de e-mail incorrecto";
			document.getElementById("form-login-mail").style.backgroundColor="#CCFF00";
		}else{
			var xmlHttpReq = false;
			var self = this;

			if (window.XMLHttpRequest){ // Mozilla/Safari	
				self.xmlHttpReq = new XMLHttpRequest();
			}else if (window.ActiveXObject){ // IE	
				self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			}

			var txt= "./phps/recordarPassword.php?nombre="+nom+"&mail="+mail;		

			self.xmlHttpReq.open('GET',txt, true);
			self.xmlHttpReq.onreadystatechange = function() {
				if (self.xmlHttpReq.readyState == 4) {
					if(self.xmlHttpReq.responseText==-1){
						document.getElementById("nombreRP").style.backgroundColor="#CCFF00";
						document.getElementById("error3").innerHTML="No existe un usuario con este nombre";
					}else if(self.xmlHttpReq.responseText==-2){
						document.getElementById("mailRP").style.backgroundColor="#CCFF00";
						document.getElementById("error3").innerHTML="e-mail incorrecto";
					}else if(self.xmlHttpReq.responseText==1){
						document.getElementById("form-recordar-password").innerHTML=
						"<p style='padding:70px 0px'><label> Petici&oacute;n en proceso."
						+"En breves momentos recibir&aacute;s la contrase&ntilde;a"
						+" a la direcci&oacute;n de correo especificada.</label></p>";
					setTimeout(llamarMapa, 5000);
					}else{
						alert("ERROR: Ponte en contacto con el administrador");		 
					}   
				}
			}
			self.xmlHttpReq.send(null);
		}

	}

	/*
	 * Funcion correspondiente al formulario de registro del usuario
	 */
	function registrar(){
    document.getElementById("central").innerHTML=
		"<div id=\"form-login\">"
			+"<form method='post' action='./phps/subirImagen.php'enctype='multipart/form-data' id='formRegistrar' target='iframeUpload'/>"
				+"<table>"
					+"<tr><td colspan=\"4\" align=\"center\"><label id=\"titulo2\">Registro de Usuario</label></td></tr>"
					+"<tr><td colspan=\"4\" align=\"center\"><label>&nbsp;</label></td></tr>"
					+"<tr>"
						+"<td><label>Nombre: </label></td>"
						+"<td><input type='text' id=\"form-login-nombre\" maxlength='30'></input></td>"
						+"<td><label style=\"color:#CF0\">(*)</label></td>"
						+"<td rowspan=\"6\" style=\"border: 1px solid grey;\"><div id=\"imagen\"><label>imagen</label></div></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>Contrase&ntilde;a: </label></td>"
						+"<td><input id='form-login-pass' type='password' maxlength='20'></input></td>"
						+"<td><label style=\"color:#CF0\">(*)</label></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>Verificar contrase&ntilde;a: </label></td>"
						+"<td><input id='form-login-pass2' type='password' maxlength='20'></input></td>"
						+"<td><label style=\"color:#CF0\">(*)</label></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>e-mail: </label></td>"
						+"<td><input type='text' id='form-login-mail' maxlength='200'></input></td>"
						+"<td><label style=\"color:#CF0\">(*)</label></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>fecha de nacimiento: </label></td>"
						+"<td style='	width: 220px'>"
							+"<form action='#'>"
								//+"<select id='anos'><option>Ano</option></select>"
								+"<input type='text' id='anos' style='width:40px' maxlength='4'></input>"
								+"&nbsp;"
								+"<select id='meses'>"
									+"<option value=''>Mes</option>"
									+"<option value='1'>Enero</option>"
									+"<option value='2'>Febrero</option>"
									+"<option value='3'>Marzo</option>"
									+"<option value='4'>Abril</option>"
									+"<option value='5'>Mayo</option>"
									+"<option value='6'>Junio</option>"
									+"<option value='7'>Julio</option>"
									+"<option value='8'>Agosto</option>"
									+"<option value='9'>Septiembre</option>"
									+"<option value='10'>Octubre</option>"
									+"<option value='11'>Noviembre</option>"
									+"<option value='12'>Diciembre</option>"
								+"</select>"
								+"&nbsp;"
								+"<select id='dias'>"
									+"<option>Dia</option>"
								+"</select>"
							+"</form>"
						+"</td>"
						+"</tr>"
					+"<tr>"
						+"<td><label>imagen: </label></td>"
						+"<td><input type='file' id='form-login-img' name='uploadfile' onchange='submit()'></input></td>"
						+"<input type='hidden' id='nombre-aleatorio-img'/>"
					+"</tr>"
					+"<iframe id='iframeUpload' name='iframeUpload' style='display:none'></iframe>"
				+"</table>"
			+"</form>"
			+"<div>"
				+"<table style='width:500px'>"
					+"<tr>"
						+"<td style='float:left'><label class='error2'>(*) Campo obligatorio</label></td>"
						+"<td style='float:right'><label class='error2' id='error2'></label></td>"
					+"<tr>"
				+"</table>"
			+"</div>"
			+"<div style='float:right'>"
				+"<input style='width:60px' type=\"button\" class=\"boton\" value=\"Borrar\" onclick=\"registrar()\"/>"
				+"<label>&nbsp;</label>"
				+"<td><input style='width:60px'type=\"button\" class=\"boton\" value=\"Enviar\" onclick=\"addUsuarioBBDD()\"/>"
			+"</div>"
			+"<div id='grafico-pestana-3-resize'></div>"
		+"</div>";
		//document.getElementById("anos").onclick=mostrarYear;
		document.getElementById("meses").selectedIndex = 0;
		document.getElementById("meses").onchange = diasMes;
	}

	/*
	 *	Esta funcion esta creada para previsualizar la imagen que el usuario haya anadido a su perfil.
	 * 	Dado que con JavaScript no se pueden mostrar imagenes que esten en un directorio local del usuario, sera
	 *  necesario utilizar un formulario y enviar los resultados de este a un iFrame.
	 */
	function previsualizarFoto(nom){
		//alert(nom);
		document.getElementById("imagen").innerHTML="";
		document.getElementById("imagen").style.background="url(./imagenes/imgsUsuario/temp/"+nom+".jpg)";
		document.getElementById("nombre-aleatorio-img").value=nom;
		
		//document.getElementById("imagen").innerHTML="<div style='background: url(./imagenes/graficas/"+nom+".jpg); background-repeat:no-repeat;'></div>";
	}

	/*
	 * Funcion que verifica los campos usuario y contrasena del formulario de usuario y se realiza la validacion de 
	 * estos en la Base de Datos
	 */
	function addUsuarioBBDD(){
		var nom = document.getElementById("form-login-nombre").value;
		var pwd =  document.getElementById("form-login-pass").value;
		var pwd2 =  document.getElementById("form-login-pass2").value;
		var mail =  document.getElementById("form-login-mail").value;
		
		document.getElementById("form-login-nombre").style.backgroundColor="#FFFFFF";
		document.getElementById("form-login-pass").style.backgroundColor="#FFFFFF";
		document.getElementById("form-login-pass2").style.backgroundColor="#FFFFFF";
		document.getElementById("form-login-mail").style.backgroundColor="#FFFFFF";

		if(nom.length==0){
			document.getElementById("form-login-nombre").style.backgroundColor="#CCFF00";
			document.getElementById("error2").innerHTML="nombre vacio";
		}else if(!(validarInput(document.getElementById("form-login-nombre").value))){
			document.getElementById("error2").innerHTML="s&oacute;lo caracteres alfanum&eacute;ricos y guiones";
			document.getElementById("form-login-nombre").style.backgroundColor="#CCFF00";
		}else if(pwd.length==0){
			document.getElementById("error2").innerHTML="contraseña vacia";
			document.getElementById("form-login-pass").style.backgroundColor="#CCFF00";
		}else if(!(validarInput(pwd))){
			document.getElementById("error2").innerHTML="s&oacute;lo caracteres alfanum&eacute;ricos y guiones";
			document.getElementById("form-login-pass").style.backgroundColor="#CCFF00";
		}else	if(pwd2.length==0){
			document.getElementById("form-login-pass2").style.backgroundColor="#CCFF00";
			document.getElementById("error2").innerHTML="validaci&oacute;n de contraseña vacio";
		}else if(!(validarInput(pwd2))){
			document.getElementById("error2").innerHTML="s&oacute;lo caracteres alfanum&eacute;ricos y guiones";
			document.getElementById("form-login-pass2").style.backgroundColor="#CCFF00";
		}else if(mail.length==0||validarMail(document.getElementById("form-login-mail").value)==-1){
			document.getElementById("error2").innerHTML="e-mail incorrecto";
			document.getElementById("form-login-mail").style.backgroundColor="#CCFF00";
		}else if(validarPassword(pwd,pwd2)==-1){
			document.getElementById("error2").innerHTML="Contraseñas distintas";
			document.getElementById("form-login-pass2").style.backgroundColor="#CCFF00";
			document.getElementById("form-login-pass").style.backgroundColor="#CCFF00";
			document.getElementById("form-login-pass2").value="";
			document.getElementById("form-login-pass").value="";
		}else{
			var xmlHttpReq = false;
			var self = this;

			if (window.XMLHttpRequest){ // Mozilla/Safari	
				self.xmlHttpReq = new XMLHttpRequest();
			}else if (window.ActiveXObject){ // IE	
				self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
			}

			var img =  document.getElementById("nombre-aleatorio-img").value;

			var fecha =  document.getElementById("anos").value+"-"+document.getElementById("meses").value+"-"+document.getElementById("dias").value;

			var txt= "./phps/crearUsuario.php?nombre="+nom+"&mail="+mail+"&img="+img+"&pass="+pwd+"&fecha="+fecha;		
			//alert(txt);
			self.xmlHttpReq.open('GET',txt, true);
			self.xmlHttpReq.onreadystatechange = function() {
				if (self.xmlHttpReq.readyState == 4) {
					if(self.xmlHttpReq.responseText==-1){
						document.getElementById("form-login-nombre").style.backgroundColor="#CCFF00";
						document.getElementById("error2").innerHTML="Nombre de usuario no disponible";
					}else if(self.xmlHttpReq.responseText==-2){
						document.getElementById("form-login-pass2").style.backgroundColor="#CCFF00";
						document.getElementById("form-login-pass").style.backgroundColor="#CCFF00";
						document.getElementById("error2").innerHTML="Formato de contrasena incorrecto";
					}else if(self.xmlHttpReq.responseText==-3){
						document.getElementById("error2").style.backgroundColor="#CCFF00";
						document.getElementById("error2").innerHTML="Fecha futura";
					}else if(self.xmlHttpReq.responseText==1){
						setCookie('usuario',nom,365);
						document.formValidarUsuario.nombre.style.backgroundColor="#FFFFFF";
						document.formValidarUsuario.pass.style.backgroundColor="#FFFFFF";
						formUsuarioRegistrado();
						
						if(img.length>0){	//Comprobamos que el usuario haya anadido una imagen a su perfil
							//Volvemos a crear un objeto XMLHTTP
							var xmlHttpReq2 = false;
							var self2 = this;

							if (window.XMLHttpRequest){ // Mozilla/Safari	
								self2.xmlHttpReq = new XMLHttpRequest();
							}else if (window.ActiveXObject){ // IE	
								self2.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
							}

							var txt2= "./phps/moverFichero.php?nom="+nom+"&img="+img;		

							self2.xmlHttpReq.open('GET',txt2, true);
							self2.xmlHttpReq.onreadystatechange = function() {
								if (self2.xmlHttpReq.readyState == 4) {
									if (self2.xmlHttpReq.readyState == 4) {
										if(self2.xmlHttpReq.responseText.length>0){
											document.getElementById("error2").innerHTML="Error al modificar la imagen";	
										}else{
											iniciarMapaRandom("central");
										}
									}
								}
							}
							self2.xmlHttpReq.send(null);
						}else{
							iniciarMapaRandom("central");						
						}
					}else{
						alert("ERROR: Ponte en contacto con el administrador");		 
					}   
				}
			}
			self.xmlHttpReq.send(null);
		}
	}

	/*
	 * Funcion que se encarga de rellenarnos el formulario con el numero de dias correspondientes de cada mes.
	 */
	function diasMes(){
		var dias = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
		var str_meses = this.options[this.selectedIndex].value;

		if(str_meses != ""){
			var mes = parseInt(str_meses);
			document.getElementById("dias").options.length=0;
			for(var i=0; i<dias[mes-1];i++){
				document.getElementById("dias").options[i] = new Option(i+1);
			}
		}
	}

	/*
	 * Funcion que se encarga de rellenarnos los anos del formulario.
	 */
	function mostrarYear(){
		var fecha = new Date();
		var actual = fecha.getFullYear();		
		for(var i=1900, j=0; i<actual;i++,j++){
			document.getElementById("anos").options[j] = new Option(i);
		}
	}

	/*
	 * Funcion que nos muestra un formulario con los atributos del usuario y le permite modificarlos
	 */
	function verPerfil(){
		document.getElementById("central").innerHTML=
		"<div id=\"form-ver-perfil\">"
			+"<form method='post' action='./phps/subirImagen.php'enctype='multipart/form-data' id='formRegistrar' target='iframeUpload'/>"
				+"<table>"
					+"<tr><td colspan=\"4\" align=\"center\"><label id=\"titulo2\">Modificar Perfil</label></td></tr>"
					+"<tr><td colspan=\"4\" align=\"center\"><label>&nbsp;</label></td></tr>"
					+"<tr>"
						+"<td><label>Contrase&ntilde;a anterior: </label></td>"
						+"<td><input id='pwd_ant' type='password' maxlength='20'></input></td>"
						+"<td><label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label></td>"
						+"<td rowspan=\"5\" style=\"border: 1px solid grey;\";><div id=\"imagen\"><label>imagen</label></div></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>Contrase&ntilde;a nueva: </label></td>"
						+"<td><input id='pwd1' type='password' maxlength='20'></input></td>"
						+"<td><label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>Repetir contrase&ntilde;a: </label></td>"
						+"<td><input id='pwd2' type='password' maxlength='20'></input></td>"
						+"<td><label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>e-mail: </label></td>"
						+"<td><input id='e-mail-perfil' maxlength='200'></input></td>"
						+"<td><label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>imagen: </label></td>"
						+"<td><input type='file' id='form-login-img' name='uploadfile' onchange='submit()'></input></td>"
						+"<input type='hidden' id='nombre-aleatorio-img'/>"
					+"</tr>"
					+"<tr>"
						+"<td><label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label></td>"
					+"</tr>"
					+"<input type='hidden' id='nombre-aleatorio-img'/>"
				+"</table>"
					+"<iframe id='iframeUpload' name='iframeUpload' style='display:none'></iframe>"
			+"</form>"
			+"<div style='float:right'>"
				+"<td colspan=\"2\"><label class='error2' id='error' style='color:#CF0'>&nbsp;</label></td>"
			+"</div>"
			+"<div style='float:left'>"
				+"<input style='width:60px' type='button' class='boton' value='Borrar' onclick='verPerfil()'/>"
				+"<label>&nbsp;</label>"
				+"<td><input style='width:60px'type='button' class='boton' value='Enviar' onclick='modificarPerfil()'/>"
			+"</div>"
		+"</div>";

		rellenarPerfil();
	}

	/*
	 * Funcion que nos rellena los campos del formulario de ver perfil y nos permitira almacenar los cambios
	 */
	function rellenarPerfil(){
		var xmlHttpReq = false;
		var self = this;

		if (window.XMLHttpRequest){ // Mozilla/Safari	
			self.xmlHttpReq = new XMLHttpRequest();
		}else if (window.ActiveXObject){ // IE	
			self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}

		var txt= "./phps/rellenarPerfil.php?nom="+getCookie('usuario');	

		self.xmlHttpReq.open('GET',txt, true);
		self.xmlHttpReq.onreadystatechange = function() {
			if (self.xmlHttpReq.readyState == 4) {
				var resp= self.xmlHttpReq.responseText;
				var names_split=resp.split("~~");
				document.getElementById("imagen").innerHTML="";
				document.getElementById("imagen").style.background="url(./imagenes/imgsUsuario/"+names_split[0]+".jpg)";
				document.getElementById("e-mail-perfil").value=names_split[1];
			}
		}	
		self.xmlHttpReq.send(null);
	}


	/*
	 * Funcion que verifica los campos usuario y contrasena del formulario de usuario y se realiza la validacion de 
	 * estos en la Base de Datos
	 */
	function modificarPerfil(){
		var pwd_ant = document.getElementById("pwd_ant").value;
		var pwd1 =  document.getElementById("pwd1").value;
		var pwd2 =  document.getElementById("pwd2").value;
		var mail =  document.getElementById("e-mail-perfil").value;
		document.getElementById("error").innerHTML="";
		var b=0;
		document.getElementById("pwd_ant").style.backgroundColor="#FFFFFF";
		document.getElementById("pwd1").style.backgroundColor="#FFFFFF";
		document.getElementById("pwd2").style.backgroundColor="#FFFFFF";
		document.getElementById("e-mail-perfil").style.backgroundColor="#FFFFFF";

		//alert(document.getElementById("nombre-aleatorio-img").value);

		if(pwd_ant.length>0){
			if(!(validarInput(pwd_ant))){
				document.getElementById("error").innerHTML="s&oacute;lo alfanum&eacute;ricos y guiones";
				document.getElementById("pwd_ant").style.backgroundColor="#CCFF00";
				document.getElementById("pwd_ant").value="";
			}else if(pwd1.length==0){
				document.getElementById("error").innerHTML="Falta la contrase&ntilde;a nueva";
				document.getElementById("pwd1").style.backgroundColor="#CCFF00";
				document.getElementById("pwd1").value="";
			}else if(!(validarInput(pwd1))){
				document.getElementById("error").innerHTML="s&oacute;lo alfanum&eacute;ricos y guiones";
				document.getElementById("pwd1").style.backgroundColor="#CCFF00";
				document.getElementById("pwd1").value="";
			}else if(!(validarInput(pwd2))){
				document.getElementById("error").innerHTML="s&oacute;lo alfanum&eacute;ricos y guiones";
				document.getElementById("pwd2").style.backgroundColor="#CCFF00";
				document.getElementById("pwd2").value="";
			}else if(pwd1.length==0 && pwd2.length==0){
				document.getElementById("error").innerHTML="Faltan las nuevas contrase&ntilde;as";
				document.getElementById("pwd1").style.backgroundColor="#CCFF00";
				document.getElementById("pwd2").style.backgroundColor="#CCFF00";
				document.getElementById("pwd1").value="";
				document.getElementById("pwd2").value="";
			}else if(pwd2.length==0){
				document.getElementById("error").innerHTML="Falta repetir la contrase&ntilde;a";
				document.getElementById("pwd2").style.backgroundColor="#CCFF00";
				document.getElementById("pwd2").value="";
			}else if(validarPassword(pwd1,pwd2)==-1){
				//las dos nuevas contrasenas son diferentes
				document.getElementById("error").innerHTML="Contrasenas distintas";
				document.getElementById("pwd1").style.backgroundColor="#CCFF00";
				document.getElementById("pwd2").style.backgroundColor="#CCFF00";
				document.getElementById("pwd1").value="";
				document.getElementById("pwd2").value="";
			}else{
				b=1;
			}
		}else if(pwd_ant.length==0 && (pwd1.length>0 || pwd2.length>0)){
			document.getElementById("error").innerHTML="Falta la contrase&ntilde;a anterior";
			document.getElementById("pwd_ant").style.backgroundColor="#CCFF00";
			document.getElementById("pwd_ant").value="";
		}else{
			//En este caso todas las contrasenas estan vacías.
			b=1;
		}

		if(b==1){
			//verificamos el mail y posteriormente podemos hacer la llamada al php para que nos modifique el perfil de usuario
			if(validarMail(mail)==1){
				var xmlHttpReq = false;
				var self = this;

				if (window.XMLHttpRequest){ // Mozilla/Safari	
					self.xmlHttpReq = new XMLHttpRequest();
				}else if (window.ActiveXObject){ // IE	
					self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
				}

				var img =  document.getElementById("nombre-aleatorio-img").value;
				var txt= "./phps/modificarPerfil.php?nom="+getCookie('usuario')+"&mail="+mail+"&img="+img+"&pwd_ant="+pwd_ant+"&pwd1="+pwd1+"&pwd2="+pwd2;		

				self.xmlHttpReq.open('GET',txt, true);
				self.xmlHttpReq.onreadystatechange = function() {
					if (self.xmlHttpReq.readyState == 4) {
						if(self.xmlHttpReq.responseText==1){
							//En este caso la modificacion de los atributos del usuario se ha realizado correctamente.
							//Ahora vamos a comprobar que haya que modificar la imagen tambien.
							if(img.length	>0){
								//Volvemos a crear un objeto XMLHTTP
								var xmlHttpReq2 = false;
								var self2 = this;

								if (window.XMLHttpRequest){ // Mozilla/Safari	
									self2.xmlHttpReq = new XMLHttpRequest();
								}else if (window.ActiveXObject){ // IE	
									self2.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
								}

								var txt2= "./phps/moverFichero.php?nom="+getCookie('usuario')+"&img="+img;		

								self2.xmlHttpReq.open('GET',txt2, true);
								self2.xmlHttpReq.onreadystatechange = function() {
									if (self2.xmlHttpReq.readyState == 4) {
										if(self2.xmlHttpReq.responseText.length>0){
											document.getElementById("error").innerHTML="Error al modificar la imagen";	
										}else{
											iniciarMapaRandom("central");
										}
									}
								}
								self2.xmlHttpReq.send(null);
							}else{
								//En este caso no hay que modificar la imagen y las posibles modificaciones de los atributos de usuario se han realizado correctamente
								iniciarMapaRandom("central");
							}
						}else if(self.xmlHttpReq.responseText==-1){
							document.getElementById("error").innerHTML="No existe ningun usuario con ese nombre";		 
						}else if(self.xmlHttpReq.responseText==-2){
							document.getElementById("error").innerHTML="Contrasena anterior incorrecta";
							document.getElementById("pwd_ant").style.backgroundColor="#CCFF00";
							document.getElementById("pwd_ant").value="";
						}else if(self.xmlHttpReq.responseText==-3){
							document.getElementById("error").innerHTML="Formato de contrasena actual incorrecto";
							document.getElementById("pwd1").style.backgroundColor="#CCFF00";
							document.getElementById("pwd1").value="";
							document.getElementById("pwd2").style.backgroundColor="#CCFF00";
							document.getElementById("pwd2").value="";
						}else{
							alert("ERROR: Ponte en contacto con el administrador.");		 
						}
					}
				}
				self.xmlHttpReq.send(null);
			}else{
				document.getElementById("error").innerHTML="e-mail incorrecto";
				document.getElementById("e-mail-perfil").style.backgroundColor="#CCFF00";
			}
		}
	}

	/*
	 * Funcion que comprueba que las dos contrasenas sean iguales
	 */
	function validarPassword(cont1,cont2){
		if(cont1==cont2){
			return 1;
		}else{
			return -1;
		}
	}

	/*
	 * Funcion para validar la direccion de e-mail
	 */
	function validarMail(str){
		var s = str;
		var filter=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
		if (filter.test(s)){
			return 1;
		}else{
			return -1;
		}
	}

	/*
	 * Funcion para validar los inputs del usuario
	 */
	function validarInput(str){
		var s = str;

		var filter=/^[A-Za-z0-9_-]*$/;
		if (filter.test(s)){
			return true;
		}else{
			return false;
		}
	}

	/*
	 * Funcion para validar la imagen
	 */
	function validarImagen(str){
		var s = str;
		var filter=/^[A-Za-z][A-Za-z0-9_]+".jpg"$/;
		if(str.length==0){
				return 0;
		}else{
			if (filter.test(s)){
				return 1;
			}else{
				return -1;
			}
		}
	}

	/*
	 * Funcion para eliminar un div
	 */
	function eliminarDiv(divPadre, divElim) {
    var Node1 = document.getElementById(divPadre); 
    var len = Node1.childNodes.length;
      
    for(var i = 0; i < len; i++){
			if(Node1.childNodes[i].id == divElim){
      	ode1.removeChild(Node1.childNodes[i]);
      }
    }
	}

	/*
	 * Funcion que crea el formulario para anadir una nueva ruta a la base de datos
SELECT `nombre` , `track` , `descripcion` , `id_categoria` , `fecha` , `dificultad_tecnica` , `dificultad_fisica`
	 */
	function addRuta(){
		document.getElementById("central").innerHTML=
			"<div id=\"form-add-ruta\">"
				+"<table>"
					+"<tr>"
						+"<td colspan=\"2\" align=\"center\"><label id=\"titulo2\">A&ntilde;adir Ruta</label></td>"
						+"<td rowspan=\"11\"><div id=\"div-ampliacion\"></div></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>Nombre: </label></td>"
						+"<td><input id=\"nombreAR\" maxlength='30'></input></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>Ruta: </label></td>"
						+"<td>"
							+"<form action=\"./phps/subirRuta.php\" method=\"post\" enctype=\"multipart/form-data\" id=\"formruta\" target=\"iframeUpload\"/>"
								+"<input type=\"file\" name=\"fileUpload\" id=\"rutaAR\" onchange=\"submit()\" style='width:20em;'/>"
								+"<iframe id=\"iframeUpload\" name=\"iframeUpload\" style=\"display:none\"></iframe>"
								+"<input type='hidden' name=\"alturas\"id=\"alturas\"/>"
								+"<input type='hidden' name=\"tiempos\"id=\"tiempos\"/>"
								+"<input type='hidden' name=\"longitud\"id=\"longitud\"/>"
								+"<input type='hidden' name=\"puntos\"id=\"puntos\"/>"
							+"</form>" 
						+"</td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>Descripci&oacute;n: </label></td>"
						+"<td><textarea id='descripcionAR' rows='1' cols='30' onclick='mostrarDescripcionAmpliacion()' onchange=\"mostrarDescripcionAmpliacion()\"></textarea></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>Categor&iacute;a: </label></td>"
						+"<td><select id='sel-categoria'>"
							+"<option value=''>Seleccionar</option>"
							+"<option value='1'>Rally</option>"
							+"<option value='2'>Maraton/Rutas</option>"
							+"<option value='3'>Descenso</option>"
							+"<option value='4'>Enduro</option>"
							+"<option value='5'>Freeride</option>"
						+"</select></td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>Nivel t&eacute;cnico: </label></td>"
						+"<td>"
							+"<select id='diftecAR'>"
								+"<option value='0'>0</option>"
								+"<option value='1'>1</option>"
								+"<option value='2'>2</option>"
								+"<option value='3'>3</option>"
								+"<option value='4'>4</option>"
								+"<option value='5'>5</option>"
								+"<option value='6'>6</option>"
								+"<option value='7'>7</option>"
								+"<option value='8'>8</option>"
								+"<option value='9'>9</option>"
								+"<option value='10'>10</option>"
							+"</select>"
						+"</td>"
					+"</tr>"
					+"<tr>"
						+"<td><label>Nivel f&iacute;sico: </label></td>"
						+"<td>"
							+"<select id='diffisAR'>"
								+"<option value='0'>0</option>"
								+"<option value='1'>1</option>"
								+"<option value='2'>2</option>"
								+"<option value='3'>3</option>"
								+"<option value='4'>4</option>"
								+"<option value='5'>5</option>"
								+"<option value='6'>6</option>"
								+"<option value='7'>7</option>"
								+"<option value='8'>8</option>"
								+"<option value='9'>9</option>"
								+"<option value='10'>10</option>"
							+"</select>"
						+"</td>"
					+"</tr>"
					+"<tr>"
							+"<td colspan=\"2\"><label class='error2' style='color:#CF0'>Todos los campos son obligatorios</label></td>"
					+"</tr>"
					+"<tr>"
							+"<td colspan=\"2\"><label class='error2' id='error3' style='color:#CF0'>&nbsp;</label></td>"
					+"</tr>"
					+"<tr>"
						+"<td></td>"
						+"<td style='float:right'>"
							+"<input style='width:60px' type=\"button\" class=\"boton\" value=\"Borrar\" onclick=\"addRuta()\"/>"
							+"<label>&nbsp;</label>"
							+"<input style='width:60px'type=\"button\" class=\"boton\" value=\"Enviar\" onclick=\"validarAddRuta()\"/>"
						+"</td>"
					+"</tr>"
				+"</table>"
				+"<form action='./phps/crearRuta.php' method=\"post\" enctype=\"multipart/form-data\" id=\"formruta2\" target=\"iframeUpload2\"/>"
					+"<iframe id=\"iframeUpload2\" name=\"iframeUpload2\" style=\"display:none\"></iframe>"
					+"<input type='hidden' name=\"usr2\"id=\"usr2\"/>"
					+"<input type='hidden' name=\"nombre2\"id=\"nombre2\"/>"
					+"<input type='hidden' name=\"descripcion2\"id=\"descripcion2\"/>"
					+"<input type='hidden' name=\"categoria2\"id=\"categoria2\"/>"
					+"<input type='hidden' name=\"diftec2\"id=\"diftec2\"/>"
					+"<input type='hidden' name=\"diffis2\"id=\"diffis2\"/>"
					+"<input type='hidden' name=\"alturas2\"id=\"alturas2\"/>"
					+"<input type='hidden' name=\"puntos2\"id=\"puntos2\"/>"
					+"<input type='hidden' name=\"tiempos2\"id=\"tiempos2\"/>"
					+"<input type='hidden' name=\"longitud2\"id=\"longitud2\"/>"
				+"</form>" 
			+"</div>";
	}

	/*
	 * Funcion que envia el archivo al servidor mediante un formulario y post. Le pasaremos a la funcion
	 * el valor del campo rutaAR.
	 *
	 * 1- Formulario para el envio.
	 * 2- Utilizando AJAX hacer una llamada a un archivo php que nos devuelve el linestring
	 * 3- Llamar a la funcion crearRuta que nos creara el GPolyline para representarlo en el mapa.
	 */ 
	function mostrarRutaAmpliacion(puntos,alts,temps){

		var mapa = new GMap2(document.getElementById("div-ampliacion"));

		var posiciones = Array();
		var array_coma = Array();
		var array_espacio = Array();

		document.getElementById("alturas").value=alts;
		document.getElementById("tiempos").value=temps;

		array_coma = puntos.split(',');

		for (pos in array_coma) {
			var s = array_coma[pos];
			as = s.split(' ');
			posiciones.push(new GLatLng(as[0],as[1]));		
		}

		var polylineEncoder = new PolylineEncoder();
		var polyline = polylineEncoder.dpEncodeToGPolyline(posiciones);
		var bounds = polyline.getBounds();	
		document.getElementById("longitud").value=polyline.getLength();


		var bounds = polyline.getBounds();	
		mapa.setCenter(bounds.getCenter(), mapa.getBoundsZoomLevel(bounds));

		mapa.addOverlay(polyline);	
		
		document.getElementById("puntos").value=puntos;
		//var bounds = polyline.getBounds();	
		//mapa.setCenter(bounds.getCenter(), mapa.getBoundsZoomLevel(bounds));
    mapa.addControl(new GMapTypeControl());
    mapa.addControl(new GLargeMapControl());
    mapa.addControl(new GScaleControl());

	}

	/*
	 *
	 */
	function mostrarDescripcionAmpliacion(){
		document.getElementById("div-ampliacion").innerHTML="<div id='div-desc-ampliacion'> <textarea id='desc-textarea' rows='25' cols='59'>"
		+document.getElementById("descripcionAR").value+"</textarea></div>";
		document.getElementById("desc-textarea").onchange=guardarDescripcionAmpliacion;
	}

	/*
	 *
	 */
	function guardarDescripcionAmpliacion(){
		document.getElementById("descripcionAR").value=document.getElementById("desc-textarea").value;
	}

	/*
	 * Funcion que verifica los campos del formulario de Anadir ruta
	 */
	function validarAddRuta(){
		var nombreAR = document.getElementById("nombreAR").value;
		var rutaAR = document.getElementById("rutaAR").value;
		var descripcionAR = document.getElementById("descripcionAR").value;
		var selcategoria = document.getElementById("sel-categoria").value;
		var diftecAR=document.getElementById("diftecAR").value;
		var diffisAR=document.getElementById("diffisAR").value;

		var alturas=document.getElementById("alturas").value;
		var tiempo=document.getElementById("tiempos").value;
		var longitud=document.getElementById("longitud").value;
		var puntos=document.getElementById("puntos").value;

		document.getElementById("nombreAR").style.backgroundColor="#FFFFFF";
		document.getElementById("rutaAR").style.backgroundColor="#FFFFFF";
		document.getElementById("descripcionAR").style.backgroundColor="#FFFFFF";
		document.getElementById("sel-categoria").style.backgroundColor="#FFFFFF";
		document.getElementById("diftecAR").style.backgroundColor="#FFFFFF";
		document.getElementById("diffisAR").style.backgroundColor="#FFFFFF";

		if(nombreAR.length==0){
			document.getElementById("nombreAR").style.backgroundColor="#CCFF00";
			document.getElementById("error3").innerHTML="Nombre vac&iacute;o";
		}else if(!(validarInput(nombreAR))){
			document.getElementById("nombreAR").style.backgroundColor="#CCFF00";
			document.getElementById("error3").innerHTML="s&oacute;lo alfanum&eacute;ricos y guiones";
		}else if(rutaAR.length==0){
			document.getElementById("error3").innerHTML="No has seleccionado una ruta";
			document.getElementById("rutaAR").style.backgroundColor="#CCFF00";
		}else if(descripcionAR.length==0){
			document.getElementById("error3").innerHTML="No hay descripci&oacute;n";
			document.getElementById("descripcionAR").style.backgroundColor="#CCFF00";
		}else if(selcategoria.length==0){
			document.getElementById("error3").innerHTML="No has seleccionado una categor&iacute;a";
		}else if(diftecAR.length==0){
			document.getElementById("error3").innerHTML="Falta nivel t&eacute;cnico";
		}else if(diffisAR.length==0){
			document.getElementById("error3").innerHTML="Falta nivel f&iacute;sico";
		}else{
			document.getElementById("usr2").value=getCookie('usuario');
			document.getElementById("nombre2").value=nombreAR;
			document.getElementById("descripcion2").value=descripcionAR;
			document.getElementById("categoria2").value=selcategoria;
			document.getElementById("diftec2").value=diftecAR;
			document.getElementById("diffis2").value=diffisAR;

			document.getElementById("puntos2").value=puntos;
			document.getElementById("alturas2").value=alturas;
			document.getElementById("tiempos2").value=tiempo;
			document.getElementById("longitud2").value=longitud;
			
			document.getElementById("formruta2").submit();
			
		}
	}

	function evolucion(){
		document.getElementById("central").innerHTML=
			"<div id=\"div-evolucion\">"
				+"<div align=\"center\">"
					+"<label id='titulo2'>Evoluci&oacute;n</label>"
				+"</div>"
				+"<div	style='float: left;'>"
					+"<div align=\"center\">"
						+"<label id='titulos-evolucion'>Datos</label>"
					+"</div>"
					+"<div id=\"evolucion-lineas\">"
						+"<table>"
							+"<tr>"
								+"<td><input type='checkbox' id='evo-km' groupKey='checkdatos' onclick='checkExcluyente(this);'></td>"
								+"<td><label>distancia</label></td>"
							+"</tr>"
							/*+"<tr>"
								+"<td><input type='checkbox' id='evo-tiempos' groupKey='checkdatos' onclick='checkExcluyente(this);'></td>"
								+"<td><label>tiempos</label></td>"
							+"</tr>"*/
							+"<tr>"
								+"<td><input type='checkbox' id='evo-despos' groupKey='checkdatos' onclick='checkExcluyente(this);'></td>"
								+"<td><label>desnivel positivo</label></td>"
							+"</tr>"
							+"<tr>"
								+"<td><input type='checkbox' id='evo-desneg' groupKey='checkdatos' onclick='checkExcluyente(this);'></td>"
								+"<td><label>desnivel negativo</label></td>"
							+"</tr>"
						+"</table>"
					+"</div>"
					+"<br>"
					+"<div align=\"center\">"
						+"<label id='titulos-evolucion'>Rutas</label>"
					+"</div>"
					+"<div id=\"evolucion-rutas\">"
					//Esta parte al ser dinámica se rellenará en la funcion gráfica dinámica.
					+"</div>"
					+"<div style='padding: 10px 0; float:right'>"
						+"<input type='button' value='dibujar' id='dibujar-grafica' onclick='dibujarGraficaDinamica()'/>"
					+"</div>"
				+"</div>"
				+"<div id=\"evolucion-grafico\">"					
				+"</div>"
				+"<div id=\"descripcion-evolucion-grafico\">"	
				+"<label style='text-decoration: underline;'>Descripci&oacute;n:</label><br>"
					+"<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;En este apartado podr&aacute;s ver como han ido evolucionando tus rutas salida tras salida y as&iacute; llevar un seguimiento a modo de entrenamiento."
					+"</p>"
				+"<label style='text-decoration: underline;'>Pasos a seguir:</label><br>"
					+"<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1- Seleccionar que par&aacute;metro de la ruta deseas que aparezca en la gr&aacute;fica.</p>"
					+"<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2- Seleccionar las rutas sobre las cuales quieres que se realice la gráfica.</p>"
				+"</div>"
			+"</div>";

		graficaDinamica();
	}

	/*
	 * Hay que hacer una consulta a la base de datos para que nos devuelva todos los nombres de las rutas del usuario.
	 * Mostraremos todos esos nombres en la parte de rutas con un checkbox a su izquierda representando que el usuario
	 * acepta el visualizar esa ruta o esa opcion.
	 */
	function graficaDinamica(){
		var xmlHttpReq = false;
		var self = this;
		var names;
		var names_split;
		if (window.XMLHttpRequest){ // Mozilla/Safari	
			self.xmlHttpReq = new XMLHttpRequest();
		}else if (window.ActiveXObject){ // IE	
			self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}

		var txt= "./phps/mostrarRutasUsuario.php?nombre="+getCookie('usuario');		

		self.xmlHttpReq.open('GET',txt, true);
		self.xmlHttpReq.onreadystatechange = function() {
			if (self.xmlHttpReq.readyState == 4) {
				var tabla_inner="<table>";
				names=self.xmlHttpReq.responseText;
				names_split=names.split("~~");
				for(var i=0;i<names_split.length-1;i+=6){
						tabla_inner+="<tr><td><input type='checkbox' id='evolucion-rutas-"+names_split[i]+"'></td>";//id
						tabla_inner+="<td><label>"+names_split[i+1]+"</label></td>";//nombre
						tabla_inner+="<td><input type='hidden' value='"+(names_split[i+5]/1000)+"'/></td>";//km_totales
						tabla_inner+="<td><input type='hidden' value='"+names_split[i+4]+"'/></td></tr>";//duracion
						tabla_inner+="<td><input type='hidden' value='"+names_split[i+2]+"'/></td>";//despos
						tabla_inner+="<td><input type='hidden' value='"+names_split[i+3]+"'/></td>";//desneg
				}
				tabla_inner+="</table>";
				document.getElementById("evolucion-rutas").innerHTML=tabla_inner;
			}
		}
		self.xmlHttpReq.send(null);
	}

	/*
	 * Funcion que enviar los valores seleccionados anteriormente y realiza una consulta a la base de datos con esos
	 * valores.
	 */
	function dibujarGraficaDinamica(){
    var datos = [];

		var distancias = [];
		var despositivos = [];
		var desnegativos = [];
		var tiempos = [];
		var i=0;
		var x;
 		var tabla_rutas =document.getElementById("evolucion-rutas");
		var trs=tabla_rutas.getElementsByTagName("tr");

		datos=tabla_rutas.getElementsByTagName("td");

		for(x=0;x<datos.length-1;x+=6){
			var str=datos[x].innerHTML;
			var y=str.split("\"")
			if(document.getElementById(y[1]).checked){//verificamos que la ruta este checked
				if(document.getElementById("evo-km").checked){//verificamos que la opcion evo-km este cheked
					var str=datos[x+2].innerHTML;
					var y=str.split("\"")
					distancias.push([i, y[1]]);
					i++;
				/*}else if(document.getElementById("evo-tiempos").checked){
					var str=datos[x+3].innerHTML;
					var y=str.split("\"")
					tiempos.push([i, y[1]]);
					i++;*/
				}else if(document.getElementById("evo-despos").checked){
					var str=datos[x+4].innerHTML;
					var y=str.split("\"")
					despositivos.push([i, y[1]]);
					i++;
				}else	if(document.getElementById("evo-desneg").checked){
					var str=datos[x+5].innerHTML;
					var y=str.split("\"")
					desnegativos.push([i, y[1]]);
					i++;
				}
			}
		}
		$.plot($("#evolucion-grafico"), [ distancias, despositivos, desnegativos, tiempos ]);
	}

	function checkExcluyente(checkBox){
		var arr = document.getElementById("evolucion-lineas");
		var arrayCB = arr.getElementsByTagName("input");
		var temp=checkBox.checked;

		document.getElementById("evo-km").checked=false;
		//document.getElementById("evo-tiempos").checked=false;
		document.getElementById("evo-despos").checked=false;
		document.getElementById("evo-desneg").checked=false;

		if(document.getElementById("evo-km").id==checkBox.id)
			document.getElementById("evo-km").checked=temp;
		/*if(document.getElementById("evo-tiempos").id==checkBox.id)
			document.getElementById("evo-tiempos").checked=temp;
		*/if(document.getElementById("evo-despos")==checkBox)
			document.getElementById("evo-despos").checked=temp;
		if(document.getElementById("evo-desneg")==checkBox)
			document.getElementById("evo-desneg").checked=temp;
	}


	/*
	 * Funcion para crear el div correspondiente a la opcion tus-rutas
	 */
	function tusRutas(){
		document.getElementById("central").innerHTML=
			"<div id=\"div-tusRutas\">"
				+"<div align=\"center\">"
					+"<label id='titulo2'>Tus Rutas</label>"
				+"</div>"
				+"<div	style='float: left;'>"
					+"<div id=\"tusRutas-rutas\">"
						//Aqui anadiremos de forma dinamica las rutas del usuario.
					+"</div>"
				+"</div>"
				+"<div>"
					+"<div id='tusRutas-pestanas'>"
						+"<div class='tusRutas-pestana-select-dcha' id='pestana-0' onclick='pestanaActivada(0);'>mapa</div>"
						+"<div class='tusRutas-pestana-select-no' 	id='pestana-1' onclick='pestanaActivada(1);'>perfil</div>"
						+"<div class='tusRutas-pestana-select-no' 	id='pestana-2' onclick='pestanaActivada(2);'>datos</div>"
						+"<div class='tusRutas-pestana-select-no' 	id='pestana-3' onclick='pestanaActivada(3);'>descargar</div>"
					+"</div>"
					+"<div id='grafico-pestana-0' class='tusRutas-grafico'></div>"
					+"<div id='grafico-pestana-1' class='tusRutas-grafico'></div>"
					+"<div id='grafico-pestana-2' class='tusRutas-grafico'></div>"
					+"<div id='grafico-pestana-3' class='tusRutas-grafico'></div>"
				+"</div>"
			+"</div>";
		completarMenuTusRutas();
		pestanaActivada(0);
	}

	/*
	 * Función que se rellenara el div correspondiente a las rutas del usuario.
	 */
	function completarMenuTusRutas(){
		var xmlHttpReq = false;
		var self = this;
	
		if (window.XMLHttpRequest){ // Mozilla/Safari	
			self.xmlHttpReq = new XMLHttpRequest();
		}else if (window.ActiveXObject){ // IE	
			self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}

		var txt= "./phps/mostrarRutasUsuario.php?nombre="+getCookie('usuario');		
	
		self.xmlHttpReq.open('GET',txt, true);
		self.xmlHttpReq.onreadystatechange = function() {
			if (self.xmlHttpReq.readyState == 4) {
				
				var tabla_inner="<table>";
				names=self.xmlHttpReq.responseText;
				names_split=names.split("~~");
				for(var i=0;i<names_split.length-1;i+=6){

						tabla_inner+="<tr onclick='rellenarPestanas("+names_split[i]+")' id='tus-rutas-filas'>";
						tabla_inner+="<td>"+names_split[i+1]+"</td>";//nombre
						tabla_inner+="<input type='hidden' id='tusRutas-rutas-"+names_split[i]+"'>";//id ruta;
						tabla_inner+="</tr>";
				}
				tabla_inner+="</table>";
				document.getElementById("tusRutas-rutas").innerHTML=tabla_inner;
			}
		}
		self.xmlHttpReq.send(null);
	}

	/*
	 * Función que se rellenara el div correspondiente a las rutas del usuario.
	 */
	function completarPestanaMapa(id){
		var xmlHttpReq = false;
		var self = this;

		if (window.XMLHttpRequest){ // Mozilla/Safari
		  self.xmlHttpReq = new XMLHttpRequest();
		}else if (window.ActiveXObject){ // IE
		  self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}

		var txt= "./phps/linestring.php?id="+id;

		self.xmlHttpReq.open('GET',txt, true);
		self.xmlHttpReq.onreadystatechange = function() {
			if (self.xmlHttpReq.readyState == 4) {
				var mapa = new GMap2(document.getElementById("grafico-pestana-0"));
		    mapa.addControl(new GMapTypeControl());
		   	mapa.addControl(new GLargeMapControl());
		   	mapa.addControl(new GScaleControl());

				var posiciones = Array();
				var array_coma = Array();
				var array_espacio = Array();

				array_coma = self.xmlHttpReq.responseText.split(',');

				for (pos in array_coma) {
					var s = array_coma[pos];
					as = s.split(' ');
					posiciones.push(new GLatLng(as[0],as[1]));		
				}

				var polylineEncoder = new PolylineEncoder();
				var polyline = polylineEncoder.dpEncodeToGPolyline(posiciones);
				var bounds = polyline.getBounds();	
				mapa.setCenter(bounds.getCenter(), mapa.getBoundsZoomLevel(bounds));
				mapa.addOverlay(polyline);
				completarPestanaDatos(id,'1');//Llamamos desde aqui a la funcion de rellenar los campos de datos.
			}
		}
		self.xmlHttpReq.send(null);	
	}

	function completarPestanaDatos(id, tipo){
		var xmlHttpReq = false;
		var self = this;

		if (window.XMLHttpRequest){ // Mozilla/Safari
		  self.xmlHttpReq = new XMLHttpRequest();
		}else if (window.ActiveXObject){ // IE
		  self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		var txt= "./phps/mostrarDatosRuta.php?id="+id;

		self.xmlHttpReq.open('GET',txt, true);
		self.xmlHttpReq.onreadystatechange = function() {
			if (self.xmlHttpReq.readyState == 4) {

				var array = Array();
				array = self.xmlHttpReq.responseText.split("~~");

				document.getElementById("grafico-pestana-2").innerHTML=
					"<div>"
						+"<table>"
							+"<tr>"
								+"<td>Nombre:</td>"
								+"<td>"+array[0]+"</td>"
								+"<td>Categoría:</td>"
								+"<td>"+array[5]+"</td>"
							+"</tr>"
							+"<tr>"
								+"<td>Distancia:</td>"
								+"<td>"+(array[1]/1000)+" km"+"</td>"
								+"<td>Dif t&eacute;cnica:</td>"
								+"<td>"+array[6]+"</td>"
							+"</tr>"
							+"<tr>"
								+"<td>Duracion:</td>"
								+"<td>"+array[2]+"</td>"
								+"<td>Dif. f&iacute;sica:</td>"
								+"<td>"+array[7]+"</td>"
							+"</tr>"
							+"<tr>"
								+"<td>Desnivel positivo:</td>"
								+"<td>"+array[3]+"</td>"
								+"<td>N&uacute;m. visitas:</td>"
								+"<td>"+array[8]+"</td>"
							+"</tr>"
							+"<tr>"
								+"<td>Desnivel negativo:</td>"
								+"<td>"+array[4]+"</td>"
								+"<td>N&uacute;m. descargas:</td>"
								+"<td>"+array[9]+"</td>"
							+"</tr>"
							+"<tr>"
								+"<td>Descripci&oacute;n:</td>"
							+"</tr>"
							+"<tr>"
								+"<td colspan=\"4\"><div id='div_desc-"+tipo+"''>"+array[10]+"</td></div>"
							+"</tr>"
						+"</table>"
					+"</div>";
			}
		}
		self.xmlHttpReq.send(null);
	}

	function pestanaActivada(identif){
		var arr=document.getElementById("tusRutas-pestanas").getElementsByTagName("div");
		for(var i=0; i<arr.length;i++){
			if(arr[i].id=="pestana-"+identif){
				if(identif==0) arr[i].className="tusRutas-pestana-select-dcha"
				else arr[i].className="tusRutas-pestana-select";
				if(arr[i].id=="pestana-0"){
					document.getElementById("grafico-pestana-0").style.display = "block";
					document.getElementById("grafico-pestana-1").style.display = "none";
					document.getElementById("grafico-pestana-2").style.display = "none";
					document.getElementById("grafico-pestana-3").style.display = "none";
				}else if(arr[i].id=="pestana-1"){
					document.getElementById("grafico-pestana-0").style.display = "none";
					document.getElementById("grafico-pestana-1").style.display = "block";
					document.getElementById("grafico-pestana-2").style.display = "none";
					document.getElementById("grafico-pestana-3").style.display = "none";
				}else if(arr[i].id=="pestana-2"){
					document.getElementById("grafico-pestana-0").style.display = "none";
					document.getElementById("grafico-pestana-1").style.display = "none";
					document.getElementById("grafico-pestana-2").style.display = "block";
					document.getElementById("grafico-pestana-3").style.display = "none";
				}else if(arr[i].id=="pestana-3"){
					document.getElementById("grafico-pestana-0").style.display = "none";
					document.getElementById("grafico-pestana-1").style.display = "none";
					document.getElementById("grafico-pestana-2").style.display = "none";
					document.getElementById("grafico-pestana-3").style.display = "block";
				}
			}else{
				if(arr[i].id=="pestana-"+0) arr[i].className="tusRutas-pestana-select-no-dcha";
				else arr[i].className="tusRutas-pestana-select-no";
			}
		}
	}

	function rellenarPestanas(identif){
		var arr_tr=document.getElementById("tusRutas-rutas").getElementsByTagName("tr");
		for(var i=0; i<arr_tr.length;i++){
			var arr_inputs=arr_tr[i].getElementsByTagName("input");
			if(arr_inputs[0].id=="tusRutas-rutas-"+identif){
				arr_tr[i].id="tus-rutas-filas-click";

				//Lineas correspondientes a la representacion de la ruta en la pestana mapa
				completarPestanaMapa(identif);
			
				//cargamos el perfil de la ruta.
				document.getElementById("grafico-pestana-1").innerHTML=
					"<div id='grafico-resize' style='background: url(./imagenes/graficas/"+identif+".png); background-repeat:no-repeat;'></div>";

				//Los datos de la ruta en lugar de cargarlos aqui los cargamos dentro del metodo completarPestanaMapa
				// porque hay algun tipo de problemas con AJAX.
		

				//pestana donde podremos seleccionar el formato de ruta para descargar.
				document.getElementById("grafico-pestana-3").style.background="#a8aee8 url(./imagenes/enConstruccion2.gif)";
			}else
				arr_tr[i].id="tus-rutas-filas";
		}
		pestanaActivada(0);
	}

	function buscarRutas(){
		document.getElementById("central").innerHTML=
			"<div id='buscador-rutas'>"
				+"<div id='titulo3'><label >Buscador de rutas</label></div>"
				+"<div id='form-busquedas'>"
					+"<table id='tabla-form-busquedas'>"
						+"<tr>"
							+"<td><label>Distancia:</label></td>"
							+"<td><select id='sel-distancia' style='size: 100px;' onchange='actualizarBusqueda();'>"
								+"<option value=''>km</option>"
								+"<option value='1'>0  .. 20km</option>"
								+"<option value='2'>20 .. 40km</option>"
								+"<option value='3'>40 .. 60km</option>"
								+"<option value='4'>60 .. 80km</option>"
								+"<option value='5'>80 .. +</option>"
							+"</select></td>"
							+"<td><label>&nbsp;</label></td>"
							+"<td><label>Dif. t&eacute;cnica:</label></td>"
							+"<td><select id='sel-tecnica' onchange='actualizarBusqueda();'>"
								+"<option value=''>Seleccionar</option>"
								+"<option value='1'>0 .. 2</option>"
								+"<option value='2'>2 .. 4</option>"
								+"<option value='3'>4 .. 6</option>"
								+"<option value='4'>6 .. 8</option>"
								+"<option value='5'>8 .. 10</option>"
							+"</select></td>"
						+"</tr>"						
						+"<tr>"
							+"<td><label>Duraci&oacute;n:</label></td>"
							+"<td><select id='sel-duracion' onchange='actualizarBusqueda();'>"
								+"<option value=''>horas</option>"
								+"<option value='1'>0 .. 2h</option>"
								+"<option value='2'>2 .. 4h</option>"
								+"<option value='3'>4 .. 6h</option>"
								+"<option value='4'>6 .. 8h</option>"
								+"<option value='5'>8 .. +</option>"
							+"</select></td>"
							+"<td><label>&nbsp;</label></td>"
							+"<td><label>Dif. f&iacute;sica:</label></td>"
							+"<td><select id='sel-fisica' onchange='actualizarBusqueda();'>"
								+"<option value=''>Seleccionar</option>"
								+"<option value='1'>0 .. 2</option>"
								+"<option value='2'>2 .. 4</option>"
								+"<option value='3'>4 .. 6</option>"
								+"<option value='4'>6 .. 8</option>"
								+"<option value='5'>8 .. 10</option>"
							+"</select></td>"
						+"</tr>"
						+"<tr>"
							+"<td><label>Categor&iacute;a:</label></td>"
							+"<td><select id='sel-categoria' onchange='actualizarBusqueda();'>"
								+"<option value=''>Seleccionar</option>"
								+"<option value='1'>Rally</option>"
								+"<option value='2'>Maraton/Rutas</option>"
								+"<option value='3'>Descenso</option>"
								+"<option value='4'>Enduro</option>"
								+"<option value='5'>Freeride</option>"
							+"</select></td>"
							+"<td><label>&nbsp;</label></td>"
							+"<td><label>Desnivel + :</label></td>"
							+"<td><select id='sel-despos' onchange='actualizarBusqueda();'>"
								+"<option value=''>metros</option>"
								+"<option value='1'>0    .. 500</option>"
								+"<option value='2'>500  .. 1000</option>"
								+"<option value='3'>1000 .. 1500</option>"
								+"<option value='4'>1500 .. 2000</option>"
								+"<option value='5'>2000 .. +</option>"
							+"</select></td>"
						+"</tr>"
						+"<tr>"
							+"<td><label>Ordenar por:</label></td>"
							+"<td><select id='sel-orden' onchange='actualizarBusqueda();'>"
								+"<option value=''>Seleccionar</option>"
								+"<option value='1' SELECTED>Distancia</option>"
								+"<option value='2'>Duraci&oacute;n</option>"
								+"<option value='3'>Categor&iacute;a</option>"
								+"<option value='4'>Dif. t&eacute;ecnica</option>"
								+"<option value='5'>Dif. f&iacute;sica</option>"
								+"<option value='6'>Desnivel +</option>"
								+"<option value='7'>Desnivel -</option>"
							+"</select></td>"
							+"<td><label>&nbsp;</label></td>"
							+"<td><label>Desnivel - :</label></td>"
							+"<td><select id='sel-desneg' onchange='actualizarBusqueda();'>"
								+"<option value=''>metros</option>"
								+"<option value='1'>0    .. 500</option>"
								+"<option value='2'>500  .. 1000</option>"
								+"<option value='3'>1000 .. 1500</option>"
								+"<option value='4'>1500 .. 2000</option>"
								+"<option value='5'>2000 .. +</option>"
							+"</select></td>"
						+"</tr>"
						+"<tr><td colspan='5' class='frase'>"
							+"<label>Estos par&aacute;metros afectan a la secci&oacute;n del mapa visualizada.</label>"
						+"</td></tr>"
					+"</table>"
				+"</div>"
				+"<div id='resultado-busquedas'>"
					//rellenaremos el contenido de este div con las rutas encontradas en funcion de los parametros del buscador	
				+"</div>"
				+"<div id='div-pestanas'>"
					+"<div id='tusRutas-pestanas'>"
						+"<div class='tusRutas-pestana-select-dcha' id='pestana-0' onclick='pestanaActivada(0);'>mapa</div>"
						+"<div class='tusRutas-pestana-select-no' 	id='pestana-1' onclick='pestanaActivada(1);'>perfil</div>"
						+"<div class='tusRutas-pestana-select-no' 	id='pestana-2' onclick='pestanaActivada(2);'>datos</div>"
						+"<div class='tusRutas-pestana-select-no' 	id='pestana-3' onclick='pestanaActivada(3);'>descargar</div>"
					+"</div>"
					+"<div id='grafico-pestana-0' class='resultado-busquedas-grafico'></div>"
					+"<div id='grafico-pestana-1' class='resultado-busquedas-grafico'></div>"
					+"<div id='grafico-pestana-2' class='resultado-busquedas-grafico'></div>"
					+"<div id='grafico-pestana-3' class='resultado-busquedas-grafico'></div>"
				+"</div>"
			+"</div>";

		addMapaBusqueda();
		pestanaActivada(0);
	}

	function actualizarBusqueda(){


		var tec=document.getElementById("sel-tecnica").value;
		var dur=document.getElementById("sel-duracion").value;
		var fis=document.getElementById("sel-fisica").value;
		var cat=document.getElementById("sel-categoria").value;
		var despos=document.getElementById("sel-despos").value;
		var desneg=document.getElementById("sel-desneg").value;
		var orden=document.getElementById("sel-orden").value;
		var dist=document.getElementById("sel-distancia").value;

		var xmlHttpReq = false;
		var self = this;

		if (window.XMLHttpRequest){ // Mozilla/Safari
		  self.xmlHttpReq = new XMLHttpRequest();
		}else if (window.ActiveXObject){ // IE
		  self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}		
		//alert("bounds "+map.getBounds());
		//alert("dist "+dist+" dur "+dur+" tec "+tec+" fis "+fis+" cat "+cat+" despos "+despos+" desneg "+desneg+" orden "+orden);
		var txt= "./phps/buscadorRutas.php?distancia="+dist+"&duracion="+dur+"&tecnica="+tec+"&fisica="+fis+"&categoria="+cat+"&despos="+despos+"&desneg="+desneg+"&orden="+orden+"&bounds="+map.getBounds();

		self.xmlHttpReq.open('GET',txt, true);
		self.xmlHttpReq.onreadystatechange = function() {
			if (self.xmlHttpReq.readyState == 4) {
				//alert(self.xmlHttpReq.responseText);
				var tabla_inner="<table>";
				names=self.xmlHttpReq.responseText;
				names_split=names.split("~~");
				for(var i=0;i<names_split.length-1;i+=2){
						//alert("i: "+i);
						tabla_inner+="<tr onclick='mostrarRuta("+names_split[i]+",\"false\")' id='resultado-busquedas-filas'>";
						tabla_inner+="<td>"+names_split[i+1]+"</td>";//nombre
						tabla_inner+="<input type='hidden' id='resultado-busquedas-rutas-"+names_split[i]+"'>";//id ruta;
						tabla_inner+="</tr>";
				}
				tabla_inner+="</table>";
				document.getElementById("resultado-busquedas").innerHTML=tabla_inner;
			}
		}
		self.xmlHttpReq.send(null);
//		alert("despues");
	}

	function addMapaBusqueda(){
		if (GBrowserIsCompatible()){

			document.getElementById("grafico-pestana-0").innerHTML="<div id='mapa' onclick='actualizarBusqueda();'><div>";

			map = new GMap2(document.getElementById("mapa"));
			map.setCenter(new GLatLng(41.378562,2.104888), 12);
      map.addControl(new GMapTypeControl());
     	map.addControl(new GLargeMapControl());
     	map.addControl(new GScaleControl());
      map.addControl(new GOverviewMapControl());
		}
	}


