function selecionaPraca(CdPraca){
	var resp_selecao = function (ajax) {
		document.location.href = "principal.php";
	}
	
	var con = new XHConn();
	con.connect("funcoes/ajax/seleciona_praca.php","POST","CdPraca="+CdPraca,resp_selecao);
}

// JavaScript Document
function ValidaCPFCNPJ(CpfCnpj, Silencioso, Campo)
{	
	if (CpfCnpj == '')
		CpfCnpj = false;
	
	if (Campo == null)
			Campo = 'CPF_CNPJ';
		
	if(CpfCnpj){
		var invalid, s;
		invalid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
	
		if (Silencioso == null)
			Silencioso = false;
	
		s = limpa_string(CpfCnpj);
	
		// checa se é cpf
		if (s.length == 11) {
			if (valida_CPF(CpfCnpj) == false )
			{
				alert("Preencha com um CPF válido");
				document.getElementById(Campo).focus();
				return false;
			}
			else
			{
				if (!Silencioso)
					alert("Ok!!! CPF válido !");
				return true;
			}
		 }
	
		 // checa se é cnpj
		else if (s.length == 14)
		{
			if (valida_CNPJ(CpfCnpj) == false )
			{
				alert("Preencha com um CNPJ válido");
				document.getElementById(Campo).focus();
				return false;
			}
			else
			{
				if (!Silencioso)
					alert("Ok!!! CNPJ válido !");
				return true;
			}
		}
		else
		{
				alert("Preencha com um CPF válido");
				document.getElementById(Campo).focus();
				return false;
		}
	}
// final da verificacao de cnpj ou cpf
}


function limpa_string(S){
    // Deixa so' os digitos no numero
    var Digitos = "0123456789";
    var temp = "";
    var digito = "";

    for (var i=0; i<S.length; i++)  {
        digito = S.charAt(i);
        if (Digitos.indexOf(digito)>=0) {
            temp=temp+digito    }
    } //for

    return temp
}
// fim da funcao


function valida_CPF(s)  {
    var i;
    s = limpa_string(s);
    var c = s.substr(0,9);
    var dv = s.substr(9,2);
    var d1 = 0;
    for (i = 0; i < 9; i++)
    {
        d1 += c.charAt(i)*(10-i);
    }
        if (d1 == 0) return false;
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(0) != d1)
    {
        return false;
    }

    d1 *= 2;
    for (i = 0; i < 9; i++)
    {
        d1 += c.charAt(i)*(11-i);
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(1) != d1)
    {
        return false;
    }
        return true;
}

function valida_CNPJ(s)
{
    var i;
    s = limpa_string(s);
    var c = s.substr(0,12);
    var dv = s.substr(12,2);
    var d1 = 0;
    for (i = 0; i < 12; i++)
    {
        d1 += c.charAt(11-i)*(2+(i % 8));
    }
        if (d1 == 0) return false;
        d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(0) != d1)
    {
        return false;
    }

    d1 *= 2;
    for (i = 0; i < 12; i++)
    {
        d1 += c.charAt(11-i)*(2+((i+1) % 8));
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(1) != d1)
    {
        return false;
    }
    return true;
}

function criaMascara(_RefObjeto, _Modelo){

var valorAtual = _RefObjeto.value;
var valorNumerico = '';
var nIndexModelo = 0;
var nIndexString = 0;
var valorFinal = '';
var adicionarValor = true;
 

// limpa a string valor atual para verificar
// se todos os caracteres são números
for (i=0;i<_Modelo.length;i++){
  if (_Modelo.substr(i,1) != '#'){
    valorAtual = valorAtual.replace(_Modelo.substr(i,1),'');
}}
 
// verifica se todos os caracteres são números
for (i=0;i<valorAtual.length;i++){
  if (!isNaN(parseFloat(valorAtual.substr(i,1)))){
    valorNumerico = valorNumerico + valorAtual.substr(i,1);
}}
 
// aplica a máscara ao campo informado usando
// o modelo de máscara informado no script
for (i=0;i<_Modelo.length;i++){
 
  if (_Modelo.substr(i,1) == '#'){
    if (valorNumerico.substr(nIndexModelo,1) != ''){
      valorFinal = valorFinal + valorNumerico.substr(nIndexModelo,1);
      nIndexModelo++;nIndexString++;
    }
      else {
        adicionarValor = false;
  }}
 
    else {
      if (adicionarValor && valorNumerico.substr(nIndexModelo,1) != ''){
      valorFinal = valorFinal + _Modelo.substr(nIndexString,1)
      nIndexString++;
    }}
}
 
_RefObjeto.value = valorFinal
 
}

