function Relogio()
{
	var hora = new Date();
	var minutos = new Date();
	var segundo = new Date();
	document.getElementById('relogio').innerHTML=hora.getHours() +':'+minutos.getMinutes()+':'+ segundo.getSeconds();
	setTimeout("Relogio()",1000) 
}
function derrubaSESSION()
{
 var Min = parseFloat(replace(replace(document.frmsession.Tsessao.value,'.',''),',','.'));
 var hora = new Date();
 var minutos = new Date();
 var segundo = new Date();
 if (parseFloat(Min) > 20){
     popup('tmxlogoff.asp?acao=LOGOFF',262,150); 	 
 }
 setTimeout("derrubaSESSION()",1000) 
}

function strReplaceChr(texto) {
var chrEspeciais = new Array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë",
"í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö",
"ú", "ù", "û", "ü", "ç",
"Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë",
"Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö",
"Ú", "Ù", "Û", "Ü", "Ç");
var chrNormais = new Array("a", "a", "a", "a", "a", "e", "e", "e", "e",
"i", "i", "i", "i", "o", "o", "o", "o", "o",
"u", "u", "u", "u", "c",
"A", "A", "A", "A", "A", "E", "E", "E", "E",
"I", "I", "I", "I", "O", "O", "O", "O", "O",
"U", "U", "U", "U", "C");
for (index in chrEspeciais) {
texto = texto.replace(chrEspeciais[index], chrNormais[index]);
}

return texto;
}


function IsNull(ITEM){
if(ITEM == null || ITEM == undefined){
  return true;
}
  return false;
}

////////////////////////////////// MAXLENGTH="13" ONKEYUP="ftel(this)"

 

function ftel( obj ) {

   var x = obj.value;

   x = x.replace( /\D+/g, '' );

   x = x.replace( /(\d{10})(\d{3})/, '$1' );

   x = x.replace( /(\d{1})/, '($1' );

   x = x.replace( /(\(\d{2})(?=\d{1,})/, '$1)' );

   x = x.replace( /(\(\d{2}\)\d{4})(?=\d{1,})/, '$1-' );

   obj.value = x;

}


////////////////////////////////// MAXLENGTH="18" ONKEYUP="fcnpj(this)"

 

function fcnpj( obj ) {

   var x = obj.value;

   x = x.replace( /\D+/g, '' );

   x = x.replace( /(\d{14})(\d{4})/, '$1' );

   x = x.replace( /(\d{2})(?=\d{1,})/, '$1.' );

   x = x.replace( /(\d{2}\.\d{3})(?=\d{1,})/, '$1.' );

   x = x.replace( /(\d{2}\.\d{3}\.\d{3})(?=\d{1,})/, '$1/' );

   x = x.replace( /(\d{2}\.\d{3}\.\d{3}\/\d{4})(?=\d{1,})/, '$1-' );

   obj.value = x;

}

////////////////////////////////// MAXLENGTH="14" ONKEYUP="fcpf(this)"

 

function fcpf( obj ) {

   var x = obj.value;

   x = x.replace( /\D+/g, '' );

   x = x.replace( /(\d{11})(\d{3})/, '$1' );

   x = x.replace( /(\d{3})(?=\d{1,})/g, '$1.' );

   x = x.replace( /(\d{3}\.\d{3}\.\d{3})(\.)(?=\d{1,})/, '$1-' );

   obj.value = x;

}

function $(id){
 return document.getElementById(id);
}

function popup(pag,x,y){
	linha = "window.open('"+ pag ;
    linha = linha + "','novoPop','toolbar=no,location=no,"
	linha = linha + "status=no,menubar=no,scrollbars=no,"
	linha = linha + "resizable=no,width=" + x +  ",height="+ y +",top=300,left=300')";
 eval(linha);
}
function popup2(pag,x,y){
	linha = "window.open('"+ pag ;
    linha = linha + "','novoPop','toolbar=no,location=no,"
	linha = linha + "status=no,menubar=no,scrollbars=yes,"
	linha = linha + "resizable=no,width=" + x +  ",height="+ y +",top=300,left=300')";
 eval(linha);
}

function resumo(){
	document.getElementById('txidentificacao_').innerHTML  = document.getElementById('txidentificacao').value;	
	document.getElementById('nmproduto_').innerHTML  = document.getElementById('nmproduto').value;		
	document.getElementById('p2tiragem_').innerHTML  = document.getElementById('p2tiragem').innerHTML;			
	document.getElementById('p2prazo_').innerHTML  = document.getElementById('p2prazo').innerHTML;			
	document.getElementById('p2dimessao_').innerHTML  = document.getElementById('p2dimessao').innerHTML;			
	document.getElementById('p2cores_').innerHTML  = document.getElementById('p2cores').innerHTML;					
	document.getElementById('p2peso_').innerHTML  = document.getElementById('p2peso').innerHTML;				
 document.getElementById('vlproduto_').innerHTML  = document.getElementById('vlproduto').value;					
 document.getElementById('vltotal_').innerHTML  = document.getElementById('vltotal').value;						
	document.getElementById('qdproduto_').innerHTML  = document.getElementById('qdproduto').value;							
	document.getElementById('totfn_').innerHTML  = document.getElementById('totfn').value;								
	document.getElementById('vltotal1_').innerHTML  = document.getElementById('vltotal1').value;
	document.getElementById('vltotal3_').innerHTML  = document.getElementById('vltotal').value;	
	if (document.getElementById('referencias').value != 'consulta'){
  	  document.getElementById('vltotal2_').innerHTML  = document.getElementById('vltotal1').value;	
	if (parseFloat(replace(replace(document.getElementById('vltotal1').value,'.',''),',','.'))<150){
		document.getElementById('TBroteiro').disabled='disabled';
		document.getElementById('TBroteiro').checked=false;
		document.dados.CdtipoRot[0].checked=false;
		document.dados.CdtipoRot[1].checked=false;
		document.dados.CdtipoRot[2].checked=false;
		document.getElementById('regiao').innerHTML='';
		
	}else{
		document.getElementById('TBroteiro').disabled=''; 	
		
	}
	}else{
	  var vltot = 0;
   var tot2   = replace(replace(document.getElementById('vltotal').value,'.',''),',','.');
  	var tot3   = replace(replace(document.getElementById('totfn').value,'.',''),',','.');
   var vlfrete = replace(replace(document.getElementById('VlFrete').value,'.',''),',','.');
   vltot = parseFloat(tot2) + parseFloat(tot3) + parseFloat(vlfrete);
			document.getElementById('vltotal1').value = formatCurrency(vltot);			
  	document.getElementById('vltotal2_').innerHTML = formatCurrency(vltot);
  	document.getElementById('vltotal1_').innerHTML = formatCurrency(vltot);			
			document.getElementById('vltotal1').value = formatCurrency(vltot);			
	}
}

function Replace(STRING,REPLACE_THIS,REPLACE_WITH){
while(STRING.indexOf(REPLACE_THIS) > -1){
STRING = STRING.replace(REPLACE_THIS,REPLACE_WITH);
}
return STRING;
}


function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + num + ',' + cents);
}


