function $N(name) {
	return document.getElementsByName(name);
}

function debug(texto) {
	$("debug").style.display = "block";
	$("debug").value = texto;
}

function enter(evt) {
	var r = false;
	var key_code = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which ? evt.which : void 0;	
	if (key_code == 13) {
		r = true;
	}
	return r;
}

// retorna o valor com . para comparações js
function Decimal(valor) {
	r = 0;
	if (valor != '') {
		r = parseFloat(valor.replace(',','.'));
	}
	return r;
}

// Função para criação do campo de data no formulário
function Calendario(id_input, id_button) {
	Calendar.setup ({
		inputField: id_input, // ID of the input field
		ifFormat: "%d/%m/%Y", // the date format
		button: id_button // ID of the button
	});
}

// marca/desmarca todos os checkbox
function MarcaCheckboxs(name, sim) {
	var chks = $N(name);
	for (i = 0; i < chks.length; i++) {
		chks[i].checked = sim;
	}
}

// Retorna a posição (left ou top) do elemento na tela
// ex: getPosicao('id').left ou getPosicao('id').top
function getPosicao(id) {
	var offsetTrail = document.getElementById(id);
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetTrail) {
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") {
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}
	return {left:offsetLeft, top:offsetTop};
}

// calcula idade informando a data de nascimento
function CalculaIdade(data) {
	var idade = 0;
	// hoje
	var hoje = new Date();
	var dia = hoje.getDate();
	var mes = hoje.getMonth()+1;
	var ano = hoje.getFullYear();
	// data nascimento
	var vdata = data.split('/');
	var dia2 = vdata[0];
	var mes2 = vdata[1];
	var ano2 = vdata[2];
	// calcula
	if (ano < 100) {
		ano = ano + 1900;
	}
	idade = ano - ano2;
	if (mes2 < mes) {
		idade = idade - 1;
	}
	if (mes2 == mes) {
		if (dia2 < dia) {
			idade = idade - 1;
		}
	}
	return idade;
}

function Aguarde(sim) {
	var div1 = $('div_aguarde');
	var div2 = $('div_conteudo');
	var div3 = $('div_bg_aguarde'); // background opaco do aguarde
	var ajuste_left = 150;
	if (window.ActiveXObject) {ajuste_left = (ajuste_left - 10);} // ie	
	if (sim) {
		if ((div2 != undefined) && (div3 != undefined)) {
			// ajusta a altura e posição do background com a div de conteudo
			div3.style.top = div2.getCoordinates().top+'px';
			div3.style.left = (div2.getCoordinates().left - ajuste_left)+'px';
			div3.style.height = div2.getSize().y+'px';
			div3.style.width = div2.getSize().x+'px';			
			div3.style.display = 'block';
		}
		if (div1 != undefined) {div1.style.display = 'block';}
	} else {
		if (div1 != undefined) {div1.style.display = 'none';}
		if (div3 != undefined) {div3.style.display = 'none';}
	}
}

function Menu(pagina) {
	Aguarde(true);
	switch(pagina) {
		case 'sair':
			Logoff();
			return;
			break;
	}
	AjaxInclude(pagina+'.php','div_conteudo');
}

function Login() {
	var login = $("txt_login")
	var senha = $("txt_senha")
	if (login.value == '') {
		alert('Informe o seu login.');
		login.focus();
		return;
	}
	if (senha.value == '') {
		alert('Informe a sua senha.');
		senha.focus();
		return;
	}		
	
	Aguarde(true);
	var ajax = new AJAX();
	ajax.url = "login_trata.php";	
	ajax.metodo = "POST";
	ajax.params = "login="+login.value+"&senha="+senha.value;
	ajax.retorno = function(r) {	
		Aguarde(false);
		switch (r) {				
			case 'erro_login':
				alert('ACESSO NEGADO!\n\nLogin Inexistente.');
				login.focus();
				break;
			case 'erro_senha':
				alert('ACESSO NEGADO!\n\nSenha Incorreta.');
				senha.focus();
				break;
			case 'OK':
				Menu('relatorio');
				AjaxInclude('menu.php','div_menu');
				AjaxInclude('login_info.php','div_info');
				break;				
			default:
				alert("ERRO - Login!");
				break;
		}
	}
	ajax.conectar();
}

function Logoff() {		
	Aguarde(true);
	var ajax = new AJAX();
	ajax.url = "logoff.php";	
	ajax.retorno = function() {				
		AjaxInclude('login_form.php','div_conteudo');
		AjaxInclude('menu.php','div_menu');
		$('div_info').innerHTML = '';
	}
	ajax.conectar();
}

function ExcluirSimulacao() {
	var marcou = false
	var checks = $N("chk_simulacao");
	var params = "opcao=excluir";	
	params += "&tipo=" + $('sel_simula').value;	

	for (i = 0; i < checks.length; i++) {
		if (checks[i].checked) {
			params += "&simulacao[]=" + checks[i].value;
			marcou = true;
		}
	}
	if (!marcou) {
		alert('Marque as simulações que deseja excluir.');
		return;
	}
	if (!confirm('Confirma a exclusão dos simulações marcadas?')) {return;}

	Aguarde(true);
	var ajax = new AJAX();
	ajax.url = "simulador_trata.php";	
	ajax.metodo = "POST";
	ajax.params = params;
	ajax.retorno = function(r) {
		switch (r) {
			case 'excluir':
				RelatorioSimulacao('');
				alert('Exclusão realizada com sucesso!');
				break;
			default:
				Aguarde(false);
				alert("ERRO - Exclusão de simulação não realizada!");
				break;
		}
	}
	ajax.conectar();
}