function confirmaExclusao(CdPraca,AaAutorizacao,NrAutorizacao,NrExtracao, NrLote){
	if(confirm("Deseja excluir este lote? Todos os bilhetes serão excluídos"))
		location.href = "escaneamento_lista_lote.php?CdPraca="+CdPraca+"&AaAutorizacao="+AaAutorizacao+"&NrAutorizacao="+NrAutorizacao+"&NrExtracao="+NrExtracao+"&NrLote="+NrLote+"&Exclui=1";
}

function validaLote(NrLote)
{
	TamanhoLote = NrLote.length;
	if(TamanhoLote > 6)
		return false;
	else
		return (CalcDig(String(parseInt(NrLote/10))) == NrLote%10);
}


function validaBilhete(NrBilhete)
{
	return (CalcDig(String(parseInt(NrBilhete/10))) == NrBilhete%10);
}


function CalcDig(Numero) {

  Tamanho = Numero.length;
  Peso = 1;
  Soma = 0;

  for (i = Tamanho; i > 0; --i) {
    Soma = Soma + (Numero.substring(i-1, i)) * Peso;
    Peso++;
  }

  Resto = Soma % 11;
  
  if (Resto == 0 || Resto == 10)
  	 return 1
  else
  if (Resto == 1)
     return 0
  else
     return Resto
}


function aviso(Tipo){
	switch (Tipo) {
    case 'EXISTE':
       alert('Registro já existente!');
       break;
	case 'NAOGRAVO':
       alert('Erro ao gravar registro. Tente novamente!');
       break;
	case 'CONCLUIDO':
       alert('Importação Concluida!');
       break;
	case 'EXISTE_CPF_DISTRIBUIDOR':
       alert('Este CPF/CNPJ já está cadastrado para outro distribuidor!');
       break;
	case 'EXISTE_CPF_ARRECADADOR':
       alert('Este CPF já está cadastrado para outro arrecadador!');
       break;
	case 'EXISTE_CPF_VENDEDOR':
       alert('Este CPF já está cadastrado para outro vendedor!');
       break;
	case 'SENHA_ATUAL':
       alert('Senha atual não confere!');
       break;
    default:
       alert('Registro já existente!');
	}
	   
}


function tamanho(){
		//alert(document.defaultView.getComputedStyle("rodape", null).currentStyle("height"));
		document.getElementById("div_menu").style.height = "400px";
}


function dataValida(data){
	var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
	if ((data.match(expReg)) && (data!='')){
		var dia = data.substring(0,2);
		var mes = data.substring(3,5);
		var ano = data.substring(6,10);
		if((mes==4 || mes==6 || mes==9 || mes==11) && dia > 30)
			return false;
		else
		if(ano%4!=0 && mes==2 && dia>28)
			return false;
		else
		if(ano%4==0 && mes==2 && dia>29)
			return false;
		else
			return true;
	}
	else
		return false;
}


var controle