function CriticasErro(id){

var strErro = '';
 var flerro = 0;	
 if((document.getElementById('Idproduto').value==0)&&(flerro==0)&&(id==1)){
    alert('Selecione o produto para o seu pedido !');		  
	flerro = 1;
 }	 
 if((document.getElementById('txidentificacao').value=='')&&(flerro==0)&&(id==2)){
    alert('Digite a identificação do produto !');		  
	document.getElementById('txidentificacao').focus();
	flerro = 1;
 }	 
 if ((document.dados.flconcorda[0].checked==false)&&(document.dados.flconcorda[1].checked==false)&&(flerro==0)&&(id==2)){
    alert('Selecione se esta de acordo com o descritivo de atenção?');		  
	flerro = 1;
 }
 
/* if ((document.dados.flconcorda[0].checked==false)&&(document.dados.flconcorda[1].checked==true)&&(flerro==0)&&(id==2)&&((document.getElementById('radio1').checked==false)||(document.getElementById('radio2').checked==false)||(document.getElementById('radio3').checked==false))){
 	strErro = strErro + 'ATENÇÃO\n\n'
  strErro = strErro + 'Você escolheu algum tipo de finalização para seu pedido.\n';
  strErro = strErro + 'Faça as seguintes considerações:\n\n';
  strErro = strErro + '01 - Gerar "boneca" da montagem do layout\n';
  strErro = strErro + '02 - Verificar o espelhamento das imagens, baseado\n';
  strErro = strErro + 'na "boneca" impressa e montada.\n';
  strErro = strErro + '03 - O prazo de finalização será acrescido + 1 dia \n';
  strErro = strErro + 'útil, considerar alem da data do sistema.\n\n';
  strErro = strErro + 'Dica:trabalhos verticais, com 1 dobra na horizontal,\n';
  strErro = strErro + '"geralmente" necessitam de giro no verso (ou na\n';
  strErro = strErro + 'frente). Conferir com a montagem de uma "boneca".\n';
    alert(strErro);
	flerro = 1;
 }*/
 
 if((document.getElementById('txarquivo').value.length <=10)&&(flerro==0)&&(id==4)){
    alert('É necessário anexar o arquivo de Frente !');		  
	flerro = 1;
 }

 if((document.getElementById('CdTipoEntrega').value=='')&&(flerro==0)&&(id==3)){
	  alert('Por favor, selecione o tipo de entrega!');		  
   flerro = 1;
	};
	
	
 if((document.getElementById('floba').value=='S')&&(flerro==0)&&(id==3)){
   var tot = 0;
   var dif = 0;  
   var a = parseFloat(replace(replace(document.getElementById('vltotal').value,'.',''),',','.'));
   var b = parseFloat(replace(replace(document.getElementById('VlFrete').value,'.',''),',','.'));
   var d = parseFloat(replace(replace(document.getElementById('vlcomprovante').value,'.',''),',','.'));
   var x = parseFloat(replace(replace(document.getElementById('totfn').value,'.',''),',','.'));
   if (document.getElementById('referencias').value !='consulta'){
	 tot = (x + a + b);
     document.getElementById('vltotpedido').value = formatCurrency(tot); 
   }else{
     tot = (x + a + b);
	 document.getElementById('vltotpedido').value = formatCurrency(tot);   
   }
   if((tot > d)&&(flerro==0)&&(id==3)){
	 dif = tot - d;  
	 strErro = strErro + 'ATENÇÃO\n\n'
     strErro = strErro + 'valor total do pedido R$ '+ formatCurrency(a) +'  \n';
     strErro = strErro + 'valor do frete R$ '+ formatCurrency(b) +'\n';
     strErro = strErro + 'Valor total do pedido c/ frete R$ '+ formatCurrency(tot) +'\n\n';
     strErro = strErro + 'Esta faltando o valor de R$'+ formatCurrency(dif) +'\n';
     strErro = strErro + 'para complenta esta operacao \n'; 
  	 alert(strErro);
	 flerro = 1;
   };

if((tot < d)&&(flerro==0)&&(id==3)){
	    dif = d - tot;  
        strErro = strErro + 'ATENÇÃO\n\n'
        strErro = strErro + 'valor total do pedido R$ '+ formatCurrency(a) +'  \n';
        strErro = strErro + 'valor do frete R$ '+ formatCurrency(b) +'\n';
        strErro = strErro + 'Valor total do pedido c/ frete R$ '+ formatCurrency(tot) +'\n\n';
        strErro = strErro + 'Esta ultrapassou o valor total do pedido em R$'+ formatCurrency(dif) +'\n';
	    strErro = strErro + 'para complenta esta operacao \n'; 
	    alert(strErro);
		flerro = 1;
   };	 
 }	 
 resumo();	
 document.getElementById('CriticaErro').value = flerro; 
}
function FE_formatDate(strData,idCampo)
{
  if(strData.length==2 || strData.length==5	)
  {
	 document.getElementById(idCampo).value = strData + '/';
  }
}

