/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function formInscripcion(estado){
    var gko = navigator.userAgent.toLowerCase();
    elemento=document.getElementById("btnInscripcion");
    nuevoEstado="";
    if (estado =="Abrir"){
        $("#contenedor").slideDown("slow");
        nuevoEstado = "Cerrar";
    } else {
        $("#contenedor").slideUp("slow");
        nuevoEstado = "Abrir";
    }
    if (gko.indexOf('gecko')!=-1) //si soporta gecko, es Mozilla, Netscape, Safari, etc
    elemento.setAttribute("onclick","formInscripcion('"+nuevoEstado+"');");//hacemos el setAttribute normalmente
    else //es I Explroer
    elemento['onclick']=new Function("formInscripcion('"+nuevoEstado+"');");//creamos en setAttribute de esta forma
    if (estado =="Abrir"){
        document.getElementById('dniBuscar').focus();
    }
}
function trim(cadena)
{
	var i=0;
	
    for(i=0; i<cadena.length; )
    {
        if(cadena.charAt(i)==" ")
            cadena=cadena.substring(i+1, cadena.length);
        else
            break;
    }

    for(i=cadena.length-1; i>=0; i=cadena.length-1)
    {
        if(cadena.charAt(i)==" ")
            cadena=cadena.substring(0,i);
        else
            break;
    }
    
    return cadena;
}

function contar(texto, letra){
	var i=0;
	var cont = 0;
	 for(i=0;i<texto.length;i++){
	   let = texto.substring(i,(i+1));
	   if (letra == let){
	      cont = cont+1;
	   }
	}
	return cont;
}
function campoCubierto(campo){
    error =false;
    var gko = navigator.userAgent.toLowerCase();
   // contenedor =document.getElementById("div_"+campo);

    var elemento =document.getElementById(campo);
    //var contenedor = document.getElementById("div_"+campo);
    
    switch(campo){
        case "email":
            error = !isMail(elemento.value);
            if (error == true){
                if (elemento.value == ""){
                    error = false;
                }
            }
            break;
        case "apellidos":
        	if (contar(trim(elemento.value)," ") >= 1){
        		error = false;
        	} else {
        		error = true;
        	}
        	break;
        case "licencia":
            if (elemento.checked != "checked") {
                error = true;
            }
            break;
        case "telefono": case "movil":
            elemento =document.getElementById("telefono");
            if (elemento.value == "" && document.getElementById("movil").value == ""){
                error = true;
            }
            break;
        default:
            if (elemento.value == "") {
                error=true;
            } else {
                error = false;
            }
            break;
    }

    if (error == true) {
        if (gko.indexOf('gecko')!=-1){ //si soporta gecko, es Mozilla, Netscape, Safari, etc
            elemento.setAttribute("class","errorInscripcionActivo");//hacemos el setAttribute normalmente
        } else {//es I Explroer
            elemento.setAttribute("className","errorInscripcionActivo");
        }
    } else {
        if (gko.indexOf('gecko')!=-1) //si soporta gecko, es Mozilla, Netscape, Safari, etc
            elemento.setAttribute("class","errorInscripcion");//hacemos el setAttribute normalmente
        else //es I Explroer
            elemento.setAttribute("className","errorInscripcion");//creamos en setAttribute de esta forma
    }
    return error;
}

function calc() {
	//window.onload = function () {document.compra.submit();}
    //vent=window.open('','tpv','width=725,height=600,scrollbars=yes,resizable=yes,status=yes,menubar=no,location=no');
    //document.compra.submit();
    //window.open('inscripcion.php','_self');
	window.name="tpv";
	document.compra.submit();
}