function fcMenu(Categoria){
	if(controle!=Categoria){
		// Fecha Todos os Menus
		document.getElementById("MenuCadastro").style.display = 'none';
		document.getElementById("MenuCadastro").style.visibility = 'hidden';
		document.getElementById("MenuDistribuicao").style.display = 'none';
		document.getElementById("MenuDistribuicao").style.visibility = 'hidden';
		document.getElementById("MenuAcerto").style.display = 'none';
		document.getElementById("MenuAcerto").style.visibility = 'hidden';
		document.getElementById("MenuEscaneamento").style.display = 'none';
		document.getElementById("MenuEscaneamento").style.visibility = 'hidden';
		document.getElementById("MenuSorteio").style.display = 'none';
		document.getElementById("MenuSorteio").style.visibility = 'hidden';
		document.getElementById("MenuDivulgacao").style.display = 'none';
		document.getElementById("MenuDivulgacao").style.visibility = 'hidden';
		document.getElementById("MenuConfiguracoes").style.display = 'none';
		document.getElementById("MenuConfiguracoes").style.visibility = 'hidden';
		document.getElementById("MenuSair").style.display = 'none';
		document.getElementById("MenuSair").style.visibility = 'hidden';
		//Abre o Menu escolhido
		document.getElementById(Categoria).style.display = 'inline';
		document.getElementById(Categoria).style.visibility = 'visible';
		controle = Categoria
	}
	else{
		if(document.getElementById(Categoria).style.display == 'none'){
			document.getElementById(Categoria).style.display = 'inline';
			document.getElementById(Categoria).style.visibility = 'visible';
		}
		else{
			document.getElementById(Categoria).style.display = 'none';
			document.getElementById(Categoria).style.visibility = 'hidden';
		}
	}
}


function filtraAaAutorizacao(CdPraca,Param)
{
	var resp = function (ajax) {
		var novo = null
		var opc = null
		var texto = ajax.responseText.replace(/\+/g," ")
		var AaAutorizacao = document.getElementById("AaAutorizacao")
		while (AaAutorizacao.length > 0)
			AaAutorizacao.remove(0)
		novo = document.createElement("option")
		novo.value = 0
		novo.text  = "<Ano>"
		AaAutorizacao.options.add(novo)
		var opcoes = texto.split("#")
		for (var x = 0; x < opcoes.length-1; x++)
		{
			novo = document.createElement("option")
			novo.value = opcoes[x]
			novo.text  = opcoes[x]
			if (opcoes[opcoes.length-1] == opcoes[x])
				novo.selected = true;
			AaAutorizacao.options.add(novo)
		}
		var NrAutorizacao = document.getElementById("NrAutorizacao")
		while (NrAutorizacao.length > 0)
			NrAutorizacao.remove(0)
		novo = document.createElement("option")
		novo.value = 0
		novo.text  = "----------"
		NrAutorizacao.options.add(novo)
		var NrExtracao = document.getElementById("NrExtracao")
		while (NrExtracao.length > 0)
			NrExtracao.remove(0)
		novo = document.createElement("option")
		novo.value = 0
		novo.text  = "------------------------------------"
		NrExtracao.options.add(novo)
	}

	var con = new XHConn()
	con.connect("ajax_filtra_aaautorizacao.php","POST","CdPraca="+CdPraca,resp)

	if (Param == 'Distribuidor') {
		var resp_distribuidor = function (ajax) {
			var novo = null
			var opc = null
			var texto = ajax.responseText.replace(/\+/g," ")
			var CdDistribuidor = document.getElementById("CdDistribuidor")
			while (CdDistribuidor.length > 0)
				CdDistribuidor.remove(0)
			novo = document.createElement("option")
			novo.value = 0
			novo.text  = "< Selecione o Distribuidor >"
			CdDistribuidor.options.add(novo)
			var opcoes = texto.split("#")
			for (var x = 0; x < opcoes.length-1; x++)
			{
				opc = opcoes[x].split("|")
				novo = document.createElement("option")
				novo.value = opc[0]
				novo.text  = opc[1]
				if (opcoes[opcoes.length-1] == opc[0])
					novo.selected = true;
				CdDistribuidor.options.add(novo)
			}
		}
		var con = new XHConn()
		con.connect("ajax_filtra_distribuidor.php","POST","CdPraca="+CdPraca,resp_distribuidor)
	}
}


