
/********* 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_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 comprueba_blanco(obj, nombreCampo) {
  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) {
	 //alert('entro');
     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 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 mostrar descripciones en toolTip y Status --------------------

function TextosMouseOver(Alt) {
  if (Alt == "") return false;
  toolTip('<table cellspacing=1 cellpadding=1 border=0>' +
            '<tr><td><font style=font-family:Tahoma;font-size:11px;>' +
              Alt +
            '</font></td></tr>' +
          '</table>', '#000000', '#FFFFE1');
 // window.status = '::' + Alt;
}

//--------- Función para ocultar descripciones en toolTip y Status --------------------

function TextosMouseOut() {
  toolTip();
  //window.status = '';
}


function FormatNum(Campo){
    var precioformato = FormatearNumero(Campo, 2, '.',',');
    precioformato = format_miles(precioformato);
    
    return precioformato;  
}


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 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 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">');
  ventimp.document.write('<html xmlns="http://www.w3.org/1999/xhtml">');
  ventimp.document.write('<head><title>azkoyen-vending.com</title>');
  ventimp.document.write('<link href="printestilo.css" rel="stylesheet" type="text/css"/>'); 
  ventimp.document.write( ficha.innerHTML );
  ventimp.document.write( '</body></html>' ); 
  ventimp.document.close();
  ventimp.print( );
  ventimp.close();
} 


    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 valida_telefono(campo){
        var RegExPattern = ^\d+$;
        if ((campo.value.match(RegExPattern)) || (campo.value!='')) {
            return false;
        } 
 
    } */
    
 function valida_telefono(texto) {
  var re_mail = /^[0-9 - /]+$/;
  if (re_mail.test(texto)) {
    return true;
  } else {
    return false;
  }
}

function valida_direccion(formulario){
    if (formulario.hlocalizacion.value == ""){
        alert("Debe seleccionar una dirección de envío");
        return false;
    }else{
        formulario.submit();
    }
    
}

function valida_fecha(caja){ 
   var borrar;
   borrar = true;

      if ((caja.substr(2,1) == "/") && (caja.substr(5,1) == "/") || (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) alert('Fecha erronea');
      return borrar;   
}
