// JavaScript Document

try{
    xmlhttp = new XMLHttpRequest();
}catch(ee){
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttp = false;
        }
    }
}


atual=0
function carrega(n){
    //Exibe o texto carregando no div conteÃºdo
    var conteudo=document.getElementById("texto_onde_comprar")
    conteudo.innerHTML='carregando...'

    //Guarda a pÃ¡gina escolhida na variÃ¡vel atual
    atual=n

    //Abre a url
    xmlhttp.open("GET", "representantes.php?estado="+n,true);

    //Executada quando o navegador obtiver o cÃ³digo
    xmlhttp.onreadystatechange=function() {

        if (xmlhttp.readyState==4){

            //LÃª o texto
            var texto=xmlhttp.responseText

            //Desfaz o urlencode
            texto=texto.replace(/\+/g," ")
            texto=unescape(texto)

            //Exibe o texto no div conteÃºdo
            var conteudo=document.getElementById("texto_onde_comprar")
            conteudo.innerHTML=texto

            //ObtÃ©m os links do menu
            var menu=document.getElementById("menu")
            var links=menu.getElementsByTagName("a")

            //Limpa as classes do menu
            for(var i=0;i<links.length;i++)
                links[i].className=""

            //Marca o selecionado
            links[atual-1].className="selected"
        }
    }
    xmlhttp.send(null)
}


function limpa_tf(obj, valor){
	if(obj.value==valor){
		obj.value = "";
	}
}

function reseta_tf(obj, valor){
	if(obj.value==""){
		obj.value = valor;
	}
}

function act_acesse(){
	if($("#box_acesse").css('display')=="none"){
		$("#box_acesse").slideDown("slow");
	} else {
		$("#box_acesse").slideUp("slow");
	}
}

function abre_produto(div){
	$("#"+div).slideToggle();
}

function confereCampos(form) {
    var campos = form.getElementsByTagName('input');
    var podeEnviar = true;
    for (i = 0; i < campos.length; i++) {
        var classe = campos[i].className;
        var valor = campos[i].value;
        if (classe == 'tf' && valor == '') podeEnviar = false;
    }
    if (podeEnviar == true) {
        return true;
    } else {
        alert('Existem campos obrigatórios em branco!')
        return false;
    }
}

function ValidaCNPJ(cnpj) {
  var i = 0;
  var l = 0;
  var strNum = "";
  var strMul = "6543298765432";
  var character = "";
  var iValido = 1;
  var iSoma = 0;
  var strNum_base = "";
  var iLenNum_base = 0;
  var iLenMul = 0;
  var iSoma = 0;
  var strNum_base = 0;
  var iLenNum_base = 0;


  l = cnpj.length;
  for (i = 0; i < l; i++) {
        caracter = cnpj.substring(i,i+1)
        if ((caracter >= '0') && (caracter <= '9'))
           strNum = strNum + caracter;
  };

   if (document.getElementById("cnpj").value.substring(0,10) != document.getElementById("cnpj_faturamento").value.substring(0,10)){
           document.formCompra.cnpj_faturamento.value = '';
           alert ("O Campo CNPJ deve ser os 8 primeiros digitos do cliente");
           }
   else
   if (document.getElementById("cnpj").value.substring(0,18) == document.getElementById("cnpj_faturamento").value.substring(0,18)){
           document.formCompra.cnpj_faturamento.value = '';
           alert ("O Campo CNPJ não pode ser igual ao do cliente selecionado");
           }

  strNum_base = strNum.substring(0,12);
  iLenNum_base = strNum_base.length - 1;
  iLenMul = strMul.length - 1;
  for(i = 0;i < 12; i++)
        iSoma = iSoma +
                        parseInt(strNum_base.substring((iLenNum_base-i),(iLenNum_base-i)+1),10) *
                        parseInt(strMul.substring((iLenMul-i),(iLenMul-i)+1),10);

  iSoma = 11 - (iSoma - Math.floor(iSoma/11) * 11);

  if(iSoma == 11 || iSoma == 10)
        iSoma = 0;

  strNum_base = strNum_base + iSoma;
  iSoma = 0;
  iLenNum_base = strNum_base.length - 1
  for(i = 0; i < 13; i++)
        iSoma = iSoma +
                        parseInt(strNum_base.substring((iLenNum_base-i),(iLenNum_base-i)+1),10) *
                        parseInt(strMul.substring((iLenMul-i),(iLenMul-i)+1),10)

  iSoma = 11 - (iSoma - Math.floor(iSoma/11) * 11);
  if(iSoma == 11 || iSoma == 10)
        iSoma = 0;
  strNum_base = strNum_base + iSoma;
  if(strNum != strNum_base && strNum != 0){
        document.formCompra.cnpj_faturamento.value = '';
        document.getElementById('cnpj_faturamento').focus();
        alert ("CNPJ Inválido.");
   }
}


