var defaultEmptyOK = false

// listas de caracteres
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyzáéíóúñü"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÑ"
var whitespace = " \t\n\r";
var whitespace2 = " \t\n\r - _ :";
var whitespace3 = " \t\n\r .";

// caracteres admitidos en nos de telefono
var phoneChars = "()-+ ";
var puntoChars = ". \ / :";
var fechaChars = "-";


// s es un numero (entero o flotante, con o sin signo)
function isNumber (s)
{   var i;
    var dotAppeared;
    dotAppeared = false;
    if (isEmpty(s)) 
       if (isNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isNumber.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if ( c == "." ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c)) return false;
        } else { 
            if ( c == "." ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}

// ---------------------------------------------------------------------- //
//                        STRINGS SIMPLES                                 //
// ---------------------------------------------------------------------- //

// s tiene solo letras
function isAlphabetic (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }
    return true;
}


// s tiene solo letras y numeros
function isAlphanumeric (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    return true;
}
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isWhitespace (s)
{   var i;
    if (isEmpty(s)) return true;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        // si el caracter en que estoy no aparece en whitespace,
        // entonces retornar falso
        if (whitespace.indexOf(c) == -1) return false;
    }
    return true;
}

// s es una direccion de correo valida
function isEmail (s)
{
    if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
    if (isWhitespace(s)) return false;
    var i = 1;
    var sLength = s.length;
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}


function selecciondeporte ()
{
if (document.myform.deportes.selectedIndex==0){
		var divMensaje=document.getElementById("mensaje");
		alert ("Seleccione un Deporte");
		//divMensaje.innerHTML="Seleccione un Deporte";
		document.myform.deportes.focus()
		return 0;

}

}
function seleccionprovincia ()
{
if (document.myform.select_0.selectedIndex==0){
		//alert("Debe seleccionar una zona.")
		var divMensaje=document.getElementById("mensaje");
		alert ("Seleccione una provincia");
		//divMensaje.innerHTML="Seleccione una zona";
		document.myform.select_0.focus()
		return 0;
}
}
function seleccionzona ()
{
if (document.myform.select_1.selectedIndex==0){
		//alert("Debe seleccionar una zona.")
		var divMensaje=document.getElementById("mensaje");
		alert ("Seleccione una zona");
		//divMensaje.innerHTML="Seleccione una zona";
		document.myform.select_1.focus()
		return 0;
}
}

function seleccionano ()
{
if (document.myform.ano.selectedIndex==0){
		//alert("Debe seleccionar una zona.")
		var divMensaje=document.getElementById("mensaje");
		alert ("Seleccione un año");
		divMensaje.innerHTML="Seleccione un año";
		document.myform.ano.focus()
		return false;
}

}

function Verificarusuario () {

			if ((seleccionano () !=0) && (seleccionprovincia () !=0) && (seleccionzona()!=0 ))
			{
				// alert( "Todo verificado con exito" );
				 return true;
				//document.myform.submit ();
			}

};


//***************************************************************************************

function eliminaEspacios(cadena)
{
	// Funcion para eliminar espacios delante y detras de cada cadena
	while(cadena.charAt(cadena.length-1)==" ") cadena=cadena.substr(0, cadena.length-1);
	while(cadena.charAt(0)==" ") cadena=cadena.substr(1, cadena.length-1);
	return cadena;
}

function validaIngreso(valor)
{
	/* Funcion encargada de validar lo que has introducido por el usuario. Se devuelve TRUE en caso de ser 
	valido, FALSE en caso contrario */
	var reg=/(^[a-zA-Z0-9._@ ]{5,200}$)/;
	if(reg.test(valor)) return true;
	else return false;
}

function validaPass(valor)
{
	/* Funcion encargada de validar lo que has introducido por el usuario. Se devuelve TRUE en caso de ser 
	valido, FALSE en caso contrario */
	var reg=/(^[a-zA-Z0-9.@ ]{5,40}$)/;
	if(reg.test(valor)) return true;
	else return false;
}

function validaFrase(valor)
{
	/* Funcion encargada de validar lo que has introducido por el usuario. Se devuelve TRUE en caso de ser 
	valido, FALSE en caso contrario */
	var reg=/(^[a-zA-Z0-9-,.-ºñ áéíóúÁÉÍÓÚÑ ]{3,250}$)/;
	if(reg.test(valor)) return true;
	else return false;
}

