// JavaScript Document
function mascCpf(v){
    v=v.replace(/\D/g,'')
    v=v.replace(/(\d{3})(\d)/,'$1.$2')
    v=v.replace(/(\d{3})(\d)/,'$1.$2')
    v=v.replace(/(\d{3})(\d{1,2})$/,'$1-$2')
    return v
}

function mascCnpj(v){
    v=v.replace(/\D/g,'')
    v=v.replace(/^(\d{2})(\d)/,'$1.$2')            
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,'$1.$2.$3')
    v=v.replace(/\.(\d{3})(\d)/,'.$1/$2')
    v=v.replace(/(\d{4})(\d)/,'$1-$2')
    return v
}
	function trim(campo){
	  var retValue = campo;
	  var ch = retValue.substring(0, 1);
	   while (ch == " ") {
		  retValue = retValue.substring(1, retValue.length);
		  ch = retValue.substring(0, 1);
	   }
	   ch = retValue.substring(retValue.length-1, retValue.length);
	   while (ch == " ") {
		  retValue = retValue.substring(0, retValue.length-1);
		  ch = retValue.substring(retValue.length-1, retValue.length);
	   }
	   while (retValue.indexOf("  ") != -1) { 
		  retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
	   }
	   return retValue;
	}
	
	function valida_cartao()	{
	
		var numero  = document.form1.cartao;

		if (numero.value.length < 16)	{
			alert("Número do cartão precisa ter 16 dígitos.");
			numero.value = "";
			numero.focus();
		}else{
			document.form1.submit();	
		}
	}
	
	function submeter()	{
		document.visaVBV.submit();	
	}
	
	function habilita_qtd_parcelas()	{
		var pagamento = document.form1.cod_tipopagto.value;

		if	(pagamento == 2)	{
			document.form1.qtdParc.style.display = "block";
		}else{
			document.form1.qtdParc.style.display = "none";
		}
	
	}
	
	function valida_produto(){
		var nome  = document.form1.nome;
		var desc  = document.form1.descricao;
		var valor = document.form1.valor;

		if (trim(nome.value) == ""){
			alert("Nome do produto precisa ser informado.");
			nome.focus();
		}else if (trim(desc.value) == ""){
			alert("Descrição do produto precisa ser informado.");
			desc.focus();
		}else if (trim(valor.value) == ""){
			alert("Valor do produto precisa ser informado.");
			valor.focus();
		}else{
			document.form1.submit();	
		}
	}
	
	function mascaraMoeda(fld, milSep, decSep, e) {
		var sep = 0;
		var key = '';
		var i = j = 0;
		var len = len2 = 0;
		var strCheck = '0123456789';
		var aux = aux2 = '';
		var whichCode = (window.Event) ? e.which : e.keyCode;
		if (whichCode == 13) return true;  // Enter
		if (whichCode == 8) return true;  // Delete (Bug fixed)
		if (whichCode == 9) return true;  // Tab
		
		if (whichCode == 0) return true; // em fase de teste
		
		key = String.fromCharCode(whichCode);  // Get key value from key code
		if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
		len = fld.value.length;
		for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
		aux = '';
		for(; i < len; i++)
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
		aux += key;
		len = aux.length;
		if (len == 0) fld.value = '';
		if (len == 1) fld.value = '0'+ decSep + '0' + aux;
		if (len == 2) fld.value = '0'+ decSep + aux;
		if (len > 2) {
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) {
		if (j == 3) {
		aux2 += milSep;
		j = 0;
		}
		aux2 += aux.charAt(i);
		j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - 2, len);
		}
		return false;
	}
	  function soNums(e,args){         
		// Função que permite apenas teclas numéricas e  
		// todos os caracteres que estiverem na lista 
		// de argumentos. 
		// Deve ser chamada no evento onKeyPress desta forma 
		//  onKeyPress ="return (soNums(event,'0'));" 
		// caso queira apenas permitir caracters como por exemplo um campo que só aceite valores em Hexadecimal (de 0 a F) usamos 
		//  onKeyPress ="return (soNums(event,'AaBbCcDdEeFf'));" 
	
		/* Esta parte comentada é a que testei exaustivamente e garanto que funciona em praticamente todos os browsers 
			var evt='';// devido a um warning gerado pelo Console de Javascript que "enxergava" uma redeclaração de "evt" decidi declará-la uma vez e alterar ser valor posteriormente  
	
			if (document.all){evt=event.keyCode;} // caso seja IE 
			else{evt = e.charCode;}    // do contrário deve ser Mozilla 
			O código a seguir teste apenas em FireFox e Internet Explorer 6 e funcionou perfeitamente. Caso vc tenha algum problema com esta função por favor entre em contato 
		*/ 
			var evt = (e.keyCode?e.keyCode:e.charCode); 
			var chr = String.fromCharCode(evt);    // pegando a tecla digitada 
			// Se o código for menor que 20 é porque deve ser caracteres de controle 
			// ex.: <ENTER>, <TAB>, <BACKSPACE> portanto devemos permitir 
			// as teclas numéricas vão de 48 a 57 
			return (evt <20 || (evt >47 && evt<58) || (args.indexOf(chr)>-1 ) ); 
		} 
	
	function valida_usuario(){
		var nome  = document.form1.nome;
		var login = document.form1.login;
		var senha = document.form1.senha;
		var confs = document.form1.conf_senha;
		var tipo  = document.form1.tipo;
		
		var retorna;
		
		if (trim(nome.value) == ""){
			alert("Nome do usuário precisa ser informado.");
			nome.focus();
		}else if (trim(login.value) == ""){
			alert("Login do usuário precisa ser informado.");
			login.focus();
		}else if (trim(senha.value) == ""){
			alert("Senha do usuário precisa ser informado.");
			senha.focus();
		}else if (trim(confs.value) == ""){
			alert("Confirmação da Senha do usuário precisa ser informado.");
			confs.focus();
		}else if (trim(tipo.value) == ""){
			alert("Tipo do usuário precisa ser informado.");
			tipo.focus();
		}else{
			retorna = confimarSenha(senha, confs);
			if (retorna){
			  document.form1.submit();
			}
		}
	}
	
	function apagar_lista(){
		var acaoexc = document.form1.acaoexc.value;	
	
		if (numeroChecados() == 0){	
			alert("Selecione apenas um registro para exclusao.");
		}else{
		  if(confirm("Confirma a Exclusao do(s) Registro(s)?")){
			mudarAction("form1", acaoexc);
			document.form1.submit();
		  }
		}
	}

	function reenviar_lista(){
		var acao = document.form1.acaoreenviar.value;
	
		if (numeroChecados() == 0){	
			alert("Selecione apenas um registro o reenvio do e-mail do boleto.");
		}else{
		  if(confirm("Confirma o envio do(s) E-mail(s) do(s) boleto(s)?")){
			mudarAction("form1", acao);
			document.form1.submit();
		  }
		}
	}
	
	// verifica o numero de checkboxs checados
	function numeroChecados() {
		var aux = 0;
		for (i = 0; i < document.forms[0].length; i++) {
			if (document.forms[0].elements[i].type == 'checkbox' && document.forms[0].elements[i].id != 'dbListCheckAll_1') {
				if (document.forms[0].elements[i].checked) {
					aux += 1;
				}
			}
		}
		return aux;
	}
	
	function valida_lista(acao){
//		var acao = document.form1.acao.value;
		if (numeroChecados() != 1){
			alert("Selecione apenas um Checkbox para alterar.");
		}else{
			mudarAction("form1", acao);
			document.form1.submit();
		}
	}

	function valida_visualiza(acao){
		if (numeroChecados() != 1){
			alert("Selecione apenas um Checkbox visualizar o pagamento.");
		}else{
	//		window.open('visualiza_pagto.php?id=$id','mywindow', 'menubar=0,resizable=1,width=613,height=500');			
			document.form1.target = "_blank";
			mudarAction("form1", "../boleto/boleto.php");
			document.form1.submit();
		}
	}


	function mudarAction(form,action) {
		document.getElementById(form).action = action;
	}

	function Voltar(){
	  window.history.go(-1);
	}
	
	function VoltarDuasPaginas(){
	  window.history.go(-2);
	}
	
	function valida_login() {
	  var login = document.form1.login;
	  var senha = document.form1.senha;  
	  
	  if (trim(login.value) == ""){
		alert("Login do usuário precisa ser informado.");
		login.focus();
	  }else if (trim(senha.value) == ""){
		alert("Senha do usuário precisa ser informado.");
		senha.focus();  
	  }else{
		document.form1.submit(); 
	  }
	}

	function confimarSenha(campo1,campo2) {
		var val1 = campo1.value;
		var val2 = campo2.value;
		 if (val1.length >= 6) {
			if (val1 != val2) {
				alert('A senha não confere');
				campo2.value='';
				campo1.value='';
				campo1.focus();
				return false;
			} else {
				return true;
			}
		} else {
				alert('Verifique o número de caracteres da senha');
				campo2.value='';
				campo1.value='';
				campo1.focus();
				return false;
		}
	}

	function maiuscula(campo){
		var val = campo.value;
			campo.value = val.toUpperCase();
	}

	function soNumero( campo ) {
    	if(((event.keyCode < 48) || (event.keyCode > 57)) && event.KeyCode != 8 && event.KeyCode !=13  ) {
        	campo.focus();
	        event.returnValue = false;
    	}
	}
	
	function autoFone(campo){
		var data = campo.value;
	    var ndata = '';
		ndata = ndata + data;
		if(event.keyCode == 8) { ndata = ""; }
		if (ndata.length == 2) {
		   ndata = ndata + '-';
			campo.value = ndata;
		}
		if (ndata.length == 7) {
		   ndata = ndata + '.';
			campo.value = ndata;
		}
	}
	


	function autoData( campo ) {
	    texto = campo.value;
		if(event.keyCode == 8) { texto = ""; }
    	if( texto.length == 2 ) {
	        texto += '/';
    	    campo.value = texto;
	    } else if( texto.length == 5 ) {
	        texto += '/';
	        campo.value = texto;
    	}
	}

	function autoCep( campo ) {
		texto = campo.value;
		if(event.keyCode == 8) { texto = ""; }
		if(texto.length == 5 ) {
			texto += "-";	
		}
		campo.value = texto;
	}