function fmtMoney(n, c, d, t){
   var m = (c = Math.abs(c) + 1 ? c : 2, d = d || ",", t = t || ".",
      /(\d+)(?:(\.\d+)|)/.exec(n + "")), x = m[1].length > 3 ? m[1].length % 3 : 0;
   return (x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g,
      "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : "");
};

function validaCampoFinalizar()
{
if(document.formCompra.nome.selectedIndex=="")
{
alert("O Campo CLIENTE é obrigatório!");
document.formCompra.nome.focus();
return false
}
else
if(document.formCompra.industrializacao[1].checked && document.formCompra.c_industrializado.selectedIndex=="" )
{
alert("O Campo CLIENTE p/ industriaçização é obrigatório!");
return false;
}
else
if(document.formCompra.faturamento[1].checked && document.formCompra.logradouro_faturamento.value=="")
{
alert("O Campo LOGRADOURO do endereço de entrega é obrigatório!");
return false;
}
else
if(document.formCompra.faturamento[1].checked && document.formCompra.numero_faturamento.value=="")
{
alert("O Campo NUMERO do endereço de entrega é obrigatório!");
return false;
}
else
if(document.formCompra.faturamento[1].checked && document.formCompra.bairro_faturamento.value=="")
{
alert("O Campo BAIRRO do endereço de entrega é obrigatório!");
return false;
}
else
if(document.formCompra.faturamento[1].checked && document.formCompra.cidade_faturamento.value=="")
{
alert("O Campo CIDADE do endereço de entrega é obrigatório!");
return false;
}
else
if(document.formCompra.faturamento[1].checked && document.formCompra.uf_faturamento.value=="")
{
alert("O Campo UF do endereço de entrega é obrigatório!");
return false;
}
else
if(document.formCompra.faturamento[1].checked && document.formCompra.cep_faturamento.value=="")
{
alert("O Campo CEP do endereço de entrega é obrigatório!!");
return false
}
else
if(document.formCompra.faturamento[1].checked && document.formCompra.cnpj_faturamento.value=="" )
{
alert("O Campo CNPJ do endereço de entrega é obrigatório!");
return false;
}
else
if(document.formCompra.faturamento[1].checked && document.formCompra.ie.value=="" )
{
alert("O Campo INSCRIÇÃO ESTADUAL é obrigatório!");
return false;
}
else
if(document.formCompra.frete.selectedIndex=="")
{
alert("O Campo FRETE é obrigatório!");
document.formCompra.frete.focus();
return false
}
else
if(document.formCompra.transportadora.selectedIndex=="")
{
alert("O Campo TRANSPORTADORA é obrigatório!");
document.formCompra.transportadora.focus();
return false
}
else
if(document.formCompra.tab_venda.selectedIndex=="")
{
alert("O Campo Tab.Venda é obrigatório!");
document.formCompra.tab_venda.focus();
return false
}
else
if(document.formCompra.prazo.selectedIndex=="")
{
alert("O Campo Condição de Pagamento é obrigatório!");
document.formCompra.prazo.focus();
return false
}
}

function formatar_mascara(src, mascara) {
	var campo = src.value.length;
	var saida = mascara.substring(0,1);
	var texto = mascara.substring(campo);
	if(texto.substring(0,1) != saida) {
		src.value += texto.substring(0,1);
	}
}

function FormataValor(id,tammax,teclapres) {

                if(window.event) { // Internet Explorer
                 var tecla = teclapres.keyCode; }
                else if(teclapres.which) { // Nestcape / firefox
                 var tecla = teclapres.which;
                }


vr = document.getElementById(id).value;
vr = vr.toString().replace( "/", "" );
vr = vr.toString().replace( "/", "" );
vr = vr.toString().replace( ",", "" );
vr = vr.toString().replace( ".", "" );
vr = vr.toString().replace( ".", "" );
vr = vr.toString().replace( ".", "" );
vr = vr.toString().replace( ".", "" );
tam = vr.length;

if (tam < tammax && tecla != 8){ tam = vr.length + 1; }

if (tecla == 8 ){ tam = tam - 1; }

if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
if ( tam <= 2 ){
document.getElementById(id).value = vr; }
if ( (tam > 2) && (tam <= 5) ){
document.getElementById(id).value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ); }
if ( (tam >= 6) && (tam <= 8) ){
document.getElementById(id).value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
if ( (tam >= 9) && (tam <= 11) ){
document.getElementById(id).value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
if ( (tam >= 12) && (tam <= 14) ){
document.getElementById(id).value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
if ( (tam >= 15) && (tam <= 17) ){
document.getElementById(id).value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );}
}
}

function mostra(obj,obj2){
obj.style.display='block';
obj2.style.display='none';
}

function esconde(obj,obj2){
obj.style.display='block';
obj2.style.display='none';
}

function desabilitaradio(){
    document.getElementById('end_faturamento1').checked = true;
    document.getElementById('end_faturamento').style.display='none';
    }
function habilitaradio(){
    document.getElementById('end_faturamento2').checked = false;
    document.getElementById('end_faturamento1').checked = true;

    }

function exibe(){
document.getElementById('end_faturamento').style.display='block';
document.getElementById('industrializacao1').checked = true;
document.getElementById('industrializado').style.display='none';
document.formCompra.c_industrializado.selectedIndex="";
document.formCompra.logradouro_industrializado.value="";
document.formCompra.numero_industrializado.value="";
document.formCompra.complemento_industrializado.value="";
document.formCompra.bairro_industrializado.value="";
document.formCompra.cidade_industrializado.value="";
document.formCompra.uf_industrializado.value="";
document.formCompra.cep_industrializado.value="";

}

function inibe(){
document.getElementById('end_faturamento').style.display='none';
document.formCompra.cnpj_faturamento.value="";
document.formCompra.ie.value="";
document.formCompra.logradouro_faturamento.value="";
document.formCompra.numero_faturamento.value="";
document.formCompra.complemento_faturamento.value="";
document.formCompra.bairro_faturamento.value="";
document.formCompra.cidade_faturamento.value="";
document.formCompra.uf_faturamento.value="";
document.formCompra.cep_faturamento.value="";
}


function mostra(){
document.getElementById('industrializado').style.display='block';
}

function esconde(){
document.getElementById('industrializado').style.display='none';
document.formCompra.c_industrializado.selectedIndex="";
document.formCompra.logradouro_industrializado.value="";
document.formCompra.numero_industrializado.value="";
document.formCompra.complemento_industrializado.value="";
document.formCompra.bairro_industrializado.value="";
document.formCompra.cidade_industrializado.value="";
document.formCompra.uf_industrializado.value="";
document.formCompra.cep_industrializado.value="";
}
  
  addEvent = function(o, e, f, s) {
   var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
   r[r.length] = [f, s || o], o[e] = function(e){
      try{
         (e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
         e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
         e.target || (e.target = e.srcElement || null);
         e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
      }catch(f){}
      for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
      return e = null, !!d;
    }
};

   $(document).ready(function(){
         $("select[name='transportadora']").change(function(){
             var frete = $("input[name='frete']");
             $( frete ).val('Carregando...');
                 $.getJSON(
                     'abrir_frete.php',
                     { codtransp: $( this ).val() },
                     function( json )
                     {
                         $( frete ).val( json.frete );

                     }
                 );
         });
     });

     	$(document).ready(function(){
		  $("select[name='nome']").change(function(){
			$("input[name='logradouro']").val('Carregando...');
			$("input[name='numero']").val('Carregando...');
			$("input[name='complemento']").val('Carregando...');
			$("input[name='bairro']").val('Carregando...');
			$("input[name='cidade']").val('Carregando...');
			$("input[name='uf']").val('Carregando...');
			$("input[name='cep']").val('Carregando...');
			$("input[name='cnpj']").val('Carregando...');
			$.getJSON(
				'function.php',
				{cod_cliente: $(this).val()},
				function(data){
					$.each(data, function(i, obj){
						$("input[name='logradouro']").val(obj.logradouro);
						$("input[name='numero']").val(obj.numero);
						$("input[name='complemento']").val(obj.complemento);
						$("input[name='bairro']").val(obj.bairro);
						$("input[name='cidade']").val(obj.cidade);
						$("input[name='uf']").val(obj.uf);
			            $("input[name='cep']").val(obj.cep);
			            $("input[name='cnpj']").val(obj.cnpj);
					})
				});
		});
	});
	
   $(document).ready(function(){
         $("select[name='acondicionamento']").change(function(){
             var fator = $("input[name='fator']");
             var qtdcaixa = $("input[name='qtdcaixa']");

             $( fator ).val('Carregando...');
             $( qtdcaixa ).val('Carregando...');
                 $.getJSON(
                     'function_fator.php',
                     { id: $( this ).val() },
                     function( json )
                     {
                         $( fator ).val( json.fator );
                         $( qtdcaixa ).val( json.qtdcaixa );

                     }
                 );
         });
     });

   $(document).ready(function() {
   $("select[name=nome]").change(function(){
      $('select[name=c_industrializado]').html('<option value="xxx">Carregando...</option>');
      $.post('nome.php',{ nome : $(this).val() },
        function(resposta){
                   $('select[name=c_industrializado]').html(resposta);

             }

      );
   });
   });

	$(document).ready(function(){
		$("select[name='c_industrializado']").change(function(){
			$("input[name='logradouro_industrializado']").val('Carregando...');
			$("input[name='numero_industrializado']").val('Carregando...');
			$("input[name='complemento_industrializado']").val('Carregando...');
			$("input[name='bairro_industrializado']").val('Carregando...');
			$("input[name='cidade_industrializado']").val('Carregando...');
			$("input[name='uf_industrializado']").val('Carregando...');
			$("input[name='cep_industrializado']").val('Carregando...');
			$.getJSON(
				'function2.php',
				{cod_cliente: $(this).val()},
				function(data){
					$.each(data, function(i, obj1){
						$("input[name='logradouro_industrializado']").val(obj1.logradouro_industrializado);
						$("input[name='numero_industrializado']").val(obj1.numero_industrializado);
						$("input[name='complemento_industrializado']").val(obj1.complemento_industrializado);
						$("input[name='bairro_industrializado']").val(obj1.bairro_industrializado);
						$("input[name='cidade_industrializado']").val(obj1.cidade_industrializado);
						$("input[name='uf_industrializado']").val(obj1.uf_industrializado);
			            $("input[name='cep_industrializado']").val(obj1.cep_industrializado);
					})
				});
		});
	});
	
	$(document).ready(function() {
   $("select[name=linha]").change(function(){
      $('select[name=artigo]').html('<option value="xxx">Carregando...</option>');
      $.post('selecionar_artigo.php',{ linha : $(this).val() },
        function(resposta){
                   $('select[name=artigo]').html(resposta);

             }
      );
   });
   $("select[name=artigo]").change(function(){
      $('select[name=acabamento]').html('<option value="xxx">Carregando...</option>');
      $.post('selecionar_acabamento.php',{ artigo : $(this).val() },
        function(resposta){
                   $('select[name=acabamento]').html(resposta);
             }
      );
   });

    $("select[name='acabamento']").change(function(){
     $('select[name=produto]').html('<option value="xxx">Carregando...</option>');
      $.post('carregar_produto.php',{
      artigo : ""+$('#artigo').val()+"",
       acabamento: ""+$('#acabamento').val()+""
       },
        function(resposta){
                   $('select[name=produto]').html(resposta);
             }
      );
   });

   $("select[name='produto']").change(function(){
     $('select[name=acondicionamento]').html('<option value="xxx">Carregando...</option>');
      $.post('carregar_acondicionamento.php',{ produto : $(this).val()},
        function(resposta){
                   $('select[name=acondicionamento]').html(resposta);
             }
      );
   });
});

     $(document).ready(function(){
         $("select[name='produto']").change(function(){
             var unidade_venda = $("input[name='unidade_venda']");

             $( unidade_venda ).val('Carregando...');

                 $.getJSON(
                     'function_unidade.php',
                     { cod_pro: $( this ).val() },
                     function( json )
                     {
                         $( unidade_venda ).val( json.unidade_venda );

                     }
                 );
         });
     });


   $(document).ready(function() {
    $("input[name='tab_venda']").change(function(){
    $("input[name='preco']").val('Carregando...');
      $.post('preco.php',{
        tab_venda : ""+$('#tab_venda').val()+"",
            prazo : ""+$('#nome_prazo').val()+"",
            artigo : ""+$('#artigo').val()+"",
            acabamento : ""+$('#acabamento').val()+"",
            composicao : ""+$('#composicao').val()+""
       },
        function(data){
                   $("input[name='preco']").val(data);
             }

      );
   });
   });
      $(document).ready(function() {
    $("input[name='nome_prazo']").change(function(){
     $("input[name='preco']").val('Carregando...');
      $.post('preco.php',{
        tab_venda : ""+$('#tab_venda').val()+"",
            prazo : ""+$('#nome_prazo').val()+"",
            artigo : ""+$('#artigo').val()+"",
            acabamento : ""+$('#acabamento').val()+"",
            composicao : ""+$('#composicao').val()+""
       },
        function(data){
                   $("input[name='preco']").val(data);
             }

      );
   });
   });
         $(document).ready(function() {
    $("select[name='artigo']").change(function(){
     $("input[name='preco']").val('Carregando...');
      $.post('preco.php',{
        tab_venda : ""+$('#tab_venda').val()+"",
            prazo : ""+$('#nome_prazo').val()+"",
            artigo : ""+$('#artigo').val()+"",
            acabamento : ""+$('#acabamento').val()+"",
            composicao : ""+$('#composicao').val()+""
       },
        function(data){
                   $("input[name='preco']").val(data);
             }

      );
   });
   });
            $(document).ready(function() {
    $("select[name='acabamento']").change(function(){
     $("input[name='preco']").val('Carregando...');
      $.post('preco.php',{
        tab_venda : ""+$('#tab_venda').val()+"",
            prazo : ""+$('#nome_prazo').val()+"",
            artigo : ""+$('#artigo').val()+"",
            acabamento : ""+$('#acabamento').val()+"",
            composicao : ""+$('#composicao').val()+""
       },
        function(data){
                   $("input[name='preco']").val(data);
             }

      );
   });
   });
   $(document).ready(function() {
    $("select[name='composicao']").change(function(){
     $("input[name='preco']").val('Carregando...');
      $.post('preco.php',{
        tab_venda : ""+$('#tab_venda').val()+"",
            prazo : ""+$('#nome_prazo').val()+"",
            artigo : ""+$('#artigo').val()+"",
            acabamento : ""+$('#acabamento').val()+"",
            composicao : ""+$('#composicao').val()+""
       },
        function(data){
                   $("input[name='preco']").val(data);
             }

      );
   });
   });

   $(document).ready(function() {
    $("select[name='preco_negociado']").change(function(){
     $("input[name='desconto']").val('Carregando...');
      $.post('desconto.php',{
        tab_venda : ""+$('#tab_venda').val()+"",
            prazo : ""+$('#nome_prazo').val()+"",
            artigo : ""+$('#artigo').val()+"",
            acabamento : ""+$('#acabamento').val()+"",
            composicao : ""+$('#composicao').val()+""
       },
        function(data){
                   $("input[name='preco']").val(data);
             }

      );
   });
   });
   
    function fmtMoney(n, c, d, t){
   var m = (c = Math.abs(c) + 1 ? c : 2, d = d || ",", t = t || ".",
      /(\d+)(?:(\.\d+)|)/.exec(n + "")), x = m[1].length > 3 ? m[1].length % 3 : 0;
   return (x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g,
      "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : "");
};

function soma() {
  var f = document.forms[0];
  var valor1 = parseFloat(f.preco_negociado.value.replace('.','').replace(',','.'));
  var valor2 = parseFloat(f.qtd.value.replace('.','').replace(',','.'));
  var valor3 = ('' + ((valor1||0) * (valor2||0)));
  f.total.value = fmtMoney(valor3);
}

function calcular() {
        var d = document.forms[0];
        var campo1 = parseFloat(d.preco.value.replace('.','').replace(',','.'));
        var campo2 = parseFloat(d.preco_negociado.value.replace('.','').replace(',','.'));
        var campo3 = ('' + ((campo1||0) / (campo2||0)-1)*100);
        d.desconto.value = fmtMoney(campo3);
}

  jQuery(function () {
  $("#telefone1").mask("(99)9999-9999");
  $("#telefone2").mask("(99)9999-9999");
  $("#fax").mask("(99)9999-9999");
  $("#telefonecobranca").mask("(99)9999-9999");
  $("#faxcobranca").mask("(99)9999-9999");
  $("#cnpj").mask("99.999.999/9999-99");
  $("#cep").mask("99999-999");
  $("#cepcobranca").mask("99999-999");
  $("#cepentrega").mask("99999-999");
  $("#cep_faturamento").mask("99999-999");
  $("#cnpj_faturamento").mask("99.999.999/9999-99");
  });

function formatar_mascara(src, mascara) {
	var campo = src.value.length;
	var saida = mascara.substring(0,1);
	var texto = mascara.substring(campo);
	if(texto.substring(0,1) != saida) {
		src.value += texto.substring(0,1);
	}
}

$(document).ready(function() {
   $("select[name=cod_estados]").change(function(){
      $('select[name=cod_cidades]').html('<option value="xxx">... Procurando ...</option>');
      $.post('cidades.php',{ cod_estados : $(this).val() },
        function(resposta){
                   $('select[name=cod_cidades]').html(resposta);
             }

      );
   });

});

function getCobranca() {

           if($.trim($("#cepcobranca").val()) == "")
           return true;

	// Se o campo CEP não estiver vazio
	if($.trim($("#cepcobranca").val()) != "" ){
		//document.getElementById("load").style.display = 'block';
			/*
					Para conectar no serviço e executar o json, precisamos usar a função
					getScript do jQuery, o getScript e o dataType:"jsonp" conseguem fazer o cross-domain, os outros
					dataTypes não possibilitam esta interação entre domínios diferentes
					Estou chamando a url do serviço passando o parâmetro "formato=javascript" e o CEP digitado no formulário
					http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val()
			*/
			$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cepcobranca").val(), function(){
     // o getScript dá um eval no script, então é só ler!
					//Se o resultado for igual a 1
					if(resultadoCEP["resultado"] && resultadoCEP["bairro"] != ""){
							// troca o valor dos elementos
							$("#ecobranca").val(unescape(resultadoCEP["tipo_logradouro"])+": "+unescape(resultadoCEP["logradouro"]));
							$("#bcobranca").val(unescape(resultadoCEP["bairro"]));
							$("#cidadecobranca").val(unescape(resultadoCEP["cidade"]));
							$("#ufcobranca").val(unescape(resultadoCEP["uf"]));
							//$("#enderecoCompleto").show("slow");
							$("#ncobranca").focus();
							//document.getElementById("load").style.display = 'none';
							//validate()
					}else{
                          return true;
							//$("#enderecoCompleto").show("slow");

					}
			});
	}
    else
    {
        alert('Antes, preencha o campo CEP DE COBRANÇA!')
		//document.getElementById("load").style.display = 'none';
    }

}

function getEntrega() {
	// Se o campo CEP não estiver vazio
	if($.trim($("#cepentrega").val()) != ""){
		//document.getElementById("load").style.display = 'block';
			/*
					Para conectar no serviço e executar o json, precisamos usar a função
					getScript do jQuery, o getScript e o dataType:"jsonp" conseguem fazer o cross-domain, os outros
					dataTypes não possibilitam esta interação entre domínios diferentes
					Estou chamando a url do serviço passando o parâmetro "formato=javascript" e o CEP digitado no formulário
					http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val()
			*/
			$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cepentrega").val(), function(){
					// o getScript dá um eval no script, então é só ler!
					//Se o resultado for igual a 1
					if(resultadoCEP["resultado"] && resultadoCEP["bairro"] != ""){
							// troca o valor dos elementos
							$("#eentrega").val(unescape(resultadoCEP["tipo_logradouro"])+": "+unescape(resultadoCEP["logradouro"]));
							$("#bentrega").val(unescape(resultadoCEP["bairro"]));
							$("#cidadeentrega").val(unescape(resultadoCEP["cidade"]));
							$("#ufentrega").val(unescape(resultadoCEP["uf"]));
							//$("#enderecoCompleto").show("slow");
							$("nentrega").focus();
							//document.getElementById("load").style.display = 'none';
							//validate()
					}else{
					
                               return true;
							//$("#enderecoCompleto").show("slow");
					}
			});
	}
    else
    {
        alert('Antes, preencha o campo CEP DE ENTREGA!')
		//document.getElementById("load").style.display = 'none';
    }

}