function validaNombre(valor)
{
	/* Funcion encargada de validar lo que has introducido por el usuario. Se devuelve TRUE en caso de ser 
	valido, FALSE en caso contrario */
	var reg=/(^[a-zA-Z-ªºñ áéíóúÁÉÍÓÚÑ ]{4,250}$)/;
	if(reg.test(valor)) return true;
	else return false;
}

function validaTitulo(valor)
{
	/* Funcion encargada de validar lo que has introducido por el usuario. Se devuelve TRUE en caso de ser 
	valido, FALSE en caso contrario */
	var reg=/(^[a-zA-Z0-9¿?!¡,:ºªñáéíóúÁÉÍÓÚÑ ]{5,60}$)/;
	if(reg.test(valor)) return true;
	else return false;
}

function validaNumero(valor)
{
	/* Funcion encargada de validar lo que has introducido por el usuario. Se devuelve TRUE en caso de ser 
	valido, FALSE en caso contrario */
	var reg=/(^[0-9]{0,10}$)/;
	if(reg.test(valor)) return true;
	else return false;
}

function validaNumeroTelefono(valor)
{
	/* Funcion encargada de validar lo que has introducido por el usuario. Se devuelve TRUE en caso de ser 
	valido, FALSE en caso contrario */
	var reg=/(^[0-9]{8,25}$)/;
	if(reg.test(valor)) return true;
	else return false;
}
function validaDireccion(valor)
{
	/* Funcion encargada de validar lo que has introducido por el usuario. Se devuelve TRUE en caso de ser 
	valido, FALSE en caso contrario */
	var reg=/(^[a-zA-Z0-9.@,-]{3,250}$)/;
	if(reg.test(valor)) return true;
	else return false;
}

function habilita(form)
{
var y;
for (i=0;y=document.getElementById("compite_" + i);i++) 
	{	
		document.getElementById("compite_" + i).disabled=false;
	
	}
}
function deshabilita(form)
{
var y;
for (i=0;y=document.getElementById("compite_" + i);i++) 
	{	
		document.getElementById("compite_" + i).disabled=true;
		document.getElementById("compite_" + i).checked=false;
		
	}
}
function deshabilita2(form)
{
var y;
for (i=0;y=document.getElementById("compite_" + i);i++) 
	{	
		document.getElementById("compite_" + i).disabled=true;
		
	}
}

 function contadorTextarea()
  {
   var tex=document.myform.texto;
   var maximo=tex.value.length;
   if(maximo>400)
    {
     tex.value=tex.value.substr(0,400);
     alert("Maximo de caracteres es 400");
    }
  }
 function contadorTextarea_800()
  {
   var tex=document.myform.texto;
   var maximo=tex.value.length;
   if(maximo>800)
    {
     tex.value=tex.value.substr(0,800);
     alert("Maximo de caracteres es 800");
    }
  }
//****************************************pop up***********************************************
function popupopinion(url) {
	var option = "width=650,height=600,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,top=10,left=10";
	window.open(url,'_blank',option);
}
//************************************************************************************************
function confirmSubmit()
{
var agree=confirm("Está seguro de eliminar este registro? Este proceso es irreversible.");
if (agree)
return true ;
else
return false ;
}

function confirmSuspender()
{
var agree=confirm("¿Está seguro de suspender esta competición?");
if (agree)
return true ;
else
return false ;
}
//****************************************publicacion de un articulo***********************************************
function publicar_articulo ()
{
	var titulo=document.getElementById("titulo");
	var tema=document.getElementById("tema");	
	
	var titulo1=titulo.value;
	var tema1=tema.value;


 if (!validaTitulo(titulo1))
	{
		alert ("El nombre que has introducido contiene caracteres o longitud invalida");
		document.myform.titulo.focus();
	}
	else if (document.myform.tema.selectedIndex==0)
	{
		alert ("Seleccione un Tema");
		document.myform.tema.focus()
	}
	else
	{
	document.myform.submit ();	
		
	}

}

//****************************************ingresar torneo***********************************************