//onKeyUp="javascript:FE_formatDate(this.value,this.id)"

function ampliarImg(id,wid,hid){
  linha = "window.open('tmx000e.asp?img="+id;
  linha = linha + "','ampliar','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width="+ wid +",height="+  hid +",top=0,left=0')";
 eval(linha);
}

function ampliarImg2(id,wid,hid){
  linha = "window.open('tmx000g.asp?img="+id;
 linha = linha + "','ampliar','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width="+ wid +",height="+ hid +",top=0,left=0')";
 eval(linha);
}

function anexar(arq,Tela) {
 var Nerro = 0 ;
 var strErro  = " ";
 if (Tela==3){
       strErro = strErro + 'Deseja anexao arquivo de deposito bancário?'
 }; 
 if ((Tela==1)||(Tela==2)){
   strErro = strErro + 'CHECKLIST DE QUALIDADE\n\n'
   strErro = strErro + '01 - O padrão de cores ultilizado foi CMYK ?\n\n';
   strErro = strErro + '02 - As fontes foram convertidas para CURVA ?\n\n';
   //strErro = strErro + '03 - As fontes foram convertidas para BITMAPS ?\n\n';
   strErro = strErro + '03 - As fontes foram convertidas para BITMAPS ( Caso estejam com efeitos abertos ) ?\n\n'; 
   strErro = strErro + '04 - As Imagens foram "fletadas" ? \n'
   strErro = strErro + 'evitando desorganização do layout ? \n\n'
   strErro = strErro + '05 - A áera de segurança foi respeitada ? \n\n'
   strErro = strErro + '06 - As imagens compactadas estão em 300 DPIS\n'
   strErro = strErro + '(observar a qualidade final após exportação) ?\n\n'
//   strErro = strErro + '07 - O trabalho foi SANGRADO em 1 mm cada lado ? \n\n\n'
   strErro = strErro + '07 - O trabalho foi SANGRADO de acordo com o gabarito ? \n\n\n'   
   strErro = strErro + 'Esta questões constam em nosso Regulamento de Revenda.\n\n'
 };
 if (Tela==4){
   strErro = strErro + 'Deseja anexao este arquivo?'
 };
 if ((Tela==7)||(Tela==100)||(Tela==101)||(Tela==102)||(Tela==103)||(Tela==104)||(Tela==25)){
   strErro = strErro + 'Deseja anexao este arquivo?'
 };
 if ((Tela==5)||(Tela==55)){
   strErro = strErro + 'Deseja anexao o arquivo do banner?'
 };
if (Nerro==0){
 if (confirm(strErro)){
 linha = "window.open('tmx600.asp?txarquivo="+ arq +"&Tela="+Tela;
 linha = linha + "','arquivo1','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=360,height=320,top=200,left=350')";
 eval(linha);
 };
}else{
 linha = "window.open('tmx600.asp?txarquivo="+ arq +"&Tela="+Tela;
 linha = linha + "','arquivo1','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=360,height=320,top=200,left=350')";
eval(linha);
}; 
};
	function txtBoxFormat(strField, sMask) {
	
	var i, nCount, sValue, fldLen, mskLen, bolMask, sCod, strField, sMask 

	sValue = strField.value;

	// Limpa todos os caracteres de formatação que
	// já estiverem no campo.
	for (var x=1; x < 10; x++) { sValue = sValue.toString().replace("-",""); }
	for (var x=1; x < 10; x++) { sValue = sValue.toString().replace(".",""); }
	for (var x=1; x < 10; x++) { sValue = sValue.toString().replace("/",""); }
	for (var x=1; x < 10; x++) { sValue = sValue.toString().replace("(",""); }
	for (var x=1; x < 10; x++) { sValue = sValue.toString().replace(")",""); }
	for (var x=1; x < 10; x++) { sValue = sValue.toString().replace(" ",""); }
	for (var x=1; x < 10; x++) { sValue = sValue.toString().replace(":",""); }
	fldLen = sValue.length;
	mskLen = sMask.length;

	i = 0;
	nCount = 0;
	sCod = "";
	mskLen = fldLen;

	while (i <= mskLen) {
	bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
	bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")")
	|| (sMask.charAt(i) == " "))
	
	if (bolMask) {
	sCod += sMask.charAt(i);
	mskLen++; }
	else {
	sCod += sValue.charAt(nCount);
	nCount++;
	}

	i++;
}

	strField.value = sCod;
	
	if( (sValue != "") && (isNaN(sValue)) ){
		strField.value = '';
		strField.focus();
		alert("Digite somente numeros");
	}else{
		return false;
		
	}
}
//---------------------------------------------------------------------------------------

