var MSIE = (document.all);
var NSN4 = (document.layers);
String.prototype.trim=function(type){switch(type){case undefined:return this.replace(/^(\s|\xA0)*/,'').replace(/(\s|\xA0)*$/,'');break;case 'alpha':return this.replace(/[A-Za-záéíóúüàâãêôõçÁÉÍÓÚÜÀÃÂÊÔÕÇ]/gi,'');break;case 'number':return this.replace(/\d/gi,'');break;}}
/*
Formata e valida o valor do textbox para um valor decimal
de acordo com os parametros informados.

Parâmetros:
	o (TextBox) = objeto textbox
	dig (inteiro) = quantidade de dígitos antes da vírgula
	dec (inteiro) = quantidade de dígitos após a vírgula
	evento (event)

Usar o método: NotaControl.Utilitarios.Util.FormataDecimal			
Modo de usar:
	txt.Attributes.Add("onPaste", "return false;")
    txt.Attributes.Add("OnKeyPress", String.Concat("javascript:formataDec(this,", digitosInteiro, ",", casasDecimais, ", event);"))
    txt.Attributes.Add("onBlur", txt.Attributes("OnKeyPress"))
*/
//var arrFieldsClearValue = new Array();
function formataDec(o, dig, dec, evento){
	var vr = o.value;
	var tammax = dig + dec;
	var tam = vr.length;
	var vetor = vr.split(",");
	//Pega o keyCode da tecla pressionada
	var tecla = capturaTecla(vr);

	//OnBlur, Validar o valor informado, acrescentando zero a direita.
	if (tecla == 0 && dec > 0 && vr != "") {
		var indexOfvirgula = vr.indexOf(',');
		if (vr !=  '' && indexOfvirgula == -1) { vr = vr + ','; indexOfvirgula = vr.indexOf(',');}
		var faltaDec = vr.length - indexOfvirgula;
		for (i = 0; i <= dec - faltaDec; i++){ 
			vr = vr + '0';
		}
		o.value = vr;
		return false;				
	}

	//Cancelar a tecla digitada quando não for numérica ou inserir mais de uma vírgula
	//ou ao inserir uma virgula para quantidade de casas decimais igual a zero
	if (!(tecla >= 48 && tecla <= 57 || tecla == 44) || (tecla == 44 && (tam > 1 || dec == 0)) || (tecla == 48 && vr == '' && dec == 0)){
		event.cancelBubble = true;
		event.returnValue = false;
		return false;
	}											
	
	if ((vetor[0].length == dig && dec > 0) && (vr.indexOf(',') == -1 && tecla != 44)) {
		o.value = vr + ',';
	}
	else {
		if ((vetor[0].length == 0 && dec > 0) && (tecla == 48 || tecla == 44)) {
			event.cancelBubble = true; event.returnValue = false;
			o.value = vr + '0,';
		}
	}
	if (vetor.length > 1) {
		tammax = dec;
		tam = vetor[1].length;
	}
	if (tam >= tammax){ 
		event.cancelBubble = true; event.returnValue = false;
	}
}
function ArmazenaValor(objeto,valor) {
	document.Form1[objeto].value = valor
}
	
// quantidade máxima de caracteres em textarea
function maxTextarea(campo,max,evento){
	if(document.Form1[campo].value.length>=max){
		evento.keyCode=0;
		return false;		
	} 
}
// CONTROLE DE FOCO AUTOMÁTICO EM POP MODAL//
function ForcaPop(clicou,Larg,Alt){
	if(clicou==0){
			desligaOnbefore();
			self.close();		
		}else{
			data= new Date();
			opener.NovaJanela(self.location,'Janela'+data.getTime(),Larg,Alt,'Yes');							
		}
}
// chama quando o formulário é submetido
function colocaFoco(){
	self.focus();
} 
var focoAutomatico;
function desligaOnbefore(){
	window.onbeforeunload="";
}
// chama quando uma caixa de seleção ganha o foco e quando a página é carregada
function ligaFocoAutomatico(){
	focoAutomatico=window.setInterval("colocaFoco()",100);
}
// chama quando uma caixa de seleção perder o foco
function desligaFocoAutomatico(){
	window.clearInterval(focoAutomatico);
}
// FIM CONTROLE DE FOCO AUTOMÁTICO EM POP MODAL //
function configCSS(){	
	var ns4 = document.layers;
	var ns6 = document.getElementById && !document.all; 
	
	var arquivo="Default/Default.css";													
	if(ns4 || ns6)	var arquivo ="estilosMozilla.css";
	
	local = window.location.href;
	b = local.split(/\//)
	caminho=b[0]+"//"+b[1]+"/"+b[2]+"/"+b[3]+"/css/"+arquivo;
	
	var tagCSS ="<link href=\""+caminho+"\" rel=\"stylesheet\" type=\"text/css\">";
	document.write(tagCSS);
}
configCSS();
/* FIM configura CSS */ 

/*----// para o menu --///// */
function showInput(isOn){
var iForm;
var iElement;
var sTipo;
	if(MSIE){
		for(iForm=0; iForm < document.forms.length; iForm++){
			for(iElement=0; iElement < document.forms[iForm].elements.length; iElement++){	
				sTipo = document.forms[iForm].elements[iElement].type; 
				if( sTipo== "select-one" || sTipo == "select-multiple")
					document.forms[iForm].elements[iElement].style.visibility = isOn ? "visible" : "hidden";

			}
		}
	}
	else 
		if(NSN4){
			if(window.document.estapagina)
				window.document.estapagina.visibility = isOn ? "show" : "hide";
		}
}

/*Fim menu*/
window.onload=function(){		
	resolucao();
	try{if(typeof startFn!='undefined'){(typeof startFn)=='string'?eval(startFn):startFn();}}catch(ex){}
}
window.onresize=function(){
	resolucao();
}

function rolar(){  // chamar esta função quando ocorrer o PostBack 
	valor=Form1.rolagemy.value;
	if(valor==""){
		//window.scroll(0,0);	para janela 
		document.getElementById("conteudo").scrollTop=valor; // para div
	}else{
		valor=parseInt(valor);
		//window.scroll(0,valor);	 // para janela
		document.getElementById("conteudo").scrollTop=valor; // para div
	}
}

function atualiza_posicao_rolagem(){ //chamar esta função no evento onmouveOver do botão que faz postBack 
	//document.Form1.rolagemy.value=document.body.scrollTop;  // para a janela 		
	document.Form1.rolagemy.value=document.getElementById("conteudo").scrollTop;		
}


function somacampo(campo_valor,campo_resp,valor_soma){
/*
// soma o valor de campo_valor com o valor_soma e atribui em campo_resp
//campo_valor	: o campo com o valor a ser somado
//campo_resp	: o campo onde será tribuido a soma
//valo_soma		: o valor a ser somado com o campo_valor
*/
	if(document.Form1[campo_resp].value==""){
		if(document.Form1[campo_valor].value!=""){	
			document.Form1[campo_resp].value=eval(parseInt(document.Form1[campo_valor].value) + parseInt(valor_soma));
		}		
	}
}

function preenche_campos(palavra_campo,valor){	
		var qtd	=opener.document.Form1.tags("input").length;	//qtd de tags input
		var tags=opener.document.Form1.tags("input");	//o objeto input		
		
		for	(i=0;i<qtd;i++){
			nome_campo=tags[i].name;
			if(nome_campo.indexOf(palavra_campo)!=-1){
				opener.document.Form1[nome_campo].value=valor;
			}
		}		
}

//-----------------------------------------------------------------
// exibe a quantidade de caracteres em um label durante a digitação
//TextBox6.Attributes.Add("onKeyUp", "qtd_carac(this.name,'qtd_rotulo',15)")
//----------------------------------------------------------------
function qtd_carac(campo,label,limite){
			var qtd_agora=document.Form1[campo].value.length;
			document.Form1[campo].maxLength=limite;
			if(qtd_agora<=limite){
				document.getElementById(label).innerText=qtd_agora;
			}		
}
//-------------------------------------------------------------
//Testa se campo esta vazio e exibe a mensagem
//------------------------------------------------------------
function VerificaVazio(campo,msg){
	if(document.Form1[campo].value==""){
		if(msg!=""){
			window.alert(msg);
			//document.Form1[campo].focus()
		}
	} 
}

function resolucao(){ // ajuste de resolução

	var largura=document.body.clientWidth;
	var altura=document.body.clientHeight;

	if(document.getElementById("tbIndividual")) {
		if(largura > 0) document.getElementById("tbIndividual").style.width=largura - 50;
	}
	
	if(document.getElementById("conteudo") != null) {
		if(largura > 0) document.getElementById("conteudo").style.width=largura -30;
	}
	
	//document.title="Largura:"+largura+", Altura:" +altura+", Navegador:"+ navigator.appName+" Versão:"+versao;
}
//-----------------------------------------------------
//Validação automática
//-----------------------------------------------------
function criar_eventos() // cria eventos para os componentes automáticos
{
		for(i=0;i<document.Form1.elements.length;i++){		
				var nome_campo=document.Form1.elements[i].name;				
				if(nome_campo.indexOf("cpf")!=-1)
					evento_cpf(nome_campo,evento);								
	
				if(nome_campo.indexOf("cnpj")!=-1)
					evento_cnpj(nome_campo,evento);								
		}
}

cpf=new Array();
cnpj=new Array();
i=0;
j=0;

function evento_cpf(nome_campo,evento){
	cpf[i]=document.getElementById(nome_campo);					
	cpf[i].onkeypress = function (){
			FormataCpf(nome_campo,evento);
	}
	cpf[i].onblur = function (){
			FormataCpf(nome_campo,evento);
			valida_cpf(nome_campo,evento);
	}
}

function evento_cnpj(nome_campo,evento){	
	cnpj[j]=document.getElementById(nome_campo);
	cnpj[j].onkeypress = function (){
		FormataCnpj(nome_campo,evento);
	}
	cnpj[j].onblur = function (){
		FormataCnpj(nome_campo,evento);
		valida_cnpj(nome_campo,evento);
	}
}
	
function valida_Form1(){	
	for(i=0;i<document.Form1.elements.length;i++)
	{
				nome_campo=document.Form1.elements[i].name;			
		
				if(nome_campo.indexOf("cpf")!=-1 ){						
					if(valida_cpf(nome_campo)==false)
						return  false;						
				}
				
				if(nome_campo.indexOf("cnpj")!=-1){
							if(valida_cnpj(nome_campo)==0)
								return false;								
				}
								
	}
}

//--------------------
//Específica pra relatórios
//------------------
var janprint;
function imprimirRelatorio(caminho_css)
{
	if (!caminho_css)
		caminho_css = '../Css/estilos.css';
	var npag = 1
	
	var versao, versao2, versaoNav, versaoSO, navegador, nav = getObj('logNavegador'), so = getObj('logSO');
	versao = navigator.appVersion.split(";");
	versaoNav = trimJS(versao[1]);
	versaoNav = ApenasNum(versaoNav);
	versaoSO = trimJS(versao[2]);
	navegador = navigator.appName;
	
	//alert(versaoNav);
	//alert(navigator.appName);
		
	var strGeral = '<html><head><link href='+caminho_css+' rev=stylesheet rel=stylesheet type=text/css></head><body>';
	var strIE7 = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head><title>Impress&atilde;o</title><meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"><meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1"><meta name="vs_defaultClientScript" content="JavaScript"><meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"><LINK href="'+caminho_css+'" type="text/css" rel="stylesheet"><script src="' + '../scripts/functions.js' + '"></script></head>';
	strIE7 += '<body onload="javascript:try{PreVisualizarRelatorio();}catch(e){opener.PreVisualizarRelatorio();}">';
	var strMeio = '';
	var strFinal = '</body></html>';
	
	/*if ((navigator.appName.indexOf('Microsoft') != -1) && (versaoNav.indexOf('7') != -1)) 
		janprint = window.open('../Controles/Blank.htm','','left=10000,top=10000,width=0,height=0,scrollbars=1,status=0');
	else*/
	//alert(navigator.appName);
	janprint = window.open('','','left=0,top=0,width=800,height=800,scrollbars=1,status=0');

	while (document.getElementById('mol' + npag)) {
		var objeto = document.getElementById('mol' + npag);
		var ultimaPag = false;
				
		try{
			var i = document.getElementById('mol' + (npag + 1));
			if(i == null){
				 throw 'ex';
			}
		}catch(e){
			ultimaPag = true;
			//document.getElementById('pag' +npag).style.pageBreakAfter = 'avoid';
		}
			
		if(!ultimaPag){		
			strMeio += objeto.innerHTML;
		}else{
			strMeio += objeto.innerHTML.replace(/page\-break\-after/i,'pbb');
		}
		npag = npag + 1;
	}
	
	/*if ((navigator.appName.indexOf('Microsoft') != -1) && (versaoNav.indexOf('7') != -1)) {
		janprint.document.write(strIE7 + strMeio + strFinal);
		janprint.document.close();
		janprint.focus();
		janprint.location.reload();
		document.getElementById('btnFechar').onclick = FechaPreVisualizacao
		janprint.print();
		janprint.close();
	} else {*/
		janprint.document.write(strGeral + strMeio + strFinal);
		janprint.document.close();
		janprint.focus();
		janprint.print();
		janprint.close();
	//}
}

function PreVisualizarRelatorio()
{
	try 
	{
		 //Utilizando o componente WebBrowser1 registrado no MS Windows Server 2000/2003 ou XP/Vista
		 WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>'; 
		 document.body.insertAdjacentHTML('beforeEnd', WebBrowser); 
		 WebBrowser1.ExecWB(7,1); 
	} 
	catch(e) 
	{
		alert("Para visualizar a impressão você precisa habilitar o uso de controles ActiveX na página.");
		return;
	}
}

function FechaPreVisualizacao() {
	if ((janprint.document.getElementById('WebBrowser1') != null) && (janprint != null)) {
		janprint.document.getElementById('WebBrowser1').ExecWB(45,1);
		janprint.close();
		self.close();
	}
}

function navegaRelatorio(valor){
	if(document.getElementById('anc' + valor)){
		location.href= '#anc' + valor;
		document.Form1.PagAtual.value = valor;
	}
}		

//--------------------
//imprime conteúdo de uma div sintaxe:Imprimir("id_div")
//------------------
function imprimir(nome_obj){
	var objeto = document.getElementById(nome_obj);
	var janprint = window.open('../Controles/Blank.htm','','left=2000,top=2000,width=1,height=1,scrollbars=0,status=0');
	//var janprint = window.open('','','left=2000,top=2000,width=1,height=1,scrollbars=0,status=0');
	janprint.document.write('<html>');
	janprint.document.write('<head>');
	janprint.document.write('<link href=../css/estilos.css rev=stylesheet rel=stylesheet type=text/css>');
	janprint.document.write('</head>');
	janprint.document.write('<body>');
	janprint.document.write(objeto.innerHTML);
	janprint.document.write('</body>');
	janprint.document.write('</html>');
	janprint.document.close();
	janprint.focus();
	janprint.print();
	janprint.close();
}

//---------------------------------------------------------------------
//Subtrai
//---------------------------------------------------------------------			
function subtrai(campo1,campo2,campo_result){
	var valor1=document.Form1[campo1].value;
	var valor2=document.Form1[campo2].value;
	
	if(valor1!="" && valor2!=""){		
		var valor1=parseFloat(valor1);		
		var valor2=parseFloat(valor2);
		
		if(valor2<valor1){
			window.alert("O valor do campo \"Pag. Final\"="+valor2+ "deve ser maior ou igual ao valor do campo \"Pag. Inicial\"="+valor1+"!")	;
			document.Form1[campo2].focus();
			if(document.Form1[campo_result].value!="")		
				document.Form1[campo_result].value=""; 
		}	
		else{	
				document.Form1[campo_result].value=eval((valor2 - valor1) + 1)		
		}
	}
}
//-------------------------------------------------------------------
//	Função desafada em desuso. por favor não usar esta função, pois
//	esta existirá apenas para correção em arquivos que ainda a utilizam
//-------------------------------------------------------------------

function seleciona_checkbox(){
	if(document.Form1.checatodos.checked)
		valor=false
		else
			valor=true
	
	qtd_elementos=document.Form1.elements.length;
	for(i=0;i<qtd_elementos;i++){
		if(document.Form1.elements[i].type=="checkbox"){
			//if(!document.Form1.elements[i].disabled)
				document.Form1.elements[i].checked=valor;				
		}
	}			
}
//---------------------------------------------------------------------
//valida se a data está correta
//---------------------------------------------------------------------			
function valida_data(campo){ 
 
	      	data= document.Form1[campo].value;
	      	if (data==""){
	      		return false;
	      	}
	      	else{
	      		data=data.replace(" ",""); // remove espaços
	      	}
	      	if(data.length != 10) {
	      		alert("Data Incorreta!");
				document.Form1[campo].focus(); 
				document.Form1[campo].select();
				//arrFieldsClearValue[campo] = 1;
				return false;
	      	}
			
				posbarra1=data.indexOf("/",0);
				posbarra2=data.indexOf("/",posbarra1+1);
				
				dia = data.substring(0,posbarra1); 
				mes = data.substring(posbarra1+1 , posbarra2); 
				ano = data.substring(posbarra2+1,10); 
				var observacao = 0;			
				var retorno = 1; 
				// o sistema  aceita de 1753 a 9999, mas este escript foi limitado desde 1900
				if((ano>=1900)&&(ano<=3000)){				
					if(ano > 80 && ano <= 99) // corrige o ano caso foi digitado com apenas dois numeros
						ano = 1900 + parseInt(ano,10);
					else
						ano = 2000 + parseInt(ano,10);					
				}else{
					if(data.length>=8){
						observacao = 1; // retorna 2 para mudar exibir mensagem de observacao e nao de erro. 
					}
				}
					
				if(dia.length==0 || mes.length==0 ){
					retorno = 0; 
				}
				// verifica o dia valido para cada mes 
				if ((dia < 1)||(dia < 1 || dia > 30) && (mes == 4 || mes == 6 || mes == 9 || mes == 11 ) || dia > 31){ 
					retorno =0;
				} 
				// verifica se o mes e valido 
				if (mes < 1 || mes > 12 ){ 
				retorno =0;
				} 
				// verifica se é ano bissexto 
				//se o resto divisao do ano por 4 for 0 o ano é bisexto senão o ano é normal
				if (mes == 2 && ( dia < 1 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4)))){ 
					retorno =0;
				} 
				if (document.Form1[campo].value == ""){ 
					retorno =0;
				}             
				if (retorno == 0 ) { 
					alert("Data Incorreta!");
					document.Form1[campo].focus(); 
					document.Form1[campo].select();
					//arrFieldsClearValue[campo] = 1;
					return false;
				} else if(observacao==1){ // mensagem de observacao
					alert("OBSERVAÇÃO: Este ano não é aceito pelo sistema!");
					document.Form1[campo].focus(); 
					document.Form1[campo].select();
					//arrFieldsClearValue[campo] = 1;
					return false;				
				}
				else{
					//arrFieldsClearValue[campo] = 0;
					return true;
				}
						
} 
//---------------------------------------------------------------------
//Verifica se a data1 é maior ou igual que a data 2 retorna true ou false
//---------------------------------------------------------------------			
function compara_datas(campo1,campo2,msg){
		
		dt1=window.document.Form1[campo1].value;
		dt2=window.document.Form1[campo2].value;		
		
		var hoje = new Date();
		var ano = hoje.getYear();
		if(ano >= 50 && ano <= 99) // formata o ano pra 4 caracteres
			ano = 1900 + ano
		else
			ano = 2000 + ano;
		
		var pos1 = dt1.indexOf("/",0)
		var dd = dt1.substring(0,pos1)

		pos2 = dt1.indexOf("/", pos1 + 1)
		var mm = dt1.substring(pos1 + 1,pos2) // captura o mes da data1
		var aa = dt1.substring(pos2 + 1,10) // captura o ano da data1

		if(aa.length < 4) // formata o ano pra 4 caracteres
			if(ano > 1999)
				aa = (2000 + parseInt(aa,10))
			else
				aa = (1900 + parseInt(aa,10));

		var data1 = new Date(parseInt(aa,10),parseInt(mm,10) - 1, parseInt(dd,10)); //cria um objeto com a data1

		var pos1 = dt2.indexOf("/",0)
		
		var dd = dt2.substring(0,pos1)
		pos2 = dt2.indexOf("/", pos1 + 1) // indexOf( StringConsulta , posicaoInicialConsulta )
		var mm = dt2.substring(pos1 + 1,pos2)
		var aa = dt2.substring(pos2 + 1,10)
		
		if(aa.length < 4)  // formata o ano pra 4 caracteres
			if(ano > 80 && ano <= 99)
				aa = (1900 + parseInt(aa,10)) // parseInt(variavel, base)
			else
				aa = (2000 + parseInt(aa,10));

		var data2 = new Date(parseInt(aa,10),parseInt(mm,10) - 1,parseInt(dd,10)); //cria um objeto com a data2

	if(data1 < data2) // compara as datas
	{
		alert(msg);
		window.document.Form1[campo1].focus();
		document.Form1[campo1].select();
		return false;
	}
	else{
		return true; 
	}

} 
//---------------------------------------------------------------------
//DIFERENÇA EM MESES ENTRE DATAS sintaxe: numMeses("16/04/2005","07/04/2005") retorna o número de meses
//---------------------------------------------------------------------		
function numMeses(campo1,campo2,foco){
	
	var vr1=document.Form1[campo1].value
	var vr2=document.Form1[campo2].value
	
	vr1 = Verifica_se_Numero(campo1);
	if (!vr1) {return false;}

	vr2 = Verifica_se_Numero(campo2); 
	if (!vr2) {return false;}
			
	if(!valida_data(foco)){return false;}	
	
	if ((vr1==true) || (vr2==true)){return false;}
	
	mesInicial	=vr1.slice(2,4);
	mesFinal	=vr2.slice(2,4);
	
	anoInicial	=vr1.slice(4,9);
	anoFinal	=vr2.slice(4,9);
	
	if(anoFinal.length!=0 && anoInicial.length!=0)
	{
		if(anoFinal < anoInicial)
		{
			window.alert("A data do vencimento deve ser maior que a data da assinatura!");
			document.Form1[campo1].focus();
			document.Form1[campo1].select();
			return 0;
		}else
		{ if ((mesFinal<mesInicial) && (anoFinal==anoInicial))
			{window.alert("A data do vencimento deve ser maior que a data da assinatura!");
			document.Form1[campo1].focus();
			document.Form1[campo1].select();
			return 0;
			}
		}
		
	}else{
		return 0;
	}
	
	valor=eval(anoFinal-anoInicial)*12;
	valor+=eval(mesFinal-mesInicial);
	
	return valor;
}
//sintaxe:  NovaJanela('arquivo.aspx','janPop',500,500,'resizable=yes , scroll=no')
var win;
function NovaJanela(pagina,nome,w,h,add_atributos){
	
	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	//Atributos
	var settings ='height='+h+',';
	settings +='width='+w+',';
	settings +='top='+wint+',';
	settings +='left='+winl+',';
	settings +='resizable=yes,location=no';
		
	if(add_atributos!=""){
		settings += ',' + add_atributos;
	}	
	win=window.open(pagina,nome,settings);
	//Correção para outros navegadores
	if(parseInt(navigator.appVersion) >= 4){win.window.focus();}
}