function ingresar_torneo ()
{
	var nombre=document.getElementById("nombre");
	var fecha=document.getElementById("sel3");	
	var deportes=document.getElementById("deportes");

	
	var nombre=nombre.value;
	var fecha=fecha.value;
	var deportes=deportes.value;

	
 if (!validaFrase(nombre))
	{
		alert ("El nombre que has introducido contiene caracteres o longitud invalida");
		document.myform.nombre.focus();
	}
	else if (fecha=="Seleccione fecha")
	{
		alert ("Seleccione una Fecha");
		document.myform.sel3.focus()
	}
	else if (document.myform.select1.selectedIndex==0)
	{
		alert ("Seleccione una Provincia");
		document.myform.select1.focus()
	}
	else if (document.myform.select2.selectedIndex==0)
	{
		alert ("Seleccione una Zona");
		document.myform.select2.focus()
	}
	else if (document.myform.select3.selectedIndex==0)
	{
		alert ("Seleccione un Club, si no existe, tiene que darlo de alta en 'Club'");
		document.myform.select3.focus();
	}
	else if (document.myform.deportes.selectedIndex==0)
	{
		alert ("Seleccione un Deporte");
		document.myform.deportes.focus()
	}
	else
	{
	document.myform.submit ();	
		
	}

}
//****************************************Modificar torneo***********************************************

function modificar_torneo ()
{
	var nombre=document.getElementById("nombre");
	var lugar=document.getElementById("lugar");

	
	var nombre=nombre.value;
	var lugar=lugar.value;
	
 if (!validaFrase(nombre))
	{
		alert ("El nombre que has introducido contiene caracteres o longitud invalida");
		document.myform.nombre.focus();
	}
	else if (document.myform.select1.selectedIndex==0)
	{
		alert ("Seleccione una Provincia");
		document.myform.select1.focus()
	}
	else if (document.myform.select2.selectedIndex==0)
	{
		alert ("Seleccione una Zona");
		document.myform.select2.focus()
	}
	else if (document.myform.select3.selectedIndex==0)
	{
		alert ("Seleccione un Club");
		document.myform.select3.focus();
	}
	else
	{
	document.myform.submit ();	
		
	}

}

//****************************************ingresar club***********************************************
function ingresar_club ()
{
	var nombre=document.getElementById("nombre");
	var direccion=document.getElementById("direccion");	
	//var telefono=document.getElementById("telefono");

	
	var nombre=nombre.value;
	var direccion=direccion.value;
	//var telefono=telefono.value;
	

var x;
var contchec=0;
var contserv=0;

for (i=0;x=document.getElementById("instalacion_" + i);i++) // el numero de instalaciones chequeados
{	
	
	if (x.checked == true)
	{
	contchec++;
	}
}

/*for (i=0;x=document.getElementById("servicio_" + i);i++) // el numero de servicios chequeados
{	
	
	if (x.checked == true)
	{
	contserv++;
	}
}*/


 if (!validaNombre(nombre))
	{
		alert ("El nombre que has introducido contiene caracteres o longitud invalida");
		document.myform.nombre.focus();
	}
	else if (document.myform.select_0.selectedIndex==0)
	{
		alert ("Seleccione una Provincia");
		document.myform.select_0.focus()
	}
	else if (!validaFrase(direccion))
	{
		alert ("La Direccion ingresada contiene caracteres o longitud invalida");
		document.myform.direccion.focus();
	}
	/*else if (!validaNumeroTelefono(telefono))
	{
		alert ("El Telefono que has introducido contiene caracteres o longitud invalida");
		document.myform.telefono.focus();
	}*/
	else if (contchec==0)
	{
		alert ("Debe introducir almenos una instalacion");
		//document.myform.deportes.focus()
	}
	/*else if (contserv==0)
	{
		alert ("Debe introducir almenos una servicio, marque Ninguno si no tiene Servicio");
		//document.myform.club.focus();
	}*/
	else
	{
	document.myform.submit ();	
		
	}

}
//****************************************ingresar Competicion***********************************************