// Valida data
function validarData(strField) {
	var date = strField.value;
	var array_data = new Array;
	var ExpReg = new RegExp("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}");
	if (ExpReg.test(date))
		erro = true;
    else{
	  	erro = false;
    }
	//vetor que contem o dia o mes e o ano
	array_data = date.split("/");
	erro = false;
	//Valido se a data esta no formato dd/mm/yyyy e se o dia tem 2 digitos e esta entre 01 e 31
	//se o mes tem 2 digitos e esta entre 01 e 12 e o ano se tem 4 digitos e esta entre 1000 e 2999
	if ( date.search(ExpReg) == -1 )
		erro = true;
	//Valido os meses que nao tem 31 dias com excecao de fevereiro
	else if ( ( ( array_data[1] == 4 ) || ( array_data[1] == 6 ) || ( array_data[1] == 9 ) || ( array_data[1] == 11 ) ) && ( array_data[0] > 30 ) )
		erro = true;
	//Valido o mes de fevereiro
	else if ( array_data[1] == 2 ) {
		//Valido ano que nao e bissexto
		if ( ( array_data[0] > 28 ) && ( ( array_data[2] % 4 ) != 0 ) )
			erro = true;
		//Valido ano bissexto
		if ( ( array_data[0] > 29 ) && ( ( array_data[2] % 4 ) == 0 ) )
			erro = true;
	}
	if (( erro ) && (date != '')) {
		alert("Data Invalida");
		strField.focus();
	}
}

//---------------------------------------------------------------------------

// Valida email
function validarEmail(strField) {
	var email = strField.value;
	var ExpReg = new RegExp("^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$");
	
	if (ExpReg.test(email))
      	erro = true;
    else{
	  	erro = false;
	}
	if (( !erro ) && (email != '')) {
		alert("Email Invalido!");
		strField.focus();
	}
   // return erro;
}
//------------------------------------------------------------------------

// Valida http
function validarUrl(strField) {
	var url = strField.value;
	var ExpReg = new RegExp("^(http[s]?://|ftp://)?(www\.)?[a-zA-Z0-9-\.]+\.(com|org|net|mil|edu|ca|co.uk|com.au|gov|br)$");
	
	if (ExpReg.test(url))
		erro = true;
    else{
	  	erro = false;
	}
	if (( !erro ) && (url != '')) {
      	alert("Web Invalido!");
      	strField.focus();
    }
    //return erro;
}
//------------------------------------------------------------------------

function imprimir(id)
{
  if (id!=''){
	document.getElementById("operimpressao").submit()}else{
	alert('Não existe consulta para imprimir...!');	
   } 	 
  
}

function aguarde(vf){
  if (vf==true){
    document.getElementById('DivAguarde').style.visibility='visible';
  }else{
    document.getElementById('DivAguarde').style.visibility='hidden';
  }	
}

function submeta(){
  aguarde(true);
  document.getElementById('bt_exibir').style.visibility='hidden';
  document.getElementById('frmacompanhamento').submit(); 
};
function anexado(id) {
 linha = "window.open('<%=caminhoWeb%>"+id;
 linha = linha + "','arquivo3','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=400,top=50,left=450')";
 eval(linha);
};
function teste(){
   document.getElementById('tmpessoal').value=document.getElementById('idrepresentante').value;
   atualizaproduto();
 };
 function a(){
 window.location ='AC_RunActiveContent.js?Acao=C&Vpessoal='+document.getElementById('filtro').Vpessoal.value;

};

function abreImpOrder2( idped ) {
 window.open ("tmx004b_a.asp?Imprimi=1&IdOrdemPagamento=" + idped, "Impreblank","toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=800,height=560,top=0,left=0")
}; 
function abreImpOrder( idped ) {
 window.open ("tmx004b.asp?Imprimi=1&IdOrdemPagamento=" + idped, "Impreblank","toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=800,height=560,top=0,left=0")
}; 

function consultapedido(Idordempagamento) {
 window.open ("tmx004a.asp?Idordempagamento=" + Idordempagamento , "blank","toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=380,height=150,top=50,left=50")
}
function consultCheque(idpessoal,combo,chamada) {
 if (combo ==4){
  window.open ("tmx004i.asp?IdRepresentante="+idpessoal+"&tipocheque=1&Idordempagamento="+chamada , "blank","toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=701,height=350,top=50,left=50")
  };
 if (combo ==3){
  window.open ("tmx004i.asp?IdRepresentante="+idpessoal+"&tipocheque=0&Idordempagamento="+chamada , "blank","toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=701,height=350,top=50,left=50")
  }; 
  if (combo ==1){
    window.open ("tmx004n.asp?IdRepresentante="+idpessoal+"&Idordempagamento="+chamada , "blank","toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=400,top=50,left=50")
  };
  if (combo ==7){
    window.open ("tmx004c.asp?IdRepresentante="+idpessoal+"&Idordempagamento="+chamada , "blank","toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=200,top=50,left=50")
  };
}
function AprovaBoleto(id,Id2){
   window.open ("tmx004c.asp?Idordempagamento="+id+"&Idpessoal="+Id2, "alt","toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=300,height=180,top=50,left=50")
};