function FecharPop(){
	if(win)
		win.close();
}



function PulaFoco(){	
	var QtdElem=document.Form1.elements.length;
	for(i=0;i<QtdElem;i++){
		var tipo=document.Form1.elements[i].type;
		var valor=document.Form1.elements[i].value;
		if((tipo=="text")&&(valor!=""))
				document.Form1.elements[i].tabindex=200+i;
		else
				document.Form1.elements[i].tabindex=i+1;				
		
	}	
}
//---------------------------------------------------------------------
//	SETA O FOCO ATUAL PARA UM CONTROLE ASP.NET
//---------------------------------------------------------------------	
function PegaFoco(Campo){ 
	var control = document.getElementById(Campo);
	if(control!=null){ 
			control.focus(); 						
	}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//  Funciona com qualquer controle: Button, Dropdownlist, txtbox, etc.
//  Metodo: Se for no href usar javascript: se não use <script>
//  Chamada: PegaFoco_AspNet('Nome_do_Campo');
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function capturaTecla(e){	
		if(MSIE){
		
			if(e!=null){
				tecla = event.keyCode;	//captura o ASC da tecla pressionada	
			}else{
				tecla=7;
			}
	
		}else{
			document.captureEvents(Event.KEYPRESS | Event.KEYUP);
			tecla=	e.which;
		}	
return tecla;	
}
//---------------------------------------------------------------------
// Permite apenas as teclas numéricas
//---------------------------------------------------------------------

function VerificaTecla(campo,evento){
	//Modo de usar: TxtBox1.Attributes.Add("onKeyPress", "VerificaTecla(this.name,event)")
	//				TxtBox1.Attributes.Add("onBlur", "VerificaTecla(this.name,event)")
	tecla=capturaTecla(evento);	
	if(tecla==0){ // retorna 0 se a tecla for especia com setinhas por exemplo
		return 0;
	}
	//esta condicao permite ele digitar apenas um sinal -
	// para se permitir valor negativo em um campo, é necessário que seu 
	//id | nome possua a flasg _neg. o JS identifica esse campo e permite o sinal de - como sendo 
	//o primeiro caractere
	if((campo.indexOf("_neg")!=-1)&& document.Form1[campo].value.length==0){ // encontrar string neg no nome do campo , habilita num negativos
		condicao=((tecla > 47 && tecla < 58) || tecla==45 || tecla==0); ////número de 0 à 9 ou sinal de -
	}else{
		condicao=(tecla > 47 && tecla < 58 || tecla==0 ); //número de 0 à 9
	}	
	
	if(condicao) 
				return 1;
	else
		
		if ((tecla != 8) && (tecla !=17) && (tecla !=16))//teclas de combinação
		{	
			if(MSIE){
				if(evento!=null){
					evento.keyCode = 0;
				}
				
			}else{
				evento.preventDefault(); // cancela digitação netscape
			}			
			return 0;			
		}
		else
			return 1;			
}				
//---------------------------------------------------------------------
// Formata os campos de cep durante a digitacao
//---------------------------------------------------------------------			

function FormataCep(campo,evento) 
{
	//Modo de usar: TxtBox1.Attributes.Add("onKeyPress", "FormataCep(this.name,event)")
	//				TxtBox1.Attributes.Add("onBlur", "FormataCep(this.name,event)")			
		try{
				var Numero = VerificaTecla(campo,evento);
				if (Numero == 0){
					return false;
				}
				vr=Verifica_se_Numero(campo); // ja tem o limpaformato
				if (!vr) {return false;}
				
				tam = vr.length + 1;

				if ( tecla != 9 && tecla != 8 )
				{
					//if ( tam == 3 )
					//	document.Form1[campo].value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, tam );
					if ( (tam >= 7) && (tam <= 10)  )
						document.Form1[campo].value = vr.substr( 0, 5 ) + '-' + vr.substr( 5, 10 ); 
				}
		}catch(err){
			alert("Ocorreu o seguinte erro:"+err.description);
		}
}

//---------------------------------------------------------------------
// Formata os campos de telefone durante a digitacao
//---------------------------------------------------------------------			

function FormataTelefone(campo,evento){
   /*
	Modo de usar: 	
	Txt_Fone.Attributes.Add("onKeyPress", "javascript:FormataTelefone(this.name);")
    Txt_Fone.Attributes.Add("onBlur", "javascript:FormataTelefone(this.name);") 
   */
	var tammax = 8 ;
	var Numero = VerificaTecla(campo,evento);
	vr=Verifica_se_Numero(campo); // ja tem o limpaformato
	if (!vr) {return false;}
	var tam = vr.length;
	if (tam >= tammax)
	{ 
		if (Numero == 0)// esta formatação so vai ocorrer caso o usuariio colar no campo a quantidade de 
		{				//caracteres maior que o tamanho maximo (tammax)
			vr = vr.slice(0, tammax);
			tam = vr.length;
		}
		else{
			return false;
		}
	} 
	tam = vr.length + Numero; // soma com o retorno da funcao verificaTecla que pode ser 0 ou 1
	if ( (tam > 4) ){
		document.Form1[campo].value = vr.substr( 0, tam - 4 ) + '-' + vr.substr( tam - 4, tam ) ; 
	}
	
	return true;
}

function FormataTelefoneCompleto(objeto){
   if(objeto.value.length == 0)
     objeto.value = '(' + objeto.value;

   if(objeto.value.length == 3)
      objeto.value = objeto.value + ')';

 if(objeto.value.length == 8)
     objeto.value = objeto.value + '-';
}


//---------------------------------------------------------------------
// Formata os campos de milhar durante a digitacao
//---------------------------------------------------------------------	
// LEMBRAR: COLOCAR MAXLENGHT=15 NO TEXTBOX DE CHAMADA
// função testada com evento onKeyUp

function FormataMilhar(campo,evento){
	
	var tammax = 15
	var Numero = VerificaTecla(campo,evento);
	vr=Verifica_se_Numero(campo); // ja tem o limpaformato
	if (!vr) {return false;}
	
	var tam = vr.length;

	if (tam >= tammax)
	{ 
		if (Numero == 0) // esta formatação so vai ocorrer caso o usuariio colar no campo a quantidade de 
		{				 //caracteres maior que o tamanho maximo (17)
			vr = vr.slice(0, tammax);
			tam = vr.length;
		}
		else
		{
			return false;
		}
	} 

	tam = vr.length + Numero; // soma com o retorno da funcao verificaTecla que pode ser 0 ou 1
	if ( tam <= 3 ){ 
		document.Form1[campo].value = vr ; 
		}
	if ( (tam > 3) && (tam <= 6)){
		valor= vr.substring( 0, tam - 3 ) + '.' + vr.substring( tam - 3, tam ) ; 
		document.Form1[campo].value =valor;
		}
		
	if((tam >= 7) && (tam <= 9) ){
		valor= vr.substring( 0, tam - 6) + '.' + vr.substring( tam - 6, tam - 3) + '.' + vr.substring( tam - 3, tam ) ; 
		document.Form1[campo].value =valor;
	}
	if ((tam >= 10) && (tam <= 12))
	{
		valor=vr.substring( 0, tam - 9 ) + '.' + vr.substring( tam - 9, tam -6 ) + '.' + vr.substring( tam - 6, tam - 3 ) + '.' + vr.substring( tam - 3, tam ) ; 
		document.Form1[campo].value =valor;
	}
	
	if ((tam >= 13) && (tam <= 15))
	{
		valor=vr.substring( 0, tam - 12 ) + '.' + vr.substring( tam - 12, tam -9 ) + '.' + vr.substring( tam - 9, tam - 6 ) + '.' + vr.substring( tam - 6, tam-3 ) + '.' + vr.substring( tam - 3, tam ); 
		document.Form1[campo].value =valor;
	}	

} //function


function BloqueiaTecla(evento){			
	if(MSIE){
		if(evento!=null){
		evento.keyCode = 0;
		}				
	}else{
		evento.preventDefault(); // cancela digitação netscape
	}			
	return false;
}

//---------------------------------------------------------------------
// Formata os campos de moeda em tempo de digitacao
//---------------------------------------------------------------------					
function FormataMoeda(campo,evento){
	/* 
	Esta rotina pode ser chamada passando como parâmetro Uma Campo ou um Valor já definido
	txt_Media.Attributes.Add("onKeyPress", "javascript:FormataMoeda(this.name,event);")
	*/		
	
	var campoNeg			=false;	
	valor					= document.Form1[campo].value;				


	var hasSelection = (document.selection && document.selection.createRange().text.length > 0) || (!isNaN(parseInt($(campo).selectionStart)) && $(campo).selectionStart < $(campo).selectionEnd);
	if(hasSelection) {
		if(evento!=null) {
			var tmpNomeEvento = evento.type;
			tmpNomeEvento = tmpNomeEvento.toLowerCase();
			if(tmpNomeEvento!="blur") document.Form1[campo].value = '';
		}
	}

	
	if(valor<1){
		document.Form1[campo].value =valor;	
	}else{
	
	
	var valor=LimpaFormato(campo);	
	if(campo.indexOf("neg")!=-1){
		campoNeg=true;			
	}	
	var sinalNeg	=(valor.charAt(0)=="-") ? true : false;	
	if (isNaN(valor)){
		document.Form1[campo].value =""		; //limpa o campo se não for número
		return false						;
	}		
	var tammax			=17					;//qtd máxima para formatar
	var tam				=valor.length		;
	var nomeEvento		=""					;
	var valorFormatado	=""					;	
	
	if(evento!=null){
		nomeEvento=evento.type;
		nomeEvento=nomeEvento.toLowerCase();	
		switch(nomeEvento){
			case "keypress":
				var tecla=VerificaTecla(campo,evento);// retorna 0 quando a tecla não é valida ou 1 quando a tecla é valida
				tam+=tecla;
				break;
			
			case "keyup":
			
			case "blur":			
				if(tam<=2){											
					if(valor.charAt(0)=="0"){						
						valor=parseFloat(valor);
						if(tam==2)
							tam--;
					}									
						valor+='00';
						tam+=2;						
				}							
				break;
			
		}
		
	}	
	valor=valor.toString();
	if(tam<=tammax){	
		//bloqueia tecla quando o usuário digitar centavos		
		if(valor.charAt(0)=="0" && tam>=4){
			return BloqueiaTecla(evento);			
			}
		if((tam > 2) && (tam <= 5) ){
			valorFormatado= valor.substr( 0, tam - 2 ) + ',' + valor.substr( tam - 2, tam ) ; }
		if((tam >= 6) && (tam <= 8)){
			valorFormatado = valor.substr( 0, tam - 5 ) + '.' + valor.substr( tam - 5, 3 ) + ',' + valor.substr( tam - 2, tam ) ; }
		if((tam >= 9) && (tam <= 11) ){
			valorFormatado = valor.substr( 0, tam - 8 ) + '.' + valor.substr( tam - 8, 3 ) + '.' + valor.substr( tam - 5, 3 ) + ',' + valor.substr( tam - 2, tam ) ; }
		if((tam >= 12) && (tam <= 14) ){
			valorFormatado = valor.substr( 0, tam - 11 ) + '.' + valor.substr( tam - 11, 3 ) + '.' + valor.substr( tam - 8, 3 ) + '.' + valor.substr( tam - 5, 3 ) + ',' + valor.substr( tam - 2, tam ) ; }
		if((tam >= 15) && (tam <= 17) ){
			valorFormatado = valor.substr( 0, tam - 14 ) + '.' + valor.substr( tam - 14, 3 ) + '.' + valor.substr( tam - 11, 3 ) + '.' + valor.substr( tam - 8, 3 ) + '.' + valor.substr( tam - 5, 3 ) + ',' + valor.substr( tam - 2, tam ) ;}

	}else{	
		//Bloqueia a tecla para nao deixar o usuário digitar mais que o tamanho máximo definido para formatação
		return BloqueiaTecla(evento);
	}	
	
	if(valorFormatado!="")
		document.Form1[campo].value  = valorFormatado;		
	
	//Coloca o sinal antes do valor
	if(sinalNeg && campoNeg){
		valor=document.Form1[campo].value;
		valor=valor.replace("-","");
		document.Form1[campo].value="-"+valor;
	}
	
	}
} 

//Recebe um número como parâmetro e retorna em formato de moeda
function FormataMoeda2(num){
	if(isNaN(num))
	num = "0";

	sinal = (num == (num = Math.abs(num)))	; // se o número do paramatro for igral o seu absoluto , quer dizer que é positivo senão quer dizer que é negativo , essa variável será true ou false
	
	num = Math.floor(num*100+0.50000000001);
	centavos = num%100;
	num = Math.floor(num/100).toString();
	
	if(centavos<10)
	centavos = "0" + centavos;	
	// formata o milhar
	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));
		
	return (((sinal)?'':'-') + num + ',' + centavos);
}


