/***************************************************************************************************************/
/*Función que muestra y oculta datos                                                                           */
/***************************************************************************************************************/
function muestra_oculta(id){
	if(document.getElementById(id) != null){
	if(document.getElementById(id).style.display == "none"){
		document.getElementById(id).style.display="";
	}
	else document.getElementById(id).style.display="none";
	}
	
}
function muestra(id){
   if(document.getElementById(id) != null) document.getElementById(id).style.display="";
}

function oculta(id){
   if(document.getElementById(id) != null) document.getElementById(id).style.display="none";
}
/***************************************************************************************************************/
/*Función abrir nueva ventana                                                                                  */
/***************************************************************************************************************/
function Abrir_ventana (pagina,anchura,altura,scroll) {
    var opciones="toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars="+scroll+", resizable=no, width="+anchura+", height="+altura+", top=85, left=140";
    window.open(pagina,"",opciones);
}
/***************************************************************************************************************/
/*Función abre nueva ventana e imprime el contenido                                                                                 */
/***************************************************************************************************************/
function imprSelec(nombre){
  var ficha = document.getElementById(nombre);
  var ventimp = window.open(' ', 'popimpr');
  
  ventimp.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n');
  ventimp.document.write('<html xmlns="http://www.w3.org/1999/xhtml">\n');
  ventimp.document.write('<head><title>AFADA</title>\n');
  ventimp.document.write('<link href="templates/afada/css/estilos.css" rel="stylesheet" type="text/css"/>\n');
  ventimp.document.write('<style type="text/css">.nover {display:none}</style>\n'); 
  ventimp.document.write('<style type="text/css">@media print { .nover {display:none}}</style>\n');
  ventimp.document.write( '<body>\n' ); 
  ventimp.document.write( ficha.innerHTML );
  ventimp.document.write( '</body>\n</html>\n' ); 
  ventimp.document.close();
  ventimp.print( );
  ventimp.close();
}
/***************************************************************************************************************/
/*Función para agregar a favoritos                                                                             */
/***************************************************************************************************************/
function Favoritos(titulo,url) {
        if (window.sidebar) {
               window.sidebar.addPanel(titulo, url,"");
        } 
        else if( document.all ) {
               window.external.AddFavorite( url, titulo);
        } 
        else if( window.opera && window.print ) {
               return true;
         }
 }
/***************************************************************************************************************/
/*Función para comprobar correo                                                                           */
/***************************************************************************************************************/ 
 function comprueba_mail(mail) {
  var re_mail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
  if (re_mail.test(mail)) {
    return true;
  } else {
    alert(mail + " no es una dirección de correo válida.");
    return false;
  }
}
/**************** Función para comprobar que un campo no esté en blanco ****************/

