function changeState(id, valor)
{
	if (valor)
	{
		checkeado = 1;
	} else {
		checkeado = 0;
	}
	$.ajax({
		type: "POST",
		url: "",
		data: "id="+id+"&valor="+checkeado,
		success: function(msg){
			alert( "Data Saved: " + msg );
		}
	});
}


function refreshData(origen, destino, url)
{
	$('#'+destino).html('<option selected>Cargando</option>');
	var id = $('#'+origen).val();
	var toLoad = url+"/"+id;
	$.post(toLoad,function (responseText){
		$('#'+destino).html(responseText);
		//alert(responseText);
	});
}

function asociateProduct(valor, idactual, url)
{
	var toLoad = url+"asociateproduct/"+idactual+"/"+valor;
	$.post(toLoad,function (responseText){
		//$('#'+destino).html(responseText);
		if (responseText=="ok")
		{
			document.location = url+"producto/form/"+idactual;
		} else {
			alert("Ha ocurrido un problema a la hora de asociar el producto");
		}
	});
}


function nif_correcto (dni) {
	dni = String(dni).toUpperCase();
	if (dni.substr(0, 1)=="X" || dni.substr(0, 1)=="Y" || dni.substr(0, 1)=="Z")
	{
		return validaNIE2008(dni);
	} else {
		var regular = new RegExp(/^[ABCDEFGHKLMNPQS]\d\d\d\d\d\d\d[0-9,A-J]$/g);
		if (!regular.exec(dni))
		{
			numero = dni.substr(0,dni.length-1);
			let = dni.substr((dni.length-1),1);
			numero = numero % 23;
			letra='TRWAGMYFPDXBNJZSQVHLCKET';
			letra=letra.substring(numero,numero+1);
			if (letra!=let) {
				return false;
			}else{
				return true;
			}
		} else {
			return validarCIF(dni);
		}
	}
}

var nav4 = window.event ? true : false;
function esDigito(evt){
	var key = nav4 ? evt.which : evt.keycode;
	return (key <= 13 || (key >= 48 && key <= 57));
}

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();

	var regular = new RegExp(/^[ABCDEFGHKLMNPQS]\d\d\d\d\d\d\d[0-9,A-J]$/g);
	 if (!regular.exec(texto)) 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
		 return false;

} 

function validaNIE2008 (strNie)
{   
    // ---- no olvidar que tb hay que usar la funci—n "HacerTrim"
    strLenNie = strNie.length;
    alfa="abcdefghijklmn–opqrstuvwxyz";
   
    var strPerfijo = strNie.substr(0,1);
           
    if (strPerfijo!='X' && strPerfijo!='x' && strPerfijo!='Y' && strPerfijo!='y' && strPerfijo!='Z' && strPerfijo!='z')
        { //No empieza por X Y Z           
        alert("N.I.E. Incorrecto\n\nEl N.I.E. debe comenzar por la letra 'X', 'Y' o 'Z'.");
        return false;       
        }
   
    strPerfijo = strPerfijo.toUpperCase();
   
   
    letraNie =strNie.substr(strLenNie-1,1)
    if (alfa.indexOf(letraNie)==-1 && (alfa.toUpperCase()).indexOf(letraNie)==-1)
        {//No acaba con una letra
        alert("N.I.E. Incorrecto\n\nEl N.I.E. debe acabar por una letra.");
        return false;
        }
    else
        letraNie=letraNie.toUpperCase();
   
    numNie =strNie.substr(1,strLenNie-2);

    // SAD:14/03/2006    Si usamos - lo toma como signo 'menos'

    if (isNaN(numNie) || numNie < 0 || numNie.length > 7)    
        { //La parte nœmerica contiene alguna letra   
        //alert("N.I.E. Incorrecto\n\nEl N.I.E. introducido es incorrecto, por favor rev’selo antes de continuar.");
        return false;
        }


    numNie = HacerTrim(numNie);

        /*
        -------------------------------------------------------------    
        En teor’a, todos deben ser de 7 d’gitos, pero en la BBDD puede estar con 8, por lo tanto:
        - Dejamos el NIE EN 7 POSICIONES
        - En programa, es donde deberemos BUSCAR el NIE con 7 y 8 d’gitos, siempre que empiece por 'X'
        - Si empieza por 'Y' — 'Z' --> debe ser de 7 d’gitos
        -------------------------------------------------------------    
        */

    while (numNie.length < 7)  // 04.07.2008
        {//Completa con 0 por la izquierda (7 DêGITOS)
        numNie="0"+numNie;
        }

               
    vletras=["T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E","T"];
    /*
    NUEVO!!! 04.07.2008
    Substituyo los pesos de las letras
        X = 0
        Y = 1
        Z = 2   
    */
    var numNie2008="";
    if (strPerfijo=='X'){ numNie2008 = "0"+ numNie; }
    if (strPerfijo=='Y'){ numNie2008 = "1"+ numNie; }
    if (strPerfijo=='Z'){ numNie2008 = "2"+ numNie; }

    valNie = numNie2008 % 23;
   
    if (valNie > vletras.length-1)
        { //Desborda el array
        //alert("N.I.E. Incorrecto\n\nEl N.I.E. introducido es incorrecto, por favor rev’selo antes de continuar.");
        return false;
        }
       
    letraAux=vletras[valNie];       
           
    //if (letraNie != letraAux)
        //alert("N.I.E. Incorrecto\n\nEl N.I.E. introducido es incorrecto, por favor rev’selo antes de continuar.");


    return (letraNie===letraAux)?true:false           
}// function validaNIE2008 (strNie)  