function ingresar_competicion ()
{
	var fecha=document.getElementById("sel4");	
	var deporte=document.getElementById("deporte");
	var jugadores=document.getElementById("jugadores");
	//var sinZona=document.getElementById("sinZona");
	//var sinClub=document.getElementById("sinClub");

	var fecha=fecha.value;
	var deporte=deporte.value;
	var jugadores=jugadores.value;
	//var sinZona=sinZona.value;
	//var sinClub=sinClub.value;
	
	if (document.myform.sinZona.checked==true) {

		var sinZona = 2;
		document.myform.sinClub.checked=true;
		var sinClub = 2;
		
		}
	if (document.myform.sinClub.checked==true) {

		var sinClub = 2;
		
		}


	if (document.myform.select1.selectedIndex==0)
	{
		alert ("Seleccione una Provincia");
		document.myform.select1.focus()
	}
	else if ((document.myform.select2.selectedIndex==0) && (sinZona != 2))
	{
		alert ("Seleccione una Zona");
		document.myform.select2.focus()
	}
	else if ((document.myform.select3.selectedIndex==0) && (sinClub != 2))
	{
		alert ("Seleccione un Club");
		document.myform.select3.focus();
	}
	else if (fecha=="Inicio fecha")
	{
		alert ("Seleccione un Inicio de Fecha");
		document.myform.sel4.focus()
	}
	else if (document.myform.deporte.selectedIndex==0)
	{
		alert ("Seleccione un Deporte");
		document.myform.deporte.focus()
	}
	else if (document.myform.dificultad.selectedIndex==0)
	{
		alert ("Seleccione un Nivel de dificultad del partido");
		document.myform.dificultad.focus()
	}
	else if (document.myform.jugadores.selectedIndex==0)
	{
		alert ("Seleccione numero de jugadores o equipos que necesitas");
		document.myform.jugadores.focus()
	}
	else
	{
	document.myform.submit ();	
		
	}

}
//******************************************cambio de password*****************************************************
function cambiar_pws()
{
	var old_password=document.getElementById("old_password");
	var new_password=document.getElementById("new_password");	
	var new_password2=document.getElementById("new_password2");
	
	var old_password=old_password.value;
	var new_password=new_password.value;	
	var new_password2=new_password2.value;
	
	if (!validaPass(old_password))
	{
		alert ("La contraseña ingresada contiene caracteres o longitud invalida");
		document.myform.old_password.focus();
	}
	else if (!validaPass(new_password))
	{
		alert ("La nueva contraseña ingresada contiene caracteres o longitud invalida");
		document.myform.new_password.focus();
	}
	else if (!validaPass(new_password2))
	{
		alert ("La nueva contraseña ingresada contiene caracteres o longitud invalida");
		document.myform.new_password2.focus();
	}
	else if (new_password!=new_password2)
	{
		alert ("Las contraseñas son diferentes");
		document.myform.new_password2.focus();
	}
	else
	{
	document.myform.submit ();		
	}
}
//*************************************Olvide password*******************************************
function olvide_pws()
{
	var email=document.getElementById("email");
	var usuario=document.getElementById("usuario");	

	
	var email=email.value;
	var usuario=usuario.value;	

	
 if (!isEmail(email))
	{
		alert ("Debe introducir un email correcto");
		document.myform.email.focus();
	}
	else if (!validaIngreso(usuario))
	{
		alert ("La nueva contraseña ingresada contiene caracteres o longitud invalida");
		document.myform.usuario.focus();
	}
	else
	{
	document.myform.submit ();		
	}
}


//*************************************modificar usuario*******************************************
function modificar_usuario ()
{

	var email=document.getElementById("email");	
	var email=email.value;

 if (!isEmail(email))
	{
		alert ("Debe introducir un email correcto");
		document.myform.email.focus();
	}else
	{
	document.myform.submit ();	
		
	}

}

//*******************************************nuevo registro de usuario**********************************************