/*********************************************************************************************************************************************************************
| USUÁRIOS
*********************************************************************************************************************************************************************/
function ValidaUsuario(opcao) {
	var params = "opcao=" + opcao;
		
	if (opcao == 'inserir' || opcao == 'alterar') {
		if ($("txt_nome_usuario").value == '') {		
			alert("Informe o nome do usuário.");
			$("txt_nome_usuario").focus();
			return;
		}		
		params += "&nome=" + escape($("txt_nome_usuario").value);
		params += "&email=" + escape($("txt_email_usuario").value);
		params += "&login=" + escape($("txt_login_usuario").value);
		params += "&senha=" + escape($("txt_senha_usuario").value);
		params += "&ativo=" + $("sel_ativo_usuario").value;		
	}
	if (opcao == 'alterar' || opcao == 'excluir') {
		var msg1 = 'alterar';
		var msg2 = 'alteração';
		if (opcao == 'excluir') {
			msg1 = 'excluir';
			msg2 = 'exclusão';			
		}
		if (!confirm("Confirma a "+msg2+" do usuário?")) {
			return;
		}
		params += "&id=" + $("hdn_usuario").value;
	}
	
	Aguarde(true);
	var ajax = new AJAX();
	ajax.url = "usuario_trata.php";	
	ajax.metodo = "POST";
	ajax.params = params;
	ajax.retorno = function(r) {
		Aguarde(false);
		switch (r) {
			case "em_uso":
				alert("Este usuário tem informações relacionadas e não pode ser excluído!");
				break;
			case "login_existe":
				alert("Este login já está em uso no sistema, escolha outro.");
				$('txt_login_usuario').focus();
				break;
			case 'inserir':
				Menu('usuario');
				alert("Usuário cadastrado com sucesso!");
				break;
			case 'alterar':
				Menu('usuario');
				alert("Usuário alterado com sucesso!");
				break;
			case 'excluir':
				Menu('usuario');
				alert("Usuário excluído com sucesso!");
				break;
			default:
				alert("ERRO - Cadastro de Usuarios!");
				break;
		}
	}
	ajax.conectar();
}

function EditaUsuario(id) {
	Aguarde(true);
	AjaxInclude('usuario_form.php?id='+id, 'div_form_usuario');
}

/*********************************************************************************************************************************************************************
| CORRETORES
*********************************************************************************************************************************************************************/
function ValidaCorretor(opcao) {
	var params = "opcao=" + opcao;
		
	if (opcao == 'inserir' || opcao == 'alterar') {
		if ($("txt_nome_corretor").value == '') {		
			alert("Informe o nome do corretor.");
			$("txt_nome_corretor").focus();
			return;
		}		
		params += "&nome=" + escape($("txt_nome_corretor").value);
		params += "&email=" + escape($("txt_email_corretor").value);
		params += "&login=" + escape($("txt_login_corretor").value);
		params += "&senha=" + escape($("txt_senha_corretor").value);
		params += "&ativo=" + $("sel_ativo_corretor").value;		
	}
	if (opcao == 'alterar' || opcao == 'excluir') {
		var msg1 = 'alterar';
		var msg2 = 'alteração';
		if (opcao == 'excluir') {
			msg1 = 'excluir';
			msg2 = 'exclusão';			
		}
		if (!confirm("Confirma a "+msg2+" do corretor?")) {
			return;
		}
		params += "&id=" + $("hdn_corretor").value;
	}
	
	Aguarde(true);
	var ajax = new AJAX();
	ajax.url = "corretor_trata.php";	
	ajax.metodo = "POST";
	ajax.params = params;
	ajax.retorno = function(r) {
		Aguarde(false);
		switch (r) {			
			case "em_uso":
				alert("Este corretor tem informações relacionadas e não pode ser excluído!");
				break;
			case "login_existe":
				alert("Este login já está em uso no sistema, escolha outro.");
				$('txt_login_corretor').focus();
				break;
			case 'inserir':
				Menu('corretor');
				alert("Corretor cadastrado com sucesso!");
				break;
			case 'alterar':
				Menu('corretor');
				alert("Corretor alterado com sucesso!");
				break;
			case 'excluir':
				Menu('corretor');
				alert("Corretor excluído com sucesso!");
				break;
			default:
				alert("ERRO - Cadastro de Corretores!");
				break;
		}
	}
	ajax.conectar();
}

function EditaCorretor(id) {
	Aguarde(true);
	AjaxInclude('corretor_form.php?id='+id, 'div_form_corretor');
}

