/***************************************************************************************************************/
/*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";
	}
	
}
/***************************************************************************************************************/
/*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>Micro-Web</title>\n');
  ventimp.document.write('<link href="templates/template_Liena/css/estilos2.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;

  }
}
/*************************************************************************************************/
/*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(event) {
  var Navegador = (window.Event) ? 1 : 0
  
  var codigo = Navegador ? event.which : event.keyCode;
  
  return codigo;
}


// sólo deja introducir números
function esNumero(event){
    
     var tecla = codigo_tecla(event);
     
     if (tecla == 8 || tecla==46 || tecla==110 || tecla==190 || tecla == 9) event.returnValue=true;
     else if (tecla >= 48 && tecla<=57) event.returnValue=true;
     //else if (tecla >= 96 && tecla<=105) event.returnValue=true;
     else {
        return continuarEvento(event,false);
     }
}
function continuarEvento(evento,continuar){ 
    if (evento.preventDefault && !continuar){
        evento.preventDefault();
        evento.stopPropagation();
    }
    return continuar;
}

function validar_contacto(obj){
    
   xajax_validarContacto(xajax.getFormValues(obj));
        return false;
}

//******************* 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 = '';

}

//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');
        
}
/****************************************************************************************************************/
/*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 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(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[0].elements['FoFaAd[]'] != undefined){
            var objFaAd = document.forms[0].elements['FoFaAd[]'];
            if(validarRadiButton(objFaAd,formulario,'familia adoptiva')) OK = true; else return false;  
        }
        if(document.forms[0].elements['FoEsSo[]'] != undefined){
            var objEsSo = document.forms[0].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 ) ;
        }
    }
}

function InicializaArray(){
    a = new Array();
    return a;
}



