// JavaScript Document

//Função do ajax
function makeRequest(url,dive,tipo_load) {
				
				 if (!dive) {
					dive = 'Corpo' 
				 }
				 				 
				loading(dive,tipo_load);
								
				url = antiCacheRand(url);
				
				//toTop();
                http_request = false;

                if (window.XMLHttpRequest) { // Mozilla, Safari,...
                    http_request = new XMLHttpRequest();
                    if (http_request.overrideMimeType) {
                        http_request.overrideMimeType('text/xml');
                    }
                } else if (window.ActiveXObject) { // IE
					
                    try {
                        http_request = new ActiveXObject("Msxml3.XMLHTTP");
						
                    } catch (e) {
                        try {
                        http_request = new ActiveXObject("Microsoft.XMLHTTP");
						
                        } catch (e) {}
                    }
                }

                if (!http_request) {
                    alert('Seu navegador não suporta este site!');
                    return false;
                }
                //alert(http_request.onreadystatechange)
				http_request.onreadystatechange = function(){ carrega_pagina(dive); };
                http_request.open('get', url, true);
                http_request.send(null);
				
            }

            function carrega_pagina(dive) {

                if (http_request.readyState == 4) {
                   if (http_request.status == 200) {
						document.getElementById(dive).innerHTML=http_request.responseText;
                   } else {
                        alert('Houve um erro nesta página. Tente novamente mais tarde!');
                   }
  	 		}
	
}
//a função que gera o randomico *********
function antiCacheRand(aurl){
    var dt = new Date();
    if(aurl.indexOf("?")>=0){// já tem parametros
        return aurl + "&" + encodeURI(Math.random() + "_" + dt.getTime());
    }else{ return aurl + "?" + encodeURI(Math.random() + "_" + dt.getTime());}
}

//Volta a uma pagina com determinado tempo. Utilizado para resposta.
function voltar_pagina() {
	var voltar_pg = document.getElementById('voltar_pg').value
	makeRequest(voltar_pg,'')
}
function timer_voltar_pagina() {
	setTimeout("voltar_pagina()",4000)
}

//Funcao do loading
function loading(dive,tipo) {
	
	if (tipo == undefined) {
		tipo = '1'
	}

	if (tipo == '' || tipo == '1') {
		document.getElementById(dive).innerHTML="<center><table width=141 border=0 cellspacing=0 cellpadding=0><tr><td width=42><img src=images/ajax-loader.gif /></td><td width=99 align=center class=arial_12_vermelho>Carregando...</td></tr></table></center>";
	} else {
		if (tipo == '2') {
			document.getElementById(dive).innerHTML="<table width=100 border=0 cellspacing=0 cellpadding=0><tr><td width=23><img src=images/load.gif></td><td width=77 class=tahoma_11_a3a>carregando...</td></tr></table>";
		}
	}
}

//Seleciona o foco
function selecionaFoco(campo){ 
	try {
		document.getElementById(campo).focus() ;
	} catch (e) {}
}

//Joga para o topo
function toTop() {
        self.scrollTo(0, 0)
}

//Funçao que abre ou fecha uma div como display
// Pode-se chamar uma função para acão quando a div aparece. (Somente com um parametro. Por exemplo fuc_div('observacoes','selecionaFoco(cli_observacao)'); )
function fuc_div(div,funcao) {
	var dive_esta = document.getElementById(div).style.display;
	if (dive_esta == '') {
		document.getElementById(div).style.display='block';
		if (funcao != '') {
			funcao_splt = funcao.split("(");						 
			funcao_fuc = funcao_splt[0];	
			funcao_campo = funcao_splt[1];
			funcao_campo = funcao_campo.replace(")", ""); 
				
			eval(funcao_fuc+'('+String.fromCharCode(39)+funcao_campo+String.fromCharCode(39)+')');
		}
	} else {
		if (dive_esta == 'block') {
			document.getElementById(div).style.display='none';
		} else {
			document.getElementById(div).style.display='block';
			if (funcao != '') {
				funcao_splt = funcao.split("(");
				funcao_fuc = funcao_splt[0];	
				funcao_campo = funcao_splt[1];
				funcao_campo = funcao_campo.replace(")", "") 
				
				eval(funcao_fuc+'('+String.fromCharCode(39)+funcao_campo+String.fromCharCode(39)+')');
			}
		}
	}
}