function filtraNrAutorizacao(AaAutorizacao)
{
	var resp = function (ajax) {
		var novo = null
		var opc = null
		var texto = ajax.responseText.replace(/\+/g," ")
		var NrAutorizacao = document.getElementById("NrAutorizacao")
		while (NrAutorizacao.length > 0)
			NrAutorizacao.remove(0)
		novo = document.createElement("option")
		novo.value = 0
		novo.text  = "<Nr.>"
		NrAutorizacao.options.add(novo)
		var opcoes = texto.split("#")
		for (var x = 0; x < opcoes.length-1; x++)
		{
			novo = document.createElement("option")
			novo.value = opcoes[x]
			novo.text  = opcoes[x]
			if (opcoes[opcoes.length-1] == opcoes[x])
				novo.selected = true;
			NrAutorizacao.options.add(novo)
		}
		var NrExtracao = document.getElementById("NrExtracao")
		while (NrExtracao.length > 0)
			NrExtracao.remove(0)
		novo = document.createElement("option")
		novo.value = 0
		novo.text  = "------------------------------------"
		NrExtracao.options.add(novo)
	}
	var CdPraca = document.getElementById("CdPraca").value
	var con = new XHConn()
	con.connect("ajax_filtra_nrautorizacao.php","POST","CdPraca="+CdPraca+"&AaAutorizacao="+AaAutorizacao,resp)
}


function filtraNrExtracao(NrAutorizacao)
{
	var resp = function (ajax) {
		var novo = null
		var opc = null
		var texto = ajax.responseText.replace(/\+/g," ")
		var NrExtracao = document.getElementById("NrExtracao")
		while (NrExtracao.length > 0)
			NrExtracao.remove(0)
		var opcoes = texto.split("#")
		for (var x = 0; x < opcoes.length-1; x++)
		{
			opc = opcoes[x].split("|")
			novo = document.createElement("option")
			novo.value = opc[0]
			novo.text  = opc[1]
			if (opcoes[opcoes.length-1] == opc[0])
				novo.selected = true;
			NrExtracao.options.add(novo)
		}
	}
	var CdPraca = document.getElementById("CdPraca").value
	var AaAutorizacao = document.getElementById("AaAutorizacao").value
	var con = new XHConn()
	con.connect("ajax_filtra_nrextracao.php","POST","CdPraca="+CdPraca+"&AaAutorizacao="+AaAutorizacao+"&NrAutorizacao="+NrAutorizacao,resp)
}

function filtraDistribuidor(CdPraca){
		var resp_distribuidor = function (ajax) {
			var novo = null
			var opc = null
			var texto = ajax.responseText.replace(/\+/g," ")
			var CdDistribuidor = document.getElementById("CdDistribuidor")
			while (CdDistribuidor.length > 0)
				CdDistribuidor.remove(0)
			novo = document.createElement("option")
			novo.value = 0
			novo.text  = "< Selecione o Distribuidor >"
			CdDistribuidor.options.add(novo)
			var opcoes = texto.split("#")
			for (var x = 0; x < opcoes.length-1; x++)
			{
				opc = opcoes[x].split("|")
				novo = document.createElement("option")
				novo.value = opc[0]
				novo.text  = opc[1]
				if (opcoes[opcoes.length-1] == opc[0])
					novo.selected = true;
				CdDistribuidor.options.add(novo)
			}
		}
		var con = new XHConn()
		con.connect("ajax_filtra_distribuidor.php","POST","CdPraca="+CdPraca,resp_distribuidor)
}

function filtraArrecadador(CdPraca, CdDistribuidor){
		var resp_arrecadador = function (ajax) {
			var novo = null
			var opc = null
			var texto = ajax.responseText.replace(/\+/g," ")
			var CdArrecadador = document.getElementById("CdArrecadador")
			while (CdArrecadador.length > 0)
				CdArrecadador.remove(0)
			novo = document.createElement("option")
			novo.value = 0
			novo.text  = "< Selecione o Arrecadador >"
			CdArrecadador.options.add(novo)
			var opcoes = texto.split("#")
			for (var x = 0; x < opcoes.length-1; x++)
			{
				opc = opcoes[x].split("|")
				novo = document.createElement("option")
				novo.value = opc[0]
				novo.text  = opc[1]
				if (opcoes[opcoes.length-1] == opc[0])
					novo.selected = true;
				CdArrecadador.options.add(novo)
			}
		}
		var con = new XHConn()
		con.connect("ajax_filtra_arrecadador.php","POST","CdPraca="+CdPraca+"&CdDistribuidor="+CdDistribuidor,resp_arrecadador)
}