function trocaentrega(id,Id2){
 if (confirm('Deseja Alterar o Tipo de Entrega ?')){
   window.open ("tmx004f.asp?Idordempagamento="+id+"&Idpessoal="+Id2, "alt","toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=300,height=180,top=50,left=50")
 };

function selecione(){
 // Esta função abre a tela de seleção do revenda
 linha = "window.open('tmx011a.asp'";
 linha = linha + ",'senhas','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,"
 linha = linha + "resizable=yes,width=320,height=320,top=20,left=450')";
 eval(linha); 
};

function envia_dados(){
var xerro = 0;
 if (document.getElementById('nomeclientetela').value=='SELECIONE'){
  if (document.getElementById('Vtodos').checked==false){
    alert('Selecione um Revendedor');
    xerro = 1; 
  }else{
    xerro = 0; 
  };
 };
 if(xerro ==0 ){
   aguarde(true);	  
   document.getElementById('exibir').style.visibility = "hidden";
   document.getElementById('filtro').submit();
 };
};
}

function IsNumeric(VALUE){
for(var ivA = 0; ivA < VALUE.length;ivA ++){
if(VALUE.charCodeAt(ivA) < 48 || VALUE.charCodeAt(ivA) > 57){
	if(VALUE.charCodeAt(ivA) != 46 && VALUE.charCodeAt(ivA) != 32 && VALUE.charAt(ivA) != ","){
	return false;
	}
}																					
}
return true;
}

function TeclaNumber(e,teclapres) {
    if (IsNumeric(e.value)){
		erro = true;
	}else{
		erro = false;
	}
	
	if (( !erro ) && (e != '')) {
		e.value = 0;
		e.focus();
		alert("Digite somente numeros");
	}
}

function TeclaAlfa(e,teclapres) {

    if (!IsNumeric(e.value)){
		erro = true;
	}else{
		erro = false;
	}
	
	if (( !erro ) && (e != '')) {
		e.value = '';
		e.focus();
        alert("Digite somente letras");
	}

}

function formatCurrency(num)
{

 num = num.toString().replace(/\R$|\,/g,'');
 if(isNaN(num))
    num = "0";
 sign = (num == (num = Math.abs(num)));
 num = Math.floor(num*100+0.50000000001);
 cents = num%100;
 num = Math.floor(num/100).toString();
 if(cents<10)
     cents = "0" + cents;
 for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
     num = num.substring(0,num.length-(4*i+3))+'.'+
           num.substring(num.length-(4*i+3));
      return (((sign)?'':'-')+ num + ',' + cents);
}

//replace em javascript------------------------------------------------------------------------;
function replace(originalString,searchText,replaceText) {
var strLength = originalString.length;
var txtLength = searchText.length;
if ((strLength == 0) || (txtLength == 0))
{ return originalString; }
var i = originalString.indexOf(searchText);
if ((!i) && (searchText != originalString.substring(0,txtLength)))
{ return originalString; }
if (i == -1)
{ return originalString; }
var newstr = originalString.substring(0,i) + replaceText;
if (i+txtLength < strLength)
{ newstr += replace(originalString.substring(i+txtLength,strLength),searchText,replaceText); }
return newstr;}
//-------------------------------------------------------------------------------------------------

// Limpa campo
function Limpar(valor, validos) {
// retira caracteres invalidos da string
var result = "";
var aux;
for (var i=0; i < valor.length; i++) {
	aux = validos.indexOf(valor.substring(i, i+1));
	if (aux>=0) {
		result += aux;
	}
}
return result;
}

//Formata número tipo moeda usando o evento onKeyDown
function Formata(campo,tammax,teclapres,decimal) {

var tecla = teclapres.keyCode;

vr = Limpar(campo.value,"0123456789");
tam = vr.length;
dec=decimal

if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

if (tecla == 8 )
{ tam = tam - 1 ; }

if (( tecla == 8 ) || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105 ))
{

if ( tam <= dec )
{ campo.value = vr ; }

if ( (tam > dec) && (tam <= 5) ){
campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 6) && (tam <= 8) ){
campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
}
if ( (tam >= 9) && (tam <= 11) ){
campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 12) && (tam <= 14) ){
campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 15) && (tam <= 17) ){
campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;}
} 

}

////Formata número tipo moeda
//function FormataCampo(campo,tammax,decimal) {
//
////var tecla = teclapres.keyCode;
//
//vr = Limpar(campo.value,"0123456789");
//tam = vr.length;
//dec=decimal
//
//if (tam < tammax){ tam = vr.length + 1 ; }
//
////if (tecla == 8 )
////{ tam = tam - 1 ; }
//
////if (( tecla == 8 ) || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105 ))
////{
//
//if ( tam <= dec )
//{ campo.value = vr ; }
//
//if ( (tam > dec) && (tam <= 5) ){
//campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }
//if ( (tam >= 6) && (tam <= 8) ){
//campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
//}
//if ( (tam >= 9) && (tam <= 11) ){
//campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
//if ( (tam >= 12) && (tam <= 14) ){
//campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
//if ( (tam >= 15) && (tam <= 17) ){
//campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;}
//} 