function mostra_cobranca(){
document.getElementById('end_cobranca').style.display='block';
}

function esconde_cobranca(){
document.getElementById('end_cobranca').style.display='none';
document.cadastro.ecobranca.value="";
document.cadastro.ncobranca.value="";
document.cadastro.bcobranca.value="";
document.cadastro.cepcobranca.value="";
document.cadastro.cidadecobranca.value="";
document.cadastro.ufcobranca.value="";
document.cadastro.telefonecobranca.value="";
document.cadastro.faxcobranca.value="";
}

function exibe_entrega(){
document.getElementById('end_entrega').style.display='block';
}

function inibe_entrega(){
document.getElementById('end_entrega').style.display='none';
document.cadastro.eentrega.value="";
document.cadastro.nentrega.value="";
document.cadastro.bentrega.value="";
document.cadastro.cepentrega.value="";
document.cadastro.cidadeentrega.value="";
document.cadastro.ufentrega.value="";
}


function ValidaCNPJCADASTRO(cnpj) {
  var i = 0;
  var l = 0;
  var strNum = "";
  var strMul = "6543298765432";
  var character = "";
  var iValido = 1;
  var iSoma = 0;
  var strNum_base = "";
  var iLenNum_base = 0;
  var iLenMul = 0;
  var iSoma = 0;
  var strNum_base = 0;
  var iLenNum_base = 0;

  l = cnpj.length;
  for (i = 0; i < l; i++) {
        caracter = cnpj.substring(i,i+1)
        if ((caracter >= '0') && (caracter <= '9'))
           strNum = strNum + caracter;
  };
  strNum_base = strNum.substring(0,12);
  iLenNum_base = strNum_base.length - 1;
  iLenMul = strMul.length - 1;
  for(i = 0;i < 12; i++)
        iSoma = iSoma +
                        parseInt(strNum_base.substring((iLenNum_base-i),(iLenNum_base-i)+1),10) *
                        parseInt(strMul.substring((iLenMul-i),(iLenMul-i)+1),10);

  iSoma = 11 - (iSoma - Math.floor(iSoma/11) * 11);

  if(iSoma == 11 || iSoma == 10)
        iSoma = 0;

  strNum_base = strNum_base + iSoma;
  iSoma = 0;
  iLenNum_base = strNum_base.length - 1
  for(i = 0; i < 13; i++)
        iSoma = iSoma +
                        parseInt(strNum_base.substring((iLenNum_base-i),(iLenNum_base-i)+1),10) *
                        parseInt(strMul.substring((iLenMul-i),(iLenMul-i)+1),10)

  iSoma = 11 - (iSoma - Math.floor(iSoma/11) * 11);
  if(iSoma == 11 || iSoma == 10)
        iSoma = 0;
  strNum_base = strNum_base + iSoma;
  if(strNum != strNum_base && strNum != 0){
        document.cadastro.cnpj.value = '';
        document.getElementById('cnpj').focus();
        alert ("CNPJ Inválido.");
   }
}


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)
  return false;
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 CheckIEROantigo(ie)
{
if (ie.length != 9) {
return false;
}

var nro = new Array(9);
b=6;
soma =0;

for( var i = 3; i <= 8; i++) {

    nro[i] = CharToInt(ie.charAt(i));

        if( i != 8 ) {
            soma = soma + ( nro[i] * b );
            b--;
        }

}

dig = 11 - (soma % 11);
if (dig >= 10)
  dig = dig - 10;

return (dig == nro[8]);

} //ro-antiga