/*********************************************************************************************************************************************************************
| PROPOSTAS
*********************************************************************************************************************************************************************/
function ValidaProposta(opcao) {
	var rede;
	var params = "opcao=" + opcao;
	var tipo = 'I';
	if ($('rdb_tipo_2').checked) {tipo = 'E';}
		
	if (opcao == 'inserir' || opcao == 'alterar') {
		if (tipo == 'I') {
			if ($("sel_rede_ind_proposta").value == '') {		
				alert("Selecione a rede da proposta.");
				$("sel_rede_ind_proposta").focus();
				return;
			}
			rede = $('sel_rede_ind_proposta').value;
		} else {
			if ($("sel_rede_emp_proposta").value == '') {		
				alert("Selecione a rede da proposta.");
				$("sel_rede_emp_proposta").focus();
				return;
			}
			rede = $('sel_rede_emp_proposta').value;			
			
			// EMPRESA
			if ($("txt_razao_proposta").value == '') {		
				alert("Informe a razão social da empresa.");
				$("txt_razao_proposta").focus();
				return;
			}
			if ($("txt_cnpj_proposta").value == '') {		
				alert("Informe o CNPJ da empresa.");
				$("txt_cnpj_proposta").focus();
				return;
			}
			if ($("txt_fantasia_proposta").value == '') {		
				alert("Informe o nome fantasia da empresa.");
				$("txt_fantasia_proposta").focus();
				return;
			}			
			params += "&razao=" + escape($("txt_razao_proposta").value);
			params += "&cnpj=" + $("txt_cnpj_proposta").value;
			params += "&fantasia=" + escape($("txt_fantasia_proposta").value);
			params += "&endereco_emp=" + escape($("txt_endereco_emp_proposta").value);
			params += "&numero_emp=" + $("txt_numero_emp_proposta").value;
			params += "&bairro_emp=" + escape($("txt_bairro_emp_proposta").value);
			params += "&municipio_emp=" + escape($("txt_municipio_emp_proposta").value);
			params += "&uf_emp=" + $("sel_uf_emp_proposta").value;
			params += "&cep_emp=" + $("txt_cep_emp_proposta").value;
			params += "&fone_emp=" + $("txt_fone_emp_proposta").value;
			params += "&celular_emp=" + $("txt_celular_emp_proposta").value;
			params += "&email_emp=" + $("txt_email_emp_proposta").value;
			params += "&representante=" + escape($("txt_representante_proposta").value);			
		}
		if ($("sel_corretor_proposta").value == '') {		
			alert("Selecione a corretor responsável pela proposta.");
			$("sel_corretor_proposta").focus();
			return;
		}		
		// TITULAR
		if ($("txt_titular_proposta").value == '') {		
			alert("Informe o nome do titular da proposta.");
			$("txt_titular_proposta").focus();
			return;
		}
		if ($("txt_cpf_titular_proposta").value == '') {		
			alert("Informe o cpf do titular.");
			$("txt_cpf_titular_proposta").focus();
			return;
		}
		if ($("txt_nascimento_proposta").value == '') {
			alert("Informe a data de nascimento do titular.");
			$("txt_nascimento_proposta").focus();
			return;
		}
		if ($("sel_ecivil_proposta").value == '') {		
			alert("Selecione a estado civil do titular.");
			$("sel_ecivil_proposta").focus();
			return;
		}		
		if ($("sel_sexo_proposta").value == '') {
			alert("Selecione o sexo do titular.");
			$("sel_sexo_proposta").focus();
			return;
		}
		if ($('txt_total_proposta').value == '') {
			alert("Contrato não calculado!\n\nVerifique se a Rede foi selecionada, as datas de nascimento estão corretas e os valores estão corretos.");
			return;
		}		
		params += "&tipo=" + tipo;
		params += "&rede=" + rede;
		params += "&corretor=" + $("sel_corretor_proposta").value;
		
		// TITULAR
		params += "&titular=" + escape($("txt_titular_proposta").value);
		params += "&cpf_titular=" + $("txt_cpf_titular_proposta").value;
		params += "&pis=" + $("txt_pis_proposta").value;
		params += "&mae=" + escape($("txt_mae_proposta").value);
		params += "&ecivil=" + $("sel_ecivil_proposta").value;
		params += "&nascimento=" + $("txt_nascimento_proposta").value;
		params += "&sexo=" + $("sel_sexo_proposta").value;
		params += "&endereco=" + escape($("txt_endereco_proposta").value);
		params += "&numero=" + $("txt_numero_proposta").value;
		params += "&bairro=" + escape($("txt_bairro_proposta").value);
		params += "&municipio=" + escape($("txt_municipio_proposta").value);
		params += "&uf=" + $("sel_uf_proposta").value;
		params += "&cep=" + $("txt_cep_proposta").value;
		params += "&fone1=" + $("txt_fone1_proposta").value;
		params += "&fone2=" + $("txt_fone2_proposta").value;
		params += "&celular=" + $("txt_celular_proposta").value;
		params += "&email=" + $("txt_email_proposta").value;
		params += "&respon=" + escape($("txt_respon_proposta").value);
		params += "&cpf_respon=" + $("txt_cpf_respon_proposta").value;
		params += "&valor=" + $("txt_valor_proposta").value;
		params += "&total=" + $("txt_total_proposta").value;
		
		// DEPENDENTES
		for (i = 0; i < 5; i++) {
			if ($N('txt_valor_dep')[i].value != '') {
				if ($N('txt_cpf_dep')[i].value == '') {		
					alert("Informe o cpf do dependente.");
					$N('txt_cpf_dep')[i].focus();
					return;
				}
				if ($N('txt_cpf_dep')[i].value == '') {		
					alert("Informe o cpf do dependente.");
					$N('txt_cpf_dep')[i].focus();
					return;
				}
				if ($N('txt_nasc_dep')[i].value == '') {		
					alert("Informe a data de nascimento do dependente.");
					$N('txt_nasc_dep')[i].focus();
					return;
				}
				if ($N('txt_mae_dep')[i].value == '') {		
					alert("Informe o nome da mãe do dependente.");
					$N('txt_mae_dep')[i].focus();
					return;
				}				
				if ($N("sel_parente_dep")[i].value == '') {		
					alert("Selecione o grau de parentesco do dependente com o titular.");
					$N("sel_parente_dep")[i].focus();
					return;
				}
				if ($N("sel_ecivil_dep")[i].value == '') {		
					alert("Selecione o estado civil do dependente.");
					$N("sel_ecivil_dep")[i].focus();
					return;
				}
				if ($N("sel_sexo_dep")[i].value == '') {		
					alert("Selecione o sexo do dependente.");
					$N("sel_sexo_dep")[i].focus();
					return;
				}
				params += "&nome_dep[]=" + escape($N('txt_dep')[i].value);
				params += "&cpf_dep[]=" + $N('txt_cpf_dep')[i].value;
				params += "&nasc_dep[]=" + $N('txt_nasc_dep')[i].value;
				params += "&valor_dep[]=" + $N('txt_valor_dep')[i].value;
				params += "&mae_dep[]=" + escape($N('txt_mae_dep')[i].value);
				params += "&parente_dep[]=" + $N('sel_parente_dep')[i].value;
				params += "&ecivil_dep[]=" + $N('sel_ecivil_dep')[i].value;
				params += "&sexo_dep[]=" + $N('sel_sexo_dep')[i].value;
			}
		}
	}	
	
	if (opcao == 'alterar' || opcao == 'excluir') {
		var msg1 = 'alterar';
		var msg2 = 'alteração';
		if (opcao == 'excluir') {
			msg1 = 'excluir';
			msg2 = 'exclusão';			
		}
		if (!confirm("Confirma a "+msg2+" do Proposta?")) {
			return;
		}
		params += "&id=" + $("hdn_proposta").value;
	}
	
	Aguarde(true);
	var ajax = new AJAX();
	ajax.url = "proposta_trata.php";	
	ajax.metodo = "POST";
	ajax.params = params;
	ajax.retorno = function(r) {
//debug(r)
		Aguarde(false);
		switch (r) {			
			case "em_uso":
				alert("Esta proposta tem informações relacionadas e não pode ser excluída!");
				break;
			case 'inserir':
				Menu('proposta');
				alert("Proposta cadastrada com sucesso!");
				break;
			case 'alterar':
				Menu('proposta');
				alert("Proposta alterada com sucesso!");
				break;
			case 'excluir':
				Menu('proposta');
				alert("Proposta excluída com sucesso!");
				break;
			default:
				alert("ERRO - Cadastro de Propostas!");
				break;
		}
	}
	ajax.conectar();
}