function filtraVendedor(CdPraca, CdArrecadador){
		var resp_vendedor = function (ajax) {
			var novo = null
			var opc = null
			var texto = ajax.responseText.replace(/\+/g," ")
			var CdVendedor = document.getElementById("CdVendedor")
			while (CdVendedor.length > 0)
				CdVendedor.remove(0)
			novo = document.createElement("option")
			novo.value = 0
			novo.text  = "< Selecione o Vendedor >"
			CdVendedor.options.add(novo)
			var opcoes = texto.split("#")
			for (var x = 0; x < opcoes.length-1; x++)
			{
				opc = opcoes[x].split("|")
				novo = document.createElement("option")
				novo.value = opc[0]
				novo.text  = opc[0]+" - "+opc[1]
				if (opcoes[opcoes.length-1] == opc[0])
					novo.selected = true;
				CdVendedor.options.add(novo)
			}
		}
		var con = new XHConn()
		con.connect("ajax_filtra_vendedor.php","POST","CdPraca="+CdPraca+"&CdArrecadador="+CdArrecadador,resp_vendedor)
}


//*****************************************//
//  FUNÇÃO PARA PREENCHER CAMPOS PELO CEP  //
//*****************************************//
function preencheCEP(CEP, cpEndereco, cpBairro, cpCidade, cpEstado){
	if (CEP == '')
		CEP = false;
	var con = new XHConn();
	if(CEP){
	var resposta = function (ajaxCEP){
		var Endereco = ajaxCEP.responseText.replace(/\+/g," ").split('name="endereco" value="');
			document.getElementById(cpEndereco).value = Endereco[1].substr(0, Endereco[1].indexOf('"'));
			Endereco = Endereco[1].split('name="bairro" value="');
			document.getElementById(cpBairro).value = Endereco[1].substr(0, Endereco[1].indexOf('"'));
			Endereco = Endereco[1].split('name="cidade" value="');
			document.getElementById(cpCidade).value = Endereco[1].substr(0, Endereco[1].indexOf('"'));
			Endereco = Endereco[1].split('name="estado" value="');
			document.getElementById(cpEstado).value = Endereco[1].substr(0, Endereco[1].indexOf('"'));
			document.getElementById('DsNumero').focus();
			return false
	}
	if(!con.connect('funcoes/buscaEndereco.php', "POST", 'cepDest='+CEP+'&urlback='+URL+'&invoca=1;', resposta)){
		alert("Não foi possível conexão, atualize a página e tente novamente.");
	}
	}
}

//******************************************************//
//  FUNÇÃO PARA VERIFICAR SE O CPF/CNPJ ESTÁ CADASTRADO //
//******************************************************//
function verificaCPFCadastrado(tabela, campo, CPF){
	if (CPF == '')
		CPF = false;
	var con = new XHConn();
	if(CPF){
		var CdPraca = document.getElementById("CdPraca").value
		var respostaCPF = function (ajaxCPF){
			var retorno = ajaxCPF.responseText.replace(/\+/g," ");
				if(retorno != 1){
					alert(retorno)
					document.getElementById(campo).focus();
					return false
				}
		}
		if(!con.connect('funcoes/verificaCPF.php', "POST", 'tabela='+tabela+'&campo='+campo+'&CPF='+CPF+'&CdPraca='+CdPraca, respostaCPF))
			alert("Não foi possível conexão, atualize a página e tente novamente.");
	}
}