//Fazendo validações
	function validarVazio( campo, mensagem ) {
    	if( campo.value == '' ) {
	        alert(mensagem );
    	    campo.focus();
        	return false;
	    } else {
    	    return true;
	    }
	}

	function validarData( campo ) {
		data = campo.value;
		resultado = true;
	
		if( data != "" ) {
			if( data.charAt(0) != '0' ) {
				dia = data.charAt(0) + data.charAt(1);
			} else {
				dia =data.charAt(1);
			}
			dia = parseInt(dia);
	
			if( data.charAt(3) != "0" ) {
				mes = data.charAt(3) + data.charAt(4);
			} else {
				mes = data.charAt(4);
			}
			mes = parseInt(mes);
			
			if( data.charAt(6) != '0' && data.charAt(7) != '0' && data.charAt(8) != '0' ) {
				ano = data.charAt(7) + data.charAt(8) + data.charAt(9);
			} else if( data.charAt(7) != '0' && data.charAt(8) != '0' ) {
				ano = data.charAt(8) + data.charAt(9);
			} else if( data.charAt(8) != '0' ) {
				ano = data.charAt(9);
			} else {
				ano = data.charAt(6) + data.charAt(7) + data.charAt(8) + data.charAt(9);
			}
			ano = parseInt(ano);
	
			if( campo.value.length != 10 ) {
				alert( "Data Inválida!\nVerifique a quantidade de dígitos" );
				campo.focus();
				resultado = false;
			} else if( (mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia > 30 ) {
				alert( "Data Inválida!\nEsse mês não permite dia 31" );
				campo.focus();
				resultado = false;
			} else if( mes == 2 && dia > 29 ) {
				alert( "Data Inválida!\nFevereiro não permite dia com esse valor" );
				campo.focus();
				resultado = false;
			} else if( campo.value.charAt( 2 ) != '/' || campo.value.charAt( 5 ) != '/' ) {
				alert( "Data Inválida!\nVerifique o formato da data" );
				campo.focus();
				resultado = false;
			} else if( dia < 1 || dia > 31 ) {
				alert( "Data Inválida!\nVerifique o valor do dia" );
				campo.focus();
				resultado = false;
			} else if( mes < 1 || mes > 12 ) {
				alert( "Data Inválida!\nVerifique o valor do mês" );
				campo.focus();
				resultado = false;
			} else if( ano < 1 ) {
				alert( "Data Inválida!\nVerifique o valor do ano" );
				campo.focus();
				resultado = false;
			}
			return resultado;
		}
	}
	
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function finaliza_pedido(testeVisa){
  if(confirm("Confirma o Fechamento do Pedido ?")){
	  document.location.href="finalizar.php"+testeVisa;
  }
}

function valida_finaliza(){
	var tipo = document.form1.cod_tipopagto;
	var nome = document.form1.nome;
	var cpf  = document.form1.cpf;
	var end  = document.form1.endereco;
	var cnpj = document.form1.cnpj;
	var cid  = document.form1.cidade;
	var cep  = document.form1.cep;
	var email  = document.form1.email;
	var fone  = document.form1.fone;
	
	var pessoa = document.getElementsByName('pessoa');

	if (trim(tipo.value) == ""){
		alert("Tipo do Pagamento precisa ser informado.");
		tipo.focus();
		return false;
	}else if (trim(nome.value) == ""){
		alert("Nome do Comprador precisa ser informado.");
		nome.focus();
		return false;
	}else if (trim(end.value) == ""){
		alert("Endereço do Comprador precisa ser informado.");
		end.focus();
		return false;
	}else if (trim(cid.value) == ""){
		alert("Cidade precisa ser informada.");
		cid.focus();
		return false;
	}else if (trim(cep.value) == ""){
		alert("Cep precisa ser informado.");
		cep.focus();
		return false;
	}else if (trim(email.value) == ""){
		alert("E-mail precisa ser informado.");
		email.focus();
		return false;
	}else if (trim(fone.value) == ""){
		alert("Telefone precisa ser informado.");
		fone.focus();
		return false;
	}else if (pessoa[0].checked){
		if (trim(cpf.value) == "") {
			alert("CPF do Comprador precisa ser informado.");
			cpf.focus();
			return false;
		}else if(!isCPF(cpf.value)){
			alert('CPF inválido');
			cpf.focus();
			return false;
		}
	}else if(pessoa[1].checked){
		if(trim(cnpj.value) == ""){
			alert("CNPJ precisa ser iformado");
			cnpj.focus();
			return false;
		}else if(!isCNPJ(cnpj.value)){
			cnpj.focus();
			return false;
		}
	}	
	
	cpf.disabled = false;
	cnpj.disabled = false;
	
	document.form1.submit();
}

function valida_email(campo){
   	if (campo.value !=''){
       	if ( campo.value.indexOf('@')==-1 ||
           	 campo.value.indexOf('.')==-1 ||
             campo.value.indexOf(' ')!=-1 ||
   	         campo.value.indexOf('@.')!=-1 ||
       	     campo.value.indexOf('.@')!=-1 ||
           	 campo.value.length<6) {
	         alert('E-mail inválido!');
	         campo.select();
         		 return false;
        }
   	}
}
	
function TelefoneFormat(Campo, e){
	var key = '';
	var len = 0;
	var strCheck = '0123456789';
	var aux = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	
	if (whichCode == 13 || whichCode == 8 || whichCode == 0)
	{
		return true;  // Enter backspace ou FN qualquer um que não seja alfa numerico
	}
	key = String.fromCharCode(whichCode);
	if (strCheck.indexOf(key) == -1){
		return false;  //NÃO E VALIDO
	}
	
	aux =  Telefone_Remove_Format(Campo.value);
	
	len = aux.length;
	if(len>=10){
		return false;	//impede de digitar um telefone maior que 10
	}
	aux += key;
	
	Campo.value = Telefone_Mont_Format(aux);
	return false;
}

function  Telefone_Mont_Format(Telefone){
	var aux = len = '';
	
	len = Telefone.length;
	if(len<=9){
		tmp = 5;
	}else{
		tmp = 6;
	}
	
	aux = '';
	for(i = 0; i < len; i++)	{
		if(i==0){
			aux = '(';
		}
		aux += Telefone.charAt(i);
		if(i+1==2){
			aux += ')';
		}
		
		if(i+1==tmp){
			aux += '-';
		}
	}
	return aux ;
}

function  Telefone_Remove_Format(Telefone){
	var strCheck = '0123456789';
	var len = i = aux = '';
	len = Telefone.length;
	for(i = 0; i < len; i++)
	{
		if (strCheck.indexOf(Telefone.charAt(i))!=-1)
		{
			aux += Telefone.charAt(i);
		}
	}
	return aux;
}

function auto_tab(campo1,campo2,qtd) {
  var val = campo1.value;
  if (val.length == qtd) {
    campo2.focus();
  }
}

	function auto_data(campo) {
	    texto = campo.value;
    	if( texto.length == 2 ) {
	        texto += '/';
    	    campo.value = texto;
	    } else if( texto.length == 5 ) {
	        texto += '/';
	        campo.value = texto;
    	}
	}


//Verifica se a data é válida
function valida_data(campo){	
	if (trim(campo.value) != ""){
		var retorna;
		retorna = validDate(campo.value, 'd/m/a');			
		if (retorna == false) {
			alert("Data inválida.");
			campo.value = "";		
			campo.focus();
		}
	}
}

function validDate(date,formatDate){
    var ER = /[\/ -]/;
    formatDate = formatDate.split(ER);
    date = date.split(ER);
    var month = [31,28,31,30,31,30,31,31,30,31,30,31];
    var a,m,d;
    for(x=0;x< formatDate.length;x++){
        /*
         onde (a,m,d) representando (a)no, (m)es, (d)ia será preenchido com o respectivo
         valor do índice em que se encontra na matriz
         ------------------------------------------------------------------------------    
         Where (a, m, d) representing year, month, day will be filled with the value of
         the index in which it is in the matrix
        */
        eval(formatDate[x]+"="+x+";");
    }
    if(bissexto(date[a]))
        month[1] = 29;
    var ER_day;
    switch(month[date[m]-1]){
        case 28:
            ER_day = "(1[\\d]|2[0-8])";
            break;
        case 29:
            ER_day = "[1-2][\\d]";
            break;
        case 30:
            ER_day = "([1-2][\\d]|30)";
            break;
        case 31:
            ER_day = "([1-2][\\d]|3[0-1])";
            break;
    }
    var ER_2 = new RegExp("(0[1-9]|"+ER_day+")\/(0[1-9]|1[0-2])\/([0-2][\\d]{3})");
    date = date[d]+"/"+date[m]+"/"+date[a];
    return ER_2.test(date);
}

function bissexto(year){
    return ((year%4)==0)?true:false;
}

function valida_entrega(){
	var acao = document.form1.acaoentregar.value;

	if (numeroChecados() == 0){	
		alert("Selecione no mínimo um registro.");
	}else{
	  if(confirm("Entregar pedido ?")){
		mudarAction("form1", acao);
		document.form1.submit();
	  }
	}
}

function atualiza_pagto(id, nome){
	var acao = document.form1.acaopagto.value;
	
	if (numeroChecados() == 0){	
		alert("Selecione apenas um pagamento para mudança de status.");
	}else{
	  if(confirm("Confirma o(s) pagamento(s) do(s) boleto(s)?")){
		mudarAction("form1", acao);
		document.form1.submit();
	  }
	}
}

function cliqueTR(objId, TR){
	var obj = document.getElementById(objId);
	obj.checked = (obj.checked)?false:true;
	TR.style.backgroundColor = (obj.checked)?'#FFFFFF':'#E5E5E5';
//	TR.style.color = (obj.checked)?'#FFFFFF':'#E5E5E5';	
}

function cliqueCheckboxLinha(objId, trId){
	var obj = document.getElementById(objId);
	obj.checked = (obj.checked)?false:true;

	var tr = document.getElementById(trId);		//alert(objId);
	tr.style.backgroundColor = (obj.checked)?'#FFFFFF':'#E5E5E5';
//	TR.style.color = (obj.checked)?'#FFFFFF':'#E5E5E5';	
}

//FunÃ§Ã£o de validaÃ§Ã£o de CPF
function isCPF(st) {
if (st == "")
	return (false);
	l = st.length;
	//aleterado para se usuÃ¡rio nÃ£o digitar os zeros na frente do CPF, completar sozinho
	if ((l == 9) || (l == 8)) {
		for (i = l ; i < 10; i++) {
			st = '0' + st
		}
	}
	l = st.length;
	st2 = "";
	for (i = 0; i < l; i++) {
		caracter = st.substring(i,i+1);
		if ((caracter >= '0') && (caracter <= '9'))
			st2 = st2 + caracter;
		}
		if ((st2.length > 11) || (st2.length < 10))
			return (false);
		if (st2.length==10)
			st2 = '0' + st2;
		digito1 = st2.substring(9,10);
		digito2 = st2.substring(10,11);
		digito1 = parseInt(digito1,10);
		digito2 = parseInt(digito2,10);
		sum = 0; mul = 10;
		for (i = 0; i < 9 ; i++) {
			digit = st2.substring(i,i+1);
			tproduct = parseInt(digit ,10) * mul;
			sum += tproduct;
			mul--;
		}
		dig1 = ( sum % 11 );
		if ( dig1==0 || dig1==1 )
			dig1=0;
		else
			dig1 = 11 - dig1;
		if (dig1!=digito1)
			return (false);
			sum = 0;
			mul = 11;
			for (i = 0; i < 10 ; i++) {
				digit = st2.substring(i,i+1);
				tproduct = parseInt(digit ,10)*mul;
				sum += tproduct;
				mul--;
			}
			dig2 = (sum % 11);
			if ( dig2==0 || dig2==1 )
				dig2=0;
			else
				dig2 = 11 - dig2;
			if (dig2 != digito2)
				return (false);
		return (true);
}

function isCNPJ(str) {
	CNPJ = str;
    erro = new String;
    if (CNPJ.length < 18) 
		erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
    if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
	    if (erro.length == 0) 
			erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
    }
    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! \n\n";
	var a = [];
	var b = new Number;
    var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
    for (i=0; i<12; i++){
	    a[i] = CNPJ.charAt(i);
        b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
	    b = 0;
        for (y=0; y<13; y++) {
        b += (a[y] * c[y]);
	}
    if ((x = b % 11) < 2) { 
		a[13] = 0; 
	} else { 
		a[13] = 11-x; 
	}
    if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
	    erro +="Dígito verificador com problema!";
    }
    if (erro.length > 0){
	    alert(erro);
        return false;
	}
    return true;
}

function desabilita(idObjDisabled){
	document.getElementById(idObjDisabled).disabled = true;
}

function habilita(idObjEnable){
	document.getElementById(idObjEnable).disabled = false;
}