function EditaProposta(id) {
	Aguarde(true);
	AjaxInclude('proposta_form.php?id='+id, 'div_form_proposta');
}

function ExibeProposta(tipo) {
	var p1 = $('p_ind');
	var p2 = $('p_emp');
	var div2 = $('div_emp');
	if (tipo == 1) { // individual		
		p2.style.display = 'none';
		div2.style.display = 'none';
		p1.style.display = 'block';		
	} else { // empresarial		
		p1.style.display = 'none';
		p2.style.display = 'block';
		div2.style.display = 'block';
	}
	CalculaTitular();
}

function CalculaTitular() {
	var rede_id, tipo;
	var params = "opcao=calcular";
	var vidas = 1;
	var nascimento = $('txt_nascimento_proposta').value;
	
	if ($('rdb_tipo_1').checked) { // individual
		tipo = 'I';
		rede_id = $('sel_rede_ind_proposta').value;
	} else { // empresarial
		tipo = 'E';
		rede_id = $('sel_rede_emp_proposta').value;
	}
	
	// totaliza qtd de vidas
	for (i = 0; i < 5; i++) {
		if ($N('txt_valor_dep')[i].value != '') {vidas++;}
	}
	
	if ((rede_id == '') || (nascimento == '')) {
		$('txt_valor_proposta').value = '';
		$('txt_total_proposta').value = '';
		return;
	}
	
	params += "&tipo=" + tipo;
	params += "&rede=" + rede_id;
	params += "&vidas=" + vidas;
	params += "&nascimento=" + nascimento;	

	var ajax = new AJAX();
	ajax.url = "proposta_trata.php";	
	ajax.metodo = "POST";
	ajax.params = params;
	ajax.retorno = function(r) {		
		$('txt_valor_proposta').value = r;
		TotalContrato();
	}
	ajax.conectar();	
}

function CalculaDependente(indice) {
	var rede_id, tipo;
	var params = "opcao=calcular";
	var vidas = 1;
	var nascimento = $N('txt_nasc_dep')[indice].value;

	if ($('rdb_tipo_1').checked) { // individual
		tipo = 'I';
		rede_id = $('sel_rede_ind_proposta').value;
	} else { // empresarial
		tipo = 'E';
		rede_id = $('sel_rede_emp_proposta').value;
	}	
	
	if ((rede_id == '') || (nascimento == '')) {
		$N('txt_valor_dep')[indice].value = '';
		$('txt_total_proposta').value = '';
		return;
	}
	
	params += "&tipo=" + tipo;
	params += "&rede=" + rede_id;
	params += "&vidas=" + vidas;
	params += "&nascimento=" + nascimento;	

	var ajax = new AJAX();
	ajax.url = "proposta_trata.php";	
	ajax.metodo = "POST";
	ajax.params = params;
	ajax.retorno = function(r) {
		$N('txt_valor_dep')[indice].value = r;
		TotalContrato();
	}
	ajax.conectar();	
}