function nuevoEvento(evento)
{
	var divMensaje=document.getElementById("mensaje");

	/* Dependiendo de cual sea el evento que ejecuto esta funcion (ingreso o verificacion) se setean
	distintas variables */	
	
	var input=document.getElementById("verificacion");
	var pass1=document.getElementById("pass1");
	var pass2=document.getElementById("pass2");	
	var ano=document.getElementById("ano");	
	var email=document.getElementById("email");	
	var select_0=document.getElementById("select_0");	
	var select_1=document.getElementById("select_1");	
	var deportes=document.getElementById("deportes");

	//var competicion=document.getElementById("competicion"); //el id de deportes de competicion
	var cont_deportes=document.getElementById("cont_deportes");  // el numero de checbox de deporte	
	var aceptocondicion=document.getElementById("aceptocondicion"); 
	
	var boton=document.getElementById("boton_1");
	
var index;
var contradio=0;
for (index=0;index<document.myform.sexo.length;index++)
{
	if (document.myform.sexo[index].checked==true) 
	{
	var sexo=document.myform.sexo[index].value;
	contradio++;
	}
}
for (index=0;index<document.myform.noticias.length;index++)
{
	if (document.myform.noticias[index].checked==true) 
	{
	var noticias=document.myform.noticias[index].value;
	}
}

for (index=0;index<document.myform.torneos.length;index++)
{
	if (document.myform.torneos[index].checked==true) 
	{
	var torneos=document.myform.torneos[index].value;
	}
}
for (index=0;index<document.myform.competir.length;index++)
{
	if (document.myform.competir[index].checked==true) 
	{
	var competir=document.myform.competir[index].value;
	}
}	

	var valor=input.value;
	var pass1=pass1.value;
	var pass2=pass2.value;	
	var ano=ano.value;
	var email=email.value;	
	var select_0=select_0.value;
	var select_1=select_1.value;
	var deportes=deportes.value;
	var cont_deportes=cont_deportes.value;
	var aceptocondicion=aceptocondicion.value;
	var accion="Ingresando...";		
	// Elimino espacios por delante y detras de lo que has introducido por el usuario
	valor=eliminaEspacios(valor);
	// Si el ingreso es invalido...

var elementos;
var x;
var contchec=0;
elementos="";
for (i=0;x=document.getElementById("compite_" + i);i++) 
{	
	
	if (x.checked == true)
	{
	var chec=document.getElementById("compite_" + i).value;
	elementos=elementos+chec+"-";
	contchec++;
	}
//alert (elementos);	
//alert (contchec);	

}
	

	if(!validaIngreso(valor)) 
	{
		divMensaje.innerHTML="El usuario que has introducido contiene caracteres o longitud invalida";
		alert ("El usuario que has introducido contiene caracteres o longitud invalida. Mínimo 5 caracteres");
		document.myform.verificacion.focus();
	}
	else if (!validaPass(pass1))
	{
		divMensaje.innerHTML="La contraseña ingresada contiene caracteres o longitud invalida";
		alert ("La contraseña que has introducido contiene caracteres o longitud invalida. Mínimo 5 caracteres");
		document.myform.pass1.focus();
	}
	else if (!validaPass(pass2))
	{
		divMensaje.innerHTML="La contraseña ingresada contiene caracteres o longitud invalida";
		alert ("La contraseña que has introducido contiene caracteres o longitud invalida");
		document.myform.pass2.focus();
	}
	else if (pass1!=pass2)
	{
		divMensaje.innerHTML="Las contraseñas son diferentes";
		alert ("Las contraseñas que has introducido son diferentes");
		document.myform.pass1.focus();
	}
	else if  (contradio==0)
		{
		alert ("Debe introducir un sexo hombre o mujer");
		divMensaje.innerHTML="Debe introducir un sexo hombre o mujer";
		}
	else if (!isEmail(email))
	{
		divMensaje.innerHTML="Debe introducir un email correcto";
		alert ("Debe introducir un email correcto");
		document.myform.email.focus();
	}
	else if (!validaIngreso(email))
	{
		divMensaje.innerHTML="Debe introducir un email correcto";
		alert ("El email debe contener caracteres correctos, ni acentos ni ñ");
		document.myform.email.focus();
	}
	else if ((contchec==0) && (competir==1))
	{
		alert ("Debe introducir un deporte preferido");
		divMensaje.innerHTML="Debe introducir un deporte en competición";

	}
	else
	{	
		divMensaje.innerHTML="";
	  if (Verificarusuario ())
	  {		
	    	if (document.myform.aceptocondicion.checked==1) // chequea que no repita dos veces insertar usuario
				{
									
			// Deshabilito inputs y botones para evitar dobles ingresos
			boton.disabled=true; input.disabled=true;
			input.value=accion;
			var ajax=nuevoAjax();
	
			ajax.open("POST", "comprobar_disponibilidad_de_apodo_proceso.php", true);
			ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//			encodeURIComponent
			ajax.send("ingreso="+valor+"&pass1="+pass1+"&pass2="+pass2+"&sexo="+sexo+"&email="+email+"&noticias="+noticias+"&torneos="+torneos+"&competir="+competir+"&elementos="+elementos+"&cont_deportes="+contchec+"&ano="+ano+"&select_0="+select_0+"&select_1="+select_1+"&deportes="+deportes);
//			ajax.send(pass1+"="+pass1);
			ajax.onreadystatechange=function()
			{
				if (ajax.readyState==4)
				{
					// Habilito nuevamente botones e inputs
					input.value="";
					boton.disabled=false; input.disabled=false;
					// Muestro el mensaje enviado desde el servidor
					//location.href='';
					//location.href='usuarioregistrado.php?usuario='+valor+'&email='+email;
					var opcionlink=ajax.responseText;
					//alert (opcionlink);
					if (opcionlink=="Usuario ya registrado, intentelo con otro usuario por favor")
					{
					alert ("Usuario ya registrado, intentelo con otro usuario por favor");
					}
					else
					{	
						location.href='usuarioregistrado.php?usuario='+valor+'&email='+email;
						
					}
					divMensaje.innerHTML=opcionlink;
					
					
				}
			}
		 } // chequeado
	  }//verificarusuario
	}
}