function FtrataBackSpace(strField)
{
var evtobj= window.event? event :  strField //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var nTecla=String.fromCharCode(unicode);

   NumDig = strField.value;
   TamDig = NumDig.length;
   TamDig--;
   Contador = 0;
   if ((TamDig >= 0) && (unicode == 8))
    { numer = "";
      for (i = TamDig; (i >= 0); i--){
          if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            {
             Contador++;
			
             if ((Contador == 4) && ((TamDig -i) < 5))
              {numer = ","+numer;
               Contador = 0;
               }
             else if ((Contador == 3) && ((numer.length) > 4))  
              {numer = "."+numer;
               Contador = 0;
              }
			  
             numer = NumDig.substr(i, 1)+numer;
			
            }
			}
			if (numer == "001") 
			    numer="";		
			if ((numer.length) == 3 )
			    numer= "0," + numer;

		strField.value = numer;
      }
}

function FmascTempoReal(strField)
{
var evtobj= window.event? event :  strField //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var nTecla=String.fromCharCode(unicode);
	
if (((unicode) > 47) && ((unicode) < 58))
{
   NumDig = strField.value;
   TamDig = NumDig.length;
   Contador = 0;
   if (TamDig > 1)
      {numer = "";
      for (i = TamDig; (i >= 0); i--){
          if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            {
             Contador++;
             if ((Contador == 2) && ((TamDig -i) < 4))
              {numer = ","+numer;
               Contador = 0;
               }
             else if (Contador == 3)
              {numer = "."+numer;
               Contador = 0;
              }
             numer = NumDig.substr(i, 1)+numer;
            }
           }
      strField.value = numer;
      }
   return(true)}
   else return(false)
}


function isValidData(vfield)
{
if (vfield.value != "")
{
	var diaStr, mesStr, anoStr
	var diaInt, mesInt, anoInt
	var tam, sep1, sep2, verAno

	var thetime=new Date();
	var nmonth=thetime.getMonth();
	var nyear=thetime.getYear();
	var ntoday=thetime.getDate();

	tam = vfield.value.length;

	sep1 = parseInt(vfield.value.indexOf("/", 0));

	if (sep1<0)
	{	alert("A Data digitada deve ter o seguinte formato: DD/MM/AAAA !");
	vfield.value = "";
	vfield.focus();
		return false;	}

	sep2 = parseInt(vfield.value.indexOf("/", sep1+1))

	if (sep2<5)
	{	alert("A Data digitada deve ter o seguinte formato: DD/MM/AAAA !");
	vfield.value = "";
	vfield.focus();
		return false;	}

	verAno = tam-sep2;

	if(verAno < 5 )
	{	alert("As datas devem ser preenchidas utilizando 4 dígitos para informar o Ano (ex.: DD/MM/AAAA)!");
	vfield.value = "";
	vfield.focus();
		return false;	}

	diaStr = vfield.value.substring(0, sep1);

	if(diaStr.substring(0, 1) == "0")
	diaStr = diaStr.substring(1, 2);
	mesStr = vfield.value.substring(sep1+1, sep2); 

	if(mesStr.substring(0, 1) == "0")
	mesStr = mesStr.substring(1, 2);
	anoStr = vfield.value.substring(sep2+1, tam);
	
	diaInt = parseInt(diaStr);
	mesInt = parseInt(mesStr);
	anoInt = parseInt(anoStr);
	
	if ((diaInt <= 0) || (diaInt > 31))
	{	alert("O dia informado não é válido!");
	vfield.value = "";
	vfield.focus();
		return false;	}

	if ((mesInt <= 0) || (mesInt > 12))
	{	alert("O mês informado não é válido!");
	vfield.value = "";
	vfield.focus();
		return false;	}

	if ((mesInt == 4) || (mesInt == 6) || (mesInt == 9) || (mesInt == 11))
	{
		if( diaInt > 30)
		{	alert("O mês informado não possui mais de 30 dias!");
		vfield.value = "";
		vfield.focus();
			return false;	}
	}

	if (mesInt == 2)
	{
		if ((anoInt % 4 == 0) && ( (anoInt % 100 != 0) || (anoInt % 400 == 0)))
		{
			if (diaInt > 29)
			{	alert("O mês informado não possui mais de 29 dias!");
			vfield.value = "";
			vfield.focus();
				return false;	}
		}
		else
		{
			if(diaInt > 28)
			{	alert("O mês informado não possui mais de 28 dias!");
			vfield.value = "";
			vfield.focus();
				return false;	}
		}
		return true;
	} 

	if (vfield.name == "DtOcorrencia" || vfield.name == "DtVoo") {
		if (anoInt < 1980)
		{	alert("O ano informado deve ser maior que 1980!");
			vfield.value = "";
			vfield.focus();
			return false;	}
	}
	
	if (anoInt < nyear)
	{	alert("O ano informado não pode ser menor que o ano atual!");
		vfield.value = "";
		vfield.focus();
		return false;	
	}
		
	if (anoInt == nyear)
	{
		if (mesInt < nmonth+1)
		{	alert("A data informada não pode ser menor que a data atual!");
		vfield.value = "";
		vfield.focus();
			return false;	}
		if (mesInt == nmonth+1)
		{
			if (diaInt < ntoday)
			{
			alert("A data informada não pode ser menor que a data atual!");
			vfield.value = "";
			vfield.focus();
				return false;
			}
		}	
	}		
	return true;
}
}
function ajustar_data(input)
  {

  input.maxLength = 10;
  if ((event.keyCode<48)||(event.keyCode>57)) {event.returnValue = false; }
  else { if ((input.value.length==2)||(input.value.length==5)) input.value=input.value + "/";
  }
}