//---------------------------------------------------------------------
// Formata os campos de data durante a digitacao
//---------------------------------------------------------------------			
function FormataData(campo,evento) {
	/*	Modo de usar:
		TextBox_Data.Attributes.Add("onpaste", "return false;")
		TextBox_Data.Attributes.Add("onKeyPress", "FormataData(this.name,event);") 
		TextBox_Data.Attributes.Add("onBlur", "FormataData(this.name,event);") */		
	var evt = (document.all)? event : e ;
	var charCode = (document.all)? evt.keyCode : evt.which ;
	
	var hasSelection = (document.selection && document.selection.createRange().text.length > 0) || (!isNaN(parseInt($(campo).selectionStart)) && $(campo).selectionStart < $(campo).selectionEnd);
	if(hasSelection) {
		document.Form1[campo].value = '';
	}
	
	/*if(charCode!=8 && charCode!=9 && charCode!=0) {
		try {
			if(typeof(arrFieldsClearValue[campo]) != 'undefined' && arrFieldsClearValue[campo]!=null) {
				if(arrFieldsClearValue[campo]==1) {
					document.Form1[campo].value = '';
					arrFieldsClearValue[campo] = 0;
				}else{
					// se a data está preenchida e a tecla pressionada não é TAB ou BACKSPACE ou DELETE, apaga seu conteúdo
					if(document.Form1[campo].value.length == 10) document.Form1[campo].value = '';
				}
			}else{
				// se a data está preenchida e a tecla pressionada não é TAB ou BACKSPACE ou DELETE, apaga seu conteúdo
				if(document.Form1[campo].value.length == 10) document.Form1[campo].value = '';
			}
		} catch(e) { }
	}*/
	
	var tammax = 8;
	var Numero = VerificaTecla(campo,evento);
	vr=Verifica_se_Numero(campo); // ja tem o limpaformato	]
	var tam = vr.length;
	var vetor = document.getElementById(campo).value.split("/");
	if (tam >= tammax){ 
		event.cancelBubble = true; event.returnValue = false;
	}
	else {
		if (vetor.length == 3){
			if(vetor[0].length == 1) { vetor[0] = '0' + vetor[0]; }
			if(vetor[1].length == 1) { vetor[1] = '0' + vetor[1]; }
			vr = vetor[0] + '' + vetor[1] + '' + vetor[2];
			document.Form1[campo].value = vetor[0] + '/' + vetor[1] + '/' + vetor[2];
			if (vetor[2].length == 4) {
				event.cancelBubble = true; event.returnValue = false;
			}
		}
	}
	tam = vr.length + Numero;
	var tecla = String.fromCharCode(event.keyCode); tecla = parseInt(tecla);
	
	var dia = 0, mes = 0, diasNoMes = 31, ano = 0;
	//Se a tecla digitada não for numérica (um tab ou enter por exemplo)
	if (!Numero) { 	
		if ( tam > 0 ) {
			if ( tam < 8) {
				document.Form1[campo].focus();
				document.Form1[campo].value = document.Form1[campo].value;			
				return false;
			} else {
				if ( !valida_data(campo) ) {
					document.Form1[campo].focus();
					document.Form1[campo].value = '';		
					return false;
				}	
			}
		}		
	//Se a tecla digitada for numérica
	} else { 
		if ( (tam == 1) && (tecla > 3) ) { 
			//o dia não pode iniciar com número maior do que 3 ou seja não existe dia 40 ou superior
			event.cancelBubble = true; event.returnValue = false; 
		}
		else {
			if ( tam == 2 ) {
				dia = parseInt(vr.substr( 0, 1 ));
				if ( (dia == 0 && tecla == 0) || (dia == 3 && tecla > 1) ) {
					//o dia não pode ser 00 nem maior do que 31
					event.cancelBubble = true; event.returnValue = false;
				} 
			}
			else {
				if ( tam == 3 ) {	
					dia = parseInt(vr.substr( 0, 2 )); 
					if ( tecla > 1 ) {
						//o mês não pode iniciar com número maior do que 1 ou seja não existe mês 20 ou superior
						event.cancelBubble = true; event.returnValue = false;
					}
				}
				else {
					if ( tam == 4 ) {
						mes = parseInt(vr.substr( 2, 1 ));
						if ( (mes == 1 && tecla > 2) || (mes == 0 && tecla == 0) ) {
							//o mês não pode ser maior do que 12 e nem 00
							event.cancelBubble = true; event.returnValue = false; 
						} else {
							dia = parseInt(vr.substr( 0, 2 ));
							mes = parseInt(vr.substr( 2, 1 ) + tecla);
							if ( mes == 2 ) {
								//a quantidade de dias do mês de fevereiro pode ser no máximo 29 (em anos bissextos)
								diasNoMes = 29; 
							} else {
								if ( mes == 4 || mes == 6 || mes == 9 || mes == 11) {
									diasNoMes = 30;
								}
							}
							if ( dia > diasNoMes ) {
								//altera o dia se a quantidade de dias digitada for maior do que a quantidade de dias permitida para o mês
								document.Form1[campo].value = diasNoMes + '/' + vr.substr( 2, 1 );
							}
						}
					}
					else {
						if ( tam == 5 ) {
							if ( !(tecla == 1 || tecla == 2) ) {
								//o ano não pode iniciar com digitos diferentes de 1 ou 2
								event.cancelBubble = true; event.returnValue = false;  }
						}
						else {
							if ( tam == 6) {
								ano = parseInt(vr.substr( 4, 1 ));
								if ( ano == 1 && tecla < 8  ) {
									//o ano não pde ser menor do que 1800
									event.cancelBubble = true; event.returnValue = false;
								}
							}
							else {
								if ( tam == 8 ) {						
									dia = parseInt(vr.substr( 0, 2 ));
									mes = parseInt(vr.substr( 2, 2 ));
									ano = parseInt(vr.substr( 4, 3 ) + tecla );								
									if ( (mes == 2 && dia == 29) && (parseInt(ano / 4) != (ano / 4)) ) {
										//altera o dia para 28 se o ano digitado for 29 e o ano não for bissexto
										diasNoMes = 28; dia = diasNoMes; vr = diasNoMes + '' + vr.substr( 2, 2 ) + vr.substr( 4, 3 );
										document.Form1[campo].value = diasNoMes + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 3 );										
									}
								}
							}
						}
					}
				}
			}
		}
		//Imprimir a data já válida no textbox
		if ( tam == 3 ) {
			document.Form1[campo].value = vr +  '/';
		} else {
			if ( tam == 5 ) {
				document.Form1[campo].value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/';
			} else {
				if ( tam == 8 ) {
					document.Form1[campo].value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
				}
			}
		}
	}
}
//---------------------------------------------------------------------
// Formata cpf durante a digitacao
//---------------------------------------------------------------------	
function FormataCpf(campo,evento) 
{
	/*Modo de usar:  TxtBox1.Attributes.Add("onKeyPress", "javascript:FormataCpf(this.name,event);")
					 TxtBox1.Attributes.Add("onBlur", "javascript:FormataCpf(this.name,event);valida_cpf(this.name);") */
	var tammax = 11;
	var Numero = VerificaTecla(campo,evento);
	if (Numero == 0){
		return false;
	}
	vr=Verifica_se_Numero(campo); // ja tem o limpaformato
	if (!vr) {return false;}
	var tam = vr.length;
	if (tam >= tammax)
	{ 
		if (Numero == 0)// esta formatação so vai ocorrer caso o usuariio colar no campo a quantidade de 
		{				//caracteres maior que o tamanho maximo (tammax)
			vr = vr.slice(0, tammax);
			tam = vr.length;
		}
		else{
			return false;
		}
	} 
	tam = vr.length + Numero;		

	if ( tam <= 2 ){ 
		document.Form1[campo].value = vr ; }
	if ( (tam > 2) && (tam <= 5) ){
		document.Form1[campo].value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 6) && (tam <= 8) ){
		document.Form1[campo].value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 9) && (tam <= 11) ){
		document.Form1[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) ){
		document.Form1[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) ){
		document.Form1[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 ) ;}
	
}
//---------------------------------------------------------------------
// VALIDAR NÚMERO DE "CPF"
//---------------------------------------------------------------------	
function valida_cpf(campo,evento) 
{ 
	// esta opção deve ser chamado juntamente com o formata_cpf ver exeplo no formata_cpf
	
	var Numero = VerificaTecla(campo,evento);
	vr=Verifica_se_Numero(campo); // ja tem o limpaformato
	if (!vr) {
		evento.returnValue =  false;
		if(evento.which && evento.which != 0) evento.preventDefault();
		else evento.keyCode = 0;
		return false;
	}
	
		cpf = vr;        
        Retorno = 1;
		var numeros, digitos, soma, i, resultado, digitos_iguais; 
		digitos_iguais = 1; 
		if (cpf.length < 11) 
            Retorno = 0 ; 
		 for (i = 0; i < cpf.length - 1; i++) 
            if (cpf.charAt(i) != cpf.charAt(i + 1)) 
            { 
              digitos_iguais = 0; 
              break; 
            } 
		if (!digitos_iguais) 
		{ 
            numeros = cpf.substring(0,9); 
            digitos = cpf.substring(9); 
            soma = 0; 
            for (i = 10; i > 1; i--) 
                  soma += numeros.charAt(10 - i) * i; 
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
            if (resultado != digitos.charAt(0)) 
                  Retorno = 0;
            numeros = cpf.substring(0,10); 
            soma = 0; 
            for (i = 11; i > 1; i--) 
                  soma += numeros.charAt(11 - i) * i; 
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
            if (resultado != digitos.charAt(1)) 
                 Retorno = 0;
		} 
			else 
				Retorno = 0; 
	  if(Retorno==0)
      {
		if(document.Form1[campo].value!="")
		{
			window.alert("CPF Incorreto !");
			evento.returnValue =  false;
			if(evento.which && evento.which != 0) evento.preventDefault();
			else evento.keyCode = 0;
			document.Form1[campo].focus();
			return false;
		}
	  } else {
		return true;
	  }
 }