function CheckIERO(ie)
{

if (ie.length != 14) {
return false;
}

var nro = new Array(14);
b=6;
soma=0;

        for(var i=0; i <= 4; i++) {

            nro[i] = CharToInt(ie.charAt(i));


                soma = soma + ( nro[i] * b );
                b--;

        }

        b=9;
        for(var i=5; i <= 13; i++) {

            nro[i] = CharToInt(ie.charAt(i));

                if ( i != 13 ) {
                soma = soma + ( nro[i] * b );
                b--;
                }

        }

                        dig = 11 - ( soma % 11);

                            if (dig >= 10)
                                  dig = dig - 10;

                                    return(dig == nro[13]);

} //ro nova





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, '');

if (ie == 0)
   return true;
          
if ( ie == 'ISENTO'|| ie == 'isento')
  return true;
switch (estado)
{
  case '14': return CheckIEMG(ie); break;
  case '1': return CheckIEAC(ie); break;
  case '2': return CheckIEAL(ie); break;
  case '4': return CheckIEAM(ie); break;
  case '3': return CheckIEAP(ie); break;
  case '5': return CheckIEBA(ie); break;
  case '6': return CheckIECE(ie); break;
  case '7': return CheckIEDF(ie); break;
  case '8': return CheckIEES(ie); break;
  case '10': return CheckIEGO(ie); break;
  case '11': return CheckIEMA(ie); break;
  case '12': return CheckIEMT(ie); break;
  case '13': return CheckIEMS(ie); break;
  case '15': return CheckIEPA(ie); break;
  case '16': return CheckIEPB(ie); break;
  case '17': return CheckIEPR(ie); break;
  case '18': return CheckIEPE(ie); break;
  case '19': return CheckIEPI(ie); break;
  case '20': return CheckIERJ(ie); break;
  case '21': return CheckIERN(ie); break;
  case '22': return CheckIERS(ie); break;
  case '23': return ((CheckIERO(ie)) || (CheckIEROantigo(ie))); break;
  case '9': return CheckIERR(ie); break;
  case '25': return CheckIESC(ie); break;
  case '26': return CheckIESP(ie); break;
  case '27': return CheckIESE(ie); break;
  case '24': return ((CheckIETO(ie)) || (CheckIETOantigo(ie))); break;//return CheckIETO(ie); break;
}
}