function HacerTrim(cadena)
{
   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;
   }
   return cadena;
}


function validaLibreta(i_entidad, i_oficina, i_digito, i_cuenta){
	// VALIDACIîN DE CUALQUIER LIBRETA DE CUALQUIER ENTIDAD BANCARIA.
	// Funcion recibe como par‡metro la entidad, la oficina,
	// el digito (concatenaci—n del de control entidad-oficina y del de control entidad)
	// y la cuenta. Espera los valores con 0's a la izquierda.
	// Devuelve true o false.
	// NOTAS:
	// Formato deseado de los par‡metros:
	// - i_entidad (4)
	// - i_oficina (4)
	// - i_digito (2)
	// - i_cuenta (10)
	var wtotal,wcociente, wresto;
	if (i_entidad.length != 4){
		return false;
	}
	if (i_oficina.length != 4){
		return false;
	}
	if (i_digito.length != 2){
		return false;
	}
	if (i_cuenta.length != 10){
		return false;
	}
	wtotal = i_entidad.charAt(0) * 4;
	wtotal += i_entidad.charAt(1) * 8;
	wtotal += i_entidad.charAt(2) * 5;
	wtotal += i_entidad.charAt(3) * 10;
	wtotal += i_oficina.charAt(0) * 9;
	wtotal += i_oficina.charAt(1) * 7;
	wtotal += i_oficina.charAt(2) * 3;
	wtotal += i_oficina.charAt(3) * 6;
	// busco el resto de dividir wtotal entre 11
	wcociente = Math.floor(wtotal / 11);
	wresto = wtotal - (wcociente * 11);
	//
	wtotal = 11 - wresto;
	if (wtotal == 11){
		wtotal=0;
	}
	if (wtotal == 10){
		wtotal=1;
	}
	if (wtotal != i_digito.charAt(0)){
		return false;
	}
	//hemos validado la entidad y oficina
	//-----------------------------------
	wtotal = i_cuenta.charAt(0) * 1;
	wtotal += i_cuenta.charAt(1) * 2;
	wtotal += i_cuenta.charAt(2) * 4;
	wtotal += i_cuenta.charAt(3) * 8;
	wtotal += i_cuenta.charAt(4) * 5;
	wtotal += i_cuenta.charAt(5) * 10;
	wtotal += i_cuenta.charAt(6) * 9;
	wtotal += i_cuenta.charAt(7) * 7;
	wtotal += i_cuenta.charAt(8) * 3;
	wtotal += i_cuenta.charAt(9) * 6;

	// busco el resto de dividir wtotal entre 11
	wcociente = Math.floor(wtotal / 11);
	wresto = wtotal - (wcociente * 11);
	//
	wtotal = 11 - wresto;
	if (wtotal == 11){wtotal=0;}
	if (wtotal == 10){wtotal=1;}

	if (wtotal != i_digito.charAt(1)){
		//alert(wtotal+' y no '+i_digito.charAt(1));
		return false;
	}
	// hemos validado la cuenta corriente

	return true;
}