function TotalContrato() {
	var total = 0;
	var valor = Decimal($('txt_valor_proposta').value);
	if (valor == '') {
		$('txt_total_proposta').value = '';
	} else {
		total = valor;
		for (i = 0; i < 5; i++) {
			if ($N('txt_valor_dep')[i].value != '') {
				total = total + Decimal($N('txt_valor_dep')[i].value);
			}
		}		
		$('txt_total_proposta').value = total.toFixed(2); // 2 casas decimais
		$('txt_total_proposta').value = $('txt_total_proposta').value.replace('.',',');
	}
}

function ImprimeProposta() {
	var proposta = $('sel_propostas').value;
	if (proposta == '') {
		alert('Selecione a proposta que deseja imprimir.');
		$('sel_propostas').focus();
		return;
	}
	var tela = window.open("proposta_imprime.php?proposta="+proposta,"VivaPlanos","type=fullWindow,directories=0,location=0,menubar=0,resizable=0,scrollbars=1,toolbar=0,left=0,top=0,width=791,height=" + (screen.availHeight - 30));
}

/*********************************************************************************************************************************************************************
| REDES
*********************************************************************************************************************************************************************/
function ValidaRede(opcao) {
	var params = "opcao=" + opcao;
		
	if (opcao == 'inserir' || opcao == 'alterar') {
		if ($("txt_descricao_rede").value == '') {		
			alert("Informe a descricão da rede.");
			$("txt_descricao_rede").focus();
			return;
		}		
		params += "&descricao=" + escape($("txt_descricao_rede").value);
		params += "&tipo=" + $("sel_tipo_rede").value;
		params += "&ativa=" + $("sel_ativa_rede").value;
	}
	if (opcao == 'alterar' || opcao == 'excluir') {
		var msg1 = 'alterar';
		var msg2 = 'alteração';
		if (opcao == 'excluir') {
			msg1 = 'excluir';
			msg2 = 'exclusão';			
		}
		if (!confirm("Confirma a "+msg2+" da rede?")) {
			return;
		}
		params += "&id=" + $("hdn_rede").value;
	}
	
	Aguarde(true);
	var ajax = new AJAX();
	ajax.url = "rede_trata.php";	
	ajax.metodo = "POST";
	ajax.params = params;
	ajax.retorno = function(r) {
		vet = r.split('|');		
		Aguarde(false);
		switch (vet[0]) {
			case 'inserir':
				Menu('rede');
				alert("Rede cadastrada com sucesso!");
				break;
			case 'alterar':
				Menu('rede');
				alert("Rede alterada com sucesso!");
				break;
			case 'excluir':
				Menu('rede');
				alert("Rede excluída com sucesso!");
				break;
			default:
				alert("ERRO - Cadastro de Redes!");
				break;
		}
	}
	ajax.conectar();
}

function EditaRede(id) {
	Aguarde(true);
	AjaxInclude('rede_form.php?id='+id, 'div_form_rede');
}

/*********************************************************************************************************************************************************************
| TABELAS
*********************************************************************************************************************************************************************/
function ExibeTabela() {
	var params = "?rede=" + $('sel_rede').value;
	var pagina = 'tabela_individual.php';
	if ($('sel_simula').value == 'E') {pagina = 'tabela_empresarial.php';}
	Aguarde(true);
	AjaxInclude(pagina + params, "div_exibe_tabela");
}

function AlteraTabelaIndividual(rede, faixa, vidas, valor) {
	var params = "opcao=altera_individual";	
	params += "&rede=" + rede;
	params += "&faixa=" + faixa;
	params += "&vidas=" + vidas;
	params += "&valor=" + valor;
	var ajax = new AJAX();
	ajax.url = "tabela_trata.php";
	ajax.metodo = "POST";
	ajax.params = params;
	ajax.retorno = function(r) {
		switch (r) {
			case 'altera_individual':
				break;
			default:
				alert("ERRO - Altera Tabela Individual!");
				break;
		}
	}
	ajax.conectar();
}

function AlteraTabelaEmpresarial(rede, faixa, valor) {
	var params = "opcao=altera_empresarial";	
	params += "&rede=" + rede;
	params += "&faixa=" + faixa;
	params += "&valor=" + valor;
	var ajax = new AJAX();
	ajax.url = "tabela_trata.php";
	ajax.metodo = "POST";
	ajax.params = params;
	ajax.retorno = function(r) {
		switch (r) {
			case 'altera_empresarial':
				break;
			default:
				salert("ERRO - Altera Tabela Empresarial!");
				break;
		}
	}
	ajax.conectar();
}

/*********************************************************************************************************************************************************************
| RELATÓRIOS
*********************************************************************************************************************************************************************/
function RelatorioSimulacao(ordem) {
	var params = "?ordem=" + ordem;
	var pagina = 'relatorio_individual.php';
	var asc_desc = 'asc';		
	if ($('sel_simula').value == 'E') {pagina = 'relatorio_empresarial.php';}
	if ($('rdb_desc').checked) {asc_desc = 'desc'}
	params += "&dataini=" + $('txt_dataini').value;
	params += "&datafim=" + $('txt_datafim').value;			
	params += "&rede=" + $('sel_rede').value;
	params += "&asc_desc=" + asc_desc;
	params += "&detalhe=";
	params += ($("chk_detalhe").checked) ? "S" : "N";	
	Aguarde(true);
	AjaxInclude(pagina + params, "div_relatorio_lista");
}