//---------------------------------------------------------------------
// Formata cpnj durante a digitacao
//---------------------------------------------------------------------	
function FormataCnpj(campo,evento) 
{	/*Modo de usar:  TxtBox1.Attributes.Add("onKeyPress", "javascript:FormataCnpj(this.name);")
					 TxtBox1.Attributes.Add("onBlur", "javascript:FormataCnpj(this.name);valida_cnpj(this.name);") */
	var tammax = 14  ;
	var Numero = VerificaTecla(campo,evento);
	vr=Verifica_se_Numero(campo); // ja tem o limpaformato
	if (!vr) {return false;}
	var tam = vr.length;
	if (tam >= tammax)
	{ 
		if (Numero == 0)// esta formatação so vai ocorrer caso o usuariio colar no campo a quantidade de 
		{				//caracteres maior que o tamanho maximo (tammax)
			vr = vr.slice(0, tammax);
			tam = vr.length;
		}
		else
		{
			return false;
		}
	} 
	tam = vr.length + Numero;		
	
	if ( tam <= 2 ){ 
		document.Form1[campo].value = vr ; }
	if ( (tam > 2) && (tam <= 6) ){
		document.Form1[campo].value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 7) && (tam <= 9) ){
		document.Form1[campo].value = vr.substr( 0, tam - 6 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 10) && (tam <= 12) ){
		document.Form1[campo].value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 13) && (tam <= 14) ){
		document.Form1[campo].value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 15) && (tam <= 17) ){
		document.Form1[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 ) ;}
			
}				

//---------------------------------------------------------------------
// FUNÇÃO PARA VALIDAR NÚMERO DE "CNPJ"
//---------------------------------------------------------------------	

function valida_cnpj(campo,evento) 
{ 	/*esta funcao deve ser chamado junto com o formata_cnpj ver exemplo na funcao formata_cnpj */
	
	var Numero = VerificaTecla(campo,evento);
	vr=Verifica_se_Numero(campo); // ja tem o limpaformato
	if (!vr) {return false;}
	
	cnpj = vr
	
	retorno=1;
   
     var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais; 
     digitos_iguais = 1; 
      if (cnpj.length < 14 ){retorno=0;}
     
     for (i = 0; i < cnpj.length - 1; i++)
     { 
           if (cnpj.charAt(i) != cnpj.charAt(i + 1)) 
           { 
                digitos_iguais = 0; 
                break; 
           } 
     }
      
      if (!digitos_iguais) 
       { 

            tamanho = cnpj.length - 2 
            numeros = cnpj.substring(0,tamanho); 
            digitos = cnpj.substring(tamanho); 
            soma = 0; 
            pos = tamanho - 7; 
            for (i = tamanho; i >= 1; i--) 
                  { 
                  soma += numeros.charAt(tamanho - i) * pos--; 
                  if (pos < 2) 
                        pos = 9; 
                  } 
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
            if (resultado != digitos.charAt(0))
            { 
                  retorno=0;//return false; 
            }
            tamanho = tamanho + 1; 
            numeros = cnpj.substring(0,tamanho); 
            soma = 0; 
            pos = tamanho - 7; 
            for (i = tamanho; i >= 1; i--) 
                  { 
                  soma += numeros.charAt(tamanho - i) * pos--; 
                  if (pos < 2) 
                        pos = 9; 
                  } 
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
            if (resultado != digitos.charAt(1)) 
            {
                  retorno=0;
             }

       } 
      else {
			retorno=0;
            //return false; 
      } 
      
      if(retorno==0)
      {
		window.alert("CNPJ Incorreto !")
		document.Form1[campo].focus();
		return 0;
      } else {
		return true;
      }
      
 }//function
 
function LimpaFormato(campo) 
{
	// pode passar o campo como parametro ou o valor
	if(campo==""){
		return "";
	}
	
	if(isNaN(campo)){ // se for campo
		vr = document.Form1[campo].value;	
	}else{ // se for o valor
		vr=campo;
		vr=vr.toString();
	}
	
	valor="";
	
	for (pos=0; pos < vr.length; pos ++)
	{
		sinalmenos	=vr.charAt(pos)!='-';		
		sinalponto	=vr.charAt(pos)!='.';
		sinalvirgula=vr.charAt(pos)!=',';
		sinalbarra	=vr.charAt(pos)!='/';
		
		if ( (sinalmenos) && (sinalponto) && (sinalvirgula) && (sinalbarra) )
		{
			valor = valor + vr.charAt(pos);
		}  
	}
	return valor;	
}

//---------------------------------------------------------------------
// Verifica se a string digitada é numerica
//---------------------------------------------------------------------	

function Verifica_se_Numero(campo){
/*
Verifica se os dados digitados é numerico
finalidade : Verificar se o valor do campo é numerico testar sempre ao sair de um campo do tipo numerico
	            evitando assim que o usuario copie e cole valores indevidos.
	            Obs se vc usa no evento onBlur alguma funcao do tipo Validar_cpf, Validar_Cnpj não é necessário 
	            fazer uso desta funcao pois a mesma ja está inclusa.
Modo de Usar :  TextBox.Attributes.Add("onBlur", "Verifica_se_Numero(this.name)")
*/
	
	var valor = LimpaFormato(campo);	
	
	if(valor!=""){		
		if (isNaN(valor)){
			window.alert("O valor digitado n\u00E3o \u00E9 v\u00E1lido, verifique sua digita\u00E7\u00E3o");	
			
			document.Form1[campo].focus();
			document.Form1[campo].select();
			return false;
		}
	}
	
	return valor;
} //func
      
//------------------------------------------------------------------
//função     :soma_populacao
//finalidade :Somar as população urbana e rural 
//Usadom em  : Parametros da central
//------------------------------------------------------------------
function soma_dois_campos(Campo1,Campo2){
	var Campo_1 = Verifica_se_Numero(Campo1);      
	if(!Campo_1){return false};

	var Campo_2 = Verifica_se_Numero(Campo2);      
	if(!Campo_2){return false};

	Campo_1=parseFloat(Campo_1);
	Campo_2=parseFloat(Campo_2);

	if (isNaN(Campo_1)){
			Campo_1=0;
	}
	if (isNaN(Campo_2)){
			Campo_2=0;
	}
	return parseFloat(Campo_1 + Campo_2);
}

//---------------------------------------------------------------------
// Copia valor de campo2 em campo1
//--------------------------------------------------------------------				

function CopiaCampos(campo1,campo2){
	try{
		document.Form1[campo1].value = document.Form1[campo2].value;
		document.Form1[campo1].focus(); 
		document.Form1[campo1].select(); 
	}catch(err){
		alert(err.description);
	}
}
//---------------------------------------------------------------------
// Copia valor de campo1-campo2 em campo3
//campo1->Valor Tributável
//campo2->Valor Documento
//campo3->Valor Dedução
//--------------------------------------------------------------------				
function CopiaCampos2(campo1,campo2,campo3){
	try{
		var valorDoc = MoedaParaFloat(campo2);
		var valorDed = MoedaParaFloat(campo3);
		var valor = valorDoc - valorDed;
		//var valor = parseFloat(document.Form1[campo2].value.replace(",",".").replace("R$","")) - parseFloat(document.Form1[campo3].value.replace(",",".").replace("R$",""));
		document.Form1[campo1].value = FormataMoeda2(valor);
		//document.Form1[campo1].focus(); 
		//document.Form1[campo1].select(); 
	}catch(err){
		alert(err.description);
	}
}

// funcao que oculta e torna visivel o elemento passado como parametro
// o elemente obrigatoriamente é referenciado pelo id 
// exemplo: <input  id="bot" type="button" name="Button" value="Button" onClick="visivel('TbAguarde',true) ; visivel('bot',false)">
// este exemplo foi usado pra exibir e ocultar ampulheta
function visivel(id,valor){
		if(valor==true){
			window.document.getElementById(id).style.visibility="visible";
		}else if (valor==false){
			window.document.getElementById(id).style.visibility="hidden";		
		}
}
// function voltar do rodape da tabela mae
//sitaxe :  voltar('')   para apenas voltar
//			voltar("arquivo.aspx") para redirecionar para um arquivo
function voltar(url){
	if(url!=""){
		location.href=url;
	}else{
		history.back(-1);
	}
}

function FecharForm(){
      opener.location.reload();
      window.close(); 
}

function sem_carac_especiais(espaco){
	// o parametro espaco quando é 1  permite espaco
	tecla = event.keyCode;	//captura o ASC da tecla pressionada	
	
	var condicao=(tecla >= 65 && tecla <= 90) || (tecla>= 48 && tecla<=57) || (tecla >=97 && tecla<=122)|| tecla==95;
	if(espaco ==1){
		condicao=condicao || tecla==32;
	}
	
	if (condicao) 
				return 1;
	else
		if ((tecla != 8) && (tecla !=17) && (tecla !=16))//teclas de combinação
		{	event.keyCode = 0;
			return 0;
		}
		else
				return 1;

}
//-----------
  function Valida_Cpf_Cnpj(campo,evento) {
   	valorcampo=document.Form1[campo].value;		
 	valorcampo=LimpaFormato(campo);
 	if(valorcampo.length<=11){	
 		return valida_cpf(campo,evento); 		
 	}else{	
 		return valida_cnpj(campo,evento); 		
 	}  	
 }	   
 
 
 function Formata_Cpf_Cnpj(campo,evento) {
 	valorcampo=document.Form1[campo].value;		
 	if(valorcampo.length<=14){	
 		FormataCpf(campo,evento);
 		titulo="Consulta por CPF";
 	}else{	
 		FormataCnpj(campo,evento);
 		titulo="Consulta por CNPJ";
 	} 
 	document.Form1[campo].title= titulo;
 } 

//----------
//funcao que apaga um campo com a condicao passada por parametro
function Limpa_Campo(campoTesta,campoLimpar){
	if(document.Form1[campoTesta].value==""){
		document.Form1[campoLimpar].value="";
	}
}

// funcao que oculta e torna visivel o elemento passado como parametro
// o elemente obrigatoriamente é referenciado pelo id 
// exemplo: <input  id="bot" type="button" name="Button" value="Button" onClick="visivel('TbAguarde',true) ; visivel('bot',false)">
// este exemplo foi usado pra exibir e ocultar ampulheta
function visivel(id,valor){
		if(valor==true){
			window.document.getElementById(id).style.visibility="visible";
		}else if (valor==false){
			window.document.getElementById(id).style.visibility="hidden";		
		}
}
// function voltar do rodape da tabela mae
//sitaxe :  voltar('')   para apenas voltar
//			voltar("arquivo.aspx") para redirecionar para um arquivo
function voltar(url){
	if(url!=""){
		location.href=url;
	}else{
		history.back(-1);
	}
}

function FecharForm(){
      opener.location.reload();
      window.close(); 
}

