var req;
var seqfolha_pdf;


/*
 *
 * ROTINAS GERAIS
 *
 */
 
function setEnabled(control, status){
         control.disabled = !status;
}
 
function habilitaCtl(controle){
         setEnabled(controle, true);
}

function desabilitaCtl(controle){
         setEnabled(controle, false);
}

 
function mostrar(txt){
	if (document.getElementById("mensagem"))
         document.getElementById("mensagem").innerHTML = txt;
}


function criarReqHttp(url, handler){
         req = null;
         if (window.XMLHttpRequest)
            req = new XMLHttpRequest();
         else if (window.ActiveXObject)
            req = new ActiveXObject('Microsoft.XMLHTTP');
         if (req != null){
            req.onreadystatechange = handler;
            req.open("GET", url, true);
            req.send(null);
         }
}

function criarReqHttpPost(url, params, handler){
         req = null;
         if (window.XMLHttpRequest)
            req = new XMLHttpRequest();
         else if (window.ActiveXObject)
            req = new ActiveXObject('Microsoft.XMLHTTP');
         if (req != null){
            req.onreadystatechange = handler;
            req.open("POST", url, true);
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			req.setRequestHeader("Content-length", params.length);
			req.setRequestHeader("Connection", "close");
            req.send(params);
         }
}


/*
 *
 * EXCLUSÃO DE ARQUIVOS
 *
 */
 
function apagarArquivo(){
         criarReqHttp("apagar.php", hApagarArquivo);
         /*alert('Arquivo excluído?');*/
}

function hApagarArquivo(){
}



function alterarSenha(atual, nova1, nova2){
	if (atual.value == ""){
		alert("Informe a senha atual!");
		atual.focus();
	}else if (nova1.value != nova2.value){
		alert("Sua nova senha não foi confirmada corretamente!");
		nova1.focus();
	}else if (nova1.value == ""){
		alert("Informe sua nova senha!");
		nova1.focus();
	}else{
		criarReqHttpPost("alterar_senha.php", "senha_atual=" + atual.value + "&senha_nova=" + nova1.value, hAlterarSenha);
	}
}

function hAlterarSenha(){
         if (req.readyState == 4)
            if (req.status == 200){
			   var resposta = req.responseText;
			   var codigo = resposta.substring(0, resposta.indexOf(':'));
			   resposta = resposta.substring(resposta.indexOf(':')+1);
			   alert(resposta);
			   if (codigo == '0')
					self.location = 'principal.php';
            }
}


/*
 *
 * CONTRACHEQUES
 *
 */

var listaLotacoes;

function preencherListaComLotacoes(lista, texto){
         listaLotacoes.options.length = 0;
         opcoes = texto.split("^");
         j = 0;
         for (i=0; i<opcoes.length-1; i=i+2){
           listaLotacoes.options[j++] = new Option(opcoes[i+1], opcoes[i]);
           /*alert(opcoes[i+1]);*/
         }
}
 
function populaLotacoes(seqfolha, lista){
         listaLotacoes = lista;
         criarReqHttp("lotacoes.php?seqfolha="+seqfolha, hPopulaLotacoes);
}


function hPopulaLotacoes(){
         if (req.readyState == 4)
            if (req.status == 200){
               preencherListaComLotacoes(listaLotacoes, req.responseText);
            }else{
               preencherListaComLotacoes(listaLotacoes, "0^TODAS^");
            }
}

function visualizarContracheque(seqfolha, tipo){
         if (tipo == 0){
            self.location = "ccheque_htm.php?seqfolha=" + seqfolha + "&atual=0";
            mostrar('<table><tr class="comboConsulta1"><td>Gerando espelho, aguarde um momento...</td></tr></table>');
         }else{
            verContracheque(seqfolha);
            mostrar('<table><tr class="comboConsulta1"><td>Gerando contracheque para impressão, aguarde um momento...</td></tr></table>');
         }
}

function carregaRelacaoContracheques(){
         criarReqHttp("contracheques.php?ano="+document.getElementById("ano").value, hCarregaListagem);
}

function carregaRelacaoEspelhos(){
         criarReqHttp("espelhos.php", hCarregaListagem);
}

function hCarregaListagem(){
         if (req.readyState == 4)
            if (req.status == 200)
               mostrar(req.responseText);
            else
               alert("Ocorreu um erro ao recuperar os dados. Tente novamente.");
}

function visualizarContrachequeFolha(seqfolha,sigla,matricula,matriculafin,lotacao,timbre,opcao){
         if ((seqfolha.value == "0")||(seqfolha.value == "")){
            alert("Informe um sequencial para a folha");
            seqfolha.focus();
         } else if ((opcao[0].checked)&&(matricula.value == "")){
              alert("Informe a matrícula inicial");
              matricula.focus();
         } else if ((opcao[0].checked)&&(matriculafin.value == "")){
              alert("Informe a matrícula final");
              matriculafin.focus();
         } else if ((opcao[1].checked)&&(lotacao.value == 0)){
            alert("Selecione uma lotação válida");
            lotacao.focus();
         } else{
            url = "gera_pdf.php?seqfolha="+seqfolha.value+"&opcao="+(opcao[0].checked? "0": "1");
			url += "&sigla=" + sigla.value;
            url += (matricula.value != "")? "&mat="+matricula.value: "";
            url += (matriculafin.value != "")? "&matfin="+matriculafin.value: "";
            url += (opcao[1].checked)? "&lotacao="+lotacao.value: "";
            url += (timbre.checked)? "&timbre=1": "&timbre=0";
            criarReqHttp(url, hVerPDF);
            mostrar('<image src="img/carregando.gif">Carregando PDF. Aguarde...');
         }
}