//Navegação
function proxima_pg(pagina,volta) {
	document.getElementById('erro_div').style.display = 'none'
	id = document.getElementById('proximo_pg').value
	if (id != '') {
		request_source(pagina+id)
	} else {
		if (volta) {
			var pergunta = confirm("Último registro alcançado!\nDeseja voltar para tela de cadastro?")
			if (pergunta){
				request_source(volta)
			}
		} else {
		alert('Último registro alcançado!')	
		}
	}
}
function anterior_pg(pagina,volta) {
	document.getElementById('erro_div').style.display = 'none'
	id = document.getElementById('anterior_pg').value
	if (id != '') {
		request_source(pagina+id)
	} else {
		if (volta) {
			var pergunta = confirm("Primeiro registro alcançado!\nDeseja voltar para tela de cadastro?")
			if (pergunta){
				request_source(volta)
			}
		} else {
			alert('Primeiro registro alcançado!')
		}
	}
}

//Função para excluir registro
function excluir_registro(pagina,volta_pg) {
	try 
	{
		id = document.getElementById('excluir_id').value
		if (id) {
			makeRequest(pagina+id)
		} else {
				alert('Não foi possível encontrar o registro!')
		}
	}
	catch(err) {
		alert('Não foi possível encontrar o registro!')
	}
}

//Funçao para busca. Funciona para 3 campos
function buscar_2_campos(pagina,campo1,campo2,campo3,aba,nu_aba) {
	try {
		valor_campo1 = document.getElementById(campo1).value;
		valor_campo2 = document.getElementById(campo2).value;
		try {
			valor_campo3 = document.getElementById(campo3).value;
		} catch(err) { valor_campo3 = '1' }
		erro = ''
	
		if (valor_campo1 != '' && valor_campo1 == '0')   {
			erro = 'Selecione o tipo de busca!'
		}
		if (valor_campo1 != 'Todos') {
			if (valor_campo2 == '') {
				if 	(erro != '') {
					erro = erro+'\nPreencha o campo de busca!'	
				} else {
					erro = 'Preencha o campo de busca!'	
				}
			}
		}
		
		if (valor_campo3 == '') {
			if 	(erro != '') {
				erro = erro+'\nSelecione o tipo de conta!'	
			} else {
				erro = 'Selecione o tipo de conta!'	
			}
		}
		
		if (erro != '') {
			alert(erro)	
		} else {
			if (aba != '') {
				alera_aba(aba,nu_aba);
			}
			request_source(pagina+'?'+campo1+'='+valor_campo1+'&'+campo2+'='+valor_campo2+'&'+campo3+'='+valor_campo3);	
		}
	} catch(err) { }
}

//Realiza a verificação de CNPJ / CPF
function validacpfcnpj(campo,acao) {
	if (acao == '') {
		validaCNPJ(campo,'');
	} else {
		document.getElementById(campo).select()	
	}
}


//Validação de CNPJ
function validaCNPJ(campo,param) {
				CNPJ = document.getElementById(campo).value;
                erro = new String;
                if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ!<br> \n\n"; 
                if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
                if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ!<br> \n\n";
                }
                //substituir os caracteres que não são números
               if(document.layers && parseInt(navigator.appVersion) == 4){
                       x = CNPJ.substring(0,2);
                       x += CNPJ. substring (3,6);
                       x += CNPJ. substring (7,10);
                       x += CNPJ. substring (11,15);
                       x += CNPJ. substring (16,18);
                       CNPJ = x; 
               } else {
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace ("-","");
                       CNPJ = CNPJ. replace ("/","");
               }
               var nonNumbers = /\D/;
               if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números!<br> \n\n"; 
               var a = [];
               var b = new Number;
               var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
               for (i=0; i<12; i++){
                       a[i] = CNPJ.charAt(i);
                       b += a[i] * c[i+1];
 }
               if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
               b = 0;
               for (y=0; y<13; y++) {
                       b += (a[y] * c[y]); 
               }
               if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
			   
               if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
                       erro +="Dígito verificador com problema!";
               }
               if (erro.length > 0){
                       //alert(erro);
					   //Caso CNPJ for inválido, pula para verificação do CPF
					   if (param == '') {
					   		validacpf(campo)
					   } else {
							document.getElementById('erro_div_msg').innerHTML=erro
					   		document.getElementById('erro_div').style.display = 'Block'	   
					   }
                       return false;
               } else {
                       document.getElementById('erro_div_msg').innerHTML=''
					   document.getElementById('erro_div').style.display = 'none'	
               }
               return true;
}