function ajustar_hora(input)
  {

  input.maxLength = 8;
  if ((event.keyCode<48)||(event.keyCode>57)) {event.returnValue = false; }
  else { if ((input.value.length==2)||(input.value.length==5)) input.value=input.value + ":";
  }
}

function emailCheck (emailStr,voltafocus) {
if (emailStr!=''){	
var checkTLD=1;
var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
//alert("Email address seems incorrect (check @ and .'s)");
alert("Endereço de email parece incorreto (verifique @ e .'s)");
voltafocus.focus();
return false;
}
var user=matchArray[1];
var domain=matchArray[2];
for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
//alert("Ths username contains invalid characters.");
alert("O nome de usuário contém caracteres inválidos.");
voltafocus.focus();
return false;
  }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
//alert("Ths domain name contains invalid characters.");
alert("O nome de domínio contém caracteres inválidos.");
voltafocus.focus();
return false;
  }
}
if (user.match(userPat)==null) {
//alert("The username doesn't seem to be valid.");
alert("O nome de usuário não parece ser válido.");
voltafocus.focus();
return false;
}
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
//alert("Destination IP address is invalid!");
alert("Endereço de IP é inválido!");
voltafocus.focus();
return false;
  }
}
return true;
}
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
//alert("The domain name does not seem to be valid.");
alert("O nome de domínio não parece ser válido.");
voltafocus.focus();
return false;
  }
}
if (checkTLD && domArr[domArr.length-1].length!=2 &&
domArr[domArr.length-1].search(knownDomsPat)==-1) {
//alert("The address must end in a well-known domain or two letter " + "country.");
alert("O endereço deve terminar num dominio conhecido ou duas letras " + "país.");
voltafocus.focus();
return false;
}
if (len<2) {
//alert("This address is missing a hostname!");
alert("Este endereço carece de um hostname!");
voltafocus.focus();
return false;
}
return true;
};
}


function TESTA(CNUMB,CTYPE)
{
  if(Verify(CNUMB, CTYPE))
  { }
  else { 
   if (CNUMB!=''){
    alert(CTYPE+" inválido!");
	 document.validcnpjcpf.value = 1;
	}else{
 	 document.validcnpjcpf.value = 0;	
	};
  }
  return true;
}

function ClearStr(str, char)
{
  while((cx=str.indexOf(char))!=-1)
  { str = str.substring(0,cx)+str.substring(cx+1); }
  return(str);
}

function ParseNumb(c) 
{
  c=ClearStr(c,'-');
  c=ClearStr(c,'.');
  c=ClearStr(c,'/');
  if((parseFloat(c) / c != 1))
  {
    if(parseFloat(c) * c == 0)
    { return(c); }
    else
    { return(0); }
  }
  else
  { return(c); }
}

function Verify(CNUMB,CTYPE)
{
  CNUMB=ParseNumb(CNUMB)
  	if (CNUMB == "00000000000" || CNUMB == "11111111111" ||
		CNUMB == "22222222222" ||	CNUMB == "33333333333" || CNUMB == "44444444444" ||
		CNUMB == "55555555555" || CNUMB == "66666666666" || CNUMB == "77777777777" ||
		CNUMB == "88888888888" || CNUMB == "99999999999")
	return false;

  if(CNUMB == 0)
  { return(false); }
  else
  {
    g=CNUMB.length-2;
    if(TestDigit(CNUMB,CTYPE,g))
    {
      g=CNUMB.length-1;
      if(TestDigit(CNUMB,CTYPE,g))
      {	return(true); }
      else
      { return(false); }
    }
    else
    { return(false); }
  }
}

function TestDigit(CNUMB,CTYPE,g)
{
  var dig=0;
  var ind=2;
  for(f=g;f>0;f--)
  {
    dig+=parseInt(CNUMB.charAt(f-1))*ind;
    if (CTYPE=='CNPJ')
    { if(ind>8) {ind=2} else {ind++} }
    else
    { ind++ }
  }
  dig%=11;
  if(dig<2)
  { dig=0; }
  else
  { dig=11-dig; }
  if(dig!=parseInt(CNUMB.charAt(g)))
  { return(false); }
  else
  { return(true); }
}


