
jQuery.validator.addMethod("valida_cpf", function(value, element) {
   value = jQuery.trim(value);
	
	value = value.replace('.','');
	value = value.replace('.','');
	cpf = value.replace('-','');
	while(cpf.length < 11) cpf = "0"+ cpf;
	var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
	var a = [];
	var b = new Number;
	var c = 11;
	for (i=0; i<11; i++){
		a[i] = cpf.charAt(i);
		if (i < 9) b += (a[i] * --c);
	}
	if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
	b = 0;
	c = 11;
	for (y=0; y<10; y++) b += (a[y] * c--);
	if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
	
	var retorno = true;
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) retorno = false;
	
	return this.optional(element) || retorno;

}, "Informe um CPF válido."); // Mensagem padrão 

jQuery.validator.addMethod("valida_cnpj", function(cnpj, element) {
	var retorno = true;

   cnpj = jQuery.trim(cnpj);
	
	// DEIXA APENAS OS NÚMEROS
   cnpj = cnpj.replace('/','');
   cnpj = cnpj.replace('.','');
   cnpj = cnpj.replace('.','');
   cnpj = cnpj.replace('-','');

   var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
   digitos_iguais = 1;

   if (cnpj.length < 14 && cnpj.length < 15){
      retorno = false;
   }
   for (i = 0; i < cnpj.length - 1; i++){
      if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
         digitos_iguais = 0;
         break;
      }
   }

   if (!digitos_iguais){
      tamanho = cnpj.length - 2
      numeros = cnpj.substring(0,tamanho);
      digitos = cnpj.substring(tamanho);
      soma = 0;
      pos = tamanho - 7;

      for (i = tamanho; i >= 1; i--){
         soma += numeros.charAt(tamanho - i) * pos--;
         if (pos < 2){
            pos = 9;
         }
      }
      resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
      if (resultado != digitos.charAt(0)){
   	   retorno = false;
      }
      tamanho = tamanho + 1;
      numeros = cnpj.substring(0,tamanho);
      soma = 0;
      pos = tamanho - 7;
      for (i = tamanho; i >= 1; i--){
         soma += numeros.charAt(tamanho - i) * pos--;
         if (pos < 2){
            pos = 9;
         }
      }
      resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
      if (resultado != digitos.charAt(1)){
			retorno = false;
      }
   }else{
      retorno = false;
   }

	return this.optional(element) || retorno;

}, "Informe um CNPJ válido."); // Mensagem padrão 


submitTest = function(){
	//alert (($('#id_pedido_produto_vc0').val() != '' || $('#saca0').val() != '' || $('#quant0').val() != '' || $('#precoU0').val() != '' || $('#precoT0').val() != ''));
	//alert (($('#produto0').val() != '' || $('#saca0').val() != '' || $('#quant0').val() != '' || $('#precoU0').val() != '' || $('#precoT0').val() != ''));
	//alert (($('#produto0').val() != '' || $('#id_pedido_produto_vc0').val() != '' || $('#quant0').val() != '' || $('#precoU0').val() != '' || $('#precoT0').val() != ''));
	//alert (($('#produto0').val() != '' || $('#id_pedido_produto_vc0').val() != '' || $('#saca0').val() != '' || $('#precoU0').val() != '' || $('#precoT0').val() != ''));
	//alert (($('#produto0').val() != '' || $('#id_pedido_produto_vc0').val() != '' || $('#saca0').val() != '' || $('#quant0').val() != '' || $('#precoT0').val() != ''));
	//alert (($('#produto0').val() != '' || $('#id_pedido_produto_vc0').val() != '' || $('#saca0').val() != '' || $('#quant0').val() != '' || $('#precoU0').val() != ''));
}

getVc = function(n, id){
    $('.load').fadeIn();
    $('#divVc' + n).load('representantes/getvc/' + id + '/' + n, false, function(){
        $('.load').fadeOut();
    });
}
getSaca = function(n, id){
    $('.load').fadeIn();
    $('#divSaca' + n).load('representantes/getsaca/' + id + '/' + n);
    $('#precoUnit' + n).load('representantes/getpreco/' + id + '/' + n, false, function(){
        $('.load').fadeOut();
    });
    $('#quant' + n).val(0);
}

entregaFutura = function(){
    $('#vendaFutura').toggle();
    $('#alertaFutura').toggle();
    $('#calendario').toggle();
    $('#babaca').toggle();
}
function numdias(mes, ano){
    if ((mes < 8 && mes % 2 == 1) || (mes > 7 && mes % 2 == 0))
        return 31;
    if (mes != 2)
        return 30;
    if (ano % 4 == 0)
        return 29;
    return 28;
}

function somaDias(data, dias){
    data = data.split('/');
    diafuturo = parseInt(data[0]) + dias;
    mes = parseInt(data[1]);
    ano = parseInt(data[2]);
    while (diafuturo > numdias(mes, ano)) {
        diafuturo -= numdias(mes, ano);
        mes++;
        if (mes > 12) {
            mes = 1;
            ano++;
        }
    }
    if (diafuturo < 10)
        diafuturo = '0' + diafuturo;
    if (mes < 10)
        mes = '0' + mes;

    return diafuturo + "/" + mes + "/" + ano;
}



function moeda2float(moeda){
    moeda = moeda.replace(/\./gi, "");
    moeda = moeda.replace(",", ".");
    return parseFloat(moeda);
}

function roundNumber(rnum){
    return Math.round(rnum * Math.pow(10, 2)) / Math.pow(10, 2);
}

function float2moeda(num){
    x = 0;
    if (num < 0) {
        num = Math.abs(num);
        x = 1;
    }
    if (isNaN(num))
        num = "0";
    cents = Math.floor((num * 100 + 0.5) % 100);
    num = Math.floor((num * 100 + 0.5) / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + '.' +
        num.substring(num.length - (4 * i + 3));
    ret = num + ',' + cents;
    if (x == 1)
        ret = ' - ' + ret;
    return ret;

}

parcelaTudo = function(){
    // START
    var lixo, dias, parcelas, vcto, subtotal, hoje;
    $('#parcelas').val('');

    // LIMPA PRA NAO VIRAR ZONA
    var lixo = $('#pedido_vencimento').val();
	// ARRUMA O FILTRO
    lixo = lixo.split('#');

    var id_vencimento = lixo[0];
    if (id_vencimento != 8)
	{

	    $('id_vencimento').val(id_vencimento);
	    var vencimento = lixo[1];
	    if (id_vencimento == 1) {
	        vencimento = '0'; // AVISTA BUGFIX
	    }

	    mydate = new Date();
	    myweekday = mydate.getDate();
	    mymonth = parseInt(mydate.getMonth()) + 1;
	    myyear = mydate.getFullYear();
	    hoje = myweekday + '/' + mymonth + '/' + myyear;

	    // PERCELA
	    lixo = vencimento.split(' '); // TIRA OS 'DIAS'
	    dias = lixo[0].split('/'); // DIAS DE CADA PARCELA
	    parcelas = dias.length; // DESCOBRE O NUMERO DE PARCELAS
	    // PEGA O TOTAL DOS TRECOS
	    subtotal = moeda2float($('#subtotal').val());


		var d0523 = new Date();
		var ano0523 = d0523.getFullYear();

		var hoje0523 = new Date();

		var dataForm = ('31/08/' + ano0523).split("/"); // DATA LIMITE PARA ALTERACAO DO METODO
		var dataFim0523 = new Date(dataForm[2], dataForm[1]-1, dataForm[0]);

		var dataForm2 = ('20/05/' + ano0523).split("/"); // DATA INICIO PARA ALTERACAO DO METODO
		var dataInicio0523 = new Date(dataForm2[2], dataForm2[1]-1, dataForm2[0]);

		// de hoje até 30 de agosto, preciso que o frete seja rateado entre as parcelas
		if(hoje0523 > dataInicio0523 && hoje0523 < dataFim0523)
		{
			var fooMetodo = 1;
			//document.write("rateado entre as parcelas");
		}
		// em 01/09, volta a lançar na primeira parcela
		else
		{
			var fooMetodo = 0;
			//document.write("lança na primeira parcela");
		}
		if ( hoje0523.getDate() == dataInicio0523.getDate() || hoje0523.getDate() == dataFim0523.getDate() )
		{
			var fooMetodo = 1;
			//document.write("rateado entre as parcelas");
		}

		if (fooMetodo == 0)
		{
		    var divide = subtotal / parcelas;
		    // MONTA O FRETE PRA 1a. PARCELA
		    if ($('#frete').val() != '') {
		        frete = moeda2float($('#frete').val());
		    }
		    else
		        frete = 0;

		    frete += divide;
		}
		else
		{
			var divide = ((moeda2float($('#valor').val())) / parcelas);
			frete = divide;
		}



	    // ORGANIZA EXIBICAO
	    divide = float2moeda(divide);
	    frete = float2moeda(frete);

	    // Finish Him!
	    for (a = 0; a < parcelas; a++) {
	        atual = $('#parcelas').val();
	        var b = parseInt(a) + 1

	        if (a == 0)
	            $('#parcelas').val(atual + 0 + b + ' - ' + somaDias(hoje, parseInt(dias[a])) + ' - R$ ' + frete);
	        else
	            $('#parcelas').val(atual + '\n' + 0 + b + ' - ' + somaDias(hoje, parseInt(dias[a])) + ' - R$ ' + divide);
	    }
	    // Fatallity !
	}
	else
	{
		//MONTA A PROPRIA PARCELA
		$('#parcelaHolder').html('<table id="tableParcela" width="100%"><tr style="height: 20px;"><td style="height: 20px;">Vencimento</td><td>Valor R$</td></tr></table><a href="javascript:addNovaLinha();">Adicionar parcela</a>');
		addNovaLinha();
		$('#customRequired').val('');
	}
};

function addNovaLinha()
{
	var time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);
	$('#tableParcela tr:last').after('<tr><td style="height: 20px;"><input maxlength="10" id="novadata_'+time+'" type="text" name="customParcela[]" class="inputz x1 thedates" onblur="checkCustom();" /></td><td style="height: 20px;" class="linhaParcela"><input type="text" name="customValor[]" class="inputz x1" onblur="checkCustom();" onkeyup="maskIt(this,event,\'#######,##\',true)" /></td></tr>');
	$("#novadata_"+time).mask("99/99/9999");
};
function checkCustom()
{
	var oTotal = moeda2float($('#valor').val());
	var subtotal = 0;
	var parcela = 0;
	var sizeCustom = $('.linhaParcela').size();
	$("#tableParcela").find(".linhaParcela").find('input').each(function() {
		subtotal += moeda2float($(this).val());
	});
	if (subtotal.toFixed(2) != oTotal)
	{
		if(!isNaN(subtotal) && !isNaN(oTotal))
			alert('Valores não conferem');
		$('#customRequired').val('');
	}
	else
	{
		$('#customRequired').val('ok');
	}

};