/**************************************************************************************************************************************************************
--| VALIDAÇÕES
**************************************************************************************************************************************************************/
// Permite apenas digitar numeros
function Numero(evt) {
	var key_code = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which ? evt.which : void 0;

	// Backspace, Tab, Del
	if (key_code == 8 || key_code == 9) {
		return true;
	}	
	
	if (key_code > 47 && key_code < 58) { // numeros de 0 a 9
		return true;
	} else {
		if (key_code != 8) { // backspace
			return false;
		} else {
			return true;
		}
	}
}

// Permite apenas digitar numeros e uma virgula
function Valor(evt,obj) {
	
	var key_code = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which ? evt.which : void 0;
	
	// Backspace, Tab, Del, Ponto e Virgula
	if (key_code == 8 || key_code == 9) {
		return true;
	}	

	// Só permite digitar a virgula 1 vez	
	if ((key_code == 44) && (obj.value.indexOf(",") == -1)) {
		return true;
	}
	
	if (key_code > 47 && key_code < 58) { // numeros de 0 a 9
		return true;
	} else {
		if (key_code != 8) { // backspace
			return false;
		} else {
			return true;
		}
	}
}

// formata o campo de data
function Data(evt,obj) {
	var key_code = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which ? evt.which : void 0;
	if (obj.value.length == 2 || obj.value.length == 5) {
		obj.value += "/";
	}
	if (key_code > 47 && key_code < 58) { // numeros de 0 a 9
		return true;
	} else {
		if ((key_code != 8) && (key_code != 9)) { // backspace e tab
			return false;
		} else {
			return true;
		}
	}
}

// formata o campo de tefefone
function Telefone(Campo) {
	fone = Campo.value;
	tamanho = fone.length;	
	if ( fone == '' ) {
		return;
	}
	for ( i = 0; i <= tamanho; i++ ) {
		if ( i == 0 && fone.charAt(i) != "(" ) {
			fone = "(" + fone;
		}
		if ( i == 3 && fone.charAt(i) != ")" ) {
			fone = fone + ") ";
		}
		if ( i == 9 && fone.charAt(i) != "-" ) {
			fone = fone + "-";
		}
	}
	Campo.value = fone;	
}

function CPF(campo) {
    var CPF = new String(campo.value);
    var wCPF = '';
	var cont = 0;
    for (i=0; i< CPF.length ; i++) {
	  if (i <= 2) {
		  if ( CPF.charAt(i) >= '0' && CPF.charAt(i) <= '9' )	{
			  	wCPF += CPF.charAt(i);
	  	  }
		  else
		  {
		  		cont++;
		  }
	  }
	  if (i == 3) {	  
		  if ( CPF.charAt(i) == '.' )	{
			  	wCPF += CPF.charAt(i);
	  	  }	  
		  else {
			  if ( CPF.charAt(i) >= '0' && CPF.charAt(i) <= '9' )	{
			  		wCPF += '.';
				  	wCPF += CPF.charAt(i);
					cont ++;
			  }
			  else {
			  		wCPF += '.';			  
					cont ++;
			  }
	  	  }
	  }
	  if (i > 3 && i <= 6) {
		  if ( CPF.charAt(i) >= '0' && CPF.charAt(i) <= '9' )	{
			  	wCPF += CPF.charAt(i);
	  	  }
		  else
		  {
		  		cont++;
		  }
	  }
	  if (i == 7) {	  
		  if ( CPF.charAt(i) == '.' )	{
			  	wCPF += CPF.charAt(i);
	  	  }	  
		  else {
			  if ( CPF.charAt(i) >= '0' && CPF.charAt(i) <= '9' )	{
			  		wCPF += '.';
				  	wCPF += CPF.charAt(i);
					cont++;
			  }
			  else {
			  		wCPF += '.';
					cont++;
			  }
	  	  }
	  }
	  if (i > 7 && i <= 10) {
		  if ( CPF.charAt(i) >= '0' && CPF.charAt(i) <= '9' )	{
			  	wCPF += CPF.charAt(i);
	  	  }
		  else
		  {
		  		cont++;
		  }
	  }
	  if (i == 11) {	  
		  if ( CPF.charAt(i) == '-' )	{
			  	wCPF += CPF.charAt(i);
	  	  }	  
		  else {
			  if ( CPF.charAt(i) >= '0' && CPF.charAt(i) <= '9' )	{
			  		wCPF += '-';
				  	wCPF += CPF.charAt(i);
					cont++;
			  }
			  else {
			  		wCPF += '-';
					cont++;
			  }
	  	  }
	  }	  
	  if (i > 11) {
		  if ( CPF.charAt(i) >= '0' && CPF.charAt(i) <= '9' )	{
			  	wCPF += CPF.charAt(i);
	  	  }
		  else
		  {
		  		cont++;
		  }
	  }
	  
    }	
	if ( cont > 0 )
	{
	    // Atualiza o campo 
    	campo.value = wCPF;
	}
}	