function validaCampo()
{
if(document.cadastro.nome.value=="")
{
alert("O Campo Nome é obrigatório!");
return false;
}
else

if(document.cadastro.razaosocial.value=="")
{
alert("O Campo Razão Social é obrigatório!");
return false;
}
else

if(document.cadastro.endereco.value=="")
{
alert("O Campo Logradouro é obrigatório!");
return false;
}
else

if(document.cadastro.numero.value=="")
{
alert("O Campo Numero é obrigatório!");
return false;
}
else

if(document.cadastro.bairro.value=="")
{
alert("O Campo Bairro para entrega é obrigatório!");
return false;
}
else

if(document.cadastro.cidade.value=="")
{
alert("O Campo Cidade é obrigatório!");
return false;
}
else

if(document.cadastro.estado.value=="")
{
alert("O Campo Estado é obrigatório!");
return false;
}
else

if(document.cadastro.cep.value=="")
{
alert("O Campo Cep é obrigatório!");
return false;
}
else

if(document.cadastro.telefone1.value=="")
{
alert("O Campo Telefone é obrigatório!");
return false;
}
else

if(document.cadastro.cnpj.value=="")
{
alert("O Campo CNPJ é obrigatório!");
return false;
}
else

if(document.cadastro.ie.value=="")
{
alert("O Campo Inscrição Estadual é obrigatório!");
return false;
}
}

function valida_ie() {
    var ie =   document.getElementById('ie').value;
    var estado = document.getElementById('uf_faturamento').value;

    if (CheckIE(ie , estado)){

    }else{
        document.formCompra.ie.value = '';
        document.getElementById('ie').focus();
        alert('Inscrição Estadual Inválida');
    }
}