function enviarDatos(){
   // var resp;
    var tipoLicencia;
    var envio = true;
    var error = false;
//    error = campoCubierto("codigo");
//    if (error == true) envio = false;
    error = campoCubierto("dni");
    if (error == true){envio = false;}

    error = campoCubierto("nombre");
    if (error == true){envio = false;}

    error = campoCubierto("apellidos");
    if (error == true){envio = false;}

    error = campoCubierto("ano");
    if (error == true){envio = false;}

    error = campoCubierto("direccion");
    if (error == true){envio = false;}

    error = campoCubierto("cpostal");
    if (error == true){envio = false;}

    error = campoCubierto("localidad");
    if (error == true){envio = false;}

    error = campoCubierto("provincia");
    if (error == true){envio = false;}

    if (campoCubierto("telefono") == true && campoCubierto("movil") == true){
        envio = false;
    }
    error = campoCubierto("maillot");
    if (error == true){envio = false;}

    error = campoCubierto("email");
    if (error == true){envio = false;}
    desactivoAviso=false;
    if (!document.getElementById("lopd").checked){
        envio=false;
        alert("Para poder tramitar su inscripción, es necesario que acepte las condiciones.");
        desactivoAviso = true;
    }

//  Envio siempre false porque ??
    if (envio == false){
        if (desactivoAviso == false){
           alert("¡¡¡ ATENCIÓN !!!\nExisten campos sin cubrir que son obligatorios para continuar con la inscripción.\nPor favor cubra los campos que le aparecen en rojo.");
        }
    } else {
        conLicencia=0;
        if (document.getElementById("licenciaSi").checked){
            tipoLicencia ="Con Licencia Federativa";
            conLicencia=1;
        } else {
            tipoLicencia="Sin Licencia Federativa";
        }
        if(confirm ("Usted ha escogido la modalidad:\n Inscripción "+tipoLicencia+"\n¿Es correcto?")){
            
            //xajax_graboParticipante(xajax.getFormValues('formInscripcion'));

            xajax_tpvVirtual(xajax.getFormValues('formInscripcion',1), conLicencia);
            
        }
    }


    //else {
    //    document.getElementById('errorDe').style.display=OCULTO;
    //}
//
//    if (document.getElementById("asunto").value == "" || document.getElementById("asunto").value == "<Asunto>"){
//        document.getElementById('errorAsunto').style.display=VISIBLE;
//        envio = false;
//    } else {
//        document.getElementById('errorAsunto').style.display=OCULTO;
//    }
//
//    if (envio == true) {
//        document.getElementById('enviando').style.display=VISIBLE;
//        xajax_enviarPhpCorreo(document.getElementById("de").value,document.getElementById("asunto").value,document.getElementById("texto").value);
//    }
    return envio;
}
function activoBuscar(estado){
    OCULTO="none";
    VISIBLE="block";
    if (estado == 0){
        document.getElementById('buscar').style.display=OCULTO;
        //document.getElementById('federado').value="";
    } else {
        document.getElementById('buscar').style.display=VISIBLE;
    }
}
function comprueboBuscar(){
    OCULTO="none";
    VISIBLE="block";
    var ok=true;
    var error=false;
   // var dorsal=false;
   // if (document.getElementById('marchaAnterior').value=='si'){
        error=campoCubierto('dniBuscar');
   //     dorsal=campoCubierto('dorsalBuscar');
   //     if (dni == false || dorsal == false){
        if (error == true){
            ok =false;
        }
    //}
    if (ok == true) {
        /*document.getElementById('paso1').style.display=OCULTO;
        document.getElementById('paso2').style.display=VISIBLE;
        document.getElementById('imgPasos').src="inscripcion/form2.gif";
        document.getElementById('dni').value=document.getElementById('dniBuscar').value;
        document.getElementById('nombre').focus();*/
        xajax_botonInscripcion('paso2',document.getElementById('dniBuscar').value);
    } else {
        alert ("Cubra los datos para continuar");
        document.getElementById('dniBuscar').focus();
    }
}

function comprueboTextoInicial(campo, e)
{
    var ok = true;
    var Key=(e.charCode)?e.charCode:e.keyCode;
    if (Key==8) {
        if (document.getElementById(campo).value.length == 1) {
            document.getElementById(campo).value = "<Introduduzca su correo electrónico>";
            document.getElementById(campo).color=red;
            ok=false;
        }
    }
    return ok;
}
function limpiarCampo(campo)
{
    document.getElementById(campo).value ="";
    document.getElementById(campo).removeAttribute("onfocus");
}

function comprobarCampo(campo)
{
    if (document.getElementById(campo).value == "") {
        document.getElementById(campo).value = "<Intoduzca su correo electrónico>";
        //Creacion del evento onfocus comprobando el navegador para que carge bien
        var gko = navigator.userAgent.toLowerCase();
        elemento=document.getElementById(campo);
        if (gko.indexOf('gecko')!=-1) //si soporta gecko, es Mozilla, Netscape, Safari, etc
        elemento.setAttribute("onfocus","limpiarCampo('"+campo+"');");//hacemos el setAttribute normalmente
        else //es I Explroer
        elemento['onfocus']=new Function("limpiarCampo('"+campo+"');");//creamos en setAttribute de esta forma
    }
}
function cambioImagen(campo, img){
    document.getElementById(campo).src = img;
}