function ValidaCPF(campo_cpf) {
   var campo = campo_cpf.value;
   var digito = campo.toString();
   if (campo_cpf.value == '000.000.000-00')
   {
      alert("CPF inválido.");
      campo_cpf.focus();
      return(false)
   }	
   if (campo_cpf.value == '111.111.111-11')
   {
      alert("CPF inválido.");
      campo_cpf.focus();
      return(false)
   }	
   if (campo_cpf.value == '222.222.222-22')
   {
      alert("CPF inválido.");
      campo_cpf.focus();
      return(false)
   }	
   if (campo_cpf.value == '333.333.333-33')
   {
      alert("CPF inválido.");
      campo_cpf.focus();
      return(false)
   }
   if (campo_cpf.value == '444.444.444-44')
   {
      alert("CPF inválido.");
      campo_cpf.focus();
      return(false)
   }
   if (campo_cpf.value == '555.555.555-55')
   {
      alert("CPF inválido.");
      campo_cpf.focus();
      return(false)
   }
   if (campo_cpf.value == '666.666.666-66')
   {
      alert("CPF inválido.");
      campo_cpf.focus();
      return(false)
   }
   if (campo_cpf.value == '777.777.777-777')
   {
      alert("CPF inválido.");
      campo_cpf.focus();
      return(false)
   }
   if (campo_cpf.value == '888.888.888-88')
   {
      alert("CPF inválido.");
      campo_cpf.focus();
      return(false)
   }
   if (campo_cpf.value == '999.999.999-99')
   {
      alert("CPF inválido.");
      campo_cpf.focus();
      return(false)
   }
   // DIGITO 1
   var soma1 = 0
       soma1 = soma1 + 10 * digito.charAt(0);
       soma1 = soma1 +  9 * digito.charAt(1);
       soma1 = soma1 +  8 * digito.charAt(2);
       soma1 = soma1 +  7 * digito.charAt(4);
       soma1 = soma1 +  6 * digito.charAt(5);
       soma1 = soma1 +  5 * digito.charAt(6);
       soma1 = soma1 +  4 * digito.charAt(8);
       soma1 = soma1 +  3 * digito.charAt(9);
       soma1 = soma1 +  2 * digito.charAt(10);
   
   var divisao1    = soma1 / 11
   var multiplica1 = parseInt(divisao1,10) * 11   
   var resto1      = soma1 - multiplica1   
   if (resto1 <= 1) 
   {
      var digi1 = 0
   } 
   else 
   {
      var digi1 = 11 - resto1
   }
 
   // DIGITO 2
   var soma2 = 0
       soma2 = soma2 + 11 * digito.charAt(0);
       soma2 = soma2 + 10 * digito.charAt(1);
       soma2 = soma2 +  9 * digito.charAt(2);
       soma2 = soma2 +  8 * digito.charAt(4);
       soma2 = soma2 +  7 * digito.charAt(5);
       soma2 = soma2 +  6 * digito.charAt(6);
       soma2 = soma2 +  5 * digito.charAt(8);
       soma2 = soma2 +  4 * digito.charAt(9);
       soma2 = soma2 +  3 * digito.charAt(10);
       soma2 = soma2 +  2 * digi1       

   var divisao2    = soma2 / 11
   var multiplica2 = parseInt(divisao2,10) * 11
   var resto2      = soma2 - multiplica2

   if (resto2 <= 1) 
   {
      var digi2 = 0
   } 
   else 
   {
      var digi2 = 11 - resto2
   }
   
   if (digito.charAt(12) == digi1.toString() & digito.charAt(13) == digi2.toString()) 
   {
      return(true)
   } 
   else 
   {
      alert("CPF inválido.");
      campo_cpf.focus();
      return(false)
   }
}

function CNPJ(campo) {
    var CNPJ = new String(campo.value);
    var wCNPJ = '';
	var cont = 0;	
    for (i=0; i< CNPJ.length ; i++) {
	  if (i <= 1) {
		  if ( CNPJ.charAt(i) >= '0' && CNPJ.charAt(i) <= '9' )	{
			  	wCNPJ += CNPJ.charAt(i);
	  	  } else {
		  	cont++;
		  }
	  }	  
	  if (i == 2) {	  
		  if ( CNPJ.charAt(i) == '.' )	{
			  	wCNPJ += CNPJ.charAt(i);
	  	  }	  
		  else {
			  if ( CNPJ.charAt(i) >= '0' && CNPJ.charAt(i) <= '9' )	{
			  		wCNPJ += '.';
				  	wCNPJ += CNPJ.charAt(i);
					cont ++;
			  }
			  else {
			  		wCNPJ += '.';			  
					cont ++;
			  }
	  	  }
	  }
	  if (i > 2 && i <= 5) {
		  if ( CNPJ.charAt(i) >= '0' && CNPJ.charAt(i) <= '9' )	{
			  	wCNPJ += CNPJ.charAt(i);
	  	  } else {
			cont++;
		  }
	  }	  
	  if (i == 6) {	  
		  if ( CNPJ.charAt(i) == '.' )	{
				wCNPJ += CNPJ.charAt(i);
	  	  }	else {
				if ( CNPJ.charAt(i) >= '0' && CNPJ.charAt(i) <= '9' )	{
			  		wCNPJ += '.';
				  	wCNPJ += CNPJ.charAt(i);
					cont++;
			  } else {
			  		wCNPJ += '.';
					cont++;
			  }
	  	  }
	  }

	  if (i > 6 && i <= 9) {
		  if ( CNPJ.charAt(i) >= '0' && CNPJ.charAt(i) <= '9' )	{
			  	wCNPJ += CNPJ.charAt(i);
	  	  } else {
		  	    cont++;
		  }
	  }	  
	  if (i == 10) {	  
		  if ( CNPJ.charAt(i) == '/' )	{
			  	wCNPJ += CNPJ.charAt(i);
	  	  }	else {
			  if ( CNPJ.charAt(i) >= '0' && CNPJ.charAt(i) <= '9' )	{
			  		wCNPJ += '/';
				  	wCNPJ += CNPJ.charAt(i);
					cont++;
			  } else {
			  		wCNPJ += '/';
					cont++;
			  }
	  	  }
	  }	  
	  if (i > 10 && i <= 14) {
		  if ( CNPJ.charAt(i) >= '0' && CNPJ.charAt(i) <= '9' )	{
			  	wCNPJ += CNPJ.charAt(i);
	  	  } else {
		  		cont++;
		  }
	  }	  
	  if (i == 15) {	  
		  if ( CNPJ.charAt(i) == '-' )	{
			  	wCNPJ += CNPJ.charAt(i);
	  	  }	else {
			  if ( CNPJ.charAt(i) >= '0' && CNPJ.charAt(i) <= '9' )	{
			  		wCNPJ += '-';
				  	wCNPJ += CNPJ.charAt(i);
					cont++;
			  } else {
			  		wCNPJ += '-';
					cont++;
			  }
	  	  }
	  }	  
	  if (i > 15) {
		  if ( CNPJ.charAt(i) >= '0' && CNPJ.charAt(i) <= '9' )	{
			  	wCNPJ += CNPJ.charAt(i);
	  	  } else {
		  		cont++;
		  }
	  }
    }	
	if ( cont > 0 ) {
    	campo.value = wCNPJ; // Atualiza o campo
	}
}