somaTudo = function(){
    var total = 0;
    var sacas = 0;
    var quants = 0;
    for (var a = 0; a < 5; a++) {
        if ($('#precoT' + a).val() != '') {
            total += moeda2float($('#precoT' + a).val());
        }
        if ($('#quant' + a).val() != '') {
            quants += moeda2float($('#quant' + a).val());
	        if ($('#saca' + a).val() != '') {
	            sacas += (moeda2float($('#quant' + a).val())/moeda2float($('#saca' + a).val()));
	        }
        }
    }
    $('#quantTarget').html(quants + ' Kg');
    $('#volumeTarget').html(sacas + ' Sacas');
    $('#subtotal').val(float2moeda(total));

    if ($('#frete').val() == '')
        $('#valor').val(float2moeda(total));
    else {
        frete = moeda2float($('#frete').val());
        // CALCULA A PORCENTAGEM DO FRETE NO PEDIDO
        $('#porcento').val(float2moeda((frete / total) * 100) + '%');
        total += frete;
        $('#valor').val(float2moeda(total));
    }



    parcelaTudo();
}

calcula = function(n){
    var soma = 0;
    var quantidade = $('#quant' + n).val();
    var unitario = $('#precoU' + n).val();
    var saca = $('#saca' + n).val();
    quantidade = moeda2float(quantidade);
    unitario = moeda2float(unitario);
    //
    if (quantidade % saca != 0 && quantidade != '' && saca != '') {
        alert('Quantidade incorreta.');
        $('#quant' + n).val(0);
    }
    else {
        soma = roundNumber(quantidade * unitario);

        soma = float2moeda(soma);

        $('#precoT' + n).val(soma);
        somaTudo();
    }
}

function maskIt(w, e, m, r, a){

    // Cancela se o evento for Backspace
    if (!e)
        var e = window.event
    if (e.keyCode)
        code = e.keyCode;
    else
        if (e.which)
            code = e.which;

    // Variáveis da função
    var txt = (!r) ? w.value.replace(/[^\d]+/gi, '') : w.value.replace(/[^\d]+/gi, '').reverse();
    var mask = (!r) ? m : m.reverse();
    var pre = (a) ? a.pre : "";
    var pos = (a) ? a.pos : "";
    var ret = "";

    if (code == 9 || code == 8 || txt.length == mask.replace(/[^#]+/g, '').length)
        return false;

    // Loop na máscara para aplicar os caracteres
    for (var x = 0, y = 0, z = mask.length; x < z && y < txt.length;) {
        if (mask.charAt(x) != '#') {
            ret += mask.charAt(x);
            x++;
        }
        else {
            ret += txt.charAt(y);
            y++;
            x++;
        }
    }

    // Retorno da função
    ret = (!r) ? ret : ret.reverse()
    w.value = pre + ret + pos;
}

// Novo método para o objeto 'String'
String.prototype.reverse = function(){
    return this.split('').reverse().join('');
};

$(function(){

	/*$("#cliente").keypress(function(event) {
		$('#assina').val($("#cliente").val());
	})
	.keyup(function(event) {
		$('#assina').val($("#cliente").val());
	})
	.blur(function() {
		$('#assina').val($("#cliente").val());
	});
	$("#cpf").keypress(function(event) {
		$('#assina_cpf').val($("#cpf").val());
	})
	.keyup(function(event) {
		$('#assina_cpf').val($("#cpf").val());
	})
	.blur(function() {
		$('#assina_cpf').val($("#cpf").val());
	});*/

    // MÁSCARAS
    jQuery(function($){
        $("#cep").mask("99999999");
        $("#telefone").mask("(99) 9999.9999");
        $("#celular").mask("(99) 9999.9999");
        $("#fax").mask("(99) 9999.9999");
        $("#nascimento").mask("99/99/9999");
        $("#cnpj").mask("99.999.999/9999-99");
        $("#cpf").mask("999.999.999-99");
        $("#assina_cpf").mask("999.999.999-99");

        $(".thedates").mask("99/99/9999");
    });

    $("#cep_corresp").keyup(function(){
        // RETORNA OS DADOS A PARTIR DE UM CEP
        var cep = $(this).val();
        var reDigits = /^\d+$/;// EXPRESSAO REGULAR PARA ACEITAR APENAS NUMEROS INTEIROS
        if (cep.length == 8 && reDigits.test(cep)) {
            $('#txtCEP').html('<img src="gfx/load.gif" /> &nbsp; Processando CEP...');
            $.post("representantes/cep/" + cep, {
                'cep': cep
            }, retornEndereco, "json");
        }
        else {
            $("#endereco_corresp").attr("value", "");
            $("#bairro_corresp").attr("value", "");
            $("#cidade_corresp").attr("value", "");
            $("#id_cidade").attr("value", "");
            $("#estado_corresp").attr("value", "");
        }
    });

    $("#cnpj").keyup(function(){
        var cnpj = $(this).val();
        if (cnpj.length == 18) {
            vcnpj(cnpj);
        }
    });

    $("#cpf").keyup(function(){
        var cpf = $(this).val();
        if (cpf.length == 14) {
            vcpf(cpf);
        }
    });
    $("#assina_cpf").keyup(function(){
        var cpf = $(this).val();
        if (cpf.length == 14) {
            vcpf(cpf);
        }
    });


//    $("#inscricao").blur(function(){
//        var ie = $(this).val();
//		CheckIE(ie, $('#estado').val());
//    });
});


function retornEndereco(rs){
    // VALIDA O RESULTADO
    if (rs.result == "falha") {
    	alert ('Ocorreu um erro.\nPreencha o restante do endereço');
    }
    if (rs.resultado == "ok") {
        $("#txtCEP").text("");
        $("#endereco_corresp").attr("value", rs.endereco);
        $("#bairro_corresp").attr("value", rs.bairro);
        $("#cidade_corresp").attr("value", rs.cidade);
        $("#id_cidade").attr("value", rs.id_cidade);
        $("#estado_corresp").attr("value", rs.uf);
    }
    else {
        $("#txtCEP").text("Digite um CEP válido");
        $("#endereco_corresp").attr("value", "");
        $("#bairro_corresp").attr("value", "");
        $("#cidade_corresp").attr("value", "");
        $("#id_cidade").attr("value", "");
        $("#estado_corresp").attr("value", "");
    }
}

function vcnpj(c){
//    var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais, cnpj = c.value.replace(/\D+/g, '');
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais, cnpj = c.replace(/\D+/g, '');
    digitos_iguais = 1;
    if (cnpj.length != 14) {
        return false;
    }
    else {
        for (i = 0; i < cnpj.length - 1; i++)
            if (cnpj.charAt(i) != cnpj.charAt(i + 1)) {
                digitos_iguais = 0;
                break;
            }
        if (!digitos_iguais) {
            tamanho = cnpj.length - 2
            numeros = cnpj.substring(0, tamanho);
            digitos = cnpj.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--) {
                soma += numeros.charAt(tamanho - i) * pos--;
                if (pos < 2)
                    pos = 9;
            }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0)) {
                alert('CNPJ inválido');
                $("#cpf").removeClass("ignore");
                return false;
            }

            tamanho = tamanho + 1;
            numeros = cnpj.substring(0, tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--) {
                soma += numeros.charAt(tamanho - i) * pos--;
                if (pos < 2)
                    pos = 9;
            }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1)) {
                alert('CNPJ inválido');
                $("#cpf").removeClass("ignore");
                return false;
            }
            else
                $("#cpf").addClass("ignore");
            return true;
        }
        else {
            alert('CNPJ inválido');
            $("#cpf").removeClass("ignore");
            return false;
        }
    }
}