function visualizarEspelhoFolha(seqespelho, sigla, matricula, matriculafin, categoria, opcao){
         if ((seqespelho.value == "0")||(seqespelho.value == "")){
            alert("Informe um sequencial para o espelho");
            seqespelho.focus();
         } else if ((opcao[0].checked)&&(matricula.value == "")){
              alert("Informe a matrícula inicial");
              matricula.focus();
         } else if ((opcao[0].checked)&&(matriculafin.value == "")){
              alert("Informe a matrícula final");
              matriculafin.focus();
         } else if ((opcao[1].checked)&&(categoria.value == "NA")){
            alert("Selecione uma categoria");
            categoria.focus();
         } else{
            url = "ccheque_htm2.php?seqfolha="+seqespelho.value+"&opcao="+(opcao[0].checked? "0": "1");
			url += "&sigla=" + sigla.value;
            url += (matricula.value != "")? "&mat="+matricula.value: "";
            url += (matriculafin.value != "")? "&matfin="+matriculafin.value: "";
            url += (opcao[1].checked)? "&categoria="+categoria.value: "";

            mostrar('<image src="img/carregando.gif">Carregando espelhos. Aguarde...');
			self.location = url;
         }
}

function verContracheque(seqfolha){
         criarReqHttp("gera_pdf.php?seqfolha="+seqfolha, hVerPDF);
}

function verIRPF(){
         criarReqHttp("gera_irpf.php", hVerPDF);
}

function verFormulario1198(){
         criarReqHttp("gera_form_1198.php", hVerPDF);
}

function hVerPDF(){
        if (req.readyState == 4){
			if (req.status == 200){
				if (req.responseText == "OK"){
					self.location = "./pdf.php";
				}else{
					alert(req.responseText);
				}
            }else{
               alert("O sistema reportou o seguinte erro HTTP: " + req.status);
			}
		}
}



/*
 * 
 * OPÇÕES SISTEMA
 *
 */

function selecionarModulo(cmb){
	url = "";
	if (cmb.value == 0)
		url = "principal.php";
	else if (cmb.value == 1)
		url = "principal_espelho.php";
	else if (cmb.value == 2)
		url = "principal_irpf.php";
	else if (cmb.value == 3)
		url = "principal_ferias.php";
	else if (cmb.value == 4)
		url = "principal_juros.php";
	else if (cmb.value == 5)
		url = "principal_sarh.php";
	else if (cmb.value == 6)
		url = "principal_plano_saude.php";
	else if (cmb.value == 7)
		url = "principal_crps.php";	// incluido em 24/02/2010 Rinaldo Meira Lins
	else if (cmb.value == 100)
		url = "principal_folha.php";
	else if (cmb.value == 101)
		url = "principal_senha.php";

	else{
		alert("Opção inválidaaa!");
		return false;
	}
	self.location = url;
	return true;
}

/*
 *
 * COMPROVANTE DE RENDIMENTOS
 *
 */

function carregaRelacaoComprovantes(){
         criarReqHttp("comprovantes_irpf.php", hCarregaListagem);
 }

function visualizarCompRendimento(ano, mat, seq){
         if (mat == ""){
            alert("Informe  a matrícula");
            mat.focus();
         }else {
			if (ano == ""){
				alert("Informe o ano");
				ano.focus();
			}else {
				if (seq == ""){
					alert("Informe o sequencial");
					seq.focus();			
				} else {
					criarReqHttp("gera_irpf.php?ano="+ano+"&mat="+mat+"&seq="+seq, hVerPDF);
					mostrar('<table><tr class="comboConsulta1"><td>Gerando comprovante para impressão, aguarde um momento...</td></tr></table>');
				}
			}
		}
	}
function visualizarCompRendimentoPlanoSaude(ano, mat, tipo){ // incluido em 24/02/2010 Rinaldo Meira Lins
         if (mat == ""){
            alert("Informe  a matrícula");
            mat.focus();
         }else if (ano == ""){
            alert("Informe o ano");
            ano.focus();
         } else {
			window.open('pop_pdf_crps.php?ano='+ano+'&mat='+mat+'&tipo='+tipo,'','copyhistory=0,directories=0, location=0, menubar=0, scrollbars=yes, status=0, toolbar=0, width=680, height=550, resizable=yes'); 						
         }
}

function hVerPDF_crps(){ // incluido em 24/02/2010 Rinaldo Meira Lins
        if (req.readyState == 4){
			if (req.status == 200){
				if (req.responseText == "OK"){
					self.location = "./pdf_crps.php";
				}else{
					alert(req.responseText);
				}
            }else{
               alert("O sistema reportou o seguinte erro HTTP: " + req.status);
			}
		}
}

function carregaRelacaoComprovantesCrps(){// incluido em 24/02/2010 Rinaldo Meira Lins
		 criarReqHttp("comprovantes_crps.php", hCarregaListagem);
 }