function ajustar_cpf(input,tamanho)
{
	input.maxLength = tamanho;
	if ((event.keyCode<48)||(event.keyCode>57))
	  { event.returnValue =false; }
	 else
	  { 
	    if (tamanho == 14)
		{
		    if((input.value.length==3)||(input.value.length==7))
		      { input.value=input.value + "." ; }
		    else
		      {
		        if(input.value.length==11)
			  {  input.value=input.value + "-" ; }
		      }
		}
	    if (tamanho == 18) 
		{
		    if((input.value.length==2)||(input.value.length==6))
	  	      { input.value=input.value + "." ; }
		    if(input.value.length==10)
	  	      { input.value=input.value + "/" ; }
		    else
		      {
		        if(input.value.length==15)
		          { input.value=input.value + "-" ; }
		      }
		}
	  }
}
///---sidinei
function selecione(){
 linha = "window.open('tmx011a.asp'";
 linha = linha + ",'Pessoal','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,"
 linha = linha + "resizable=no,width=320,height=320,top=20,left=450')";
 eval(linha); 
};
function openlink(id){
  if (id!=''){
    aguarde(true);
    window.location.href=id;	  
  };	
}
function logoff(Id){
var thetime=new Date();	
 if (Id =='1'){ 
  if (confirm('Deseja sair do sistema ?')){	 
    popup('tmxlogoff.asp?acao=LOGOFF&dummy='+thetime,262,150);

  };
	}else{
		window.location.href='../default.asp';
	};
}  

function login(){
var trataErro = 0;
  if ((document.getElementById('txemail').value=='')&&(trataErro==0)&&(document.getElementById('IdErro').value==0)){
   alert('É necessário informar o e-mail...!');
   document.getElementById('txemail').focus();
   trataErro=1;
  }   
  if ((document.getElementById('cdsenha').value=='')&&(trataErro==0)&&(document.getElementById('IdErro').value==0)){
   alert('É necessário informar a senha...!');
   document.getElementById('cdsenha').focus();
   trataErro=1;
  }   
  if (trataErro==0){
    document.getElementById("frmlogin").submit();
  };	
};

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
	  case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

function validaCNPJ(val_cnpj,ref) {
	CNPJ = val_cnpj;	
//	CNPJ = document.validacao.CNPJID.value;
	erro = new String;

	if (CNPJ.length < 18){
		erro += "É necessario preencher corretamente o número do CNPJ! ";
		var volta = "S"
	}
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
	if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! ";
	}
	//substituir os caracteres que não são números
	if(document.layers && parseInt(navigator.appVersion) == 4){
		x  = CNPJ.substring(0,2);
		x += CNPJ.substring (3,6);
		x += CNPJ.substring (7,10);
		x += CNPJ.substring (11,15);
		x += CNPJ.substring (16,18);
		CNPJ = x; 
	} else {
		CNPJ = CNPJ.replace (".","");
		CNPJ = CNPJ.replace (".","");
		CNPJ = CNPJ.replace ("-","");
		CNPJ = CNPJ.replace ("/","");
	}
	var nonNumbers = /\D/;
	
	if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! "; 
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		
		for (i=0; i<12; i++){
			a[i] = CNPJ.charAt(i);
			b += a[i] * c[i+1];
		}
	
		if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
			b = 0;
			for (y=0; y<13; y++) {
				b += (a[y] * c[y]); 
			}
		
		if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
			erro +="Dígito verificador com problema!";
		}
		
		if (erro.length > 0){
			if (volta != "S"){
				alert(erro);
				document.getElementById(ref).value="";
				document.getElementById(ref).focus();
			}
			return true;
		} else {
			alert("CNPJ valido!");
			return true;
		}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// AJUSTA E VERIFICA CPF OU CNPJ
// COMANDO CPF: onKeyPress="Javascript: ajustar_cpf(this,14);" onBlur="javascript:TESTA(this.value, 'CPF');"
// FORMATO CPF: 000.000.000-00

function validaCPF(CNUMB,CTYPE,ref){
  if (CNUMB.length != 0){
	  if(Verify(CNUMB, CTYPE))
	  { }
	  else
	  { alert(CTYPE+" inválido!");
		document.getElementById(ref).value="";
		document.getElementById(ref).focus(); }
  }
  return;
}

function Verify(CNUMB,CTYPE)
{
  CNUMB=ParseNumb(CNUMB)
  	if (CNUMB == "00000000000" || CNUMB == "11111111111" ||
		CNUMB == "22222222222" || CNUMB == "33333333333" || CNUMB == "44444444444" ||
		CNUMB == "55555555555" || CNUMB == "66666666666" || CNUMB == "77777777777" ||
		CNUMB == "88888888888" || CNUMB == "99999999999")
	return false;

  if(CNUMB == 0)
  { return(false); }
  else
  {
    g=CNUMB.length-2;
    if(TestDigit(CNUMB,CTYPE,g))
    {
      g=CNUMB.length-1;
      if(TestDigit(CNUMB,CTYPE,g))
      {	return(true); }
      else
      { return(false); }
    }
    else
    { return(false); }
  }
}

function formata(campo, mask, evt) { 
 if(document.all) { // Internet Explorer 
    key = evt.keyCode; } 
    else{ // Nestcape 
       key = evt.which; 
     } 

 string = campo.value;  
 i = string.length;

 if (i < mask.length) {
  if (mask.charAt(i) == '§') {
       return (key > 47 && key < 58);
      } else {
       if (mask.charAt(i) == '!') {  return true;  }
   for (c = i; c < mask.length; c++) {
         if (mask.charAt(c) != '§' && mask.charAt(c) != '!')
         campo.value = campo.value + mask.charAt(c);
      else if (mask.charAt(c) == '!'){
                return true;
       } else {
         return (key > 47 && key < 58);
          }
       }
    }
  } else return false;
}