function vcpf(c){
//    var numeros, digitos, soma, i, resultado, digitos_iguais, cpf = c.value.replace(/\D+/g, '');
	var numeros, digitos, soma, i, resultado, digitos_iguais, cpf = c.replace(/\D+/g, '');
    digitos_iguais = 1;

    if (cpf.length != 11) {
        return false;
    }
    else {

        for (i = 0; i < cpf.length - 1; i++)
            if (cpf.charAt(i) != cpf.charAt(i + 1)) {
                digitos_iguais = 0;
                break;
            }
        if (!digitos_iguais) {
            numeros = cpf.substring(0, 9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0)) {
                alert('CPF Inválido');
                $("#cnpj").removeClass("ignore");
                return false;
            }
            numeros = cpf.substring(0, 10);
            soma = 0;
            for (i = 11; i > 1; i--)
                soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1)) {
                alert('CPF Inválido');
                $("#cnpj").removeClass("ignore");
                return false;
            }
            $("#cnpj").addClass("ignore");
            return true;
        }
        else {
            alert('CPF Inválido');
            $("#cnpj").removeClass("ignore");
            return false;
        }
    }
}

$(document).ready(function(){
	$('#futura').click(function(){
		parcelaTudo();
	});

	// REMOVE O LAYER
	$('.layer_banner').click(function(){
		$(this).remove();
	});

    // CONFIGURA A VALIDACAO DO FORMULARIO
    $("#form_pedido").validate({
        rules: {
            cliente: {required: true},
            email: {required: true,email: true},
            fazenda: {required: true},
            cep: {required: true},
            cidade: {required: true},
            inscricao: {required: true},
            cnpj: { required:'#cpf:blank', valida_cnpj:true },
            cpf: { required:'#cnpj:blank', valida_cpf:true },
            cep_corresp: {required: true},
            endereco_corresp: {required: true},
            numero_corresp: {required: true},
            bairro_corresp: {required: true},
            cidade_corresp: {required: true},
            estado_corresp: {required: true},
            telefone: {required: true},
            rebanho: {required: true},
				
				assina: {required: true},
				assina_cpf: {required: true},
				cargo: {required: true},
				
			customRequired: {required: true},
			
			produto0: {
				required: "#id_pedido_produto_vc0:filled, #saca0:filled, #quant0:filled, #precoU0:filled, #precoT0:filled"
    		},
			id_pedido_produto_vc0: {
				required: "#produto0:filled, #saca0:filled, #quant0:filled, #precoU0:filled, #precoT0:filled"
    		},
			saca0: {
				required: "#produto0:filled, #id_pedido_produto_vc0:filled, #quant0:filled, #precoU0:filled, #precoT0:filled"
    		},
			quant0: {
				required: "#produto0:filled, #id_pedido_produto_vc0:filled, #saca0:filled, #precoU0:filled, #precoT0:filled"
    		},
			precoU0: {
				required: "#produto0:filled, #id_pedido_produto_vc0:filled, #saca0:filled, #quant0:filled, #precoT0:filled"
    		},
			precoT0: {
				required: "#produto0:filled, #id_pedido_produto_vc0:filled, #saca0:filled, #quant0:filled, #precoU0:filled"
    		},
			
			produto1: {
				required: "#id_pedido_produto_vc1:filled, #saca1:filled, #quant1:filled, #precoU1:filled, #precoT1:filled"
    		},
			id_pedido_produto_vc1: {
				required: "#produto1:filled, #saca1:filled, #quant1:filled, #precoU1:filled, #precoT1:filled"
    		},
			saca1: {
				required: "#produto1:filled, #id_pedido_produto_vc1:filled, #quant1:filled, #precoU1:filled, #precoT1:filled"
    		},
			quant1: {
				required: "#produto1:filled, #id_pedido_produto_vc1:filled, #saca1:filled, #precoU1:filled, #precoT1:filled"
    		},
			precoU1: {
				required: "#produto1:filled, #id_pedido_produto_vc1:filled, #saca1:filled, #quant1:filled, #precoT1:filled"
    		},
			precoT1: {
				required: "#produto1:filled, #id_pedido_produto_vc1:filled, #saca1:filled, #quant1:filled, #precoU1:filled"
    		},

			produto2: {
				required: "#id_pedido_produto_vc2:filled, #saca2:filled, #quant2:filled, #precoU2:filled, #precoT2:filled"
    		},
			id_pedido_produto_vc2: {
				required: "#produto2:filled, #saca2:filled, #quant2:filled, #precoU2:filled, #precoT2:filled"
    		},
			saca2: {
				required: "#produto2:filled, #id_pedido_produto_vc2:filled, #quant2:filled, #precoU2:filled, #precoT2:filled"
    		},
			quant2: {
				required: "#produto2:filled, #id_pedido_produto_vc2:filled, #saca2:filled, #precoU2:filled, #precoT2:filled"
    		},
			precoU2: {
				required: "#produto2:filled, #id_pedido_produto_vc2:filled, #saca2:filled, #quant2:filled, #precoT2:filled"
    		},
			precoT2: {
				required: "#produto2:filled, #id_pedido_produto_vc2:filled, #saca2:filled, #quant2:filled, #precoU2:filled"
    		},

			produto3: {
				required: "#id_pedido_produto_vc3:filled, #saca3:filled, #quant3:filled, #precoU3:filled, #precoT3:filled"
    		},
			id_pedido_produto_vc3: {
				required: "#produto3:filled, #saca3:filled, #quant3:filled, #precoU3:filled, #precoT3:filled"
    		},
			saca3: {
				required: "#produto3:filled, #id_pedido_produto_vc3:filled, #quant3:filled, #precoU3:filled, #precoT3:filled"
    		},
			quant3: {
				required: "#produto3:filled, #id_pedido_produto_vc3:filled, #saca3:filled, #precoU3:filled, #precoT3:filled"
    		},
			precoU3: {
				required: "#produto3:filled, #id_pedido_produto_vc3:filled, #saca3:filled, #quant3:filled, #precoT3:filled"
    		},
			precoT3: {
				required: "#produto3:filled, #id_pedido_produto_vc3:filled, #saca3:filled, #quant3:filled, #precoU3:filled"
    		},
			
			produto4: {
				required: "#id_pedido_produto_vc4:filled, #saca4:filled, #quant4:filled, #precoU4:filled, #precoT4:filled"
    		},
			id_pedido_produto_vc4: {
				required: "#produto4:filled, #saca4:filled, #quant4:filled, #precoU4:filled, #precoT4:filled"
    		},
			saca4: {
				required: "#produto4:filled, #id_pedido_produto_vc4:filled, #quant4:filled, #precoU4:filled, #precoT4:filled"
    		},
			quant4: {
				required: "#produto4:filled, #id_pedido_produto_vc4:filled, #saca4:filled, #precoU4:filled, #precoT4:filled"
    		},
			precoU4: {
				required: "#produto4:filled, #id_pedido_produto_vc4:filled, #saca4:filled, #quant4:filled, #precoT4:filled"
    		},
			precoT4: {
				required: "#produto4:filled, #id_pedido_produto_vc4:filled, #saca4:filled, #quant4:filled, #precoU4:filled"
    		}
            
			},
		messages: {
            cliente: {
                required: "<small class='red'>Digite o nome</small>"
            },
            email: {
                required: "<small class='red'>Digite um email válido</small>",
                email: "<small class='red'>Digite um email válido</small>"
            },
            fazenda: {
                required: '<small class="red">Digite o nome da fazenda</small>'
            },
            cep: {
                required: '<small class="red">Digite o cep</small>'
            },
            cidade: {
                required: '<small class="red">Digite a cidade</small>'
            },
            inscricao: {
                required: '<small class="red">Digite a I.E.</small>'
            },
            cnpj: {
                required: '<small class="red">Informe um CNPJ</small>',
					 cnpj: '<small class="red">Informe um CNPJ válido</small>'
            },
            cpf: {
                required: '<small class="red">Ou informe um CPF</small>',
					 cpf: '<small class="red">Informe um CPF válido</small>'
            },
            cep_corresp: {
                required: '<small class="red">Digite o CEP</small>'
            },
            endereco_corresp: {
                required: '<small class="red">Digite o endereço</small>'
            },
            numero_corresp: {
                required: '<small class="red">Digite o número</small>'
            },
            bairro_corresp: {
                required: '<small class="red">Digite o bairro</small>'
            },
            cidade_corresp: {
                required: '<small class="red">Digite a cidade</small>'
            },
            estado_corresp: {
                required: '<small class="red">Digite o estado</small>'
            },
            telefone: {
                required: '<small class="red">Digite o telefone</small>'
            },
				rebanho: {
                required: '<small class="red">Digite o rebanho</small>'
            },
				assina: {
                required: '<small class="red">Digite quem assina</small>'
            },
				assina_cpf: {
                required: '<small class="red">Digite o cpf</small>'
            },
				cargo: {
                required: '<small class="red">Digite o cargo</small>'
            },

			customRequired: {required: '<big style="font-size: 13px; color: #F00; font-weight: bold; text-align: center;">A soma das parcelas está incorreta.</big>'},
        	
			produto0: { required: "<br /><small class='red'>Selecione</small>" },
        	id_pedido_produto_vc0: { required: "<small class='red'>Selecione</small>" },
        	saca0: { required: "<small class='red'>Preencha</small>" },
        	quant0: { required: "<small class='red'>Preencha</small>" },
        	precoU0: { required: "<small class='red'>Preencha</small>" },
        	precoT0: { required: "<small class='red'>Preencha</small>" },
        	
			produto1: { required: "<br /><small class='red'>Selecione</small>" },
        	id_pedido_produto_vc1: { required: "<small class='red'>Selecione</small>" },
        	saca1: { required: "<small class='red'>Preencha</small>" },
        	quant1: { required: "<small class='red'>Preencha</small>" },
        	precoU1: { required: "<small class='red'>Preencha</small>" },
        	precoT1: { required: "<small class='red'>Preencha</small>" },
        	
			produto2: { required: "<br /><small class='red'>Selecione</small>" },
        	id_pedido_produto_vc2: { required: "<small class='red'>Selecione</small>" },
        	saca2: { required: "<small class='red'>Preencha</small>" },
        	quant2: { required: "<small class='red'>Preencha</small>" },
        	precoU2: { required: "<small class='red'>Preencha</small>" },
        	precoT2: { required: "<small class='red'>Preencha</small>" },
        	
			produto3: { required: "<br /><small class='red'>Selecione</small>" },
        	id_pedido_produto_vc3: { required: "<small class='red'>Selecione</small>" },
        	saca3: { required: "<small class='red'>Preencha</small>" },
        	quant3: { required: "<small class='red'>Preencha</small>" },
        	precoU3: { required: "<small class='red'>Preencha</small>" },
        	precoT3: { required: "<small class='red'>Preencha</small>" },
        	
			produto4: { required: "<br /><small class='red'>Selecione</small>" },
        	id_pedido_produto_vc4: { required: "<small class='red'>Selecione</small>" },
        	saca4: { required: "<small class='red'>Preencha</small>" },
        	quant4: { required: "<small class='red'>Preencha</small>" },
        	precoU4: { required: "<small class='red'>Preencha</small>" },
        	precoT4: { required: "<small class='red'>Preencha</small>" }
        },
		submitHandler: function(form) {
			$("#formPreloader").css("display", "block");
			$('#Submeter').hide();
			
			$.post('representantes/inserepedido', $(form).serializeArray(), function(data){
				if(data.rs=='ok' && data.url!=''){
					window.location = data.url;
				}
				$('#aguardeContato').html(data.msg);
				$('#Submeter').show();
			}, "json");
			
			return false;
		}
    });
	 
	$('#cpf, #cnpj').blur(function(){
		$('#cpf, #cnpj').next('label.error').remove();
	});




    $("#form_pedido_OLD").validate({
        rules: {
            cliente: {required: true,minlength: 5},
            email: {required: true,email: true},
            fazenda: {required: true,minlength: 5},
            cep: {required: true,minlength: 5},
            cidade: {required: true,minlength: 5},
            inscricao: {required: true,minlength: 5},
            cpf: {required: true},
            cnpj: {required: true},
            cep_corresp: {required: true},
            endereco_corresp: {required: true,minlength: 5},
            numero_corresp: {required: true},
            bairro_corresp: {required: true,minlength: 5},
            cidade_corresp: {required: true,minlength: 5},
            estado_corresp: {required: true,minlength: 2},
            telefone: {required: true},
            rebanho: {required: true},
			customRequired: {required: true},
			produto0: {
				required: function(element) {
        			return (($('#id_pedido_produto_vc0').val() != '' || $('#saca0').val() != '' || $('#quant0').val() != '' || $('#precoU0').val() != '' || $('#precoT0').val() != ''));
      			}
    		},
			id_pedido_produto_vc0: {
				required: function(element) {
        			return (($('#produto0').val() != '' || $('#saca0').val() != '' || $('#quant0').val() != '' || $('#precoU0').val() != '' || $('#precoT0').val() != ''));
      			}
    		},
			saca0: {
				required: function(element) {
        			return (($('#produto0').val() != '' || $('#id_pedido_produto_vc0').val() != '' || $('#quant0').val() != '' || $('#precoU0').val() != '' || $('#precoT0').val() != ''));
      			}
    		},
			quant0: {
				required: function(element) {
        			return (($('#produto0').val() != '' || $('#id_pedido_produto_vc0').val() != '' || $('#saca0').val() != '' || $('#precoU0').val() != '' || $('#precoT0').val() != ''));
      			}
    		},
			precoU0: {
				required: function(element) {
        			return (($('#produto0').val() != '' || $('#id_pedido_produto_vc0').val() != '' || $('#saca0').val() != '' || $('#quant0').val() != '' || $('#precoT0').val() != ''));
      			}
    		},
			precoT0: {
				required: function(element) {
        			return (($('#produto0').val() != '' || $('#id_pedido_produto_vc0').val() != '' || $('#saca0').val() != '' || $('#quant0').val() != '' || $('#precoU0').val() != ''));
      			}
    		},
			produto1: {
				required: function(element) {
        			return (($('#id_pedido_produto_vc1').val() != '' || $('#saca1').val() != '' || $('#quant1').val() != '' || $('#precoU1').val() != '' || $('#precoT1').val() != ''));
      			}
    		},
			id_pedido_produto_vc1: {
				required: function(element) {
        			return (($('#produto1').val() != '' || $('#saca1').val() != '' || $('#quant1').val() != '' || $('#precoU1').val() != '' || $('#precoT1').val() != ''));
      			}
    		},
			saca1: {
				required: function(element) {
        			return (($('#produto1').val() != '' || $('#id_pedido_produto_vc1').val() != '' || $('#quant1').val() != '' || $('#precoU1').val() != '' || $('#precoT1').val() != ''));
      			}
    		},
			quant1: {
				required: function(element) {
        			return (($('#produto1').val() != '' || $('#id_pedido_produto_vc1').val() != '' || $('#saca1').val() != '' || $('#precoU1').val() != '' || $('#precoT1').val() != ''));
      			}
    		},
			precoU1: {
				required: function(element) {
        			return (($('#produto1').val() != '' || $('#id_pedido_produto_vc1').val() != '' || $('#saca1').val() != '' || $('#quant1').val() != '' || $('#precoT1').val() != ''));
      			}
    		},
			precoT1: {
				required: function(element) {
        			return (($('#produto1').val() != '' || $('#id_pedido_produto_vc1').val() != '' || $('#saca1').val() != '' || $('#quant1').val() != '' || $('#precoU1').val() != ''));
      			}
    		},
			produto2: {
				required: function(element) {
        			return (($('#id_pedido_produto_vc2').val() != '' || $('#saca2').val() != '' || $('#quant2').val() != '' || $('#precoU2').val() != '' || $('#precoT2').val() != ''));
      			}
    		},
			id_pedido_produto_vc2: {
				required: function(element) {
        			return (($('#produto2').val() != '' || $('#saca2').val() != '' || $('#quant2').val() != '' || $('#precoU2').val() != '' || $('#precoT2').val() != ''));
      			}
    		},
			saca2: {
				required: function(element) {
        			return (($('#produto2').val() != '' || $('#id_pedido_produto_vc2').val() != '' || $('#quant2').val() != '' || $('#precoU2').val() != '' || $('#precoT2').val() != ''));
      			}
    		},
			quant2: {
				required: function(element) {
        			return (($('#produto2').val() != '' || $('#id_pedido_produto_vc2').val() != '' || $('#saca2').val() != '' || $('#precoU2').val() != '' || $('#precoT2').val() != ''));
      			}
    		},
			precoU2: {
				required: function(element) {
        			return (($('#produto2').val() != '' || $('#id_pedido_produto_vc2').val() != '' || $('#saca2').val() != '' || $('#quant2').val() != '' || $('#precoT2').val() != ''));
      			}
    		},
			precoT2: {
				required: function(element) {
        			return (($('#produto2').val() != '' || $('#id_pedido_produto_vc2').val() != '' || $('#saca2').val() != '' || $('#quant2').val() != '' || $('#precoU2').val() != ''));
      			}
    		},
			produto3: {
				required: function(element) {
        			return (($('#id_pedido_produto_vc3').val() != '' || $('#saca3').val() != '' || $('#quant3').val() != '' || $('#precoU3').val() != '' || $('#precoT3').val() != ''));
      			}
    		},
			id_pedido_produto_vc3: {
				required: function(element) {
        			return (($('#produto3').val() != '' || $('#saca3').val() != '' || $('#quant3').val() != '' || $('#precoU3').val() != '' || $('#precoT3').val() != ''));
      			}
    		},
			saca3: {
				required: function(element) {
        			return (($('#produto3').val() != '' || $('#id_pedido_produto_vc3').val() != '' || $('#quant3').val() != '' || $('#precoU3').val() != '' || $('#precoT3').val() != ''));
      			}
    		},
			quant3: {
				required: function(element) {
        			return (($('#produto3').val() != '' || $('#id_pedido_produto_vc3').val() != '' || $('#saca3').val() != '' || $('#precoU3').val() != '' || $('#precoT3').val() != ''));
      			}
    		},
			precoU3: {
				required: function(element) {
        			return (($('#produto3').val() != '' || $('#id_pedido_produto_vc3').val() != '' || $('#saca3').val() != '' || $('#quant3').val() != '' || $('#precoT3').val() != ''));
      			}
    		},
			precoT3: {
				required: function(element) {
        			return (($('#produto3').val() != '' || $('#id_pedido_produto_vc3').val() != '' || $('#saca3').val() != '' || $('#quant3').val() != '' || $('#precoU3').val() != ''));
      			}
    		},
			produto4: {
				required: function(element) {
        			return (($('#id_pedido_produto_vc4').val() != '' || $('#saca4').val() != '' || $('#quant4').val() != '' || $('#precoU4').val() != '' || $('#precoT4').val() != ''));
      			}
    		},
			id_pedido_produto_vc4: {
				required: function(element) {
        			return (($('#produto4').val() != '' || $('#saca4').val() != '' || $('#quant4').val() != '' || $('#precoU4').val() != '' || $('#precoT4').val() != ''));
      			}
    		},
			saca4: {
				required: function(element) {
        			return (($('#produto4').val() != '' || $('#id_pedido_produto_vc4').val() != '' || $('#quant4').val() != '' || $('#precoU4').val() != '' || $('#precoT4').val() != ''));
      			}
    		},
			quant4: {
				required: function(element) {
        			return (($('#produto4').val() != '' || $('#id_pedido_produto_vc4').val() != '' || $('#saca4').val() != '' || $('#precoU4').val() != '' || $('#precoT4').val() != ''));
      			}
    		},
			precoU4: {
				required: function(element) {
        			return (($('#produto4').val() != '' || $('#id_pedido_produto_vc4').val() != '' || $('#saca4').val() != '' || $('#quant4').val() != '' || $('#precoT4').val() != ''));
      			}
    		},
			precoT4: {
				required: function(element) {
        			return (($('#produto4').val() != '' || $('#id_pedido_produto_vc4').val() != '' || $('#saca4').val() != '' || $('#quant4').val() != '' || $('#precoU4').val() != ''));
      			}
    		},
			assina: {required: true},
			assina_cpf: {required: true},
			cargo: {required: true}
			},
        messages: {
        	produto0: {
        		required: "<br /><small class='red'>Selecione</small>"
        	},
        	id_pedido_produto_vc0: {
        		required: "<small class='red'>Selecione</small>"
        	},
        	saca0: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	quant0: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	precoU0: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	precoT0: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	produto1: {
        		required: "<br /><small class='red'>Selecione</small>"
        	},
        	id_pedido_produto_vc1: {
        		required: "<small class='red'>Selecione</small>"
        	},
        	saca1: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	quant1: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	precoU1: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	precoT1: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	produto2: {
        		required: "<br /><small class='red'>Selecione</small>"
        	},
        	id_pedido_produto_vc2: {
        		required: "<small class='red'>Selecione</small>"
        	},
        	saca2: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	quant2: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	precoU2: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	precoT2: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	produto3: {
        		required: "<br /><small class='red'>Selecione</small>"
        	},
        	id_pedido_produto_vc3: {
        		required: "<small class='red'>Selecione</small>"
        	},
        	saca3: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	quant3: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	precoU3: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	precoT3: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	produto4: {
        		required: "<br /><small class='red'>Selecione</small>"
        	},
        	id_pedido_produto_vc4: {
        		required: "<small class='red'>Selecione</small>"
        	},
        	saca4: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	quant4: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	precoU4: {
        		required: "<small class='red'>Preencha</small>"
        	},
        	precoT4: {
        		required: "<small class='red'>Preencha</small>"
        	},
            cliente: {
                required: "<small class='red'>Digite o nome</small>",
                minlength: "<small class='red'>Informe pelo menos 5 caracteres</small>"
            },
            email: {
                required: "<small class='red'>Digite um email válido</small>",
                email: "<small class='red'>Digite um email válido</small>"
            },
            fazenda: {
                required: '<small class="red">Digite o nome da fazenda</small>',
                minlength: '<small class="red"></small>'
            },
            cep: {
                required: '<small class="red">Digite o cep</small>',
                minlength: '<small class="red"></small>'
            },
            cidade: {
                required: '<small class="red">Digite a cidade</small>',
                minlength: '<small class="red"></small>'
            },
            inscricao: {
                required: '<small class="red">Digite a I.E.</small>',
                minlength: '<small class="red"></small>'
            },
            cpf: {
                required: '<small class="red"></small>'
            },
            cnpj: {
                required: '<small class="red">Digite o CNPJ ou o CPF</small>'
            },
            cep_corresp: {
                required: '<small class="red">Digite o CEP</small>'
            },
            endereco_corresp: {
                required: '<small class="red">Digite o endereço</small>',
                minlength: '<small class="red"></small>'
            },
            numero_corresp: {
                required: '<small class="red">Digite o número</small>'
            },
            bairro_corresp: {
                required: '<small class="red">Digite o bairro</small>',
                minlength: '<small class="red"></small>'
            },
            cidade_corresp: {
                required: '<small class="red">Digite a cidade</small>',
                minlength: '<small class="red"></small>'
            },
            estado_corresp: {
                required: '<small class="red">Digite o estado</small>',
                minlength: '<small class="red"></small>'
            },
            telefone: {
                required: '<small class="red">Digite o telefone</small>'
            },
			rebanho: {
                required: '<small class="red">Digite o rebanho</small>'
            },
			customRequired: {required: '<big style="font-size: 13px; color: #F00; font-weight: bold; text-align: center;">A soma das parcelas está incorreta.</big>'},
			assina: {
                required: '<small class="red">Digite quem assina</small>'
            },
			assina_cpf: {
                required: '<small class="red">Digite o cpf</small>'
            },
			cargo: {
                required: '<small class="red">Digite o cargo</small>'
            }
        },
		submitHandler: function(form) {
			// APAGA O BOTAO
			$("#formPreloader").css("display", "block");
			$("#Submeter").css("display", "none");
			form.submit();
		},
        ignore: ".ignore"
    });

// ALTERAR A SPAN DE ENTREGA PARA RETIRADA EM LOCAL
$('#despachar').click(function(){
	if ($(this).attr('checked'))
		$('#dispoText').html('Data de despacho');
	else
		$('#dispoText').html('Disponibilidade de Semente a partir de');
});

});