function ValidaCNPJ(campo_cnpj) {   
   var campo = campo_cnpj.value;
   var digito = campo.toString();
   if (campo_cnpj.value == '00.000.000/0000-00') {
	  alert("CNPJ inválido.");
	  campo_cnpj.focus();
	  return(false)
   } else {
	   // DIGITO 1
	   var soma1 = 0
	       soma1 = soma1 + 5 * digito.charAt(0)
	       soma1 = soma1 + 4 * digito.charAt(1)
	       soma1 = soma1 + 3 * digito.charAt(3)
	       soma1 = soma1 + 2 * digito.charAt(4)
	       soma1 = soma1 + 9 * digito.charAt(5)
	       soma1 = soma1 + 8 * digito.charAt(7)
	       soma1 = soma1 + 7 * digito.charAt(8)
	       soma1 = soma1 + 6 * digito.charAt(9)
	       soma1 = soma1 + 5 * digito.charAt(11)
	       soma1 = soma1 + 4 * digito.charAt(12)
	       soma1 = soma1 + 3 * digito.charAt(13)
	       soma1 = soma1 + 2 * digito.charAt(14)   
	   
	   var divisao1    = soma1 / 11	   
	   var multiplica1 = parseInt(divisao1,10) * 11   
	   var resto1      = soma1 - multiplica1
   
	   if (resto1 <= 1) {
	      var digi1 = 0
	   } else {
	      var digi1 = 11 - resto1
	   }

	   // DIGITO 2
	   var soma2 = 0
	       soma2 = soma2 + 6 * digito.charAt(0)
	       soma2 = soma2 + 5 * digito.charAt(1)
	       soma2 = soma2 + 4 * digito.charAt(3)
	       soma2 = soma2 + 3 * digito.charAt(4)
	       soma2 = soma2 + 2 * digito.charAt(5)
	       soma2 = soma2 + 9 * digito.charAt(7)
	       soma2 = soma2 + 8 * digito.charAt(8)
	       soma2 = soma2 + 7 * digito.charAt(9)
	       soma2 = soma2 + 6 * digito.charAt(11)
	       soma2 = soma2 + 5 * digito.charAt(12)
	       soma2 = soma2 + 4 * digito.charAt(13)
	       soma2 = soma2 + 3 * digito.charAt(14)
	       soma2 = soma2 + 2 * digi1       
   
	   var divisao2    = soma2 / 11   
	   var multiplica2 = parseInt(divisao2,10) * 11   
	   var resto2      = soma2 - multiplica2

	   if (resto2 <= 1) {
	      var digi2 = 0
	   } else {
	      var digi2 = 11 - resto2
	   }
	   if (digito.charAt(16) == digi1.toString() & digito.charAt(17) == digi2.toString()) {
	      return(true)
	   } else {
	      alert("CNPJ inválido.");
	      campo_cnpj.focus();
	      return(false)
	   }
   }
}

function DigitaCEP(campo) {
    var CEP = new String(campo.value);
    var wCEP = '';
	var cont = 0;
    for (i=0; i< CEP.length ; i++) {
	  if (i <= 4) {
		  if ( CEP.charAt(i) >= '0' && CEP.charAt(i) <= '9' ) {
			  	wCEP += CEP.charAt(i);
	  	  } else {
			cont++;
		  }
	  }
	  if (i == 5) {	  
		  if ( CEP.charAt(i) == '-' )	{
			  	wCEP += CEP.charAt(i);
	  	  }	  
		  else {
			  if ( CEP.charAt(i) >= '0' && CEP.charAt(i) <= '9' )	{
			  		wCEP += '-';
				  	wCEP += CEP.charAt(i);
					cont ++;
			  }
			  else {
			  		wCEP += '-';			  
					cont ++;
			  }
	  	  }
	  }
	  if (i > 5) {
		  if ( CEP.charAt(i) >= '0' && CEP.charAt(i) <= '9' )	{
			  	wCEP += CEP.charAt(i);
	  	  }
		  else
		  {
		  		cont++;
		  }
	  }
    }
	if ( cont > 0 )
	{
	    // Atualiza o campo 
    	campo.value = wCEP;
	}
}