function sem_carac_especiais(espaco){
	// o parametro espaco quando é 1  permite espaco
	tecla = event.keyCode;	//captura o ASC da tecla pressionada	
	
	var condicao=(tecla >= 65 && tecla <= 90) || (tecla>= 48 && tecla<=57) || (tecla >=97 && tecla<=122)|| tecla==95;
	if(espaco ==1){
		condicao=condicao || tecla==32;
	}
	
	if (condicao) 
				return 1;
	else
		if ((tecla != 8) && (tecla !=17) && (tecla !=16))//teclas de combinação
		{	event.keyCode = 0;
			return 0;
		}
		else
				return 1;

}
//-----------
  /*function Valida_Cpf_Cnpj(campo,evento) {
   	valorcampo=document.Form1[campo].value;		
 	valorcampo=LimpaFormato(campo);
 	if(valorcampo.length<=11){	
 		return valida_cpf(campo,evento); 		
 	}else{	
 		return valida_cnpj(campo,evento); 		
 	}  	
 }	*/   
 
 
 function Formata_Cpf_Cnpj(campo,evento) {
 	valorcampo=document.Form1[campo].value;		
 	if(valorcampo.length<=14){	
 		FormataCpf(campo,evento);
 		titulo="Consulta por CPF";
 	}else{	
 		FormataCnpj(campo,evento);
 		titulo="Consulta por CNPJ";
 	} 
 	document.Form1[campo].title= titulo;
 } 

//----------
//funcao que apaga um campo com a condicao passada por parametro
function Limpa_Campo(campoTesta,campoLimpar){
	if(document.Form1[campoTesta].value==""){
		document.Form1[campoLimpar].value="";
	}
}

//funcao muito cabulosíssima - Muita atenção na passagem de Parâmetros 
// chame no evento onBlur
function cImposto(CvalorTributavel,Caliquota,CvalorImposto,CsomaValorDoc,CsomaValorTributavel,CsomaValorImposto,palavraCSomaValorDoc,palavraCSomaValorTributavel,palavraCSomaValorImposto,CimpostoRetido,tipo,naturezaOperacao,evento)
{
	/*
	CvalorTributavel	= Campo Valor Tributável
	Caliquota			= Campo Valor Alíquota
	CvalorImposto		= Campo que recebe o imposto calculado
	
	CsomaValorDoc		= Campo que recebe o resultado da soma do campo de valor do documento
	CsomaValorTributavel= Campo que recebe o resultado da soma do campo de valor tributável
	CsomaValorImposto	= Campo que recebe o resultado da soma do campo de valor do imposto calculado
	
	palavraCSomaValorDoc		= Nome dos campos que serão somados - Use a palavra comum para os campos serão somados. ex: os campos campo1  , campo2 e campo3 , use a palavra "campo" como parâmetro, que é o texto em comum entre os 3 campos,
	palavraCSomaValorTributavel		= Nome dos campos que serão somados - Use a palavra comum para os campos serão somados. ex: os campos campo1  , campo2 e campo3 , use a palavra "campo" como parâmetro, que é o texto em comum entre os 3 campos,	
	palavraCSomaValorImposto		= Nome dos campos que serão somados - Use a palavra comum para os campos serão somados. ex: os campos campo1  , campo2 e campo3 , use a palavra "campo" como parâmetro, que é o texto em comum entre os 3 campos,
	
	impostoRetido		= Valor do imposto retido
	tipo				= Valor do Tipo
	naturezaOperacao	= Valor da natureza da operação
	evento				= O evento que chamou esta funcção - use event no parâmetro
	*/
	var impostoCalculado=0											;
	var valorTributavel	=MoedaParaFloat(CvalorTributavel)			; // retorna o valor do campo substituindo a vírgula por ponto
	var aliquota		=MoedaParaFloat(Caliquota)					;//  retorna o valor do campo substituindo a vírgula por ponto
	
	naturezaOperacao=naturezaOperacao.toString();
	
	if(naturezaOperacao!=""){
		if(naturezaOperacao!="1"){ 
			//O campo recebe o valor
			document.Form1[CvalorImposto].value="0,00";
		}else{
			impostoCalculado=calculaImposto(valorTributavel,aliquota,CimpostoRetido,tipo,evento);
		}
	}else{
   			impostoCalculado=calculaImposto(valorTributavel,aliquota,CimpostoRetido,tipo,evento);
	}
	document.Form1[CvalorImposto].value=FormataMoeda2(impostoCalculado);						 //O campo recebe o valor  // aqui tem que formatar	
	
	//Todos esses parametros serão passados com o valor zero quanto não for necessário fazer cálculos somatórios nos campos do grid
	if(CsomaValorDoc!=0 && CsomaValorTributavel!=0 && CsomaValorImposto!=0 && palavraCSomaValorDoc!=0 && palavraCSomaValorTributavel!=0 && palavraCSomaValorImposto!=0){
		document.Form1[CsomaValorDoc].value			=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorDoc,evento)));				//Atribui a soma dos campos no campo de soma
		document.Form1[CsomaValorTributavel].value	=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorTributavel,evento)));	//Atribui a soma dos campos no campo de soma
		//alert(palavraCSomaValorImposto);
		document.Form1[CsomaValorImposto].value		=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorImposto,evento)));		//Atribui a soma dos campos no campo de soma
	}
}


//funcao muito cabulosíssima 2 - Muita atenção na passagem de Parâmetros 
// chame no evento onBlur
function cImposto2(CvalorTributavel,Caliquota,CvalorImposto,CsomaValorDoc,CsomaValorDed,CsomaValorTributavel,CsomaValorImposto,palavraCSomaValorDoc,palavraCSomaValorDed,palavraCSomaValorTributavel,palavraCSomaValorImposto,CimpostoRetido,tipo,naturezaOperacao,evento)
{
	/*
	CvalorTributavel	= Campo Valor Tributável
	Caliquota			= Campo Valor Alíquota
	CvalorImposto		= Campo que recebe o imposto calculado
	
	CsomaValorDoc		= Campo que recebe o resultado da soma do campo de valor do documento
	CsomaValorDed		= Campo que recebe o resultado da soma do campo de valor das deduções
	CsomaValorTributavel= Campo que recebe o resultado da soma do campo de valor tributável
	CsomaValorImposto	= Campo que recebe o resultado da soma do campo de valor do imposto calculado
	
	palavraCSomaValorDoc		= Nome dos campos que serão somados - Use a palavra comum para os campos serão somados. ex: os campos campo1  , campo2 e campo3 , use a palavra "campo" como parâmetro, que é o texto em comum entre os 3 campos,
	palavraCSomaValorDed		= Nome dos campos que serão somados
	palavraCSomaValorTributavel		= Nome dos campos que serão somados - Use a palavra comum para os campos serão somados. ex: os campos campo1  , campo2 e campo3 , use a palavra "campo" como parâmetro, que é o texto em comum entre os 3 campos,	
	palavraCSomaValorImposto		= Nome dos campos que serão somados - Use a palavra comum para os campos serão somados. ex: os campos campo1  , campo2 e campo3 , use a palavra "campo" como parâmetro, que é o texto em comum entre os 3 campos,
	
	impostoRetido		= Valor do imposto retido
	tipo				= Valor do Tipo
	naturezaOperacao	= Valor da natureza da operação
	evento				= O evento que chamou esta funcção - use event no parâmetro
	*/
	var impostoCalculado=0											;
	var valorTributavel	=MoedaParaFloat(CvalorTributavel)			; // retorna o valor do campo substituindo a vírgula por ponto
	var aliquota		=MoedaParaFloat(Caliquota)					;//  retorna o valor do campo substituindo a vírgula por ponto
	
	naturezaOperacao=naturezaOperacao.toString();
	
	if(naturezaOperacao!=""){
		if(naturezaOperacao!="1"){ 
			//O campo recebe o valor
			document.Form1[CvalorImposto].value="0,00";
		}else{
			impostoCalculado=calculaImposto(valorTributavel,aliquota,CimpostoRetido,tipo,evento);
		}
	}else{
   			impostoCalculado=calculaImposto(valorTributavel,aliquota,CimpostoRetido,tipo,evento);
	}
	document.Form1[CvalorImposto].value=FormataMoeda2(impostoCalculado);						 //O campo recebe o valor  // aqui tem que formatar	
	
	//Todos esses parametros serão passados com o valor zero quanto não for necessário fazer cálculos somatórios nos campos do grid
	if(CsomaValorDoc!=0 && CsomaValorDed!=0 && CsomaValorTributavel!=0 && CsomaValorImposto!=0 && palavraCSomaValorDoc!=0 && palavraCSomaValorDed!=0 && palavraCSomaValorTributavel!=0 && palavraCSomaValorImposto!=0){
		document.Form1[CsomaValorDoc].value			=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorDoc,evento)));				//Atribui a soma dos campos no campo de soma
		document.Form1[CsomaValorDed].value			=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorDed,evento)));				//Atribui a soma dos campos no campo de soma
		document.Form1[CsomaValorTributavel].value	=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorTributavel,evento)));	//Atribui a soma dos campos no campo de soma
		//alert(palavraCSomaValorImposto);
		document.Form1[CsomaValorImposto].value		=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorImposto,evento)));		//Atribui a soma dos campos no campo de soma
	}
}
function cImpostoConstrucaoCivil(CvalorDoc,CvalorDeducao,Caliquota,CvalorImposto,CvalorTrib,CsomaValorDoc,CsomaValorDeducao,CsomaValorImposto,palavraCSomaValorDoc,palavraCSomaValorDeducao,palavraCSomaValorImposto,CimpostoRetido,tipo,naturezaOperacao,evento)
{
	
	
	var impostoCalculado = 0;
	var valorDocumento = MoedaParaFloat(CvalorDoc);
	var valorDeducao = MoedaParaFloat(CvalorDeducao);
	var valorTributavel	= valorDocumento - valorDeducao;
	alert(valorDocumento);
	var aliquota = MoedaParaFloat(Caliquota);
	
		
	naturezaOperacao=naturezaOperacao.toString();
	
	if (naturezaOperacao!="") {
		if (naturezaOperacao!="1") {
			//O campo recebe o valor
			document.Form1[CvalorImposto].value="0,00";
		} else {
			impostoCalculado = calculaImposto(valorTributavel,aliquota,CimpostoRetido,tipo,evento);
			
		}
	} else {
   			impostoCalculado = calculaImposto(valorTributavel,aliquota,CimpostoRetido,tipo,evento);
   			
	}
	document.Form1[CvalorImposto].value = FormataMoeda2(impostoCalculado);
	document.Form1[CvalorTrib].value = FormataMoeda2(valorTributavel);
	//document.Form1[CvalorDoc].value = FormataMoeda2(valorTributavel);
	
	//Todos esses parametros serão passados com o valor zero quanto não for necessário fazer cálculos somatórios nos campos do grid
	if(CsomaValorDoc!=0 && CsomaValorDeducao!=0 && CsomaValorImposto!=0 && palavraCSomaValorDoc!=0 && palavraCSomaValorDeducao!=0 && palavraCSomaValorImposto!=0){
		document.Form1[CsomaValorDoc].value			=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorDoc,evento)));				//Atribui a soma dos campos no campo de soma
		document.Form1[CsomaValorDeducao].value	=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorDeducao,evento)));	//Atribui a soma dos campos no campo de soma
		document.Form1[CsomaValorImposto].value		=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorImposto,evento)));		//Atribui a soma dos campos no campo de soma
		
	}
}


function cImpostoConstrucaoCivilRetifica(CvalorDoc,CvalorDeducao,Caliquota,CvalorImposto,CvalorTrib,CsomaValorDoc,CsomaValorDeducao,CsomaValorImposto,palavraCSomaValorDoc,palavraCSomaValorDeducao,palavraCSomaValorImposto,CimpostoRetido,tipo,naturezaOperacao,evento)
{

	var valor="";
	var strMoeda=CvalorDoc;
	// laço pra tirar os pontos e trocar a virgula por ponto
		for (i=0;i<strMoeda.length;i++)	{
			if(strMoeda.charAt(i)!="."){
					if(strMoeda.charAt(i)!=","){		
						valor=valor+strMoeda.charAt(i);					
					}else{
						valor=valor+".";  //colocar ponto no lugar da vírgula
					}
			}		
		}
		
	var valoAlr="";
	var strMoedaAl=Caliquota;
	// laço pra tirar os pontos e trocar a virgula por ponto
		for (i=0;i<strMoedaAl.length;i++)	{
			if(strMoedaAl.charAt(i)!="."){
					if(strMoedaAl.charAt(i)!=","){		
						valoAlr=valoAlr+strMoedaAl.charAt(i);					
					}else{
						valoAlr=valoAlr+".";  //colocar ponto no lugar da vírgula
					}
			}		
		}
	
		
	var impostoCalculado = 0;
	var valorDocumento = valor;
	var valorDeducao = MoedaParaFloat(CvalorDeducao);
	var valorTributavel	= valorDocumento - valorDeducao;
	var aliquota = valoAlr;
	
	naturezaOperacao=naturezaOperacao.toString();
	
	if (naturezaOperacao!="") {
		if (naturezaOperacao!="1") {
			//O campo recebe o valor
			document.Form1[CvalorImposto].value="0,00";
		} else {
			impostoCalculado = calculaImposto(valorTributavel,aliquota,CimpostoRetido,tipo,evento);

		}
	} else {
   			impostoCalculado = calculaImposto(valorTributavel,aliquota,CimpostoRetido,tipo,evento);

   			
	}
	document.Form1[CvalorImposto].value = FormataMoeda2(impostoCalculado);
	document.Form1[CvalorTrib].value = FormataMoeda2(valorTributavel);
	//document.Form1[CvalorDoc].value = FormataMoeda2(valorTributavel);
	
	//Todos esses parametros serão passados com o valor zero quanto não for necessário fazer cálculos somatórios nos campos do grid
	if(CsomaValorDoc!=0 && CsomaValorDeducao!=0 && CsomaValorImposto!=0 && palavraCSomaValorDoc!=0 && palavraCSomaValorDeducao!=0 && palavraCSomaValorImposto!=0){
		document.Form1[CsomaValorDoc].value			=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorDoc,evento)));				//Atribui a soma dos campos no campo de soma
		document.Form1[CsomaValorDeducao].value	=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorDeducao,evento)));	//Atribui a soma dos campos no campo de soma
		document.Form1[CsomaValorImposto].value		=FormataMoeda2(arredondaNumero(somaCampos(palavraCSomaValorImposto,evento)));		//Atribui a soma dos campos no campo de soma
		
	}
}


