

/********* FUNCIONES DE VALIDACION DE FORMATO *****************/

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;
  }
}

function comprueba_nif(nif){

    dni=nif.substring(0,nif.length-1)
    letra=nif.charAt(nif.length-1)
    
    if (!isNaN(letra))                                      
     {
        alert('El NIF debe tener 8 dígitos y una letra');
        return false;
     }                     
    else
     {
        cadena="TRWAGMYFPDXBNJZSQVHLCKET";
        posicion = dni % 23;
        letra2 = cadena.substring(posicion,posicion+1);
        if (letra2!=letra.toUpperCase())
         {
            alert("Nif no válido")
            return false
         }
     }
     return true;
}

function validarCIF(texto){ 
				var pares = 0; 
        var impares = 0; 
        var suma; 
        var ultima; 
        var unumero; 
        var uletra = new Array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I"); 
        var xxx; 

				texto = texto.toUpperCase(); 
        
				if (texto.length != 9){
						alert('El CIF debe tener 9 dígitos');
						return false;
				}
				
        var regular =/^[ABCDEFGHKLMNPQS]\d\d\d\d\d\d\d[0-9,A-J]$/g; 
        
				if (!regular.exec(texto)) {
					alert('El CIF no es correcto');
					return false; 
				}
         ultima = texto.substr(8,1); 

         for (var cont = 1 ; cont < 7 ; cont ++){ 
             xxx = (2 * parseInt(texto.substr(cont++,1))).toString() + "0"; 
             impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1)); 
             pares += parseInt(texto.substr(cont,1)); 
         } 
         xxx = (2 * parseInt(texto.substr(cont,1))).toString() + "0"; 
         impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1)); 
          
         suma = (pares + impares).toString(); 
         unumero = parseInt(suma.substr(suma.length - 1, 1)); 
         unumero = (10 - unumero).toString(); 
         if(unumero == 10) unumero = 0; 
          
         if ((ultima == unumero) || (ultima == uletra[unumero])){
         	return true; 
				 }else{
					alert('El CIF no es correcto');
         	return false; 
				 }

} 

function comprueba_select(obj,nombreCampo){
	 for (i=0;i<obj.length;i++){ 
			if ( obj.options[obj.selectedIndex].value != '' ){
				return true;
			}
	 }
	 alert('El campo '+ nombreCampo +' es obligatorio');
	 return false;
	
}

//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) 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;
}

/********* VALIDACION DE NUMEROS **************/
function esEntero_Rango(obj,min,max){
	valor = obj.value;
    entero = parseInt(valor);
    if (isNaN(entero)){
    	alert("El valor no es correcto. Debe de ser un número entero de " + min + " a " + max);
	    return false;
    }
    if (min<= entero && entero <= max){
    	obj.value = entero;
    	return true;
    }else{
        alert("El valor no es correcto. Debe de ser un número entero de " + min + " a " + max);
	    return false;
    }
}


function esEntero(obj){
    valor = obj.value;
    entero = parseInt(valor);
    if (isNaN(entero)){
       alert("El valor no es correcto. Debe de ser un número entero");
	    return false;
    }else{
    	return true;
    }
}

                                             
function comprueba_blanco(obj, nombreCampo) {
  //alert('-----' + obj.name + ' ---- ' + obj.value);
  if (obj.value == "") {                               
    alert('El campo '+ nombreCampo +' es obligatorio');
    return false;
  } else {
    return true;
  }
}

function comprueba_radio(obj, nombreCampo) {
	 valor = false;
	 for (i=0;i<obj.length;i++){ 
       if (obj[i].checked){
				 	valor = true;
          break; 
			 }
   }
	 if (!valor){
		 	alert('El campo '+ nombreCampo +' es obligatorio');
	 		return false;
	 }else{
		return true; 
	}

	
}

function comprueba_radio2(obj) {
	 valor = false;
	 for (i=0;i<obj.length;i++){ 
       if (obj[i].checked){
				 	valor = true;
          break; 
			 }
   }
	 if (!valor){
	 		return false;
	 }else{
		return true; 
	}

	
}


/*********** *****************/

// voy a mostrat el objeto que me pasan con display o con visibility
function mostrarCapa(nombre){
   obj = eval(document.getElementById(nombre));
   if (eval(document.getElementById(nombre))){
	   if (obj.style.display == "block"){
	        obj.style.display = "none";
	   }else{
       		if (obj.style.display == "none"){
		        obj.style.display = "block";
            }
	   }
		 if (obj.style.visibility == "hidden"){
			obj.style.visibility = "visible";
		 }else{
			if (obj.style.visibility == "visible") obj.style.visibility = "hidden";
		 }
   }
}