function limitText(limitField, limitCount, limitNum){
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
    var soma = limitNum - limitField.value.length;
    $(limitCount).html(soma.toString(10));
};


/*/---AQUI COMECA VALIDACAO DE I.E. PARA TODOS ESTADOS----/*/
var OrdZero = '0'.charCodeAt(0);

function CharToInt(ch){
    return ch.charCodeAt(0) - OrdZero;
}

function IntToChar(intt){
    return String.fromCharCode(intt + OrdZero);
}

function CheckIEAC(ie){
    if (ie.length != 13)
        return false;
    var b = 4, soma = 0;

    for (var i = 0; i <= 10; i++) {
        soma += CharToInt(ie.charAt(i)) * b;
        --b;
        if (b == 1) {
            b = 9;
        }
    }
    dig = 11 - (soma % 11);
    if (dig >= 10) {
        dig = 0;
    }
    resultado = (IntToChar(dig) == ie.charAt(11));
    if (!resultado) {
        return false;
    }

    b = 5;
    soma = 0;
    for (var i = 0; i <= 11; i++) {
        soma += CharToInt(ie.charAt(i)) * b;
        --b;
        if (b == 1) {
            b = 9;
        }
    }
    dig = 11 - (soma % 11);
    if (dig >= 10) {
        dig = 0;
    }
    if (IntToChar(dig) == ie.charAt(12)) {
        return true;
    }
    else {
        return false;
    }
} //AC
function CheckIEAL(ie){
    if (ie.length != 9)
        return false;
    var b = 9, soma = 0;
    for (var i = 0; i <= 7; i++) {
        soma += CharToInt(ie.charAt(i)) * b;
        --b;
    }
    soma *= 10;
    dig = soma - Math.floor(soma / 11) * 11;
    if (dig == 10) {
        dig = 0;
    }
    return (IntToChar(dig) == ie.charAt(8));
} //AL
function CheckIEAM(ie){
    if (ie.length != 9)
        return false;
    var b = 9, soma = 0;
    for (var i = 0; i <= 7; i++) {
        soma += CharToInt(ie.charAt(i)) * b;
        b--;
    }
    if (soma < 11) {
        dig = 11 - soma;
    }
    else {
        i = soma % 11;
        if (i <= 1) {
            dig = 0;
        }
        else {
            dig = 11 - i;
        }
    }
    return (IntToChar(dig) == ie.charAt(8));
} //am
function CheckIEAP(ie){
    if (ie.length != 9)
        return false;
    var p = 0, d = 0, i = ie.substring(1, 8);
    if ((i >= 3000001) && (i <= 3017000)) {
        p = 5;
        d = 0;
    }
    else
        if ((i >= 3017001) && (i <= 3019022)) {
            p = 9;
            d = 1;
        }
    b = 9;
    soma = p;
    for (var i = 0; i <= 7; i++) {
        soma += CharToInt(ie.charAt(i)) * b;
        b--;
    }
    dig = 11 - (soma % 11);
    if (dig == 10) {
        dig = 0;
    }
    else
        if (dig == 11) {
            dig = d;
        }
    return (IntToChar(dig) == ie.charAt(8));
} //ap
function CheckIEBA(ie){
    if (ie.length != 8)
        return false;
    die = ie.substring(0, 8);
    var nro = new Array(8);
    var dig = -1;
    for (var i = 0; i <= 7; i++) {
        nro[i] = CharToInt(die.charAt(i));
    }
    var NumMod = 0;
    if (String(nro[0]).match(/[0123458]/))
        NumMod = 10;
    else
        NumMod = 11;
    b = 7;
    soma = 0;
    for (i = 0; i <= 5; i++) {
        soma += nro[i] * b;
        b--;
    }
    i = soma % NumMod;
    if (NumMod == 10) {
        if (i == 0) {
            dig = 0;
        }
        else {
            dig = NumMod - i;
        }
    }
    else {
        if (i <= 1) {
            dig = 0;
        }
        else {
            dig = NumMod - i;
        }
    }
    resultado = (dig == nro[7]);
    if (!resultado) {
        return false;
    }
    b = 8;
    soma = 0;
    for (i = 0; i <= 5; i++) {
        soma += nro[i] * b;
        b--;
    }
    soma += nro[7] * 2;
    i = soma % NumMod;
    if (NumMod == 10) {
        if (i == 0) {
            dig = 0;
        }
        else {
            dig = NumMod - i;
        }
    }
    else {
        if (i <= 1) {
            dig = 0;
        }
        else {
            dig = NumMod - i;
        }
    }
    return (dig == nro[6]);
} //ba
function CheckIECE(ie){
    if (ie.length > 9)
        return false;
    die = ie;
    if (ie.length < 9) {
        while (die.length <= 8)
            die = '0' + die;
    }
    var nro = Array(9);
    for (var i = 0; i <= 8; i++)
        nro[i] = CharToInt(die[i]);
    b = 9;
    soma = 0;
    for (i = 0; i <= 7; i++) {
        soma += nro[i] * b;
        b--;
    }
    dig = 11 - (soma % 11);
    if (dig >= 10)
        dig = 0;
    return (dig == nro[8]);
} //ce
function CheckIEDF(ie){
    if (ie.length != 13)
        return false;
    var nro = new Array(13);
    for (var i = 0; i <= 12; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 4;
    soma = 0;
    for (i = 0; i <= 10; i++) {
        soma += nro[i] * b;
        b--;
        if (b == 1)
            b = 9;
    }
    dig = 11 - (soma % 11);
    if (dig >= 10)
        dig = 0;
    resultado = (dig == nro[11]);
    if (!resultado)
        return false;
    b = 5;
    soma = 0;
    for (i = 0; i <= 11; i++) {
        soma += nro[i] * b;
        b--;
        if (b == 1)
            b = 9;
    }
    dig = 11 - (soma % 11);
    if (dig >= 10)
        dig = 0;
    return (dig == nro[12]);
}

// CHRISTOPHE T. C. <wG @ codingz.info>
function CheckIEES(ie){
    if (ie.length != 9)
        return false;
    var nro = new Array(9);
    for (var i = 0; i <= 8; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 9;
    soma = 0;
    for (i = 0; i <= 7; i++) {
        soma += nro[i] * b;
        b--;
    }
    i = soma % 11;
    if (i < 2)
        dig = 0;
    else
        dig = 11 - i;
    return (dig == nro[8]);
}

function CheckIEGO(ie){
    if (ie.length != 9)
        return false;
    s = ie.substring(0, 2);
    if ((s == '10') || (s == '11') || (s == '15')) {
        var nro = new Array(9);
        for (var i = 0; i <= 8; i++)
            nro[i] = CharToInt(ie.charAt(i));
        n = Math.floor(ie / 10);
        if (n = 11094402) {
            if ((nro[8] == 0) || (nro[8] == 1))
                return true;
        }
        b = 9;
        soma = 0;
        for (i = 0; i <= 7; i++) {
            soma += nro[i] * b;
            b--;
        }
        i = soma % 11;
        if (i == 0)
            dig = 0;
        else {
            if (i == 1) {
                if ((n >= 10103105) && (n <= 10119997))
                    dig = 1;
                else
                    dig = 0;
            }
            else
                dig = 11 - i;
        }
        return (dig == nro[8]);
    }
}

function CheckIEMA(ie){
    if (ie.length != 9)
        return false;
    var nro = new Array(9);
    for (var i = 0; i <= 8; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 9;
    soma = 0;
    for (i = 0; i <= 7; i++) {
        soma += nro[i] * b;
        b--;
    }
    i = soma % 11;
    if (i <= 1)
        dig = 0;
    else
        dig = 11 - i;
    return (dig == nro[8]);
}

function CheckIEMT(ie){
    if (ie.length < 9)
        return false;
    die = ie;
    if (die.length < 11) {
        while (die.length <= 10)
            die = '0' + die;
        var nro = new Array(11);
        for (var i = 0; i <= 10; i++)
            nro[i] = CharToInt(die[i]);
        b = 3;
        soma = 0;
        for (i = 0; i <= 9; i++) {
            soma += nro[i] * b;
            b--;
            if (b == 1)
                b = 9;
        }
        i = soma % 11;
        if (i <= 1)
            dig = 0;
        else
            dig = 11 - i;
        return (dig == nro[10]);
    }
} //muito
function CheckIEMS(ie){
    if (ie.length != 9)
        return false;
    if (ie.substring(0, 2) != '28')
        return false;
    var nro = new Array(9);
    for (var i = 0; i <= 8; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 9;
    soma = 0;
    for (i = 0; i <= 7; i++) {
        soma += nro[i] * b;
        b--;
    }
    i = soma % 11;
    if (i <= 1)
        dig = 0;
    else
        dig = 11 - i;
    return (dig == nro[8]);
} //ms
function CheckIEPA(ie){
    if (ie.length != 9)
        return false;
    if (ie.substring(0, 2) != '15')
        return false;
    var nro = new Array(9);
    for (var i = 0; i <= 8; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 9;
    soma = 0;
    for (i = 0; i <= 7; i++) {
        soma += nro[i] * b;
        b--;
    }
    i = soma % 11;
    if (i <= 1)
        dig = 0;
    else
        dig = 11 - i;
    return (dig == nro[8]);
} //pra
function CheckIEPB(ie){
    if (ie.length != 9)
        return false;
    var nro = new Array(9);
    for (var i = 0; i <= 8; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 9;
    soma = 0;
    for (i = 0; i <= 7; i++) {
        soma += nro[i] * b;
        b--;
    }
    i = soma % 11;
    if (i <= 1)
        dig = 0;
    else
        dig = 11 - i;
    return (dig == nro[8]);
} //pb
function CheckIEPR(ie){
    if (ie.length != 10)
        return false;
    var nro = new Array(10);
    for (var i = 0; i <= 9; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 3;
    soma = 0;
    for (i = 0; i <= 7; i++) {
        soma += nro[i] * b;
        b--;
        if (b == 1)
            b = 7;
    }
    i = soma % 11;
    if (i <= 1)
        dig = 0;
    else
        dig = 11 - i;
    resultado = (dig == nro[8]);
    if (!resultado)
        return false;
    b = 4;
    soma = 0;
    for (i = 0; i <= 8; i++) {
        soma += nro[i] * b;
        b--;
        if (b == 1)
            b = 7;
    }
    i = soma % 11;
    if (i <= 1)
        dig = 0;
    else
        dig = 11 - i;
    return (dig == nro[9]);
} //pr
function CheckIEPE(ie){
    if (ie.length != 14)
	{
		var soma1 = 0;
		var soma2 = 0;
		var resto1 = 0;
	    soma1 = ((ie.substr(0,1)*8)+(ie.substr(1,1)*7)+(ie.substr(2,1)*6)+(ie.substr(3,1)*5)+(ie.substr(4,1)*4)+(ie.substr(5,1)*3)+(ie.substr(6,1)*2));
		resto1 = (soma1 % 11);
		if (resto1 == 0 || resto1 == 1)
			var dg1 = 0;
		else
			var dg1 = (11 - resto1);

	    soma2 = ((ie.substr(0,1)*9)+(ie.substr(1,1)*8)+(ie.substr(2,1)*7)+(ie.substr(3,1)*6)+(ie.substr(4,1)*5)+(ie.substr(5,1)*4)+(ie.substr(6,1)*3)+(dg1*2));
		resto2 = (soma2 % 11);
		if (resto2 == 0 || resto2 == 1)
			var dg2 = 0;
		else
			var dg2 = (11 - resto2);

		return (dg1+''+dg2 == (ie.substr(7,1))+''+(ie.substr(8,1)))
	}
	else
	{
	    var nro = new Array(14);
	    for (var i = 0; i <= 13; i++)
	        nro[i] = CharToInt(ie.charAt(i));
	    b = 5;
	    soma = 0;
	    for (i = 0; i <= 12; i++) {
	        soma += nro[i] * b;
	        b--;
	        if (b == 0)
	            b = 9;
	    }
	    dig = 11 - (soma % 11);
	    if (dig > 9)
	        dig = dig - 10;
	    return (dig == nro[13]);
    }
} //pe
function CheckIEPI(ie){
    if (ie.length != 9)
        return false;
    var nro = new Array(9);
    for (var i = 0; i <= 8; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 9;
    soma = 0;
    for (i = 0; i <= 7; i++) {
        soma += nro[i] * b;
        b--;
    }
    i = soma % 11;
    if (i <= 1)
        dig = 0;
    else
        dig = 11 - i;
    return (dig == nro[8]);
} //pi
function CheckIERJ(ie){
    if (ie.length != 8)
        return false;
    var nro = new Array(8);
    for (var i = 0; i <= 7; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 2;
    soma = 0;
    for (i = 0; i <= 6; i++) {
        soma += nro[i] * b;
        b--;
        if (b == 1)
            b = 7;
    }
    i = soma % 11;
    if (i <= 1)
        dig = 0;
    else
        dig = 11 - i;
    return (dig == nro[7]);
} //rj
// CHRISTOPHE T. C. <wG @ codingz.info>
function CheckIERN(ie){
    if (ie.length != 9)
        return false;
    var nro = new Array(9);
    for (var i = 0; i <= 8; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 9;
    soma = 0;
    for (i = 0; i <= 7; i++) {
        soma += nro[i] * b;
        b--;
    }
    soma *= 10;
    dig = soma % 11;
    if (dig == 10)
        dig = 0;
    return (dig == nro[8]);
} //rn
function CheckIERS(ie){
    if (ie.length != 10)
        return false;
    i = ie.substring(0, 3);
    if ((i >= 1) && (i <= 467)) {
        var nro = new Array(10);
        for (var i = 0; i <= 9; i++)
            nro[i] = CharToInt(ie.charAt(i));
        b = 2;
        soma = 0;
        for (i = 0; i <= 8; i++) {
            soma += nro[i] * b;
            b--;
            if (b == 1)
                b = 9;
        }
        dig = 11 - (soma % 11);
        if (dig >= 10)
            dig = 0;
        return (dig == nro[9]);
    } //if i&&i
} //rs

function CheckIERO(ie){
	var s = '';
	var teste1, teste2;
	var a, soma = 0;
	if (ie.length == 9)
	{
		// TENTA VALIDAR PELO METODO ANTIGO
		soma = (ie.substr(3,1)*6)+(ie.substr(4,1)*5)+(ie.substr(5,1)*4)+(ie.substr(6,1)*3)+(ie.substr(7,1)*2);
		dig = 11 - (soma % 11);
		if (dig > 9)
			dig = dig - 10;

		if (dig == ie[8])
			teste1 = 'ok';
		else
			teste1 = 'erro';
	}
	if (ie.length != 14)
	{
		// PREENCHE COM ZERO
		for (a=0;a<(14-(ie.length));a++)
			s = s + '0';
		ie = s+ie;
	}
	if (ie.length == 14)
	{
		// TENTA VALIDAR PELO METODO NOVO
		soma = (ie.substr(0,1)*6)+(ie.substr(1,1)*5)+(ie.substr(2,1)*4)+(ie.substr(3,1)*3)+(ie.substr(4,1)*2)+(ie.substr(5,1)*9)+(ie.substr(6,1)*8)+(ie.substr(7,1)*7)+(ie.substr(8,1)*6)+(ie.substr(9,1)*5)+(ie.substr(10,1)*4)+(ie.substr(11,1)*3)+(ie.substr(12,1)*2);
		dig = 11 - (soma % 11);
		if (dig > 9)
			dig = dig - 10;

		if (dig == ie.substr(13,1))
			teste2 = 'ok';
		else
			teste2 = 'erro';
	}
	if (teste1 == 'ok' || teste2 == 'ok')
		return true;
	else
		return false;
};

function CheckIERR(ie){
    if (ie.length != 9)
        return false;
    if (ie.substring(0, 2) != '24')
        return false;
    var nro = new Array(9);
    for (var i = 0; i <= 8; i++)
        nro[i] = CharToInt(ie.charAt(i));
    var soma = 0;
    var n = 0;
    for (i = 0; i <= 7; i++)
        soma += nro[i] * ++n;
    dig = soma % 9;
    return (dig == nro[8]);
} //rr
function CheckIESC(ie){
    if (ie.length != 9)
        return false;
    var nro = new Array(9);
    for (var i = 0; i <= 8; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 9;
    soma = 0;
    for (i = 0; i <= 7; i++) {
        soma += nro[i] * b;
        b--;
    }
    i = soma % 11;
    if (i <= 1)
        dig = 0;
    else
        dig = 11 - i;
    return (dig == nro[8]);
} //sc
// CHRISTOPHE T. C. <wG @ codingz.info>

function CheckIESP(ie){
    if (((ie.substring(0, 1)).toUpperCase()) == 'P') {
        s = ie.substring(1, 9);
        var nro = new Array(12);
        for (var i = 0; i <= 7; i++)
            nro[i] = CharToInt(s[i]);
        soma = (nro[0] * 1) + (nro[1] * 3) + (nro[2] * 4) + (nro[3] * 5) +
        (nro[4] * 6) +
        (nro[5] * 7) +
        (nro[6] * 8) +
        (nro[7] * 10);
        dig = soma % 11;
        if (dig >= 10)
            dig = 0;
        resultado = (dig == nro[8]);
        if (!resultado)
            return false;
    }
    else {
        if (ie.length < 12)
            return false;
        var nro = new Array(12);
        for (var i = 0; i <= 11; i++)
            nro[i] = CharToInt(ie.charAt(i));
        soma = (nro[0] * 1) + (nro[1] * 3) + (nro[2] * 4) + (nro[3] * 5) +
        (nro[4] * 6) +
        (nro[5] * 7) +
        (nro[6] * 8) +
        (nro[7] * 10);
        dig = soma % 11;
        if (dig >= 10)
            dig = 0;
        resultado = (dig == nro[8]);
        if (!resultado)
            return false;
        soma = (nro[0] * 3) + (nro[1] * 2) + (nro[2] * 10) + (nro[3] * 9) +
        (nro[4] * 8) +
        (nro[5] * 7) +
        (nro[6] * 6) +
        (nro[7] * 5) +
        (nro[8] * 4) +
        (nro[9] * 3) +
        (nro[10] * 2);
        dig = soma % 11;
        if (dig >= 10)
            dig = 0;
        return (dig == nro[11]);
    }
} //sp
function CheckIESE(ie){
    if (ie.length != 9)
        return false;
    var nro = new Array(9);
    for (var i = 0; i <= 8; i++)
        nro[i] = CharToInt(ie.charAt(i));
    b = 9;
    soma = 0;
    for (i = 0; i <= 7; i++) {
        soma += nro[i] * b;
        b--;
    }
    dig = 11 - (soma % 11);
    if (dig >= 10)
        dig = 0;
    return (dig == nro[8]);
} //se
function CheckIETO(ie){
    if (ie.length != 9) {
        return false;
    }

    var nro = new Array(9);
    b = 9;
    soma = 0;

    for (var i = 0; i <= 8; i++) {

        nro[i] = CharToInt(ie.charAt(i));

        if (i != 8) {
            soma = soma + (nro[i] * b);
            b--;
        }


    }

    ver = soma % 11;

    if (ver < 2)

        dig = 0;

    if (ver >= 2)
        dig = 11 - ver;

    return (dig == nro[8]);
} //to
//inscrição estadual antiga
function CheckIETOantigo(ie){

    if (ie.length != 11) {
        return false;

    }


    var nro = new Array(11);
    b = 9;
    soma = 0;

    s = ie.substring(2, 4);

    if (s != '01' || s != '02' || s != '03' || s != '99') {


        for (var i = 0; i <= 10; i++) {

            nro[i] = CharToInt(ie.charAt(i));

            if (i != 3 || i != 4) {

                soma = soma + (nro[i] * b);
                b--;

            } // if ( i != 3 || i != 4 )
        } //fecha for
        resto = soma % 11;

        if (resto < 2) {

            dig = 0;

        }


        if (resto >= 2) {

            dig = 11 - resto;

        }

        return (dig == nro[10]);

    } // fecha if
}//fecha função CheckIETOantiga
function CheckIEMG(ie){
    if (ie.substring(0, 2) == 'PR')
        return true;
    if (ie.substring(0, 5) == 'ISENT')
        return true;
    if (ie.length != 13)
        return false;
    dig1 = ie.substring(11, 12);
    dig2 = ie.substring(12, 13);
    inscC = ie.substring(0, 3) + '0' + ie.substring(3, 11);
    insc = inscC.split('');
    npos = 11;
    i = 1;
    ptotal = 0;
    psoma = 0;
    while (npos >= 0) {
        i++;
        psoma = CharToInt(insc[npos]) * i;
        if (psoma >= 10)
            psoma -= 9;
        ptotal += psoma;
        if (i == 2)
            i = 0;
        npos--;
    }
    nresto = ptotal % 10;
    if (nresto == 0)
        nresto = 10;
    nresto = 10 - nresto;
    if (nresto != CharToInt(dig1))
        return false;
    npos = 11;
    i = 1;
    ptotal = 0;
    is = ie.split('');
    while (npos >= 0) {
        i++;
        if (i == 12)
            i = 2;
        ptotal += CharToInt(is[npos]) * i;
        npos--;
    }
    nresto = ptotal % 11;
    if ((nresto == 0) || (nresto == 1))
        nresto = 11;
    nresto = 11 - nresto;
    return (nresto == CharToInt(dig2));
}

function CheckIE(ie, estado){
    ie = ie.replace(/\./g, '');
    ie = ie.replace(/\\/g, '');
    ie = ie.replace(/\-/g, '');
    ie = ie.replace(/\//g, '');
    switch (estado) {
        case "AC":
            foo = CheckIEAC(ie);
            break;
        case "AL":
            foo = CheckIEAL(ie);
            break;
        case "AP":
            foo = CheckIEAP(ie);
            break;
        case "AM":
            foo = CheckIEAM(ie);
            break;
        case "BA":
            foo = CheckIEBA(ie);
            break;
        case "CE":
            foo = CheckIECE(ie);
            break;
        case "DF":
            foo = CheckIEDF(ie);
            break;
        case "ES":
            foo = CheckIEES(ie);
            break;
        case "GO":
            foo = CheckIEGO(ie);
            break;
        case "MA":
            foo = CheckIEMA(ie);
            break;
        case "MT":
            foo = CheckIEMT(ie);
            break;
        case "MS":
            foo = CheckIEMS(ie);
            break;
        case "MG":
            foo = CheckIEMG(ie);
            break;
        case "PA":
            foo = CheckIEPA(ie);
            break;
        case "PB":
            foo = CheckIEPB(ie);
            break;
        case "PR":
            foo = CheckIEPR(ie);
            break;
        case "PE":
            foo = CheckIEPE(ie);
            break;
        case "PI":
            foo = CheckIEPI(ie);
            break;
        case "RJ":
            foo = CheckIERJ(ie);
            break;
        case "RN":
            foo = CheckIERN(ie);
            break;
        case "RS":
            foo = CheckIERS(ie);
            break;
        case "RO":
            foo = CheckIERO(ie);
            break;
        case "RR":
            foo = CheckIERR(ie);
            break;
        case "SC":
            foo = CheckIESC(ie);
            break;
        case "SP":
            foo = CheckIESP(ie);
            break;
        case "SE":
            foo = CheckIESE(ie);
            break;
        case "TO":
            foo = ((CheckIETO(ie)) || (CheckIETOantigo(ie)));
            break;//foo = CheckIETO(ie); break;
    }
    if (ie == 'ISENTO')
        foo = true;

    if (!foo && ie != '') {
        $('#inscricao').val('');
		alert('Inscrição Inválida');
    }
}

// AUTOCOMPLETE   ////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
autocomplete = function(){
	$("#cliente").autocomplete('representantes/autocomplete', {
		selectFirst: false,
		matchCase: true,
		minChars: 3
	});

	$("#cliente").result(function(event, data, formatted) {
		$.post("representantes/cliente/" + data[1], {'idcliente': data[1] }, retornCliente, "json");
	});
}

function retornCliente(rs){
    // VALIDA O RESULTADO
    if (rs.resultado == "ok") {
        $("#cliente").attr("value", rs.cliente);
        $("#email").attr("value", rs.email);
        $("#fazenda").attr("value", rs.fazenda);
        $("#cep").attr("value", rs.cep);
        $("#cidade").attr("value", rs.cidade);
        $("#id_cidade").attr("value", rs.id_cidade);
        $("#cnpj").attr("value", rs.cnpj);
        $("#cpf").attr("value", rs.cpf);
        $("#inscricao").attr("value", rs.inscricao);
        $("#cep_corresp").attr("value", rs.cep_corresp);
        $("#endereco_corresp").attr("value", rs.endereco_corresp);
        $("#numero_corresp").attr("value", rs.numero_corresp);
        $("#bairro_corresp").attr("value", rs.bairro_corresp);
        $("#cidade_corresp").attr("value", rs.cidade_corresp);
        $("#estado_corresp").attr("value", rs.estado_corresp);
        $("#telefone").attr("value", rs.telefone);
		$("#op"+rs.estado).attr("selected", "selected");

		$("#codigo").attr("value", rs.codigo);
		$("#nascimento").attr("value", rs.nascimento);
		$("#caixa_postal").attr("value", rs.caixapostal);
		$("#fax").attr("value", rs.fax);
		$("#rebanho").attr("value", rs.rebanho);

        if (rs.cnpj != '') {
            vcnpj(rs.cnpj);
        }
        if (rs.cpf != '') {
            vcpf(rs.cpf);
        }
    }
}

