
/********* 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_mail_sinalert(mail) {
  var re_mail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
  if (re_mail.test(mail)) {
    return true;
  } else {
    return false;
  }
}

function comprueba_tarjetaresidencia(valor){
  letra = valor.substring(0,1);
  //alert(letra);
  
  if ((letra == "X") || (letra== "x") ) { 
    return true;
  }else{
    alert('Tarjeta de residencia no 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;
	
}

/********* 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 trim(str){
   /*devuelve la cadena sin espacios*/
   return str.replace(/^\s*|\s*$/g,"");
}

function comprueba_blanco(obj, nombreCampo) {
  valor=trim(obj.value);
  if (valor == "") {
    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";
		 }
   }
}

// voy a mostrat el objeto que me pasan con display o con visibility
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(); }
}


 function poPup(adonde,alto,ancho) {
    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=1,status=0,toolbar=0', '" + nomeWin + "'";
    window.open(adonde, nomeWin, params); 
}


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 (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; 
		} 
	}
    //--------- Función para agregar a favoritos --------------------

function Favoritos(miurl,mititulo) {
  if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
    var url = miurl;
    var titulo = mititulo;
    window.external.AddFavorite(url,titulo);
  } else {
    if(navigator.appName == "Netscape")
    alert ("Presione Crtl+D para agregar este sitio en sus Bookmarks");
  }
}