function calculaImposto(valorTributavel,aliquota,CimpostoRetido,tipo,evento){
		//alert(document.Form1[CimpostoRetido].value);
					
		if(valorTributavel !=""  && aliquota!="" && CimpostoRetido!="" && tipo>-1 && valorTributavel>0 && aliquota>0 && tipo!=document.Form1[CimpostoRetido].value) 
		{
			var imposto=eval(valorTributavel * aliquota /100);
			return arredondaNumero(imposto);
		}else{
			return 0;
		}
}
function DisparaSomaImposto(){
	if (document.Form1['dgContratados:_ctl12:txtTotalImp']) 
		document.Form1['dgContratados:_ctl12:txtTotalImp'].value = FormataMoeda2(arredondaNumero(somaCampos('txtValor_Imp',event)));		//Atribui a soma dos campos no campo de soma
}
			
//Soma campos de uma coluna e atribui o resultado em um campo resposta 
function somaCampos(palavraCampo,evento){	
		var qtd=document.Form1.elements.length; //qtd de elementos no formulário		
		var somavalor=0;		
		for	(var i=0;i<qtd;i++){
			nome_campo=document.Form1.elements[i].name;			
			if(nome_campo.indexOf(palavraCampo)!=-1){
				//if (nome_campo.indexOf("txtValorImposto")!=-1){ 
				//	alert(nome_campo);
				//}
				var valor=MoedaParaFloat(nome_campo);
				//if (valor!=""){
				//	alert(nome_campo);
				//	alert(valor);
				//}
				//var valor=document.Form1[nome_campo].value;
				
				if(valor.indexOf("R$ ")!=-1){
					//alert(valor);
					valor = valor.substr(2, valor.length-2);
					//alert(valor);
				}
				
				if(valor!=""){				
					somavalor=(somavalor+valor/1); // força um cálculo
					//alert(somavalor);
				}
			}
		}
		return somavalor;	
}

/**********
// Atendendo ao post: http://helpdesk.issnetonline.com.br/Messages.aspx?ThreadID=18100
// Arredondamento Decl. Serviços Contratados - (Mal Funcionamento)
// R$2.407,50 * 3% arredondado deve ser R$72,23 e não R$72,22.
**********/
function arredondaNumero(valor){
	var imposto_string = new String(valor);
	
	if(imposto_string.indexOf('.') != -1) {// verifica se tem casa decimal
		var imposto_string_split = imposto_string.split('.'); // separa para pegar o decimal
		if(imposto_string_split[imposto_string_split.length-1]!='' && imposto_string_split[imposto_string_split.length-1].length >= 3) { //verifica se tem 3 casas ou mais
			if(imposto_string_split[imposto_string_split.length-1].charAt(imposto_string_split[imposto_string_split.length-1].length-1) == 5) {//verifica se o ultimo numero da casa decimal é igual a 5
				var valor_arredondar = '0.';
				for(i=0; i<imposto_string_split[imposto_string_split.length-1].length-1; i++) valor_arredondar += '0';
				
				valor_arredondar += '1'; // se casa decimal = 225 então soma 0.001
				valor += parseFloat(valor_arredondar);
			}
		}
	}
				
	var resp = Math.round(parseFloat(valor)*100)/100;
	return resp;	
}

//converte um valor no formato moeda para float Válido para Cálculos
function MoedaParaFloat(campoMoeda){
var valor="";
var campo = document.Form1[campoMoeda];
var strMoeda="";
if (campo.type=="select-one"){
	strMoeda = campo.options[campo.selectedIndex].value;
}else{
	strMoeda = campo.value;
}
//alert('str '+strMoeda);
//var strMoeda=document.Form1[campoMoeda].value;
// laço pra tirar os pontos e trocar a virgula por ponto
	for (i=0;i<strMoeda.length;i++)	{
		if(strMoeda.charAt(i)!="."){
				if(strMoeda.charAt(i)!=","){		
					valor=valor+strMoeda.charAt(i);					
				}else{
					valor=valor+".";  //colocar ponto no lugar da vírgula
				}
		}		
	}
return valor;
}

//movimento econômico
function calculaMovEconomico(campoTributavel,campoAliquota,campoImposto,evento){
	if (document.Form1[campoTributavel].value != "" && document.Form1[campoAliquota].value!=""){
		var trib = MoedaParaFloat(campoTributavel);		
		var aliq = MoedaParaFloat(campoAliquota);		
		var imp = eval((trib * aliq) / 100);	
		document.Form1[campoImposto].value=FormataMoeda2(arredondaNumero(imp));		
		//FormataMoeda(campoImposto,evento);	
	}
}

function Compara_Valores2(campo1,campo2,campo3){
    var Vl1 = campo1;
    var Vl2 = parseFloat(document.Form1[campo2].value) ;     			
    var Vl3 = parseFloat(document.Form1[campo3].value);
 	if((Vl2 - Vl3) > Vl1){	
 		   window.alert("O valor tributável deve ser menor que o valor total do documento.");
 		   document.Form1[campo2].focus();		
 	}
}
//Calcula Imposto Instituição Financeira
function calculaImpostoInstFin(campoQtd,campoUni,campoRes,valorAliquota,lblTotal,evento){	
	
	valorAliquota=valorAliquota.toString();
	valorAliquota=valorAliquota.replace(",",".");
	valorAliquota=parseFloat(valorAliquota);
	
	var qtd=document.Form1[campoQtd].value;
	//alert('Antes de "MoedaParaFloat": '+document.Form1[campoUni].value);
	var valorUni=MoedaParaFloat(campoUni);
	///alert('Aliquota: '+valorAliquota+'\nQtde: '+qtd+'\nCampo Unitario: '+document.Form1[campoUni].value+' -- '+valorUni); 

	if(qtd!="" && valorAliquota!=""){
		var imposto =(qtd * valorUni ) *  (valorAliquota/100);
		//alert('Imposto: '+imposto);
		document.Form1[campoRes].value=FormataMoeda2(imposto);
		
		if($(lblTotal)!=null) {
			$(lblTotal).innerText = 'R$ ' + FormataMoeda2(arredondaNumero(somaCampos('txtImposto',evento)));
			//alert('TotalFinal: '+$(lblTotal).innerText);
		}
	}
}


function multiplica2valores(campo1,campo2,campo_resp,evento){
	valor1=LimpaFormato(campo1);
	valor2=LimpaFormato(campo2);
	var multi = eval((valor1 * valor2));
	document.Form1[campo_resp].value=multi;
	FormataMoeda(campo_resp,evento);		
}