function muestraCapa(nombre){
   obj = eval(document.getElementById(nombre));
   if (eval(document.getElementById(nombre))){
       if (obj.style.display == "none"){
            obj.style.display = "block";
       }
       if (obj.style.visibility == "hidden") obj.style.visibility = "visible";
         
   }
}

function ocultaCapa(nombre){
   obj = eval(document.getElementById(nombre));
   if (eval(document.getElementById(nombre))){
       if (obj.style.display == "block"){
            obj.style.display = "none";
       }
       if (obj.style.visibility == "visible") obj.style.visibility = "hidden";
         
   }
}

/********** VARIAS ***********/

//--------- Función para abrir popup --------------------
function NuevaVentana (MyURL, MyNombre, Ancho, Alto, PosX, PosY, Botones, CampoURL, BarraEstado, MenuNavegador, Scrolls, Redimensionable) {
  if (PosX == "c") {
    var CoordenadaX = (screen.width - Ancho) / 2;
  } else {
    var CoordenadaX = PosX;
  }
  if (PosY == "c") {
    var CoordenadaY = (screen.height - Alto) / 2;
  } else {
    var CoordenadaY = PosY;
  }
  Propiedades = 'width=' + Ancho + ',height=' + Alto + ',top=' + CoordenadaY + ',left=' + CoordenadaX +
                ',toolbar=' + Botones + ',location=' + CampoURL + ',status=' + BarraEstado +
                ',menubar=' + MenuNavegador + ',scrollbars=' + Scrolls + ',resizable=' + Redimensionable;
  win = window.open(MyURL, MyNombre, Propiedades);
  if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

//--------- Función para agregar a favoritos --------------------

function Favoritos() {
  if (document.all){
    var url = "http://www.clubgentesaludable.com";
    var titulo = "Club Gente Saludable";
    window.external.AddFavorite(url,titulo);
  } else {
    if(navigator.appName == "Netscape")
    alert ("Presione Crtl+D para agregar este sitio en sus Bookmarks");
  } 
}

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 == '0000') && (arrCC[1].value == '0000') && (arrCC[2].value == '00') && (arrCC[3].value == '0000000000')){
                str_error = "El número de cuenta no es válido";
            } 
            
       		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 (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 para imagen
/*function resizeImg(cualImg,ancho) { 
		var maxwidth = ancho; 
		var maxheight = ancho; 
		var imagen = document.getElementById(cualImg); 
		if (imagen.width>maxwidth || imagen.height>maxheight) { 
			var scale = Math.min((maxwidth/imagen.width),(maxheight/imagen.height), 1 ); 
			var new_width = Math.floor(scale*imagen.width); 
			var new_height = Math.floor(scale*imagen.height); 
			imagen.width = new_width; 
			imagen.height = new_height; 
		} 
	}*/
	function resizeImg(cualImg,ancho) { 
		var maxwidth = ancho; 
		var imagen = document.getElementById(cualImg); 
		if (imagen.width>maxwidth) { 
			imagen.width = ancho; 
		} 
	}
    

// si mensaje == 1 quiere decir que no saco el alert del final
// si no le paso valor o le paso otra cosa si q saco el mensaje    
function valida_fecha(caja,mensaje){ 
   var borrar;
   borrar = true;
   
      if ((caja.substr(2,1) == "/") && (caja.substr(5,1) == "/")){      
         for (i=0; i<10; i++){    
            if (((caja.substr(i,1)<"0") || (caja.substr(i,1)>"9")) && (i != 2) && (i != 5))
            {
               borrar = false;
               break;  
            }  
         }
         if (borrar){ 
            a = caja.substr(6,4);
            m = caja.substr(3,2);
            d = caja.substr(0,2);
            if((a < 1900) || (a > 2050) || (m < 1) || (m > 12) || (d < 1) || (d > 31))
               borrar = false;
            else
            {
               if((a%4 != 0) && (m == 2) && (d > 28))       
                  borrar = false; // Año no viciesto y es febrero y el dia es mayor a 28
               else    
               {
                  if ((((m == 4) || (m == 6) || (m == 9) || (m==11)) && (d>30)) || ((m==2) && (d>29)))
                     borrar = false;                                 
               }  // else
            } // fin else
         } // if (error)
      } else{
      borrar= false;
      }                            
     
      if (borrar == false && eval(mensaje) != 1) alert('Fecha erronea');
      return borrar;   
}


function busqueda_seccion() {
         var valor = "secciones/s_bus_seccion.php";
         var alto = 350;
         var ancho = 600;
         var nomeWin = 'win' + alto;
         var params="height=" + alto + ",width=" + ancho + ",channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0', '" + nomeWin + "'";
         window.open(valor, nomeWin, params); 
}
                                                        
//la voy a utilizar para saltar la seguridad de windows
function carga_flash(archivo,pelicula,ancho,alto){
    
    // document.write('<object classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0 width='+ancho+' height='+alto+'>'); 
    // document.write('<param name=movie value='+archivo+' />') ;
    // document.write('<param name=quality value=high />') ;
    // document.write('<param name=wmode value=transparent />') ;
    // document.write('<param name="allowFullScreen" value="true" />') ;
    // document.write('<param name=flashvars value=&Banners='+pelicula+' />') ;
    document.write('<embed wmode="transparent" src='+archivo+' allowFullScreen="true" quality=high pluginspage=http://www.macromedia.com/go/getflashplayer type=application/x-shockwave-flash flashvars=&Banners='+pelicula+' width='+ancho+' height='+alto+'></embed>'); 
   // document.write('</object>')
}


//la voy a utilizar para saltar la seguridad de windows
function carga_publicidadflash(archivo,ancho,alto){
    
    document.write('<object classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0 width='+ancho+' height='+alto+'>'); 
    document.write('<param name=movie value='+archivo+' />') ;
    document.write('<param name=quality value=high />') ;
    document.write('<param name=wmode value=transparent />') ;
    document.write('<param name="allowFullScreen" value="true" />') ;       
    document.write('<embed wmode="transparent" src='+archivo+' allowFullScreen="true" quality=high pluginspage=http://www.macromedia.com/go/getflashplayer type=application/x-shockwave-flash width='+ancho+' height='+alto+'></embed>'); 
    document.write('</object>')
}

                                                        

//la voy a utilizar para saltar la seguridad de windows
function carga_videoflash(archivo,video,tiempo,ancho,alto){
    
    document.write('<object classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0 width='+ancho+' height='+alto+'>'); 
    document.write('<param name=movie value='+archivo+' />') ;
    document.write('<param name=quality value=high />') ;
    document.write('<param name=wmode value=transparent />') ;
    document.write('<param name="allowFullScreen" value="true" />') ;
    document.write('<param name=flashvars value="&archivo='+video+'&tiempo='+tiempo+'" />') ;
    document.write('<embed wmode="transparent" src='+archivo+' allowFullScreen="true" quality=high pluginspage=http://www.macromedia.com/go/getflashplayer type=application/x-shockwave-flash flashvars="&archivo='+video+'&tiempo='+tiempo+'" width='+ancho+' height='+alto+'></embed>'); 
    document.write('</object>')
}


function imprSelec(nombre)
{
  var ficha = document.getElementById(nombre);
  var ventimp = window.open('imprimir.html', 'popimpr');
  
  /*ventimp.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
  ventimp.document.write('<html xmlns="http://www.w3.org/1999/xhtml">');
  ventimp.document.write('<head><title>Gente Saludable. Portal de Salud. Saber Vivir</title>');
  ventimp.document.write('<link href="plantillas/plantilla2/css/estilo1.css" rel="stylesheet" type="text/css"/>');
  ventimp.document.write('<style type="text/css">@media print { .nover {display:none}}</style>');
  ventimp.document.write('<style type="text/css">.nover {display:none}</style>');
  ventimp.document.write('</head><body>'); */
  //ventimp.pinta('ficha.innerHTML');
 // ventimp.document.write( 'ficha.innerHTML' );
  //alert(ficha.innerHTML);                                                      
 // ventimp.document.write( '</body></html>' ); 
  ventimp.document.close();
  
  //ventimp.print();            
  //ventimp.close();
}

function guarda_acceso_ofertas(idoferta,destacada) {       
        var pagina;
        pagina = 'modulos/mod_ofertas/modofertasaccesos.php?Oferta='+idoferta+'&Destacada='+destacada;
        FAjax(pagina,'acciones','','get');        
}

function guarda_acceso_juegosofertas(idoferta,destacada) {       
        var pagina;
        pagina = 'modulos/mod_juegosofertas/modofertasaccesos.php?Oferta='+idoferta+'&Destacada='+destacada;
        FAjax(pagina,'acciones','','get');        
}

function redondear(cantidad) {
        var cantidad = parseFloat(cantidad);
        return Math.round(cantidad * Math.pow(10,2)) / Math.pow(10,2);
}



function FormatNum(Campo){
    var precioformato = FormatearNumero(Campo, 2, '.',',');
    precioformato = format_miles(precioformato);
    
    return precioformato;  
}

function FormatearNumero(Campo, CantDecimales, SimboloDec,SimboloPongo) 
{ 
    var Campo = Campo+"";
    var PosicDecimal = Campo.indexOf(SimboloDec) ; 
    var ParteEntera = ""; 
    var ParteDecimal = ""; 
    var ParteDecimalBis = ""; 
     

    //Sin decimales 
    if (PosicDecimal == -1) 
    { 
        ParteEntera = Campo ; 
        ParteDecimal = ""; 
    } 
    else 
    { 
        ParteEntera = Campo.substr(0, PosicDecimal ) ; 
        ParteDecimal = Campo.substr(PosicDecimal + 1, CantDecimales ) ; 
    } 



    //Completar la parte decimal para que cumpla los dec requeridos 
    if (ParteDecimal.length < CantDecimales) 
    { 
        for (var i= ParteDecimal.length; i < CantDecimales; i++) 
        {       
            ParteDecimalBis += "0"; 
        } 

    } 

    //tengo que coger la parte entera y ponerle el punto de millar
    
    return Campo = ParteEntera + SimboloPongo + ParteDecimal + ParteDecimalBis; 

}

function format_miles(nStr) 
{ 
    nStr += ''; 
    x = nStr.split(','); 
    x1 = x[0]; 
    x2 = x.length > 1 ? ',' + x[1] : ''; 
    var rgx = /(\d+)(\d{3})/; 
    while (rgx.test(x1)) { 
        x1 = x1.replace(rgx, '$1' + '.' + '$2'); 
    } 
    return x1 + x2; 
} 
function modificar_hiddencapa(id,precio){
    
    document.getElementById(id).value = precio; 
    if (precio != "") 
        document.getElementById('c_'+id).innerHTML = FormatNum(precio);
    else
        document.getElementById('c_'+id).innerHTML = "";

}  

function quitablancos(obj){
    cadena = obj.value;
    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;
    }
    obj.value=cadena;

}
                             