//Validação de CPF
function validacpf(campo){ 
	var i; 
	s = document.getElementById(campo).value; 
	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){ 
		document.getElementById(campo).select()
		document.getElementById('erro_div_msg').innerHTML="ERRO: CPF / CNPJ Invalido. Informe somente os números para CPF"
		document.getElementById('erro_div').style.display = 'block'
		validacpfcnpj(campo,'s')
		return false;  
	} else {
		document.getElementById('erro_div_msg').innerHTML=''
		document.getElementById('erro_div').style.display = 'none'	
	}
	  
	d1 = 11 - (d1 % 11); 
	  
	if (d1 > 9) d1 = 0; 
	  
	if (dv.charAt(0) != d1) {   
		document.getElementById(campo).select()
		document.getElementById('erro_div_msg').innerHTML="ERRO: CPF / CNPJ Invalido. Informe somente os números para CPF"
		document.getElementById('erro_div').style.display = 'block'
		validacpfcnpj(campo,'s')
		return false;  
	} else {
		document.getElementById('erro_div_msg').innerHTML=''
		document.getElementById('erro_div').style.display = 'none'	
	}

	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) {  
		document.getElementById(campo).select()
		document.getElementById('erro_div_msg').innerHTML="ERRO: CPF / CNPJ Invalido. Informe somente os números para CPF."
		document.getElementById('erro_div').style.display = 'block'

		validacpfcnpj(campo,'s')
		return false; 
	} else {
		document.getElementById('erro_div_msg').innerHTML=''
		document.getElementById('erro_div').style.display = 'none'	
	}
	  
	return true; 	  
} 

//Validação de data
function validarData(campo) {
	Verifica_Data(campo, '1')
}