fmtMoney = function(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 Multiply(idField1, idField2 ,idFieldR){
	var v1 = $(idField1).value.replace(/\./g,'').replace(',','.');
	var v2 = $(idField2).value.replace(/\./g,'').replace(',','.');

	//v1 = 12.79
	//v2 = 2200
	//problema de aredondamento
	$(idFieldR).value = fmtMoney(Math.round(v1*v2*100)/100);
}

function Sum(idField1, idField2 ,idFieldR){
	var v1 = $(idField1).value.replace(/\./g,'').replace(',','.');
	var v2 = $(idField2).value.replace(/\./g,'').replace(',','.');
	
	$(idFieldR).value = fmtMoney(v1+v2);
}

function Subtract(idField1, idField2 ,idFieldR){
	var v1 = $(idField1).value.replace(/\./g,'').replace(',','.');
	var v2 = $(idField2).value.replace(/\./g,'').replace(',','.');
	
	$(idFieldR).value = fmtMoney(v1-v2);
}

function valida_dia(campo){
	var dia=document.Form1[campo].value;
	if(dia!=""){
		if(dia <1 || dia>31){
			window.alert("Dia incorreto !");	
			document.Form1[campo].value="";	
			document.Form1[campo].focus();			
			return false;
		}
		return true;
	}	
}
//----------------------------------------------------
// função gera espelho de valores de um campo especifico
//Sintaxe :  espelho_campo("palavra em comum nos campos",1)  // valor zero (nao soma os campos) e valor 1 (soma)
//----------------------------------------------------
function espelho_campo(palavra_campo,incremento) //palavra_campo = palavra comum entre os campos ex: TextBox de (TextBox1 ,TextBox2 ...)
{
		var qtd=document.Form1.elements.length; //qtd de tags input
		//var tags=document.Form1.tags("input"); // o objeto input
		var p=0; // flas para nao pegar o primeiro campo mais de uma vez
		var primeiro_campo=0;				
		var vez=0;
		if	(parseInt(incremento)==1){ // No caso de fazer soma dos valores nos campos espelhos(com um nome em comum)  
									//apartir do valor do primeiro campo
			var primeiro_valor;
				for(j=0;j<qtd;j++){ 
					var nome_campo=document.Form1.elements[j].name; // nome do campo no instante			 
					if(nome_campo.indexOf(palavra_campo)!=-1){	//testa se o campo atual tem o texto comum passado no parametro						
						
						if(vez==0){
							 primeiro_valor=parseInt(document.Form1[nome_campo].value);
							 if(isNaN(primeiro_valor))
										break ;
								
							}else{
								document.Form1[nome_campo].value=primeiro_valor+vez;
							}
						vez++;
					}
				}
		}else{								
				for(i=0;i<qtd;i++){
					var nome_campo=document.Form1.elements[i].name; // nome do campo no instante													 
					if(nome_campo.indexOf(palavra_campo)!=-1){	//testa se o campo atual tem o texto comum passado no parametro						
						if((document.Form1.elements[i].value!="")&&(p==0)){ // captura o valor do primeiro campo preenchido
							primeiro_campo=document.Form1.elements[i].value;
							i=0; // retorna o laço
							p++; //flag
						}
						if(primeiro_campo!="") {
							document.Form1[nome_campo].value=primeiro_campo	; //atribui nos outros campos
						}
					}		
				}
		}
}
//função utilizada na tela de  varias aliquotas para retornar os valores para a declaração de ser
function PassaResultado(valor1,valor2,campo1,campo2,campo3,campo4,botao,ret)
{
	opener.Form1[campo1].value=valor1;
	opener.Form1[campo2].value='Dif.';
	opener.Form1[campo2].disable=true;
	//opener.Form1[ret].disable=true;
	opener.Form1[campo4].value=valor2;	
	opener.__doPostBack('txtPost','');
	//window.close();		
}
function Compara_Valores(campo1,campo2){
    var Vl1 = campo1
    var Vl2 = parseFloat(document.Form1[campo2].value)      			
 	if(Vl2 > Vl1){	
 		   window.alert("O valor tributável deve ser menor que o valor total do documento.");
 		   document.Form1[campo2].focus();		
 	}
}


function PassaParametros_Cep(valor1,campo1,valor2,campo2,valor3,campo3,valor4,campo4,valor5,campo5,valor6,campo6,valor7,campo7,valor8,campo8,post,codLogradouroVal,codLogradouroCampo) {
	var d;
	
	if(opener != undefined) 
		d = opener.document;
	else if(parent != undefined) 
		d = parent.document;
	else if(top != undefined) 
		d = top.document;
		
	if(d.getElementById(campo1) != null) d.getElementById(campo1).value = valor1;
	if(d.getElementById(campo2) != null) d.getElementById(campo2).value = valor2;
	if(d.getElementById(campo3) != null) d.getElementById(campo3).value = valor3;
	if(d.getElementById(campo4) != null) d.getElementById(campo4).value = valor4;
	if(d.getElementById(campo5) != null) d.getElementById(campo5).value = valor5;
	
	if(campo6.toLowerCase().indexOf("ddd") == -1 && campo6.toLowerCase().indexOf("telefone") != -1) {
		if(d.getElementById(campo6) != null) {
			if(d.getElementById(campo6).value.length <= 4) d.getElementById(campo6).value = '(' + valor6 + ')';
		}
	}else{
		if(d.getElementById(campo6) != null) d.getElementById(campo6).value = valor6;
	}
	
	if(d.getElementById(campo7) != null) d.getElementById(campo7).value = valor7;
	if(d.getElementById(campo8) != null) d.getElementById(campo8).value = valor8;
	if(d.getElementById('hdnTempBloqueiaPostCep') != null) d.getElementById('hdnTempBloqueiaPostCep').value = '1'; //pra nao dar post do campo de cep
	
	if (codLogradouroCampo != undefined) {
		if(d.getElementById(codLogradouroCampo) != null) 
			d.getElementById(codLogradouroCampo).value = codLogradouroVal;
	}
	
	if(opener != undefined) {
		opener.FocoNumCep();
		opener.focus();
		self.close();
	}
	
	return;
}
function PassaParametros_Cep(valor1,campo1,valor2,campo2,valor3,campo3,valor4,campo4,valor5,campo5,valor6,campo6,valor7,campo7,valor8,campo8,post,codLogradouroVal,codLogradouroCampo, codibgeVal, codibgeCampo)
{
	var d;
	
	if(opener != undefined) 
		d = opener.document;
	else if(parent != undefined) 
		d = parent.document;
	else if(top != undefined) 
		d = top.document;
		
	if(d.getElementById(campo1) != null) d.getElementById(campo1).value = valor1;
	if(d.getElementById(campo2) != null) d.getElementById(campo2).value = valor2;
	if(d.getElementById(campo3) != null) d.getElementById(campo3).value = valor3;
	if(d.getElementById(campo4) != null) d.getElementById(campo4).value = valor4;
	if(d.getElementById(campo5) != null) d.getElementById(campo5).value = valor5;
	
	if(campo6.toLowerCase().indexOf("ddd") == -1 && campo6.toLowerCase().indexOf("telefone") != -1) {
		if(d.getElementById(campo6) != null) {
			if(d.getElementById(campo6).value.length <= 4) d.getElementById(campo6).value = '(' + valor6 + ')';
		}
	}else{
		if(d.getElementById(campo6) != null) d.getElementById(campo6).value = valor6;
	}
	
	if(d.getElementById(campo7) != null) d.getElementById(campo7).value = valor7;
	if(d.getElementById(campo8) != null) d.getElementById(campo8).value = valor8;
	if(d.getElementById('hdnTempBloqueiaPostCep') != null) d.getElementById('hdnTempBloqueiaPostCep').value = '1'; //pra nao dar post do campo de cep
	
	if (codLogradouroCampo != undefined) {
		if(d.getElementById(codLogradouroCampo) != null) 
			d.getElementById(codLogradouroCampo).value = codLogradouroVal;
	}
	if (codibgeCampo != undefined) {
		if(d.getElementById(codibgeCampo) != null) 
			d.getElementById(codibgeCampo).value = codibgeVal;
	}
	
	if(opener != undefined) {
		opener.FocoNumCep();
		opener.focus();
		self.close();
	}
	
	return;
}
function FocoNumCep() {
	setTimeout('FocoNumCep2()', 50);
}
function FocoNumCep2() {
	if(document.getElementById('txtemail') != null) {
		document.getElementById('txtemail').focus();
	}
	setTimeout('FocoNumCep3()', 5);
}
function FocoNumCep3() {
	if(document.getElementById('TxtNumero') != null) {
		document.getElementById('TxtNumero').focus();
	}
}

function LimpaCamposEndereco(idlogradouro,cep,endereco,num,bairro,complemento,cidade,uf,pais,ddd,fone,dddfax,fax)
{
	Form1[idlogradouro].value='';
	Form1[cep].value='';
	Form1[endereco].value='';
	Form1[num].value='';
	Form1[bairro].value='';
	Form1[complemento].value='';
	Form1[cidade].value='';
	Form1[uf].value='';
	Form1[pais].value='';
	Form1[ddd].value='';
	Form1[fone].value='';
	Form1[dddfax].value='';
	Form1[fax].value='';
}

//---------------------------------------------------------------------
//	SETA O FOCO ATUAL PARA UM CONTROLE ASP.NET
//---------------------------------------------------------------------	
function PegaFoco2(Campo){ 
		var control = document.getElementById(Campo);
		if(control){ 
				control.focus(); 						
		}
		else
			window.setTimeout("PegaFoco2('"+Campo+"');", 100);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//  Funciona com qualquer controle: Button, Dropdownlist, txtbox, etc.
//	Continua tentando colocar o foco até conseguir
//  Chamada: PegaFoco('Nome_do_Campo');
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

addEvent = function(o, e, f, s){//obj, evento, funcao
	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;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

var botoes_requisicoes = new Array();
//window.onload=init

//function init(){
	//distribuiEvento();
//}
function distribuiEvento(){
	var b = document.getElementsByTagName('input');
	for( var i=0; i<b.length; i++ ){
		if( b[i].type=='image' || b[i].type=='submit' ){
			botoes_requisicoes.push(b[i])
				//addEvent(b[i], "click", desabilita);
		}
	}
}
function desabilita(){
	for(var j=0; j<botoes_requisicoes.length; j++)
		botoes_requisicoes[j].disabled = true
}
function abilita(){
	for(var j=0; j<botoes_requisicoes.length; j++)
		botoes_requisicoes[j].disabled = false
}

//#######################################################################################
//by Fábio
/* TIPOS
	alpha    -> aceita letras sem acentos
	beta     -> aceita letras com acentos
	alphanum -> aceita letras sem acentos e numeros e sublinhado
	betanum  -> aceita letras com acentos e numeros
	num      -> aceita somente numeros
	caract   -> aceita somente caracters especiais
*/
function checkKey(evt,type) {//onkeypress="checkKey(event,'alpha')"
// depende das funcoes capASC , blockKey e escASC
	var regs={"alpha":/^[a-zA-Z\.\-]*$/, "beta":/[A-Za-áéíóúàâãêôõçÁÉÍÓÚÀÃÂÊÔÕÇ]/,"alphanum":/^\w+$/,"betanum":/[A-Za-z0-9áéíóúàâãêôõçÁÉÍÓÚÀÃÂÊÔÕÇ]/,"num":/^\d+$/,"caract":/^\W+$/};
	if(escASC(capASC(evt))&&!regs[type].test(String.fromCharCode(capASC(evt))))blockKey(evt);
}
function capASC(evt){return(window.event)?evt.keyCode:evt.which;}
function escASC(a){return(a==8||a==0||a==32)?false:true;}
function blockKey(evt){return(window.event)?evt.keyCode=0:evt.preventDefault();}

//#######################################################################################
/*
	onkeyup="aliquotaDecimal(this)"
	Formata campo para 1 casa decimal
*/
//#######################################################################################
function aliquotaDecimal(field){
	var evt = (document.all)? event : e ;
	var charCode = (document.all)? evt.keyCode : evt.which ; 
	
	if(charCode!=8 && charCode!=9 && charCode!=0 && charCode!=16 && charCode!=17 && charCode!=20 && charCode!=46) {
		var ol=(ov=(o=document.getElementById(field)||field).value.replace(/,/,"")).length;
		ol==2?o.value=ov.substr(0,ol-1)+","+ov.substr(ol-1,ol):ol>2?o.value=ov.substr(0,ol-2)+","+ov.substr(ol-2,ol):o.value=ov;
	}
}

//#######################################################################################
//by Alessandro
/*
	FixIEOnChange(elemento ou id do elemento)  <-- chamar somente uma vez, preferencialmente no window.onload
	Corrige o bug do internet explorer que ocorre em textbox com autopostback que não funciona
		com o recurso de autocompletar
*/
//#######################################################################################

function FixIEOnChange(el) {
	if(typeof el == 'string')
		el = document.getElementById(el);
	
	if(el) {
		el.fnchange = el.onchange;
		el.onchange=null;
		el.attachEvent("onfocus", function() {
				var el=event.srcElement;
				el.valorAntigo=el.value;
			});
		el.attachEvent("onblur", function() {
				var el=event.srcElement;
				if(el.valorAntigo!=el.value) {
					el.fnchange();
				}
				
			});
	}
}

function FixIEOnChangeDoc() {
	for(var i=0;i<document.forms.length;i++) {
		var f=document.forms[i];
		for(var j=0;j<f.elements.length;j++) {
			var el=f.elements[j];
			if(el.tagName.toLowerCase()=='input'&&el.type.toLowerCase()=='text'&&el.onchange) {
				FixIEOnChange(el);
			}
		}
	}
}




   
var msg = 'Fun\u00E7\u00E3o Desativada!';
var asciiF2        = 113;
var asciiF3        = 114;
var asciiF4        = 115;
var asciiF5        = 116;
var asciiF6        = 117;
var asciiF11       = 122;
var asciiF12       = 123;
var asciiF1        = 112;

var asciiSHIFT     = 16;
var asciiALT	   = 18;
var asciiHome      = 36;
var asciiLeftArrow = 37;
var asciiRightArrow= 39;
var asciiBack	   = 8;
var asciiTab       = 9;

function _addEvent(node,evtType,func) {
	if(node.addEventListener){
		node.addEventListener(evtType,func,false);
		return true;
	}
	else if(node.attachEvent)
		return node.attachEvent("on"+evtType,func);
	else
		return false;
}

if(window.location.host.toLowerCase().indexOf('localhost')==-1){
	_addEvent(document,'mousedown',function(event){ 
		document.oncontextmenu=function(){return false}
	});
	if(document.all)
		addEvent(document,'keydown',onKeyPress);
	else if(document.layers || document.getElementById)
		document.onkeypress = onKeyPress;
}
function onKeyPress(evt){

    window.status = '';
    //get the event object
    var oEvent = (window.event) ? window.event : evt;

    var nKeyCode =  oEvent.keyCode ? oEvent.keyCode : oEvent.which ? oEvent.which : void 0;
    var bIsFunctionKey = false;

    if(oEvent.charCode == null || oEvent.charCode == 0)
        bIsFunctionKey = (nKeyCode >= asciiF1 && nKeyCode <= asciiF12);
    
    //convert the key to a character, makes for more readable code
    var sChar = String.fromCharCode(nKeyCode).toUpperCase();

    //get the active tag that has the focus on the page, and its tag type
    var oTarget = (oEvent.target) ? oEvent.target : oEvent.srcElement;
    var sTag = oTarget.tagName.toLowerCase();
	try{var sTagType = oTarget.getAttribute("type");}catch(er){}
	
    var bAltPressed = (oEvent.altKey) ? oEvent.altKey : oEvent.modifiers & 1 > 0;
    var bShiftPressed = (oEvent.shiftKey) ? oEvent.shiftKey : oEvent.modifiers & 4 > 0;
    var bCtrlPressed = (oEvent.ctrlKey) ? oEvent.ctrlKey : oEvent.modifiers & 2 > 0;
    //var bMetaPressed = (oEvent.metaKey) ? oEvent.metaKey : oEvent.modifiers & 8 > 0;

    var bRet = true; 
    if(sTagType != null){sTagType = sTagType.toLowerCase();}
    
    if((!oTarget.readOnly) && (sTag == "textarea" || (sTag == "input"&& sTagType=="text")) &&  nKeyCode != asciiF5 && 
		(nKeyCode == asciiBack || nKeyCode == asciiSHIFT || nKeyCode == asciiHome || bShiftPressed || bCtrlPressed ||
		(bCtrlPressed && (nKeyCode == asciiLeftArrow || nKeyCode == asciiRightArrow) || (sChar == 'A' || sChar == 'C' || sChar == 'V' || sChar == 'X') ))){
        return true;
    }else if(bAltPressed && (nKeyCode == asciiLeftArrow || nKeyCode == asciiRightArrow)){ // block alt + left or right arrow
        bRet = false;
    }else if(bCtrlPressed && (sChar == 'A' || sChar == 'C' || sChar == 'V' || sChar == 'X')){ // ALLOW cut, copy and paste, and SELECT ALL
        bRet = true;
    }else if(bShiftPressed && nKeyCode == asciiTab){//allow shift + tab
        bRet = true;
    }else if(bIsFunctionKey){
        bRet = false;
    }else if( bCtrlPressed && sChar == 'N' ){ //block ALL other sequences, includes CTRL+O, CTRL+P, CTRL+N, etc....
        bRet = false;
    }else if( nKeyCode == asciiBack && ((sTag != "textarea" && ((sTagType!="text") &&(sTagType!="password"))) || (oTarget.disabled != '' || oTarget.readOnly) )){
		bRet = false;
	}
	
    if(!bRet){
        try{
            oEvent.returnValue = false;
            oEvent.cancelBubble = true;
            if(document.all){
                oEvent.keyCode = 0;
            }else{
                oEvent.preventDefault();
                oEvent.stopPropagation();
            }
			alert(msg);
        }catch(ex){
            alert(msg);
        }
    }
    return bRet;
}

function $(){
  var elements=[]
  for(var o,i=0;i<arguments.length,o=arguments[i];i++){
    if(typeof o=='string')
      o=document.getElementById(o)||null;
    elements.push(o);
  }
  return elements.length<2?elements[0]:elements;
}

MaskInput=function(f, m){//page.client... MaskInput($(''),'99/99/9999')
	function mask(e){
		var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[áéíóúàâãêôõçÁÉÍÓÚÀÃÂÊÔÕÇ]/i, "8": /./ },
			rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
		function accept(c, rule){
			for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
				if(r & i && patterns[i].test(c))
					break;
				return i <= r || c == rule;
		}
		var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
		(!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
			r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
			: (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
			r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
	}
	for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
		addEvent(f, i, mask);
};

String.prototype.mask=function(m){var m,l=(m=m.split('')).length,s=this.split(''),j=0,h='';for(var i=-1;++i<l;)if(m[i]!='#'){if(m[i]=='\\'&&(h+=m[++i]))continue;h+=m[i];i+1==l&&(s[j-1]+=h,h='');}else{if(!s[j]&&!(h=''))break;(s[j]=h+s[j++])&&(h='');}return s.join('')+h;}

function validaCPFCNPJ(idCampo,type){
	var l = $(idCampo).value.replace(/[^\d]/g,"").length;
	if(l==11)
		return isCPF(idCampo,type);
	else if(l==14)
		return isCNPJ(idCampo,type);
	else{
		alert('CPF/CNPJ Incorreto.')
		return false;
	}}
function formataCPFCNPJ(idCampo){
	var l = (m=(v=$(idCampo)).value.replace(/[^\d]/g,"")).length;
	if(l==11)
		v.value = m.mask('###.###.###-##');
	else if(l==14)
		v.value = m.mask('##.###.###/####-##');
}
isCPF=function(campo,type){/*type -> 0 para alert e 1 para return*/
	var c = $(campo).value.trim(),erro=false;
	if(c=="")return;
	if((c = c.replace(/[^\d]/g,"").split("")).length != 11 && !erro) erro=true;
	if(new RegExp("^" + c[0] + "{11}$").test(c.join("")) && !erro) erro=true;
	for(var s = 10, n = 0, i = 0; s >= 2 && !erro; n += c[i++] * s--);
	if(c[9] != (((n %= 11) < 2) ? 0 : 11 - n)) erro=true;
	for(var s = 11, n = 0, i = 0; s >= 2 && !erro; n += c[i++] * s--);
	if(c[10] != (((n %= 11) < 2) ? 0 : 11 - n)) erro=true;
	if(erro){return (type==0 || type==undefined) ? alert('CPF Inv\u00e1lido'):false;}else return true;
};
isCNPJ=function(campo,type){/*type -> 0 para alert e 1 para return*/
	var b = [6,5,4,3,2,9,8,7,6,5,4,3,2], c = $(campo).value.trim(), erro=false;
	if(c=="")return;
	if((c = c.replace(/[^\d]/g,"").split("")).length != 14 && !erro) erro=true;
	if(new RegExp("^" + c[0] + "{14}$").test(c.join("")) && !erro) erro=true;
	for(var i = 0, n = 0; i < 12  && !erro; n += c[i] * b[++i]);
		if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n)) erro=true;
	for(var i = 0, n = 0; i <= 12 && !erro; n += c[i] * b[i++]);
		if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n)) erro=true;
	if(erro){(type==0 || type==undefined) ? alert('CNPJ Inv\u00e1lido'):false;}else return true;
};

function formataCurrency(o,e){
	o=document.getElementById(o);
	o.c = 2, o.dec = ",", o.dig = ".";
	var stop=function(){e.returnValue=false;e.cancelBubble = true;return false;}
	if(e.keyCode > 47 && e.keyCode < 58){
		var o, s = (o.value.replace(/^0+/g, "") + String.fromCharCode(e.keyCode)).replace(/\D/g, ""), l, n;
		(l = s.length) <= (n = o.c) && (s = new Array(n - l + 2).join("0") + s);
		for(var i = (l = (s = s.split("")).length) - n; (i -= 3) > 0; s[i - 1] += o.dig);
		n && n < l && (s[l - ++n] += o.dec);
		o.value = s.join("");
	}e.keyCode > 30 && stop();
}