function CompruebaBlanco(Campo, NombreCampo) {

  if (Campo == "") {

    alert('El campo ' + NombreCampo + ' es obligatorio');
    return false;

  } else {

    return true;

  }
}
function noVacio(Campo){
   
   if (Campo != "") return true;
       
}
/*************************************************************************************************/
/*funcion que valida CCC                                                                          */
/*************************************************************************************************/
function validarCCC(cc1,cc2,cc3,cc4){
       
         var str_error = "";
         var arrCC = new Array(document.getElementById(cc1), document.getElementById(cc2),
                               document.getElementById(cc3), document.getElementById(cc4));
         /*if (arrCC[0].value=='' && arrCC[1].value=='' && arrCC[2].value=='' & arrCC[3].value=='')
      return true;  */
            /*
             * Si algún campo no ha sido completado satisfactoriamente cambiar su estilo,
             * darle el foco y mostrar el error
            */
         if (arrCC[0].value.length != 4){ 
      str_error = "No ha completado todos los datos";
          arrCC[0].focus();
     }
         if (arrCC[1].value.length != 4){ 
      str_error = "No ha completado todos los datos";
          arrCC[1].focus();
     }
         if (arrCC[2].value.length != 2){ 
      str_error = "No ha completado todos los datos";
          arrCC[2].focus();
     }
         if (arrCC[3].value.length != 10){
      str_error = "No ha completado todos los datos";
          arrCC[3].focus();
     }
         
         if ("" != str_error) {
          alert (str_error);
          return;
     }
         
   /*
    * Comprobar la cuenta corriente introducida
   */
      if(arrCC[2].value=='**') return true;
      
      if (checkDC(arrCC[0].value+arrCC[1].value,arrCC[3].value,arrCC[2].value))
       return true;
      else
       alert ("La cuenta corriente introducida no es correcta.\nPor favor, compruebe los datos.");
         
  } // end validate()
  
  
  /**
   * Validación de una cuenta corriente
   * 
   * Comprueba un número de cuenta corriente
   *
   * IN:  cc1  string  Primeros ocho dígitos de la cuenta corriente (entidad.oficina)
   * IN:  cc2  string  Últimos diez dígitos de la cuenta corriente  (#cuenta)
   * IN:  dc   string  Dígitos de control
   * OUT:      bool    ¿Cuenta válida? 
  */
  function checkDC(cc1,cc2,dc){
            
   /*
    * Comprobar que los datos son correctos
   */
       if (!(cc1.match(/^\d{8}$/) && cc2.match(/^\d{10}$/) && dc.match(/^\d{2}$/) )) return false;
            
       var arrWeights = new Array(1,2,4,8,5,10,9,7,3,6); // vector de pesos
       var dc1=0, dc2=0;
            
      /*
       * Cálculo del primer dígito de cintrol
      */
         for (i=7;i>=0;i--) dc1 += arrWeights[i+2] * cc1.charAt(i);
      dc1 = 11 - (dc1 % 11);
        if (11 == dc1) dc1 = 0;
         if (10 == dc1) dc1 = 1;
            
         /*
          * Cálculo del segundo dígito de control
         */
         for (i=9;i>=0;i--) dc2 += arrWeights[i] * cc2.charAt(i);
      dc2 = 11 - (dc2 % 11);
         if (11 == dc2) dc2 = 0;
      if (10 == dc2) dc2 = 1;
      /*
       * Comprobar la coincidencia y delvolver el resultado
      */
      return (10*dc1+dc2 == dc); // Javascript infiere tipo entero para dc1 y dc2
       
  } // end checkDC()

/*************************************************************************************************/
/*funcion Valida CP                                                                                 */
/*************************************************************************************************/
function validarCP(cp){
    result = "";
    if (!validarInt(cp)){
        result = "El Codigo Postal solo se compone de numeros.";
    }
    else {
        if (cp.length != 5){
            result = "El Codigo Postal solo se compone de 5 digitos";
        }
    }
    return result;
}

/*************************************************************************************************/
/*funcion Valida enteros                                                                         */
/*************************************************************************************************/
function validarInt (numeroEntero){
        /*if (numeroEntero >32767) {
            alert("El numero introducido es demasiado grande");
            return false;
        }*/
    expr = /^\d+$/;
    if (expr.test(numeroEntero)) {
        return true;
    }
    else {
        return false;
    }
}

/*************************************************************************************************/
/*funcion Valida Telefono                                                                         */
/*************************************************************************************************/
function validarTelefono(telf){
    if (telf.length<9){
        return "no puede tener menos de 9 cifras";
    }
    var correcto="";
    for (var i=0;i<=telf.length;i++) {
        if (isNaN(telf.substring(i,i+1))){
            correcto+=telf.substring(i,i+1);
        }
    }
    return correcto;
}

//Devuelve el código de la tecla pulsada
function codigo_tecla() {
  var Navegador = (window.Event) ? 1 : 0
  var codigo = Navegador ? evento.which : event.keyCode
  return codigo;
}


// sólo deja introducir números
function esNumero(){
    //comprueba_tecla();
     var tecla = codigo_tecla();
     //alert(tecla);
     if (tecla == 8 || tecla==46 || tecla==110 || tecla==190 || tecla == 9) event.returnValue=true;
     else if (tecla >= 47 && tecla<=57) event.returnValue=true;
     else if (tecla >= 96 && tecla<=105) event.returnValue=true;
     else event.returnValue=false;
    //if (event.keyCode == 46 || event.keyCode == 8) event.returnValue=true;
 // if ( (event.keyCode < 47 || event.keyCode > 57)) event.returnValue = false;
}

function validar_contacto(obj){
    var frmName = document.getElementById('form').value;
    var formulario = eval( 'document.forms.' + frmName );
    //var message="Los siguientes campos no son válidos:\n";
    var conformidad = document.getElementById('conformidad');  
    var nombre = document.getElementById('nombre').value;
    var email = document.getElementById('email').value;
    var asunto = document.getElementById('asunto').value;
    var mensaje = document.getElementById('mensaje').value;
   if(conformidad.checked){
        if(CompruebaBlanco(nombre, 'Nombre') && comprueba_mail(email) && CompruebaBlanco(asunto, 'Asunto') && CompruebaBlanco(mensaje, 'Mensaje')){       
            formulario.submit();
        } 
   }
   else alert('Debe marcar la pestaña de conformidad');
}