function Verifica_Data(data, obrigatorio){   
//Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não   
var data = document.getElementById(data); 
    var strdata = data.value;   
    if((obrigatorio == 1) || (obrigatorio == 0 && strdata != "")){   
        //Verifica a quantidade de digitos informada esta correta.   
        if (strdata.length != 10){   
			document.getElementById('erro_div_msg').innerHTML="ERRO: Formato da data não é válido.   Formato correto: - dd/mm/aaaa."
			document.getElementById('erro_div').style.display = 'block'
            data.focus();   
			} else {
				document.getElementById('erro_div_msg').innerHTML=''
				document.getElementById('erro_div').style.display = 'none'
					
        }   
        //Verifica máscara da data   
        if ("/" != strdata.substr(2,1) || "/" != strdata.substr(5,1)){   
			document.getElementById('erro_div_msg').innerHTML="ERRO: Formato da data não é válido.   Formato correto:   - dd/mm/aaaa."
			document.getElementById('erro_div').style.display = 'block'
            data.focus();   
            return false   
        }   
        dia = strdata.substr(0,2)   
        mes = strdata.substr(3,2);   
        ano = strdata.substr(6,4);   
        //Verifica o dia   
        if (isNaN(dia) || dia > 31 || dia < 1){   
			document.getElementById('erro_div_msg').innerHTML="ERRO: Formato do dia não é válido."
			document.getElementById('erro_div').style.display = 'block'
            data.focus();   
            } else {
				document.getElementById('erro_div_msg').innerHTML=''
				document.getElementById('erro_div').style.display = 'none'  
        }   
        if (mes == 4 || mes == 6 || mes == 9 || mes == 11){   
            if (dia == "31"){   
				document.getElementById('erro_div_msg').innerHTML="ERRO: O mês informado não possui 31 dias."
				document.getElementById('erro_div').style.display = 'block'
                data.focus();   
                } else {
				document.getElementById('erro_div_msg').innerHTML=''
				document.getElementById('erro_div').style.display = 'none'   
            }   
        }   
        if (mes == "02"){   
            bissexto = ano % 4;   
            if (bissexto == 0){   
                if (dia > 29){   
					document.getElementById('erro_div_msg').innerHTML="ERRO: O mês informado possui somente 29 dias."
					document.getElementById('erro_div').style.display = 'block'
                    data.focus();   
                    } else {
				document.getElementById('erro_div_msg').innerHTML=''
				document.getElementById('erro_div').style.display = 'none'  
                }   
            }else{   
                if (dia > 28){    
					document.getElementById('erro_div_msg').innerHTML="ERRO: O mês informado possui somente 28 dias."
					document.getElementById('erro_div').style.display = 'block'
                    data.focus();   
                    } else {
				document.getElementById('erro_div_msg').innerHTML=''
				document.getElementById('erro_div').style.display = 'none'   
                }   
            }   
        }   
    //Verifica o mês   
        if (isNaN(mes) || mes > 12 || mes < 1){   
			document.getElementById('erro_div_msg').innerHTML="ERRO: Formato do mês não é válido."
			document.getElementById('erro_div').style.display = 'block'
            data.focus();   
           } else {
				document.getElementById('erro_div_msg').innerHTML=''
				document.getElementById('erro_div').style.display = 'none'  
        }   
        //Verifica o ano   
        if (isNaN(ano)){   
			document.getElementById('erro_div_msg').innerHTML="ERRO: Formato do ano não é válido."
			document.getElementById('erro_div').style.display = 'block'
            data.focus();   
            } else {
				document.getElementById('erro_div_msg').innerHTML=''
				document.getElementById('erro_div').style.display = 'none'  
        }   
    }   
} 

//Permissão UPPER e permite somente RWUD
function permissao_cad(campo) {
		valor_campo = document.getElementById(campo).value
		valor_campo_splt = valor_campo.split("")
		
		campo_fim = ''
		erro = ''
		for(f = 0; f < valor_campo_splt.length; f++){
			letra = valor_campo_splt[f]
			letra = letra.toUpperCase()
			
			if (letra == 'R' || letra == 'W' || letra == 'U' || letra == 'D')  {
				campo_fim = campo_fim+letra
			} else {
				erro = 'S';
			}
			
		}
		
		if (erro != '') {
			document.getElementById('erro_div_msg').innerHTML='ERRO: Você informou uma letra inválida.';
			document.getElementById('erro_div').style.display = 'block';
			document.getElementById(campo).select();
		} else {
			document.getElementById('erro_div_msg').innerHTML='';
			document.getElementById('erro_div').style.display = 'none';
			document.getElementById(campo).value=campo_fim
		}
			
}

function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@")
dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2) 
  {alert(alerttxt);return false}
else {return true}
}
}function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"Not a valid e-mail address!")==false)
  {email.focus();return false}
}
}


function FormataReais(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true;
key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida
len = fld.value.length;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) fld.value = '';
if (len == 1) fld.value = '0'+ decSep + '0' + aux;
if (len == 2) fld.value = '0'+ decSep + aux;
if (len > 2) {
aux2 = '';
for (j = 0, i = len - 3; i >= 0; i--) {
if (j == 3) {
aux2 += milSep;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}
fld.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
fld.value += aux2.charAt(i);
fld.value += decSep + aux.substr(len - 2, len);
}
return false;
}

//Função que permite só números
function SoNumeros() {
	var carCode = event.keyCode;
	if ((carCode < 48) || (carCode > 57))
	{
	 document.getElementById('erro_div_msg').innerHTML='ERRO: Por favor digite apenas números.';
	 document.getElementById('erro_div').style.display = 'block';
	 event.cancelBubble = true
	 event.returnValue = false;
	} else {
	 document.getElementById('erro_div_msg').innerHTML='';
	 document.getElementById('erro_div').style.display = 'none';	
	}
}