function ComprobarEvento(evento)
{
	var divMensaje=document.getElementById("mensaje");

	/* Dependiendo de cual sea el evento que ejecuto esta funcion (ingreso o verificacion) se setean
	distintas variables */	

		var input=document.getElementById("verificacion");
		var boton=document.getElementById("boton_2");
		var valor=input.value;
		var accion="Comprobando...";

	// Elimino espacios por delante y detras de lo que has introducido por el usuario
	valor=eliminaEspacios(valor);
	// Si el ingreso es invalido...
	if(!validaIngreso(valor)) 
	{
		//divMensaje.innerHTML="El texto que has introducido contiene caracteres o longitud invalida";
		alert ("El nombre que has introducido contiene caracteres o longitud invalida");
	}
	else
	{

			
		// Deshabilito inputs y botones para evitar dobles ingresos
		boton.disabled=true; input.disabled=true;
		input.value=accion;
		var ajax=nuevoAjax();

		ajax.open("POST", "comprobar_disponibilidad_de_apodo_proceso.php", true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send(evento+"="+valor);
		
		ajax.onreadystatechange=function()
		{
			if (ajax.readyState==4)
			{
				// Habilito nuevamente botones e inputs
				input.value="";
				boton.disabled=false; input.disabled=false;
				// Muestro el mensaje enviado desde el servidor
				divMensaje.innerHTML=ajax.responseText;
				input.value=valor;
				//document.myform.verificacion="lala";
			}
		}

	}
}

//****************************************Login***********************************************

function login_usuario ()
{
	var username=document.getElementById("username");
	var password=document.getElementById("password");

	
	var username=username.value;
	var password=password.value;
	
 	if (!validaIngreso(username))
	{
		alert ("El usuario que has introducido contiene caracteres o longitud invalida");
		document.myform.username.focus();
	}
	else if (!validaPass(password))
	{
		alert ("El Password que has introducido contiene caracteres o longitud invalida");
		document.myform.password.focus();
	}
	else
	{
	document.myform.submit ();	
		
	}

}

// ---------------------------------CALENDARIO------------------------------------ //
var oldLink = null;

// code to change the active stylesheet

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked && (cal.sel.id == "sel2" || cal.sel.id == "sel3"))
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
    cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  calendar = null;
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (calendar != null) {
    // we already have some calendar created
    calendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(true, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    calendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  calendar.setDateFormat(format);    // set the specified date format
  calendar.parseDate(el.value);      // try to parse the text in field
  calendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  calendar.showAtElement(el.nextSibling, "Br");        // show the calendar

  return false;

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;
}




// ---------------------------------------------------------------------- //
//                                Ajax                               //
// ---------------------------------------------------------------------- //
function nuevoAjax2()
{ 
	/* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
	lo que se puede copiar tal como esta aqui */
	var xmlhttp=false;
	try
	{
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			// Creacion del objet AJAX para IE
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(E)
		{
			if (!xmlhttp && typeof XMLHttpRequest!='undefined') xmlhttp=new XMLHttpRequest();
		}
	}
	return xmlhttp; 
}

// Declaro los selects que componen el documento HTML. Su atributo ID debe figurar aqui.
var listadoSelects=new Array();
listadoSelects[0]="select1";
listadoSelects[1]="select2";
listadoSelects[2]="select3";

function buscarEnArray(array, dato)
{
	// Retorna el indice de la posicion donde se encuentra el elemento en el array o null si no se encuentra
	var x=0;
	while(array[x])
	{
		if(array[x]==dato) return x;
		x++;
	}
	return null;
}



function cargaContenido2(idSelectOrigen)
{
	// Obtengo la posicion que ocupa el select que debe ser cargado en el array declarado mas arriba
	//alert (idSelectOrigen);
	var posicionSelectDestino=buscarEnArray(listadoSelects, idSelectOrigen)+1;
	// Obtengo el select que el usuario modifico
	var selectOrigen=document.getElementById(idSelectOrigen);
	// Obtengo la opcion que el usuario selecciono
	var opcionSeleccionada=selectOrigen.options[selectOrigen.selectedIndex].value;
	// Si el usuario eligio la opcion "Elige", no voy al servidor y pongo los selects siguientes en estado "Selecciona opcion..."
	if(opcionSeleccionada==0)
	{
		var x=posicionSelectDestino, selectActual=null;
		// Busco todos los selects siguientes al que inicio el evento onChange y les cambio el estado y deshabilito
		while(listadoSelects[x])
		{
			selectActual=document.getElementById(listadoSelects[x]);
			selectActual.length=0;
			
			var nuevaOpcion=document.createElement("option"); nuevaOpcion.value=0; nuevaOpcion.innerHTML="Selec Opci&oacute;n...";
			selectActual.appendChild(nuevaOpcion);	selectActual.disabled=true;
			x++;
		}
	}
	// Compruebo que el select modificado no sea el ultimo de la cadena
	else if(idSelectOrigen!=listadoSelects[listadoSelects.length-1])
	{
		// Obtengo el elemento del select que debo cargar
		var idSelectDestino=listadoSelects[posicionSelectDestino];
		var selectDestino=document.getElementById(idSelectDestino);
		// Creo el nuevo objeto AJAX y envio al servidor el ID del select a cargar y la opcion seleccionada del select origen
		var ajax=nuevoAjax2();
		ajax.open("GET", "../usuario/select_dependientes_3_niveles_proceso.php?select="+idSelectDestino+"&opcion="+opcionSeleccionada, true);
		ajax.onreadystatechange=function() 
		{ 
			if (ajax.readyState==1)
			{
				// Mientras carga elimino la opcion "Selecciona Opcion..." y pongo una que dice "Cargando..."
				selectDestino.length=0;
				var nuevaOpcion=document.createElement("option"); nuevaOpcion.value=0; nuevaOpcion.innerHTML="Cargando...";
				selectDestino.appendChild(nuevaOpcion); selectDestino.disabled=true;	
			}
			if (ajax.readyState==4)
			{
				selectDestino.parentNode.innerHTML=ajax.responseText;
			} 
		}
		ajax.send(null);
	}
}
//************************************************PARA DOS PROVINCIAS************************************************************


function nuevoAjax()
{ 
	/* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
	lo que se puede copiar tal como esta aqui */
	var xmlhttp=false; 
	try 
	{ 
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch(e)
	{ 
		try
		{ 
			// Creacion del objet AJAX para IE 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest(); } 

	return xmlhttp; 
}

function cargaContenido() // provincias
{
	var valor=document.getElementById("select_0").options[document.getElementById("select_0").selectedIndex].value;
	if(valor==0)
	{
		// Si el usuario eligio la opcion "Elige", no voy al servidor y pongo todo por defecto
		combo=document.getElementById("select_1");
		combo.length=0;
		var nuevaOpcion=document.createElement("option"); nuevaOpcion.value=0; nuevaOpcion.innerHTML="Selecciona zona...";
		combo.appendChild(nuevaOpcion);	combo.disabled=true;
	}
	else
	{
		ajax=nuevoAjax();
		ajax.open("GET", "select_dependientes_proceso.php?seleccionado="+valor, true);
		ajax.onreadystatechange=function() 
		{ 
			if (ajax.readyState==1)
			{
				// Mientras carga elimino la opcion "Elige pais" y pongo una que dice "Cargando"
				combo=document.getElementById("select_1");
				combo.length=0;
				var nuevaOpcion=document.createElement("option"); nuevaOpcion.value=0; nuevaOpcion.innerHTML="Cargando...";
				combo.appendChild(nuevaOpcion); combo.disabled=true;	
			}
			if (ajax.readyState==4)
			{ 
				document.getElementById("fila_2").innerHTML=ajax.responseText;
			} 
		}
		ajax.send(null);
	}
}