//******************* Función para mostrar textos en toolTip y Status *******************

function TextosMouseOver(Alt) {
 
  toolTip(Alt);

  window.status = '::' + Alt;

}

//******************* Función para ocultar textos en toolTip y Status *******************

function TextosMouseOut() {

  toolTip();
  window.status = '';

}
function valida_nif_cif_nie(a) {
//Retorna: 1 = NIF ok, 2 = CIF ok, 3 = NIE ok, -1 = NIF error, -2 = CIF error, -3 = NIE error, 0 = ??? error
   
    var temp=a.toUpperCase();
    var cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";
    var letra = a.substr(8,1);
    letra = letra.toUpperCase();
    if (temp!==''){
        //si no tiene un formato valido devuelve error
        if ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp))
        {
            return 0;
        }
 
        //comprobacion de NIFs estandar
        if (/^[0-9]{8}[A-Z]{1}$/.test(temp))
        {
            posicion = a.substring(8,0) % 23;
            letra = cadenadni.charAt(posicion);
            var letradni=temp.charAt(8);
            if (letra == letradni)
            {
                   return 1;
            }
            else
            {
                return -1;
            }
        }
 
        //algoritmo para comprobacion de codigos tipo CIF
        suma = parseInt(a[2])+parseInt(a[4])+parseInt(a[6]);
        for (j = 1; j < 8; j += 2)
        {
            temp1 = 2 * parseInt(a[j]);
            temp1 += '';
            temp1 = temp1.substring(0,1);
            temp2 = 2 * parseInt(a[j]);
            temp2 += '';
            temp2 = temp2.substring(1,2);
            if (temp2 == '')
            {
                temp2 = '0';
            }
 
            suma += (parseInt(temp1) + parseInt(temp2));
        }
        suma += '';
        n = 10 - parseInt(suma.substring(suma.length-1, suma.length));
 
        //comprobacion de NIFs especiales (se calculan como CIFs)
        if (/^[KLM]{1}/.test(temp))
        {
            if (letra == String.fromCharCode(64 + n))
            {
                return 1;
            }
            else
            {
                return -1;
            }
        }
 
        //comprobacion de CIFs
        if (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp))
        {
            temp = n + '';
            if (letra == String.fromCharCode(64 + n) || a[8] == parseInt(temp.substring(temp.length-1, temp.length)))
            {
                return 2;
            }
            else
            {
                return -2;
            }
        }
 
        //comprobacion de NIEs
        //T
        if (/^[T]{1}/.test(temp))
        {
            if (letra == /^[T]{1}[A-Z0-9]{8}$/.test(temp))
            {
                return 3;
            }
            else
            {
                return -3;
            }
        }
 
        //XYZ
        if (/^[XYZ]{1}/.test(temp))
        {  
            pos = str_replace(['X', 'Y', 'Z'], ['0','1','2'], temp).substring(0, 8) % 23;
           
            if (letra == cadenadni.substring(pos, pos + 1))
            {
                return 3;
            }
            else
            {
                return -3;
            }
        }
    }
 
    return 0;
}
//funcion envioPOST para ajax
function envio_post(capa,pagina,parametros) {
        var frmName = document.getElementById('form').value;
        var formulario = eval( 'document.forms.' + frmName );  
        var variables = "";
        array_parametros = parametros.split('#');
    
        for(i=0;i<array_parametros.length;i++){
            
             if(formulario.elements[array_parametros[i]].value == undefined){//si sólo hay un elemento
                if(formulario.elements[array_parametros[i]][i].type == 'radio'){//compruebo si es un radio                   
                    for(j=0;j<formulario.elements[array_parametros[i]].length;j++){//recorro todas la opciones de radio                       
                        if(formulario.elements[array_parametros[i]][j].checked){//si esta checked recogo el valor
                            variables += array_parametros[i]+"="+formulario.elements[array_parametros[i]][j].value+"&";       
                            //alert(variables);
                        }
                    }                   
                }
                else{//si es un text      
                    variables += array_parametros[i]+"="+formulario.elements[array_parametros[i]][i].value+"&";
                }
             }
             else{
                variables += array_parametros[i]+"="+formulario.elements[array_parametros[i]].value+"&";
             }
            
        }
       
        variables = variables.substring(0,variables.length-1)
        //variables += "accion="+accion;
        
        // pagina = 'acciones.php?texto='+formulario.elements['texto'].value;
              
        FAjax(pagina,capa,variables,'post');
        
}
//******************** Función para comprobar que un mail sea válido ********************