//Função que seleciona todos checkbox
function seleciona_checkbox(campo) {
try {
	todos_checkbox = document.getElementById('todos_checkbox').value;
	todos_checkbox = parseFloat(todos_checkbox) + 1
	
	for (i = 1; i < todos_checkbox; i++) {
		document.getElementById(campo+i).checked = true; 
	}
	
} catch(err) { }
}
//Funcao abre popup
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

//Left e right
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}


//Dia da semana
function dia_semana(campo_data,campo){
	try {	
		data = document.getElementById(campo_data).value
		
		data_sp = data.split("/");						 
		
		data = data_sp[2]+'/'+data_sp[1]+'/'+data_sp[0]
	
		var d=new Date(data);
		
		var weekday=new Array(7);
		weekday[0]="Domingo";
		weekday[1]="Segunda";
		weekday[2]="Terça";
		weekday[3]="Quarta";
		weekday[4]="Quinta";
		weekday[5]="Sexta";
		weekday[6]="Sábado";
		semana = weekday[d.getDay()];
		document.getElementById(campo).value = weekday[d.getDay()];
		
	} catch(err) { }
}

//Função joga campos em queristring
function leva_campos(campos,pagina) {
	try {	
		campos_sp = campos.split(",");
		
		dados = '?'
		
		for(i=0; i<campos_sp.length; i++){
			if (campos_sp[i]) {
				dados = dados+campos_sp[i]+'='+document.getElementById(campos_sp[i]).value+'&'
			}
		}
		dados = Left(dados,dados.length-1)
		
		request_source(pagina+dados);	
	} catch(err) { }
}


//Formata reais
function formatareais(valor_trabalho) {
	repaseaed = valor_trabalho.replace(".",",")
	sp_valor_trabalho = repaseaed.split(",")
	
	
	if (sp_valor_trabalho[1] != 'un') {
		centavos = Left(sp_valor_trabalho[1], 2)
	} else { centavos = '00' }
	
	if (centavos == 'un') { centavos = '00' }
	
	if (centavos.length == 1) { centavos = centavos+'0' }
	
	valor_total = sp_valor_trabalho[0]
	LN_valor_total = valor_total.length-1
	
	sp_cada_valor =  valor_total.split("")
	
	novo_valor = ''
	
	j = -1
	for (t=LN_valor_total; t>=0; t--){
	j++
		if (j == 3) {
			j = 0
			novo_valor = sp_cada_valor[t]+'.'+novo_valor
		} else {
		novo_valor = sp_cada_valor[t]+novo_valor
		}
	}
	
	valor_trabalho = novo_valor+','+centavos	
	
	return valor_trabalho;
}

//Dados da leitura de cheque
function quebra_dados_cheque(campo0,comp,banco,conta,agencia,numero,valor,div) {
	var linha_cod = document.getElementById(campo0).value;
	
	if (linha_cod.length == 47) {
		var tipo = 'Boleto'
	} 
	if (linha_cod.length == 34) {
		var tipo = 'Cheque'	
	}
	
	
	if (tipo == 'Boleto') {
		document.getElementById(div).value="Boleto";
		try {
			document.getElementById(comp).value='';
		} catch(err) { }
		document.getElementById(banco).value=boleto_banco(''+linha_cod+'');
		document.getElementById(conta).value='';
		document.getElementById(agencia).value='';
		document.getElementById(numero).value=boleto_numero(''+linha_cod+'');
		document.getElementById(valor).value=formatareais(boleto_valor(''+linha_cod+''));
	}
	
	if (tipo == 'Cheque') {
				
		document.getElementById(div).value="Cheque";
		var codigo = ''+linha_cod+''
		
		codigo = Right(codigo,33)
		
		codigo = codigo.replace('<',';')
		codigo = codigo.replace('Ç',';')
		codigo = codigo.replace(':',';')
		codigo = codigo.replace('>',';')
		
		var sp_bloco = codigo.split(";")
		var bloco_1 = sp_bloco[0]
		var bloco_2 = sp_bloco[1]
		var bloco_3 = sp_bloco[2]
		
		try {
			document.getElementById(comp).value=cheque_comp(''+bloco_2+'');
		} catch(err) { }
		document.getElementById(banco).value=cheque_banco(''+bloco_1+'');
		document.getElementById(conta).value=cheque_conta(''+bloco_3+'');
		document.getElementById(agencia).value=cheque_agencia(''+bloco_1+'');
		document.getElementById(numero).value=cheque_nu(''+bloco_2+'');
	}
}
function boleto_valor(temp) {
	var valor = Right(temp,10);	
	var cinco = Left(valor,5)
	var valor_car = valor.length
	
	if (cinco == '00000') {
		var retira = parseFloat(valor_car)-5
		valor = Right(valor,retira)	
	}
	
	valor_car = valor.length
	
	var menos_dois = parseFloat(valor_car)-2
	var centavos = Right(valor,2)
	var valor_real = Left(valor,menos_dois)
	valor = valor_real+'.'+centavos

	return valor;
}

