
	function cancelar(tipo) {
		window.close();
	}
	
	function carregar_tela_inserir(tipo, url, largura, altura) {
		urlMontada = null;
		if (url.indexOf('?') != -1) {
			urlMontada = url + '&operacao' + tipo + '=0';
		} else {
			urlMontada = url + '?operacao' + tipo + '=0';
		}
		janela = abrirJanela(urlMontada, tipo, largura + 'px', altura + 'px');
		if (window.focus) {
			janela.focus()
		}		
	}
	
	function addemails(id, tipo, url, largura, altura) {
		urlMontada = url + '?idUsuario=' + id;			
		janela = abrirJanela(urlMontada, tipo, largura + 'px', altura + 'px');
		if (window.focus) {
			janela.focus()
		}		
	}
	
	function carregar_tela_inserir_especifica(tipo, id, url, largura, altura) {
		urlMontada = url + '?operacao' + tipo + '=0&idApoio=' + id;			
		janela = abrirJanela(urlMontada, tipo, largura + 'px', altura + 'px');
		if (window.focus) {
			janela.focus()
		}		
	}
	
	function carregar_tela_editar(tipo, id, url, largura, altura) {
		urlMontada = url + '?operacao' + tipo + '=2&idApoio=' + id;			
		janela = abrirJanela(urlMontada, tipo, largura + 'px', altura + 'px');
		if (window.focus) {
			janela.focus()
		}
	}
	
	function carregar_tela_visualizacao(tipo, id, url, largura, altura) {
		urlMontada = url + '?idApoio=' + id;			
		janela = abrirJanela(urlMontada, tipo, largura + 'px', altura + 'px');
		if (window.focus) {
			janela.focus()
		}
	}	
		
	function inserir(tipo) {
		form = document.forms['form' + tipo + 'Aquisicao'];
		if (tipo == 'Classe') { retorno = validarClasse(form); }
		if (tipo == 'Chave') { retorno = validarChave(form); }
		if (tipo == 'MenuSuperior') { retorno = validarMenuSuperior(form, 'menu superior'); }
		if (tipo == 'MenuEsquerdo') { retorno = validarMenuEsquerdo(form, 'menu esquerdo'); }		
		if (tipo == 'Cliente') { retorno = validarCliente(form); }
		if (tipo == 'Device') { retorno = validarDevice(form); }
		if (tipo == 'Usuario') { 
			retorno = validarUsuario(form); 
			if (retorno) {
				if (form.senha.value == "") {
					alert('Senha em branco.');
					form.senha.focus();
					return false;
				}		
				if (form.csenha.value == "") {
					alert('Confirmação de senha em branco.');
					form.csenha.focus();
					return false;
				}	
				if (form.senha.value != form.csenha.value) {
					alert('A senha é incompatível com a confirmação de senha.');
					form.senha.focus();
					return false;
				}
				limpaCaracteres(form.fone, '()-');
				limpaCaracteres(form.celular, '()-');
				limpaCaracteres(form.cep, '.-');
			}
			if (form.notificacao.checked) {
				form.notificacao.value = 1;
			} else {
				form.notificacao.value = 0;
			}			
			if (form.condreplicacao.type == 'checkbox') {
				if (form.condreplicacao.checked) {
					form.replicacao.value = 1;
				} else {
					form.replicacao.value = 0;		
				}
			}
		}
		if (tipo == 'Sn') { retorno = validarSn(form); }
		if (tipo == 'Cambio') { retorno = validarCambio(form); }
		if (tipo == 'Moeda') { retorno = validarMoeda(form); }
		if (tipo == 'Configuracao') { retorno = validarConfiguracao(form); }
		if (tipo == 'Extensoes') { 
			retorno = validarExtensoes(form); 
			// Fragmento respons�vel por tratar o comportamento da senha a ser utilizada
			// se ser� a senha do usu�rio da extens�o ou a senha opcional informada pelo
			// usu�rio			
			if (retorno) {
				if (form.senha.value == "" && form.csenha.value == "") {
					form.suouse.value = 0;
				} else {
					if (form.senha.value != form.csenha.value) {
						retornoAux = confirm("As senhas informadas sao diferentes.\nDeseja assumir a senha do usuario como senha da extensao?");
						if (retornoAux) {
							form.suouse.value = 0;
						} else {
							retorno = false;
						}
					} else {
						form.suouse.value = 1;
					}
				}	
			}
		}
		if (tipo == 'Aliases') { retorno = validarAliases(form); }		
		if (retorno) {
			form.submit();
		}
	}
	
	function limpar(tipo) {
		form = document.forms['form' + tipo + 'Aquisicao'];
		if (tipo == 'Senha') { limparSenha(form); }
	}
	
	function limparSenha(form) {
		form.senhaAtual.value = "";
		form.csenha.value = "";
		form.senha.value = "";
		form.senhaAtual.focus();
	}
	
	function alterar(tipo) {
		form = document.forms['form' + tipo + 'Aquisicao'];
		if (tipo == 'Classe') { retorno = validarClasse(form); }
		if (tipo == 'Chave') { retorno = validarChave(form); }
		if (tipo == 'MenuSuperior') { retorno = validarMenuSuperior(form, 'menu superior'); }
		if (tipo == 'MenuEsquerdo') { retorno = validarMenuEsquerdo(form, 'menu esquerdo'); }
		if (tipo == 'Cliente') { retorno = validarCliente(form); }
		if (tipo == 'Device') { retorno = validarDevice(form); }
		if (tipo == 'Usuario') { 
			habilitarCamposFormulario(form);
			retorno = validarUsuario(form);
			if (!retorno) {
				// desabilitarCamposFormulario(form);
				// form.senha.disabled = false;
				// form.csenha.disabled = false;
				// form.senhaAtual.disabled = false;
				//form.operacao.disabled = false;
				form.device.disabled = true;
			}
			if (form.notificacao.checked) {
				form.notificacao.value = '1';
			} else {
				form.notificacao.value = '0';
			}
			if (form.condreplicacao.type == 'checkbox') {
				if (form.condreplicacao.checked) {
					form.replicacao.value = 1;
				} else {
					form.replicacao.value = 0;		
				}
			}
			if (retorno) {
				if (form.senha.value == "" && form.csenha.value == "") {
					form.aon.value = 0;
				} else {
					if (form.senha.value != form.csenha.value) {
						alert('A senha é incompatível com a confirmação de senha.');
						form.senha.focus();
						retorno = false;
					} else {
						form.aon.value = 1;
					}
				}			
				limpaCaracteres(form.fone, '()-');
				limpaCaracteres(form.celular, '()-');
				limpaCaracteres(form.cep, '.-');				
			}
		}		
		if (tipo == 'Sn') { retorno = validarSn(form); }
		if (tipo == 'Cambio') { retorno = validarCambio(form); }
		if (tipo == 'Moeda') { retorno = validarMoeda(form); }
		if (tipo == 'Senha') { retorno = validarSenha(form); }
		if (tipo == 'Configuracao') { retorno = validarConfiguracao(form); }
		if (tipo == 'Extensoes') { 
			retorno = validarExtensoes(form); 
			// Fragmento respons�vel por tratar o comportamento da senha a ser utilizada
			// se ser� a senha do usu�rio da extens�o ou a senha opcional informada pelo
			// usu�rio
			if (retorno) {
				if (form.senha.value == "" && form.csenha.value == "") {
					form.suouse.value = 2;
				} else {
					if (form.senha.value != form.csenha.value) {
						retornoAux = confirm("As senhas informadas sao diferentes.\nDeseja assumir a senha do usuario como senha da extensao?");
						if (retornoAux) {
							form.suouse.value = 0;
						} else {
							retorno = false;
						}
					} else {
						form.suouse.value = 1;
					}
				}
			}
		}
		if (tipo == 'Aliases') { retorno = validarAliases(form); }
		if (retorno) {
			form.submit();
		}
	}
	
	function excluir(tipo, id) {
		resposta = confirm("Deseja realmente confirmar a exclusão?");
		if (resposta) {
			form = document.forms['form' + tipo];
			document.getElementById('operacao' + tipo).value = 4;
			document.getElementById('idApoio').value = id;
			form.submit();
		}
	}
	
	function desativar(tipo, id) {
		resposta = confirm("Deseja realmente confirmar a desativação?");
		if (resposta) {
			form = document.forms['form' + tipo];
			document.getElementById('operacao' + tipo).value = 4;
			document.getElementById('idApoio').value = id;
			form.submit();
		}
	}	
	
	function pagina(pagina, tipo) {
		form = document.forms['form' + tipo];
		document.getElementById('pagina' + tipo).value = pagina;
		form.submit();
	}	
	
	function abrirJanela(url, id, largura, altura) {
		var janela = window.open(url, id, 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=' + largura + ',height=' + altura + ',left=490,top=362');
		return janela;
	}

	/***********************************************/
	/**** Validadores de telas *********************/
	/***********************************************/	
	function validarExtensaoLogo(arquivo) {
		var ext = new Array();
		ext[0] = ".gif";
		
		extensao = arquivo.value;
		posicao = extensao.indexOf(".");
		tamanho = extensao.length;
		extensao = extensao.substring(posicao, tamanho);
		
		var retorno = false;
		
		for (var i = 0; i < ext.length; ++i){
			if (ext[i] == extensao){
				retorno = true;
			}
		}
		
		return retorno;	
	}	
	
	function validarClasse(form) {
		if (trim(form.nome.value) == "") {
			alert('Informe o nome da classe.');
			form.nome.focus();
			return false;
		}
		if (trim(form.descricao.value) == "") {
			alert('Informe a descrição da classe.');
			form.descricao.focus();
			return false;
		}
		return true;
	}	
	
	function validarChave(form) {
		if (trim(form.nome.value) == "") {
			alert('Informe o nome da chave.');
			form.nome.focus();
			return false;
		}
		if (trim(form.descricao.value) == "") {
			alert('Informe a descrição da chave.');
			form.descricao.focus();
			return false;
		}		
		return true;
	}	
	
	function validarMenuSuperior(form, texto_menu) {
		if (trim(form.nome.value) == "") {
			alert('Informe o nome do ' +  texto_menu + '.');
			form.nome.focus();
			return false;
		} 
		if (trim(form.url.value) == "" || !isURL(trim(form.url.value))) {
			alert('Informe uma URL válida para o ' +  texto_menu + '.');
			form.url.focus();
			return false;			
		}
		if (trim(form.chave.value) == "") {
			alert('Informe a chave a ser associada ao ' +  texto_menu + '.');
			form.chave.focus();
			return false;
		}		
		return true;
	}		
	
	function validarMenuEsquerdo(form, texto_menu) {
 		return validarMenuSuperior(form, texto_menu);
	}
	
	function validarCliente(form) {
		limpaCaracteres(form.cnpj, './-');
		if (trim(form.cnpj.value) == "" || !validaCnpj(trim(form.cnpj.value))) {
			alert('Informe um CNPJ válido para o cliente.');
			form.cnpj.focus();		
			return false;
		}
		if (trim(form.nome.value) == "") {
			alert('Informe o nome do cliente.');
			form.nome.focus();
			return false;
		}
		if (trim(form.alias.value) == "") {
			alert('Informe o alias associado ao cliente.');
			form.alias.focus();
			return false;
		}		
		/* if ((trim(form.email.value) == "") || !validaEmail(trim(form.email.value))) {
			alert('email inv�lido.');
			form.email.focus();
			return false;			
		} */
		if (form.siglaCnl.value == '0') {
			alert('Selecione uma localidade.');
			form.siglaCnl.focus();
			return false;			
		}
		// Realiza a limpeza de caracteres de pontua��o que
		// n�o ser�o armazenados
		limpaCaracteres(form.cep, '.-');
		limpaCaracteres(form.fone, '()-');
		limpaCaracteres(form.fax, '()-');
		limpaCaracteres(form.celular, '()-');
		return true;
	}
	
	function validarDevice(form) {
		if(form.cnpj.value == '0') {
			alert('Selecione o cliente associado a device.');
			form.cnpj.focus();
			return false;
		}
		if (trim(form.nome.value) == "") {
			alert('Informe o nome do device.');
			form.nome.focus();
			return false;
		}		
		if (trim(form.ip.value) == "" || !isIP(trim(form.ip.value))) {
			alert('Informe um IP válido para a device.\nExemplo: 200.114.225.63');
			form.ip.focus();
			return false;
		}
		//if (trim(form.dominio.value) == "" || !isURL(trim(form.dominio.value))) {
		//	alert('Informe o dom�nio da device.\nExemplo: http://www.faleok.com.br');
		//	form.dominio.focus();
		//	return false;
		//}		
		if ((trim(form.email.value) == "") || !validaEmail(trim(form.email.value))) {
			alert('email inválido.');
			form.email.focus();
			return false;			
		}
		return true;
	}
	
	function validarUsuario(form) {
		limpaCaracteres(form.cnpj, './-');
		/*if (trim(form.cnpj.value) != "") {
			if (getRadioValue(form.opcaocc) == 'cnpj' && !validaCnpj(trim(form.cnpj.value))) {
				alert('Informe um CNPJ v�lido para o usu�rio.');
				form.cnpj.focus();		
				return false;								
			}
			if (getRadioValue(form.opcaocc) == 'cpf' && !validaCpf(trim(form.cnpj.value))) {
				alert('Informe um CPF v�lido para o usu�rio.');
				form.cnpj.focus();		
				return false;				
			}			
		} else {
			if (getRadioValue(form.opcaocc) == 'cnpj') {
				alert('Informe um CNPJ para o usu�rio.');
			} else {
				alert('Informe um CPF para o usu�rio.');
			}
			form.cnpj.focus();		
			return false;
		}*/
		if (form.tipo != null && form.extensao != null) {
			if ((form.tipo.value != 0 && form.extensao.value == 0) 
				|| (form.tipo.value == 0 && form.extensao.value != 0)) {
				alert('Para associar uma extensão ao usuário, é necessário que seja selecionado\n' + 
					  'o número da extensão e o tipo da extensão');
				form.extensao.focus();
				return false;
			}
		}		
		if (trim(form.nome.value) == "") {
			alert('Informe o nome do usuário.');
			form.nome.focus();
			return false;
		}			
		if(form.device.value == '0') {
			alert('Selecione a device a ser associada ao usuário.');
			form.device.focus();
			return false;
		}		
		if(form.classe.value == '0') {
			alert('Selecione a classe a ser associada ao usuário.');
			form.classe.focus();
			return false;
		}
		if (trim(form.login.value) == "") {// ) || !validaEmail(trim(form.login.value))) {
			alert('Login inválido.');
			form.login.focus();
			return false;			
		}
		return true;
	}
	
	function validarSn(form) {
		if (trim(form.ddd.value) == "" || form.ddd.value.length != 2) {
			alert('DDD inválido.');
			form.ddd.focus();
			return false;
		}
		if (trim(form.snInicio.value) == "" || form.snInicio.value.length != 8) {
			alert('Número inicial da faixa de numeração inválido.');
			form.snInicio.focus();
			return false;
		}
		if (trim(form.snFim.value) == "" || form.snFim.value.length != 8) {
			alert('Número final da faixa de numeração inválido.');
			form.snFim.focus();
			return false;
		}
		if (form.snTipo.value == 0) {
			alert('Selecione o tipo de sistema de numeração.');
			form.snTipo.focus();
			return false;
		}
		form.snInicio.value = form.ddd.value + form.snInicio.value;
		form.snFim.value = form.ddd.value + form.snFim.value;
		return true;
	}
	
	function validarCambio(form) {
		if (trim(form.data.value) == "") {
			alert('Informe a data da cotação.');
			form.data.focus();
			return false;			
		}
		if (trim(form.valor.value) == "") {
			alert('Informe o valor da cotação.');
			form.valor.focus();
			return false;			
		}
		if (form.moeda.value == 0) {
			alert('Associe uma moeda a cotação.');
			form.moeda.focus();
			return false;			
		}		
		return true;
	}
	
	function validarMoeda(form)	{
		if (trim(form.nome.value) == "") {
			alert('Informe o nome da moeda. Ex.: R$, US$.');
			form.nome.focus();
			return false;			
		}
		return true;
	}
	
	function validarSenha(form)	{
		if (form.senha.value == "") {
			alert('Senha em branco.');
			form.senha.focus();
			return false;
		}		
		if (form.csenha.value == "") {
			alert('Confirmação de senha em branco.');
			form.csenha.focus();
			return false;
		}	
		if (form.senha.value != form.csenha.value) {
			alert('A senha é incompatível com a confirmação de senha.');
			form.senha.focus();
			return false;
		}
		return true;
	}
	
	function validarConfiguracao(form)	 {
		if(form.device.value == '0') {
			alert('Selecione a device a qual a configuracao sera associada.');
			form.device.focus();
			return false;
		}		
		if (trim(form.arquivo.value) == "" || !validarExtensaoLogo(form.arquivo)) {
			alert('Extensao invalida, selecione uma imagem GIF.');
			form.arquivo.focus();
			return false;
		}
		return true;
	}
	
	function validarExtensoes(form) {
		if (form.numero.value == '0') {
			alert('Selecione um número de extensão.');
			form.numero.focus();
			return false;
		}
		if (form.nome.value == '0') {
			alert('Selecione o usuário da extensão.');
			form.nome.focus();
			return false;			
		}
		if (form.tipo.value == '0') {
			alert('Selecione um tipo a ser associado a extensão.');
			form.tipo.focus();
			return false;			
		}
		return true;
	}
	
	function validarAliases(form) {
		return false;
	}	
	
	function limitaTextArea(elemento, limite ) {
		  if ( elemento.value.length > limite ) { 
			 elemento.value =  elemento.value.substr( 0, limite);
		  }
	}
	
	/********************************************************************/
	/*********** Validadores diversos ***********************************/
	/********************************************************************/
	
	/*****[ Verifica se uma determinada URL � v�lida ]*****/
	function isURL(strURL) {
		if(!strURL) return false;
		strURL = strURL.toLowerCase();
		urlRegExp = /^(((ht|f)tp(s?))\:\/\/)([0-9a-zA-Z\-]+\.)+[a-zA-Z]{2,6}(\:[0-9]+)?(\/\S*)?$/
		return urlRegExp.test(strURL);
	}
	
	/*****[ O CPF informado n�o deve possuir . ou - ]*****/
	function validaCpf(cpf) {
		var numeros, digitos, soma, i, resultado, digitos_iguais;
		digitos_iguais = 1;
		if (cpf.length < 11) {
			return false;
		}
		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))
				  return false;
			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))
				  return false;
			return true;
			}
		else
			return false;
	}	
	
	/*****[ O CPF informado n�o deve possuir ., / ou - ]*****/
	function validaCnpj(cnpj) {
		var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
		digitos_iguais = 1;
		if (cnpj.length < 14 && cnpj.length < 15) {
			return false;
		}
		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)) {
				  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)) {
				return false;
			}
			return true;
		} else {
			return false;
		}
	}	
	
	/*****[ Valida o email ]*****/
	function validaEmail(emailad){
		var exclude=/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
		var check=/@[\w\-]+\./;
		var checkend=/\.[a-zA-Z]{2,3}$/;
		if (((emailad.search(exclude) != -1)||(emailad.search(check)) == -1)||(emailad.search(checkend) == -1)) {
			return false;
		}
		else {
			return true;
		}
	}	
	
	/*****[ Verifica se o caracter infomrado � um n�mero]*****/
	function isNum(caractere)	{
		var strValidos = "0123456789";
		if ( strValidos.indexOf( caractere ) == -1 )
			return false;
		else 
			return true;
	}	
	
	/*****[ de um determinado CNPJ ]*****/
	function formataCNPJ(elemento) {
		limpaCaracteres(elemento, '.-/');
		vr = elemento.value;
		tam = vr.length;
		 
		if ( vr.indexOf(".") == -1 ) {
			if ( tam <= 2 )
				elemento.value = vr;
		 
			if ( (tam > 2) && (tam <= 6) )
				elemento.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, tam );
		 
			if ( (tam >= 7) && (tam <= 10) )
				elemento.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '.' + vr.substr( 5, 3 ) + '/';
		 
			if ( (tam >= 11) && (tam <= 18) )
				elemento.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '.' + vr.substr( 5, 3 ) + '/' + vr.substr( 8, 4 ) + '-' + vr.substr( 12, 2 ) ;
		 
		}
		return true;
	} 	
	
	/*****[ Formata um determinado CNPJ ]*****/
	function formataCPF(elemento) {
		limpaCaracteres(elemento, '.-/');
		vr = elemento.value;
		tam = vr.length;
		 
		if ( vr.indexOf(".") == -1 ) {
			if ( tam <= 3 )
				elemento.value = vr;
		 
			if ( (tam > 3) && (tam <= 6) )
				elemento.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, tam );
		 
			if ( (tam >= 7) && (tam <= 9) )
				elemento.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 3 ) + '.' + vr.substr( 6, 3 );
		 
			if (tam >= 10)
				elemento.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 3 ) + '.' + vr.substr( 6, 3 ) + '-' + vr.substr( 9, 2 ) ;
		 
		}
		return true;
	}	
	
	/*****[ Formata um determinado Telefone ]*****/
	function formataTelefone(elemento) {
		vr = elemento.value;
		tam = vr.length;
		 
		if ( vr.indexOf("(") == -1 ) {
			if ( tam > 0 && tam < 2) 
				elemento.value = '(' + vr.substr( 0, tam);
											  
			if ( tam >= 2 && tam <= 6)
				elemento.value = '(' + vr.substr( 0, 2 ) + ')' + vr.substr( 2, tam );
		 
			if (tam > 6 && tam <= 10)
				elemento.value = '(' + vr.substr( 0, 2 ) + ')' + vr.substr( 2, 4 ) + '-' + vr.substr(6, tam);
				
			if (tam > 10)
				elemento.value = '(' + vr.substr( 0, 2 ) + ')(' + vr.substr( 2, 2 ) + ')' + vr.substr( 4, 4) + '-' + vr.substr(8, tam);
		 
		}
		return true;
	}	
	
	/*****[ Formata um determinado CEP ]*****/
	function formataCEP(elemento) {
		vr = elemento.value;
		tam = vr.length;
		 
		if ( vr.indexOf(".") == -1 ) {  
			if ( tam >= 2 && tam <= 5)
				elemento.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, tam );
		 
			if (tam > 5)
				elemento.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '-' + vr.substr(5, tam);
		 
		}
		return true;
	}	
	
	/*****[ Verifica e restringe a formata��o de um endere�o IP ]*****/
	function verificaFormatacaoIP(e, obj) {
		if (document.all){var evt=event.keyCode;} // caso seja IE
		else{var evt = e.charCode;}    // do contr�rio deve ser Mozilla
		if (evt <20) return true;    // liberando teclas de controle
		if ( (/^(\d{1,3}\.){3}\d{3}$/).test(obj.value) ) return false;        
		var chr= String.fromCharCode(evt);    // pegando a tecla digitada
		if (! (/[\d\.]/).test(chr)) return false; // testando se � uma tecla v�lida (um digito ou um ponto)
		if (chr=='.')
			return (!(/\.$|^(\d{1,3}\.){3}/).test(obj.value) );
		else 
			if( (/\d{3}$/).test(obj.value) )
				obj.value+='.';            
		return true;
	}
		
	
	/*********[ Limpa o conjuntos de caracteres informado no "digitos" ]*******/
	function limpaCaracteres(campo, digitos) {
		var temp = "";
		var digito = "";
		for (var i=0; i < campo.value.length; i++) {
			digito = campo.value.charAt(i);
			if (digitos.indexOf(digito) == -1) {
				temp = temp + digito;
			}
		}		
		campo.value = temp;
	} 	
	
	// Retira caracteres inv�lidos da string informada, baseado nos caracteres
	// do segundo par�metro v�lido
	function limparCaracteresInvalidos(valor, validos) {
		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 formataMoeda(campo, tammax, teclapres, decimal) {
		var tecla = teclapres.keyCode;
		var negativo = '';
		
		if (campo.value.indexOf('-') != -1) {
			negativo = '-';
		}
			
		vr = limparCaracteresInvalidos(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 = negativo + vr ; }
			
			if ( (tam > dec) && (tam <= 5) ){
			campo.value = negativo + vr.substr( 0, tam - dec ) + "," + vr.substr( tam - dec, tam ) ; }
			if ( (tam >= 6) && (tam <= 8) ){
			campo.value = negativo + vr.substr( 0, tam - (3 + dec)) + "." + vr.substr( tam - (3 + dec), 3 ) + "," + vr.substr( tam - dec, tam ) ; 
			}
			if ( (tam >= 9) && (tam <= 11) ){
			campo.value = negativo + vr.substr( 0, tam - (6 + dec)) + "." + vr.substr( tam - (6 + dec), 3 ) + "." + vr.substr( tam - (3 + dec), 3 ) + "," + vr.substr( tam - dec, tam ) ; }
			if ( (tam >= 12) && (tam <= 14) ){
			campo.value = negativo + vr.substr( 0, tam - (9 + dec)) + "." + vr.substr( tam - (9 + dec), 3 ) + "." + vr.substr( tam - (6 + dec), 3 ) + "." + vr.substr( tam - (3 + dec), 3 ) + "," + vr.substr( tam - dec, tam ) ; }
			if ( (tam >= 15) && (tam <= 17) ){
			campo.value = negativo + vr.substr( 0, tam - (12 + dec) ) + "." + vr.substr( tam - (12 + dec), 3 ) + "." + vr.substr( tam - (9 + dec), 3 ) + "." + vr.substr( tam - (6 + dec), 3 ) + "." + vr.substr( tam - (3 + dec), 3 ) + "," + vr.substr( tam - dec, tam ) ;}
		}
	}	
	
	//Formata n�mero tipo moeda usando o evento onKeyDown	
	function formataData(campo, tammax, teclapres) {
		var tecla = teclapres.keyCode;		
		vr = limparCaracteresInvalidos(campo.value,"0123456789");
		tam = vr.length;
		
		if (tam < tammax && tecla != 8) { tam = vr.length + 1 ; }
		
		if (tecla == 8 ) { tam = tam - 1 ; }
		
		if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) {
			if ( tam <= 2 ) { campo.value = vr ; }
			
			if ( (tam > 2) && (tam <= 4) ) {
				campo.value = vr.substr(0, 2) + "/" + vr.substr(2, tam); 
			}
			if (tam > 4) {
				campo.value = vr.substr(0, 2) + "/" + vr.substr(2, 2) + "/" + vr.substr( 4, tam ) ; 
			}
		} 
	}
	
	function IsNumeric(valor){
		var log=valor.length;
		var sw="S";
		for (x=0; x<log; x++){
			v1=valor.substr(x,1);
			v2 = parseInt(v1);
			//Comprovo se é um valor numérico
			if (isNaN(v2)) { sw= "N";}
		}
		if (sw=="S") {return true;} else { return false; }
	}
	
	var primeiroslap=false;
	var segundoslap=false;
	
	function formateadata(data){
		long = data.length;
		var dia;
		var mes;
		var ano;
		if ((long>=2) && (primeiroslap==false)) {
			dia = data.substr(0,2);
			if ((IsNumeric(dia)==true) && (dia<=31) && (dia!="00")) {
				data=data.substr(0,2)+"/"+data.substr(3,7); 
				primeiroslap=true;
			} else {
				data=""; primeiroslap=false;
			}
		}else{
			dia = data.substr(0,1);
			if (IsNumeric(dia)==false) {data="";}
			if ((long<=2) && (primeiroslap=true)) {data=data.substr(0,1); primeiroslap=false; }
		}
		if ((long>=5) && (segundoslap==false)){
			mes=data.substr(3,2);
			if ((IsNumeric(mes)==true) &&(mes<=12) && (mes!="00")) {
				data=data.substr(0,5)+"/"+data.substr(6,4); 
				segundoslap=true;
			} else { data=data.substr(0,3);; segundoslap=false;}
		} else {
			if ((long<=5) && (segundoslap=true)) {
				data=data.substr(0,4); segundoslap=false; }
		}
		if (long>=7){
			ano=data.substr(6,4);
			if (IsNumeric(ano)==false) { data=data.substr(0,6); }
			else {
				if (long==10){
					if ((ano==0) || (ano<1900) || (ano>2100)) { data=data.substr(0,6); }
				}
			}
		}
		if (long>=10){
			data=data.substr(0,10);
			dia=data.substr(0,2);
			mes=data.substr(3,2);
			ano=data.substr(6,4);
			// Ano nao bisexto e é fevereiro e o dia é maior a 28
			if ( (ano%4 != 0) && (mes ==02) && (dia > 28) ) {
				data=data.substr(0,2)+"/";
			}else if ( ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0)) && (mes ==02) && (dia 
	
	> 29) ) {
				data=data.substr(0,2)+"/";
			}
		}
		return (data);
	}	
	
	/** Valida se uma determinada tecla � um n�mero negativo*/
	function validaTeclaSeNumeroNegativo(campo, event) {
		var MINUS = 45;
		var tecla

		if(navigator.appName.indexOf("Netscape")!= -1)
			tecla= event.which;
		else
			tecla= event.keyCode;		

		if (tecla == MINUS && campo.value.length == 0) {
			return true;
		} else {
			return validaTeclaSeNumero(campo, event);
		}
	}
	
	/*****[ Realiza o tratamento necess�rio referente a tecla pressionada ]*****/
	function validaTeclaSeNumero(campo, event) { 
		var BACKSPACE = 8;
		var TAB = 9;
		var ENTER = 13;
		var DELETE = 46;
		var key;
		var tecla;
		 
		CheckTAB=true;
		if(navigator.appName.indexOf("Netscape")!= -1)
			tecla= event.which;
		else
			tecla= event.keyCode;
		 
		key = String.fromCharCode(tecla); 
		 
		if ( tecla == ENTER) 
			return false;
		 
		if ( event.keyCode == BACKSPACE 
			|| event.keyCode == DELETE
			|| event.keyCode == TAB
			|| event.keyCode == 35 //end
			|| event.keyCode == 36 //home
			|| event.keyCode == 37 //left
			|| event.keyCode == 39 //right
			)
			return true;
		 
		return ( isNum(key));
	}
	
	// valida nome da tabela tarifaria no evento onKeyDown
	function testaDecimal(num, idCampo){
		if (!checkDecimal(num)) {
			//alert('erro');
			$(idCampo).value = '';
			return false;
		}/* else {
			alert('OK!');
			return true;
		}*/	
	}
	function checkDecimal(num){
	    var er = new RegExp(/^[+-]?((\d+|\d{1,3}(\,\d{3})+)(\.\d*)?|\.\d+)$/);
	    if(typeof(num) == "string"){
	        if(er.test(num)){ return true; }
	    }else if(typeof(num) == "object"){
	        if(er.test(num.value)){
				return true;
			}
	    }else{
			return false;
		}
	}

	// valida nome da tabela tarifaria no evento onKeyDown
	function validaTeclaSeTraco(campo, event) {
		var MINUS = 45;
		var SPACEBAR = 32;
		var tecla
		

		if(navigator.appName.indexOf("Netscape")!= -1)
			tecla= event.which;
		else
			tecla= event.keyCode;		

		if (tecla == MINUS) {
			alert("Nome da tabela n�o pode conter '-'");			
			return false;	
		}else if (tecla == SPACEBAR){
			alert("Nome da tabela n�o pode conter espa�os");			
			return false;			
		}else{
			return true;			
		}
	}
	
	/*****[ Eleva um determinado caracter para mai�sculo - se 0 ent�o min�scula, caso contr�rio mai�scula]*****/
	function isCaracter(event) {
		if (navigator.appName.indexOf("Netscape")!= -1)
			tecla = event.which;
		else
			tecla = event.keyCode;
		
		 if ((tecla < 45 || tecla > 57) && (tecla < 96 || tecla > 105)) {
			return true;
		 } else {
			 return false;
		 }
	}
	   
	/*****[ Valida um determinado endere�o IP]*****/	   
	function isIP(ip) {
		return (/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/).test(ip);
	} 	
	
	/** Fun��o Trim() usada para remover os espa�os antes e depois do campo ****/
	function trim(texto) {
		while (texto.substring(0,1) == ' ') {
			if (texto.length == 1) {
				texto = '';
			} else {
				texto = texto.substring(1, texto.length);
			}
		}
		while ((texto != '') && (texto.substring(texto.length-1, texto.length) == ' ')) {
			if (texto.length == 1) {
				texto = '';
			} else {
				texto = texto.substring(0, texto.length-1);
			}
		}
		return texto;	
	}
	
	/** 
	 * Fun��o responsavel por recuperar o valor do 
	 * RadioButton selecionado
	 */
	function getRadioValue(elemento) {
		for (i = 0; i < elemento.length; i++){
		   if (elemento[i].checked)
			  return elemento[i].value;
		}
		return null;
	}
	
	/******
	* select_innerHTML - altera o innerHTML de um select independente se � FF ou IE
	* Corrige o problema de n�o ser poss�vel usar o innerHTML no IE corretamente
	* Veja o problema em: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228
	* 
	* Parametros:
	* objeto(tipo object): o select a ser alterado
	* innerHTML(tipo string): o novo valor do innerHTML
	*******/	
	function select_innerHTML(objeto,innerHTML){
		objeto.innerHTML = ""
		var selTemp = document.createElement("micoxselect")
		var opt;
		selTemp.id="micoxselect1"
		document.body.appendChild(selTemp)
		selTemp = document.getElementById("micoxselect1")
		selTemp.style.display="none"
		if(innerHTML.toLowerCase().indexOf("<option")<0){//se n�o � option eu converto
			innerHTML = "<option>" + innerHTML + "</option>"
		}
		innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span")
		selTemp.innerHTML = innerHTML
		for(var i=0;i<selTemp.childNodes.length;i++){
			if(selTemp.childNodes[i].tagName){
				opt = document.createElement("OPTION")
				for(var j=0;j<selTemp.childNodes[i].attributes.length;j++){
					opt.setAttributeNode(selTemp.childNodes[i].attributes[j].cloneNode(true))
				}
				opt.value = selTemp.childNodes[i].getAttribute("value")
				opt.text = selTemp.childNodes[i].innerHTML
				if(document.all){ //IEca
					objeto.add(opt)
				}else{
					objeto.appendChild(opt)
				}                    
			}    
		}
		document.body.removeChild(selTemp)
		selTemp = null
	}	
	
	function habilitarCamposFormulario(form) {
	   for (i = 0; i < form.elements.length; i++){
		   form.elements[i].disabled = false;
	   }
	}
	
	function desabilitarCamposFormulario(form) {
	   for (i = 0; i < form.elements.length; i++){
		   form.elements[i].disabled = true;
	   }
	}	
	
	function confirmaexclusao(idtab, tabela){
		if(window.confirm("Deseja excluir o registro?") == true){
			location.href = "excluir.php?idtab="+idtab+"&tabela="+tabela;
			
		}
	}
	