function validar(tipo, e, obj){
    // tipo => 'n'=Numero
    // tipo => ''= Normal
    tecla = (document.all)?e.keyCode:e.which;
    var i=0;
    switch(tecla){
        case 8:
            valor= true;
            break;
        case 0:
            valor= true;
            break;
        case 13:
            frm=obj.form;
            for(i=0;i<frm.elements.length;i++)
              if(frm.elements[i]==obj) {
                if (i==frm.elements.length-1) i=-1;
                break;
              }
            frm.elements[i+1].focus();
            valor = false;
            break;
        default:
        	switch (tipo){
        	case 'n':
                patron = /\d/; //Patron solo para pasar numeros
                te = String.fromCharCode(tecla);
                valor = patron.test(te);
        		break;
        	case 'p':
        		patron=/^[0-9]{1,5}(\.[0-9]{0,2})?$/; //Patron 99999.99
        		te=obj.value  + String.fromCharCode(tecla);
        		valor=patron.test(te);
        		break;
        	default:
        		valor = true;
        		break;
        	}
    }

    return valor;
}

function isMail(Cadena) {

	Punto = Cadena.substring(Cadena.lastIndexOf('.') + 1, Cadena.length);			// Cadena del .com
	Dominio = Cadena.substring(Cadena.lastIndexOf('@') + 1, Cadena.lastIndexOf('.')); 	// Dominio @lala.com
	Usuario = Cadena.substring(0, Cadena.lastIndexOf('@'));					// Cadena lalala@
	Reserv = "@/ï¿½\"\'+*{}\\<>?ï¿½[]ï¿½ï¿½ï¿½ï¿½ï¿½#ï¿½ï¿½!^*;,:";						// Letras Reservadas

	// Aï¿½adida por El Codigo para poder emitir un alert en funcion de si email valido o no
	valido = true;
    var Cont =0;
	// verifica qie el Usuario no tenga un caracter especial
	for (Cont=0; Cont<Usuario.length; Cont++) {
		X = Usuario.substring(Cont,Cont+1);
		if (Reserv.indexOf(X)!=-1)
                	valido = false;
	}

	// verifica qie el Punto no tenga un caracter especial
	for (Cont=0; Cont<Punto.length; Cont++) {
		X=Punto.substring(Cont,Cont+1);
		if (Reserv.indexOf(X)!=-1)
			valido = false;
	}

	// verifica qie el Dominio no tenga un caracter especial
	for (Cont=0; Cont<Dominio.length; Cont++) {
		X=Dominio.substring(Cont,Cont+1);
		if (Reserv.indexOf(X)!=-1)
			valido = false;
		}

	// Verifica la sintaxis bï¿½sica.....
	if (Punto.length<2 || Dominio <1 || Cadena.lastIndexOf('.')<0 || Cadena.lastIndexOf('@')<0 || Usuario<1) {
		valido = false;
	}

    return valido;
}
function imprSelec(nombre)
{
  //window.name="cccastro";
  //var Padre = window.opener();	
  var ficha = document.getElementById(nombre);
  var ventimp = window.open('','popimpr','width=400,height=600,scrollbars=yes,resizable=yes,status=yes,menubar=no,location=no');
  ventimp.document.write( ficha.innerHTML );
  ventimp.document.close();
  ventimp.print( );
  ventimp.close();
  //window.open("inscripcion.php","cccastro");
  window.open('inscripcion.php','_self');
}

function buscarListado(){
    var filtro=$('#filtro').val();
    var tam=$('#tamPagina').val();
    var privado=$('#tipoListado').val();
    var id=$('#idListado').val();
    xajax_listado('si', '1', tam, filtro, privado, id);
}

function procesolistado(pagina){
    var filtro=$('#filtro').val();
    var tam=$('#tamPagina').val();
    var privado=$('#tipoListado').val();
    var id=$('#idListado').val();
    xajax_listado('si',pagina,tam,filtro,privado,id);

}