function boleto_numero(temp) {
	var direita = Right(temp,18)
	var esquerda = Left(temp,21)
	numero = temp.replace(direita,'')
	numero = numero.replace(esquerda,'')
	
	var tres = Left(numero,3)
	
	if (tres == '000') {
		var conta_car = numero.length
		var retira = parseFloat(conta_car)-3
		numero = Right(numero,retira)
	}
	
	return numero;
}

function boleto_banco(temp) {
	var banco = Left(temp,3)
	return banco;
}

function cheque_comp(temp) {
		var comp = Left(temp,3)
		return comp;
}

function cheque_banco(temp) {
		var banco = Left(temp,3)
		return banco;
}

function cheque_agencia(temp) {
		var agencia = Right(temp,5)
		agencia = Left(agencia,4)
		return agencia;
}

function cheque_nu(temp) {
		var cheque_nu = Right(temp,7)
		cheque_nu = Left(cheque_nu,6)
		return cheque_nu;
}

function cheque_conta(temp) {
		var conta = Right(temp,10)
		conta = Left(conta,9)
		conta = Left(conta,8)+"-"+Right(conta,1)
		return conta;
}

function selecina_semelhante(area,linhas,acc) {
		linhas_cp = document.getElementById(linhas).value;
		
		for (i=1; i<=linhas_cp; i++){
			try {
				if (acc == '') {
					document.getElementById(area+'_'+i).style.fontWeight = 'bold';	
				} else {
					document.getElementById(area+'_'+i).style.fontWeight = 'normal';		
				}
			} catch(err) { }
		}
		
}
function libera(e) {
	if (event.keyCode == '120') {
		makeRequest('cria_session_liberada.asp')
	}
}
function balloon(titulo,texto) {
	agora_visi = document.getElementById('balloon').style.visibility;
		
	if (agora_visi == 'hidden') {
		
		Y = event.clientY - 95;
		X = event.clientX - 18;
			
		document.getElementById('balloon').style.left=X+'px';
		document.getElementById('balloon').style.top=Y+'px';
		document.getElementById('balloon_titulo').innerHTML=titulo;
		document.getElementById('balloon_texto').innerHTML=texto;
		document.getElementById('balloon').style.visibility='visible';
	
	} else {
		document.getElementById('balloon').style.visibility='hidden';
	}
}

//Mascara de data
function mascaraData(campoData){
	var data = document.getElementById(campoData).value;              
	if (data.length == 2){                  
		data = data + '/';                  
		document.getElementById(campoData).value = data;      
		return true;                            
	}              
	if (data.length == 5){                  
		data = data + '/';                  
		document.getElementById(campoData).value = data;                  
		return true;              
	}         
}

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}

function cnpj(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}

function romanos(v){
    v=v.toUpperCase()             //Maiúsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
    //Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}

function site(v){
    //Esse sem comentarios para que você entenda sozinho ;-)
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}