// Fábio Rodrigues
//Alterado : Erickson http://helpdesk.issnetonline.com.br/Messages.aspx?ThreadID=18085
// Permite que o usuário informe até 6 casas decimais no campo quantidade
function ValidaQuantidade(o,e){
	o=document.getElementById(o);
	var reg = /^\d{1,5}(,\d{1,6})?$/;
	return reg.test(o.value);

}
// Fábio Rodrigues
// Formata sempre informando no mínimo 2 casas decimais tanto no campo quantidade
// quanto no campo valor unitário
function FormataCasasDecimais(o,e){
	o=document.getElementById(o);
	if (o.value.indexOf(',') != -1){
		var vetor = o.value.split(",");
		if (vetor[1].length == 1){
			return o.value + '0';
		}
		else{
			return o.value;
		}
	}
	return o.value + ',00';
}
// Fábio Rodrigues
// Permite somente números [0-9] e a vírgula
function SomenteNumerosVirgula(o,e){
	if(e.keyCode > 47 && e.keyCode < 58 || e.keyCode == 44)
		return true;
	else
		return false;
}

//------
// 27/10/2009
// Hernandes Martins
// Permite somente a digitação de números e vírgulas num campo, máximo de 4 casas decimais (15,4)
// se houver 4 caracteres numéricos após a vírgula anula o evento.
// Uso: txtID.Attributes.Add("onkeypress", "SomenteNumVirgula(this, event);")
//------
function SomenteNumVirgula(o, evt, formato){
	evt = evt ? evt : window.event;
	var e = (evt.which) ? evt.which : evt.keyCode; // evt.which == FF | evt.keyCode == IE
	
	if(e < 48 || e > 57) {
		if(e != 44) {
			if(evt.which){evt.preventDefault(); return false;}
			else{evt.keyCode=0; evt.cancelBubble=true; evt.returnValue = false; return false;}
		}
	}
	
	// Se digitou caracter válido
	if(o.value.indexOf(',') != -1 && o.value.indexOf(',') != (o.value.length-1)) {
		var reg;
		if(!formato || formato == "15,4") {
			reg = /^\d{1,15}(,\d{1,4})?$/;
		}else if(formato == "10,4") {
			reg = /^\d{1,10}(,\d{1,4})?$/;
		}else if(formato == "10,6"){
			reg = /^\d{1,10}(,\d{1,6})?$/;
		}
		
		if(!reg.test(o.value)) {
			if(evt.which){evt.preventDefault(); return false;}
			else{evt.keyCode=0; evt.cancelBubble=true; evt.returnValue = false; return false;}
		}else{
			switch(formato){
				case "10,4":
					if(o.value.substr(o.value.indexOf(','), (o.value.length-1)).replace(',','').length == 4){
						if(evt.which){evt.preventDefault(); return false;}
						else{evt.keyCode=0; evt.cancelBubble=true; evt.returnValue = false; return false;}
					}
					break;
				case "10,6":
					if(o.value.substr(o.value.indexOf(','), (o.value.length-1)).replace(',','').length == 6){
						if(evt.which){evt.preventDefault(); return false;}
						else{evt.keyCode=0; evt.cancelBubble=true; evt.returnValue = false; return false;}
					}
					break;
			}
		}//fim else
	}
}

// Rodrigo Perez Swinerd
// Permite somente números, nada mais.
function SoNumeros()
{
  var carCode = event.keyCode;
  if ((carCode < 48) || (carCode > 57))
  {   
   event.cancelBubble = true;
   event.returnValue = false;
  }
}

// Fábio Rodrigues
// Permite que o usuário informe até 4 casas decimais no campo valor unitário
// Exemplo: 1234567890,1234
function ValidaValorUnitario(o,e){
	o=document.getElementById(o);
	var reg = /^\d{1,10}(,\d{1,4})?$/;
	return reg.test(o.value);
}

function blockCtrl(e){/*onkeydown="blockCtrl(event)"*/
	var ctrl=(e.ctrlKey)?e.ctrlKey:e.modifiers&2>0;
	if(ctrl){
		if(e.preventDefault){
		  e.preventDefault();
		  e.stopPropagation();
		}else{
		  e.returnValue = false;
		  e.cancelBubble = true;
		}
	}
}

function MultiplyAliq(idField1, idFieldAliq, idFieldR){
	var v1 = $(idField1).value.replace(/\./g,'').replace(',','.');
	var v2 = $(idFieldAliq).value.replace(/\./g,'').replace(',','.');
	
	$(idFieldR).value = fmtMoney(v1*v2/100);
}


/*
	by fabio
	onchange="completeDecimalFormat(this)"
*/
function completeDecimalFormat(objField){
	var str=objField.value;
	if(str.length==1)str+=',00';
	else if((str.replace(/\D/g, "")).length==2)str+='0';
	objField.value=str;
}


//************************************
/*
Hernandes Martins
02/05/2008
*/
//************************************

function getObj(IdOrName) {
	var ret = null;
	
	if (document.getElementById) 
	   ret = document.getElementById(IdOrName);
	else if (document.all) 
	   ret = document.all[IdOrName];
	else if (document.layers) {
		if (document.layers[IdOrName]) 
			ret = document.layers[IdOrName];
		else
			ret = document.layers.testP.layers[IdOrName];
	}
	
	return ret;
}

function trimJS(string_param)
{
	var n_string = new String(string_param);
	return n_string.replace(/^\s*/, "").replace(/\s*$/, "");
}

function ApenasNum(strParm) {
	strParm = String(strParm);
	var chrPrt = "0";
	var strRet = "";
	var j=0;
	for (var i=0; i < strParm.length; i++) {
		chrPrt = strParm.substring(i, i+1);
		if ( chrPrt.match(/\d/) || chrPrt == '\.') {
			if (j==0) {
				strRet = chrPrt;
				j=1;
			}else{
				strRet = strRet.concat(chrPrt);
			}
		}
	}
	return strRet;
}

function GetNavigatorInfo()
{
	var versao, versao2, versaoNav, versaoSO, navegador, nav = getObj('logNavegador'), so = getObj('logSO');
	
	if (navigator.appName.indexOf('Microsoft') != -1) {
		//alert('i.e');
		versao = navigator.appVersion.split(";");
		//alert(versao);
		versaoNav = trimJS(versao[1]);
		versaoNav = ApenasNum(versaoNav);
		//alert(versaoNav);
		versaoSO = trimJS(versao[2]);
		//alert(versaoSO);
		navegador = navigator.appName;
		//alert(navegador);
	}else if (navigator.appName.indexOf('Netscape') != -1) {
		versao = navigator.userAgent.split(";");
		versaoSO = versao[2].substr(1, versao[2].length);
		
		if (navigator.userAgent.indexOf('Firefox') != -1 && navigator.userAgent.indexOf('Navigator') == -1) {
			versaoNav = navigator.userAgent.substr(navigator.userAgent.indexOf('Firefox'), navigator.appVersion.length);
			versaoNav = ApenasNum(versaoNav);
			navegador = "Firefox";
		}else if (navigator.userAgent.indexOf('Firefox') != -1 && navigator.userAgent.indexOf('Navigator') != -1) {
			versaoNav = navigator.userAgent.substr(navigator.userAgent.indexOf('Navigator'), navigator.appVersion.length);
			versaoNav = ApenasNum(versaoNav);
			navegador = navigator.appName;
		}else if (navigator.userAgent.indexOf('Gecko') != -1 && navigator.userAgent.indexOf('Firefox') == -1 && navigator.userAgent.indexOf('Navigator') == -1 && navigator.userAgent.indexOf('Safari') == -1) {	
			versaoNav = navigator.userAgent.substr(navigator.userAgent.indexOf('Gecko'), navigator.appVersion.length);
			versaoNav = versaoNav.replace("/", " ");
			navegador = "Mozilla";
		}else if (navigator.userAgent.indexOf('Gecko') != -1 && navigator.userAgent.indexOf('Firefox') == -1 && navigator.userAgent.indexOf('Navigator') == -1 && navigator.userAgent.indexOf('Safari') != -1) {
			versaoNav = navigator.userAgent.substr(navigator.userAgent.indexOf('Safari'), navigator.appVersion.length);
			versaoNav = versaoNav.replace("/", " ").replace("Safari ", "");
			navegador = "Safari";
		}
	}else if (navigator.appName.indexOf('Opera') != -1) {
		versao = navigator.appVersion.split(";");
		versao2 = versao[0].split("(");
		versaoNav = trimJS(versao2[0]);
		versaoSO = trimJS(versao2[1]);
		navegador = navigator.appName;
	}else{
		navegador = navigator.appName;
		versaoNav = navigator.appVersion;
		if (navigator.platform.indexOf('Win') != -1) {
			versaoSO = "Windows";
		}else versaoSO = navigator.platform;
	}
	
	nav.value = navegador + ' ' + versaoNav;
	so.value = versaoSO;
}

function EnviarPerguntaFaleConosco(Id, Modo, TxtNome, TxtAssunto, LinkEnviar, LabelPerguntaPai)
{
	var txt;
	
	var div = getObj(Id);
	if(div != null) {
		div.style.display = Modo;
	}
	txt = getObj(TxtAssunto);
	if(txt != null) {
		if(getObj(LabelPerguntaPai) != null) {
			txt.value = 'Re: ' + getObj(LabelPerguntaPai).innerHTML;
			txt.readOnly = true;
		}else{
			txt.readOnly = false;
		}
	}
	txt = getObj(TxtNome);
	if(txt != null) {
		txt.focus();
	}
	txt = getObj(LinkEnviar);
	if(txt != null) {
		if(getObj(LabelPerguntaPai) == null) {
			txt.style.display = "none";
		}
	}
}

function CancelarEnvioFaleConosco(Id, Modo, TxtCodMsgPai, TxtNome, TxtAssunto, TxtMsg, LinkEnviar, CodMsgPrincipal)
{
	var txt;
	CodMsgPrincipal = (!CodMsgPrincipal)?0:CodMsgPrincipal;
	
	var div = getObj(Id);
	if(div != null) {
		div.style.display = Modo;
	}
	txt = getObj(TxtCodMsgPai);
	if(txt != null) {
		if(CodMsgPrincipal > 0) txt.value = CodMsgPrincipal;
		else txt.value = '';
	}
	txt = getObj(TxtNome);
	if(txt != null) {
		txt.value = '';
	}
	txt = getObj(TxtAssunto);
	if(txt != null) {
		txt.value = '';
		txt.readOnly = false;
	}
	txt = getObj(TxtMsg);
	if(txt != null) {
		txt.value = '';
	}
	txt = getObj(LinkEnviar);
	if(txt != null) {
		txt.style.display = "block";
	}
}

function ResponderMsgFaleConosco(Id, Modo, CodMsg, TxtCodMsgPai, TxtNome, TxtAssunto, Assunto, LinkEnviar)
{
	var txt;
	var div = getObj(Id);
	if(div != null) {
		div.style.display = Modo;
	}
	txt = getObj(TxtCodMsgPai);
	if(txt != null) {
		txt.value = CodMsg;
	}
	txt = getObj(TxtAssunto);
	if(txt != null) {
		txt.value = 'Re: ' + Assunto;
		txt.readOnly = true;
	}
	txt = getObj(TxtNome);
	if(txt != null) {
		txt.focus();
	}
	txt = getObj(LinkEnviar);
	if(txt != null) {
		txt.style.display = "none";
	}
}
function parseMoney(str) {
	str = str.replace(/[^0-9,]/g,'');
	str = str.replace(',','.');
	
	try { return parseFloat(str); }
	catch(e) { return 0.0; }
}

function tiraCasasDecimais(val)
{
    flr = Math.floor(val);
    intVal = Math.round(val);
    
    if (intVal == flr)  //Arredontamento para baixo (round está correto)
        return intVal;
    
    if (val > flr + 0.5)    //Fração maior que .5
        return intVal;
        
    if (flr % 2 == 0)
        return flr;
    else
        return intVal;
}

function toMoneyStr(val) {
	if (isNaN(val))
		return '';
	else {
		var v = tiraCasasDecimais(val * 100) % 100;
		return Math.floor(val) + ',' + (v<10?'0':'') + v;
	}
}

function CalcularQtdeValor(chk, valor){
	if(document.getElementById('lblQtdSelecionados')!= null){
		var lblQtdSelecionados = document.getElementById('lblQtdSelecionados');
		var lblValorSelecionados = document.getElementById('lblValorSelecionados');
		//var lblQtdNaoSelecionados = document.getElementById('lblQtdNaoSelecionados');
		//var lblValorNaoSelecionados = document.getElementById('lblValorNaoSelecionados');
		//var lblQtdTotal = document.getElementById('lblQtdTotal');
		//var lblValorTotal = document.getElementById('lblValorTotal');
		var btnGerarGuias = document.getElementById('btnGerarGuias');
		//if(parseInt(lblQtdTotal.innerText) ==0){
		//	document.getElementById('hdfQtdSelecionados').value = '0';
		//	document.getElementById('hdfValorSelecionados').value = '0,00';
		//}
		lblQtdSelecionados.innerText = document.getElementById('hdfQtdSelecionados').value;
		lblValorSelecionados.innerText = document.getElementById('hdfValorSelecionados').value;	
		if(chk && valor){
			valor = parseMoney(valor);
			if(chk.checked){
				lblQtdSelecionados.innerText = parseInt(lblQtdSelecionados.innerText) + 1;		
				lblValorSelecionados.innerText = toMoneyStr(parseMoney(lblValorSelecionados.innerText) + valor);
			}	
			else{
				lblQtdSelecionados.innerText = parseInt(lblQtdSelecionados.innerText) - 1;				
				lblValorSelecionados.innerText = toMoneyStr(parseMoney(lblValorSelecionados.innerText) - valor);		
			}
		}
		//lblQtdNaoSelecionados.innerText = parseInt(lblQtdTotal.innerText) - parseInt(lblQtdSelecionados.innerText);
		//lblValorNaoSelecionados.innerText = toMoneyStr(parseMoney(lblValorTotal.innerText) - parseMoney(lblValorSelecionados.innerText));
		document.getElementById('hdfQtdSelecionados').value = lblQtdSelecionados.innerText;
		document.getElementById('hdfValorSelecionados').value = lblValorSelecionados.innerText;
		btnGerarGuias.disabled = !(parseInt(lblQtdSelecionados.innerText) > 0);
	}
}