//************************************************//
//  FUNÇÃO PARA ATUALIZAR O TOTAL DA CALCULADORA  //
//************************************************//
function atualizaCalculadora(){
	
		var moeda001 = document.getElementById("moeda_001").value * 0.01;
		var moeda005 = document.getElementById("moeda_005").value * 0.05;
		var moeda010 = document.getElementById("moeda_010").value * 0.1;
		var moeda025 = document.getElementById("moeda_025").value * 0.25;
		var moeda050 = document.getElementById("moeda_050").value * 0.5;
		var moeda100 = document.getElementById("moeda_100").value * 1;
		var dinheiro001 = document.getElementById("dinheiro_001").value * 1;
		var dinheiro002 = document.getElementById("dinheiro_002").value * 2;
		var dinheiro005 = document.getElementById("dinheiro_005").value * 5;
		var dinheiro010 = document.getElementById("dinheiro_010").value * 10;
		var dinheiro020 = document.getElementById("dinheiro_020").value * 20;
		var dinheiro050 = document.getElementById("dinheiro_050").value * 50;
		var dinheiro100 = document.getElementById("dinheiro_100").value * 100;
		
		var Total = moeda001 + moeda005 + moeda010 + moeda025 + moeda050 + moeda100 + dinheiro001 + dinheiro002 + dinheiro005 + dinheiro010 + dinheiro020 + dinheiro050 + dinheiro100;
		
		document.getElementById('calculadora_resultado').innerHTML = float2moeda(Total);
}


//******************************************//
//  FUNÇÃO PARA TRANSFORMAR FLOAT EM MOEDA  //
//******************************************//
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;

}

//**********************************//
//  FUNÇÃO PARA CHAMAR CALCULADORA  //
//**********************************//
function abreCalculadora(campoAtualiza){
	document.getElementById('calculadora').style.display = 'inline';
	document.getElementById('calculadora').style.visibility = 'visible';
	document.getElementById('campo_atualizar').value = campoAtualiza;
}

//**********************************//
//  FUNÇÃO PARA FECHAR CALCULADORA  //
//**********************************//
function fechaCalculadora(campoAtualiza){
	limpaCalculadora();
	document.getElementById('calculadora').style.display = 'none';
	document.getElementById('calculadora').style.visibility = 'hidden';
}

//******************************************************//
//  FUNÇÃO PARA FECHAR CALCULADORA CONFIRMANDO CALCULO  //
//******************************************************//
function okCalculadora(campoAtualiza){
	var atualiza = document.getElementById('campo_atualizar').value;
	document.getElementById(atualiza).value = document.getElementById('calculadora_resultado').innerHTML;
	limpaCalculadora();
	document.getElementById('calculadora').style.display = 'none';
	document.getElementById('calculadora').style.visibility = 'hidden';
}

//*********************************//
//  FUNÇÃO PARA LIMPAR CALCULADORA //
//*********************************//
function limpaCalculadora(){
	document.getElementById("moeda_001").value = '';
	document.getElementById("moeda_005").value = '';
	document.getElementById("moeda_010").value = '';
	document.getElementById("moeda_025").value = '';
	document.getElementById("moeda_050").value = '';
	document.getElementById("moeda_100").value = '';
	document.getElementById("dinheiro_001").value = '';
	document.getElementById("dinheiro_002").value = '';
	document.getElementById("dinheiro_005").value = '';
	document.getElementById("dinheiro_010").value = '';
	document.getElementById("dinheiro_020").value = '';
	document.getElementById("dinheiro_050").value = '';
	document.getElementById("dinheiro_100").value = '';	
	document.getElementById('calculadora_resultado').innerHTML = '';
}

//*****************************************//
//  VERIFICA SE DISTRIBUIDOR FOI ESCOLHIDO //
//*****************************************//
function verificaDistribuidor(){
	if(document.getElementById('CdDistribuidor').value == '0'){
		alert('Por favor escolha um distribuidor');
		return false;
	}
}

//*****************************************//
//  VERIFICA SE VENDEDOR FOI ESCOLHIDO //
//*****************************************//
function verificaVendedor(){
	if(document.getElementById('CdVendedor').value == '0'){
		alert('Por favor escolha um vendedor');
		return false;
	}
}