function CompruebaMail(Mail) {

  var reMail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;

  if (reMail.test(Mail)) {

    return true;

  } else {

    alert(Mail + " no es una dirección de correo válida.");
    return false;

  }

}

/*************************************************************************************************/
/*funcion valida fecha con formato d-m-Y                                                     */
/*************************************************************************************************/
function IsNumeric(valor){ 
    var log=valor.length; var sw="S"; 
    for (x=0; x<log; x++){
        v1=valor.substr(x,1); 
        v2 = parseInt(v1); 
    //Compruebo si es un valor numérico 
        if (isNaN(v2)) { 
            sw= "N";
        } 
    } 
    if (sw=="S") {return true;} else { return false; } 
} 

//******************** Función para comprobar la fecha y formatearla ********************  

function FormateaFecha(fecha){
    var objfecha = fecha
    var primerslap=false; 
    var segundoslap=false; 
    var ahora = new Date();  
    var mensaje ="";
    var long = fecha.length; 
    var dia; 
    var mes; 
    var ano;
    var ano_actual = ahora.getFullYear(); 
    
    if ((long>=2) && (primerslap==false)) { 
        dia=fecha.substr(0,2); 
        if ((IsNumeric(dia)==true) && (dia<=31) && (dia!="00")) { fecha=fecha.substr(0,2)+"-"+fecha.substr(3,7); primerslap=true;
          
    
    } 
        else { 
            fecha="";         
            mensaje = "La Fecha ("+objfecha+") no es correcta";    
            primerslap=false;
        } 
    } 
    else{ 
        dia=fecha.substr(0,1); 
        if (IsNumeric(dia)==false){
            fecha=""; 
            mensaje = "La Fecha ("+objfecha+") no es correcta";   
        } 
        if ((long<=2) && (primerslap=true)) {
            fecha=fecha.substr(0,1);
            primerslap=false;
            mensaje = "La Fecha ("+objfecha+") no es correcta";    
            } 
    } 
    if ((long>=5) && (segundoslap==false)) {
        mes=fecha.substr(3,2);
        
        if ((IsNumeric(mes)==true) &&(mes<=12) && (mes!="00")) { 
            fecha=fecha.substr(0,5)+"-"+fecha.substr(6,4);
            segundoslap=true;
            
        } 
        else { 
            fecha=fecha.substr(0,3);
            segundoslap=false;
            mensaje = "La Fecha ("+objfecha+") no es correcta";   
        } 
    } 
    else { 
        if ((long<=5) && (segundoslap=true)) { 
            fecha=fecha.substr(0,4); 
            segundoslap=false; 
            mensaje = "La Fecha ("+objfecha+") no es correcta";   
        }
    } 
    if (long>=7){
        ano=fecha.substr(6,4);
        if (IsNumeric(ano)==false) { 
            fecha=fecha.substr(0,6);
            mensaje = "La Fecha ("+objfecha+") no es correcta";
        } 
        else { 
            if (long==10){ 
                
                if ((ano==0) || (ano<1900) || (ano>ano_actual+1)) { 
                    fecha=fecha.substr(0,6); 
                    mensaje = "La Fecha ("+objfecha+") no es correcta";   
                }
            }
            else    mensaje = "La Fecha ("+objfecha+") no es correcta";   
        } 
    } 
    
    if (long>=10){ 
    
        fecha=fecha.substr(0,10); 
        dia=fecha.substr(0,2); 
        mes=fecha.substr(3,2); 
        ano=fecha.substr(6,4); 
    // Año no viciesto y es febrero y el dia es mayor a 28 
        if ( (ano%4 != 0) && (mes ==02) && (dia > 28) ) { 
            fecha=fecha.substr(0,2)+"/";
            mensaje = "La Fecha ("+objfecha+") no es correcta";    
        }
       // mensaje = "La Fecha no es correcta"; 
    }
    if(mensaje !="") alert(mensaje); 
    else return true; 
} 
/****************************************************************************************************************/
/*Funcción que valida los formularios de las actividades em el frontend*/
/****************************************************************************************************************/
function ValidaActividades(){
    var OK = false;
    var objFoNomb = document.getElementById('FoNomb').value;
    var objFoApel = document.getElementById('FoApel').value;
    var objFoCnif = document.getElementById('FoCnif').value;
    var objFoTel1 = document.getElementById('FoTel1').value;
    var objFoMail = document.getElementById('FoMail').value;
    var objFoDire = document.getElementById('FoDire').value;
    var objFoCopo = document.getElementById('FoCopo').value;
    var objFoProv = document.getElementById('FoProv').value;
    var objFoPobl = document.getElementById('FoPobl').value;
    var objFoPais = document.getElementById('FoPais').value;
    //var objFoNac1 = document.getElementById('FoNac1').value;
    var conformidad = document.getElementById('conformidad');   
    var formulario = eval( 'document.forms.factividades' ); 
    
    result = validarCP(objFoCopo)
    if(conformidad.checked){
       
        if(CompruebaBlanco(objFoNomb,'Nombre') && CompruebaBlanco(objFoApel,'Apellidos')  && CompruebaBlanco(objFoDire,'Dirección') && CompruebaBlanco(objFoCopo,'Código postal') && CompruebaBlanco(objFoProv,'Provincia') && CompruebaBlanco(objFoPobl,'Población') && CompruebaBlanco(objFoPais,'Pais') && CompruebaBlanco(objFoCnif,'Nif/Cif') && CompruebaBlanco(objFoTel1,'Teléfono') && CompruebaBlanco(objFoMail,'Correo') ) OK= true; else return false;   
        
        
        if(result != "") {alert(result); return false;} else  OK = true;  
        
        //if(esNIF(objFoCnif)) OK= true; else return false;
        if(valida_nif_cif_nie(objFoCnif)== 1 || valida_nif_cif_nie(objFoCnif)== 2 || valida_nif_cif_nie(objFoCnif)== 3) OK= true; else {alert('el DNI/nif/nie del titular es incorrecto');return false;  }
        if(validarInt(objFoTel1)) OK = true; else  {alert('El campo teléfono no es correcto');return false;}
        
        if(CompruebaMail(objFoMail)) OK = true; else return false;
        
        if(document.getElementById('FoCurs') != undefined){
            
            var objFoCurs = document.getElementById('FoCurs').value;
            if(CompruebaBlanco(objFoCurs,'Curso escolar')) OK = true; else return false;
        }
        
        if(document.getElementById('FoEdad') != undefined){
            
            var objFoEdad = document.getElementById('FoEdad').value;  
            if(CompruebaBlanco(objFoEdad,'Edad')) OK = true; else return false;
        }
        
        if(document.getElementById('FoNoTu') != undefined){
            var objNoTu = document.getElementById('FoNoTu').value;
            if(CompruebaBlanco(objNoTu,'Nombre del padre, tutor o representante legal')) OK = true; else return false;
        }    
        
        if(document.getElementById('FoApTu') != undefined){
            var objApTu = document.getElementById('FoApTu').value;
            if(CompruebaBlanco(objApTu,'Apellidos del padre, tutor o representante legal')) OK = true; else return false;         
        }
        
        if(document.forms.factividades.elements['FoFaAd[]'] != undefined){
            var objFaAd = document.forms.factividades.elements['FoFaAd[]'];
            if(validarRadiButton(objFaAd,formulario,'familia adoptiva')) OK = true; else return false;  
        }
        if(document.forms.factividades.elements['FoEsSo[]'] != undefined){
            var objEsSo = document.forms.factividades.elements['FoEsSo[]'];
            if(validarRadiButton(objEsSo,formulario,'Es socio de AFADA')) OK = true; else return false;       
        } 
        
        if(OK==true){ 
        formulario.submit();   
       }
        
   }
   else alert('Debe marcar la pestaña de conformidad'); 
    
      
}
/***************************************************************************************************************/
/*Validar Radio Button                                                                                         */
/***************************************************************************************************************/
function validarRadiButton(obj,formulario,campo) {
    
    var marcado = "no";
    with (formulario){
        for ( var i = 0; i < obj.length; i++ ) {
            if ( obj[i].checked ) {
                return true;
            }
        }
        if ( marcado == "no" ){
            window.alert("Debe marcar el campo "+campo ) ;
        }
    }
}
/***********************************************/
/*Funcion que llama a RellenaDatos, funcion php*/
/**********************************************/
function RellenarDatos(){
    xajax_RellenaDatos();
    return false;

}