function quitablancostotal(obj){
    cadena = obj.value;
    
    out = " "; // reemplaza la letra a
    add = ""; // por la letra ba
    temp = "" + cadena;

    //bucle mientras se encuentre la cadena de busqueda
    while (temp.indexOf(out)>-1)
    {
        //pos es igual a la posicion donde se encuentra la coincidencia
        pos=temp.indexOf(out);
        //coge la cadena desde el principio hasta la primera coincidencia, añade
        // el caracter de reemplazo, y coge el resto de cadena, realizando de esta
        // mantera el reemplazo
        temp = "" + (temp.substring(0, pos) + add + temp.substring((pos + out.length), temp.length));
    }
    obj.value=temp;    

} 

function calcular_edad(fecha){ 

    //calculo la fecha de hoy 
    hoy=new Date() 
    

    //calculo la fecha que recibo 
    //La descompongo en un array 
    var array_fecha = fecha.split("/") 
    //si el array no tiene tres partes, la fecha es incorrecta 
    if (array_fecha.length!=3) 
       return false 

    //compruebo que los ano, mes, dia son correctos 
    var ano 
    ano = parseInt(array_fecha[2]); 
    if (isNaN(ano)) 
       return false 

    var mes 
    mes = parseInt(array_fecha[1]); 
    if (isNaN(mes)) 
       return false 

    var dia 
    dia = parseInt(array_fecha[0]); 
    if (isNaN(dia)) 
       return false 


    //si el año de la fecha que recibo solo tiene 2 cifras hay que cambiarlo a 4 
    if (ano<=99) 
       ano +=1900 

    //resto los años de las dos fechas 
    edad=hoy.getFullYear()- ano - 1; //-1 porque no se si ha cumplido años ya este año 

    //si resto los meses y me da menor que 0 entonces no ha cumplido años. Si da mayor si ha cumplido 
    if (hoy.getMonth() + 1 - mes < 0) //+ 1 porque los meses empiezan en 0 
       return edad 
    if (hoy.getMonth() + 1 - mes > 0) 
       return edad+1 

    //entonces es que eran iguales. miro los dias 
    //si resto los dias y me da menor que 0 entonces no ha cumplido años. Si da mayor o igual si ha cumplido 
    if (hoy.getUTCDate() - dia >= 0) 
       return edad + 1 

    return edad 
} 

function InfoCamerfirma() 
{
//window.open ("https://secure.camerfirma.com/cmfecs/info.php?serial=0640" ,"ESTADO","width=390,height=320,scrollbars=no,status=no");
window.open ("https://secure.camerfirma.com/cmfecsv3/info.php?serial=0640" ,"ESTADO","width=390,height=320,scrollbars=no,status=no");

}

//Función para mostrar u ocultar las respuestas en el módulo FAQ
function muestra_oculta_respuesta(npregunta){
    if(document.getElementById("respuesta_"+npregunta).style.display=="none"){
        //Alberto 29/03/2011. Arrelga faqz en FF y Chrome. Salian mal posicionadas
		//document.getElementById("respuesta_"+npregunta).style.display="block";
		document.getElementById("respuesta_"+npregunta).style.display="";
    }
    else{
        document.getElementById("respuesta_"+npregunta).style.display="none";
    }
}    
    
                                