//*********************************************************//
//  FUNÇÂO QUE CHAMA TELA DE IMPRESSÃO DA NOTA PROMISSÓRIA //
//*********************************************************//
function fcImprimirNotaPromissoria(tabela, CdPraca, AaAutorizacao, NrAutorizacao, NrExtracao, codigo){
	location.href = "distribuicao_impressao_nota_promissoria.php?CdPraca="+CdPraca+"&AaAutorizacao="+AaAutorizacao+"&NrAutorizacao="+NrAutorizacao+"&NrExtracao="+NrExtracao+"&Codigo="+codigo+"&Tabela="+tabela+"&Exclui=1";
}


function FormataValor(campo,tammax,teclapres)
{
    //uso:
    //<input type="Text" name="fat_vr_bruto" maxlength="17" onKeyDown="FormataValor(this,17,event)">

    var tecla = teclapres.keyCode;
    vr = campo.value;
    vr = vr.replace( "/", "" );
    vr = vr.replace( "/", "" );
    vr = vr.replace( ",", "" );
    vr = vr.replace( ".", "" );
    vr = vr.replace( ".", "" );
    vr = vr.replace( ".", "" );
    vr = vr.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 ){
             campo.value = vr; }
         if ( (tam > 2) && (tam <= 5) ){
             campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ); }
         if ( (tam >= 6) && (tam <= 8) ){
             campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
         if ( (tam >= 9) && (tam <= 11) ){
             campo.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) ){
             campo.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) ){
             campo.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 FormataValorInteiro(campo,tammax,teclapres)
{
    //uso:
    //<input type="Text" name="fat_vr_bruto" maxlength="17" onKeyDown="FormataValor(this,17,event)">

    var tecla = teclapres.keyCode;
    vr = campo.value;
    vr = vr.replace( "/", "" );
    vr = vr.replace( "/", "" );
    vr = vr.replace( ",", "" );
    vr = vr.replace( ".", "" );
    vr = vr.replace( ".", "" );
    vr = vr.replace( ".", "" );
    vr = vr.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 <= 3 ){
             campo.value = vr; }
         if ( (tam > 3) && (tam <= 6) ){
             campo.value = vr.substr( 0, tam - 3 ) + '.' + vr.substr( tam - 3, tam ); }
         if ( (tam >= 7) && (tam <= 9) ){
             campo.value = vr.substr( 0, tam - 6 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, tam ); }
    }            
}

function imprimeRecibo(praca, aaAutorizacao, nrAutorizacao, nrExtracao, codigo, tabela){
	var total = 0;
	var totalRegistros = document.getElementById('TotalRegistros').value;
	for(var i=1; i<=totalRegistros; i++){
		if(document.getElementById('cb_'+i).checked == true)
			total = total + (document.getElementById('cb_'+i).value*1);
	}
	var oPrint, oJan;
	oJan = window.open("impressaoRecibo.php?Tabela="+tabela+"&CdPraca="+praca+"&AaAutorizacao="+aaAutorizacao+"&NrAutorizacao="+nrAutorizacao+"&NrExtracao="+nrExtracao+"&Codigo="+codigo+"&Total="+total);
	oJan.focus();	
	
	return false;
}

//******************************************************//
//  FUNÇÃO PARA VERIFICAR SE O CPF/CNPJ ESTÁ CADASTRADO //
//******************************************************//
function gravaContrato(CdPraca, Codigo, Tabela, Contrato){
	var con = new XHConn();
		var respostaContrato = function (ajax){
			var retorno = ajax.responseText.replace(/\+/g," ");
				if(retorno != 1){
					alert(retorno)
					return false
				}
		}
		if(!con.connect('funcoes/grava_contrato.php', "POST", 'CdPraca='+CdPraca+'&Codigo='+Codigo+'&Tabela='+Tabela+'&Contrato='+Contrato, respostaContrato))
			alert("Não foi possível conexão, atualize a página e tente novamente.");
}