function getCodFinalidade()
{
    document.getElementById("txtFinalidade").value = document.getElementById("cmbFinalidade").value;
	texto = document.getElementById("txtFinalidade").value;
	posBarra = texto.indexOf("-");
	codigo = parseInt(texto.substr(0,posBarra));
	return codigo;
}

function mudarFinalidade()
{
	var posBarra;
    var codigo;
    var texto;
    var pararAnima = false;

	document.getElementById("txtFinalidade").value = document.getElementById("cmbFinalidade").value;
	texto = document.getElementById("txtFinalidade").value;
	posBarra = texto.indexOf("-");
	if (posBarra>-1) {
		/* O usuário escolheu um valor da lista */
		codigo = parseInt(texto.substr(0,posBarra));
		validaAno();
		
		if (codigo==9) {
        	document.getElementById("lblEstado").innerHTML = "Estado:";
			document.getElementById("cmbEstados").style.display = "";
            document.getElementById("cmbPeriodos").style.display = "NONE";
			document.getElementById("lblEstado").style.visibility = "";
			document.getElementById("lblAno").style.display = "NONE";
			document.getElementById("txtAno").style.display = "NONE";
			document.getElementById("cmbTrienios").style.display = "NONE";
		} else if (codigo==8) {
			document.getElementById("lblEstado").innerHTML = "Período:";
			document.getElementById("cmbEstados").style.display = "NONE";
			document.getElementById("cmbPeriodos").style.display = "";
			document.getElementById("lblEstado").style.visibility = "";
			document.getElementById("lblAno").style.display = "";
			document.getElementById("txtAno").style.display = "";

			var periodo = document.getElementById("cmbPeriodos").value;

			if (periodo == "2") {
				document.getElementById("lblAno").innerHTML = "Triênio:"
				document.getElementById("txtAno").style.display = "NONE";
				document.getElementById("cmbTrienios").style.display = "";
			} else {
				document.getElementById("lblAno").innerHTML = "Ano:";
                document.getElementById("txtAno").style.display = "";
                
                var dt = new Date();
                var ano = dt.getFullYear();
                
                if (dt.getMonth() < 12) {
                    ano = ano - 1;
                }
                
                document.getElementById("txtAno").value = ano.toString();
                
				document.getElementById("cmbTrienios").style.display = "NONE";
			}

		} else {
			document.getElementById("cmbEstados").style.display = "NONE";
			document.getElementById("lblEstado").style.visibility = "HIDDEN";
			document.getElementById("cmbPeriodos").style.display = "NONE";
			document.getElementById("lblAno").style.display = "NONE";
			document.getElementById("txtAno").style.display = "NONE";
			document.getElementById("cmbTrienios").style.display = "NONE";
        }
    }
}

function validaAno() {

	var posBarra;
	var codigo;
	var texto;

	texto = document.getElementById("cmbFinalidade").value;
	posBarra = texto.indexOf("-");
	if (posBarra>-1) {
		codigo = parseInt(texto.substr(0,posBarra));
		if (codigo==8) {

			var menorAno = new Number(document.getElementById("txtAnoMinimo").value);
			var anoDigitado = new Number(document.getElementById("txtAno").value);

			//document.getElementById("cmbPeriodos").disabled = (anoDigitado < menorAno);
			document.getElementById("cmbPeriodos").disabled = false;
		} else
			document.getElementById("cmbPeriodos").disabled = false;
			//document.getElementById("cmbPeriodos").disabled = false;
	} else
		document.getElementById("cmbPeriodos").disabled = false;
		//document.getElementById("cmbPeriodos").disabled = false;
}

function verifica() {
	valor  = document.getElementById(vEdtReg).value;
	select = document.getElementById(vCmbFinalidade);
	valSel = select.value;
	
    for (var c=(select.length-1);c>=0;c--) {
  		select.options[c] = null;
	}
	opcao = new Option("Escolha uma finalidade:", "Escolha uma finalidade:", false, false);
	select.options[select.length] = opcao;
	
	opcao = new Option("1- Atendimento à Lei 5.307/86 (Prestação de Contas)", "1- Atendimento à Lei 5.307/86 (Prestação de Contas)", false, false);
	select.options[select.length] = opcao;
	
	if (valor.charAt(0) != '2' && valor.charAt(0) != '3' ) {
	    opcao = new Option("2- Auditoria, Perícia Judicial e Extrajudicial", "2- Auditoria, Perícia Judicial e Extrajudicial", false, false);
	    select.options[select.length] = opcao;
	}
	
	opcao = new Option("3- Comprovação de Registros", "3- Comprovação de Registros", false, false);
	select.options[select.length] = opcao;
	
	opcao = new Option("4- Convênio CEF/PROGER (Financiamento)", "4- Convênio CEF/PROGER (Financiamento)", false, false);
	select.options[select.length] = opcao;
	
	opcao = new Option("5- Instituto Nacional de Seguridade Social (Contagem de Tempo)", "5- Instituto Nacional de Seguridade Social (Contagem de Tempo)", false, false);
	select.options[select.length] = opcao;
	
	opcao = new Option("6- Transferência de Registro", "6- Transferência de Registro", false, false);
	select.options[select.length] = opcao;
	
	opcao = new Option("7- Licitações e Concorrência", "7- Licitações e Concorrência", false, false);
	select.options[select.length] = opcao;
	
	if (valor.charAt(0) != '2' && valor.charAt(0) != '3' ) {
		opcao = new Option("8- Atendimento à Res. CFC nº1377/11 (Educ. Profissional Continuada)", "8- Atendimento à Res. CFC nº1377/11 (Educ. Profissional Continuada)", false, false);
		select.options[select.length] = opcao;
	}
	/*opcao = new Option("9- Verificação de Regularidade para Registro Secundário", "9- Verificação de Regularidade para Registro Secundário", false, false);
	select.options[select.length] = opcao;*/
	
	try {
	    select.value = valSel;
	} catch (err) {
	    select.selectedIndex = 0;
	}
	
	/*opcao = new Option("10- Certidão de Capacitadora", "10- Certidão de Capacitadora", false, false);
	opcao.style.display = "none";
	select.options[select.length] = opcao;*/
	
	document.getElementById(vTxtFinalidade).value = valSel;
}

function validaCodCapacitadora(numReg)
{
    r = new RegExp("^[A-Z]{2}[0-9]{5}");    
    ok = r.exec(numReg);
  
    if (!ok)
        return false;
    else
        return true;
}

function validarCertidao(numReg, codFin, uf, periodo, trienio, ano, listarResp, anoMin) {
    var _msg = "";
    
    if (document.getElementById(vCmbFinalidade).value == 'Escolha uma finalidade:')
        _msg += " - Selecione uma finalidade.<br/>";
    
    if (codFin != "10") {    
        if ((numReg.length < 9))
            _msg += " - Informe o número de registro.<br/>";
        else
        {
            if (!validaNumeroRegistro(numReg))
                _msg += " - O número de registro informado não é válido.<br/>";
        }
    } else {
        if ((numReg.length != 7))
            _msg += " - Informe o número de registro.<br/>";
        else
        {
            if (!validaCodCapacitadora(numReg))
                _msg += " - O código da capacitadora informado não é válido.<br/>";
        }
    }
    
    if (codFin == "E")
        _msg += " - Informe a finalidade da certidão.<br/>";
        
    if ((codFin == "8")&&(periodo == 1)&&(ano.length != 4))
        _msg += " - Informe o ano da certidão.<br/>";
        
    if (codFin == "8") 
    {
        nAno = new Number(ano);
        nAnoMin = new Number(anoMin);
        
        if ((periodo == 1)&&(nAno < nAnoMin))
        {
            _msg += " - O ano informado não pode ser inferior a " + nAnoMin + ".<br/>";
        }
    }
    
    if (_msg != "")
        document.getElementById(vMsg).innerHTML = _msg;        
    
    return _msg == "";
}

function acertarNumeroRegistro(txt) 
{
    nreg = codigoToSiglaEstado(txt.value);    
    txt.value = nreg;
}

function gerarCertidao()
{
    document.getElementById(vTxtDados).value = "";
    
    acertarNumeroRegistro(document.getElementById(vEdtReg));
    
    var numReg = document.getElementById(vEdtReg).value.toUpperCase();
    var codFin = document.getElementById(vCmbFinalidade).value;
    var uf = document.getElementById(vCmbEstados).value;
    var periodo = document.getElementById(vCmbPeriodos).value;
    var trienio = document.getElementById(vCmbTrienios).value;
    var ano = document.getElementById(vTxtAno).value;
    var listarResp = document.getElementById(vCbListResp).checked;
    var lr = listarResp ? "1" : "0";
    var anoMin = document.getElementById(vTxtAnoMinimo).value;
 
    codFin = getCodFinalidade();//codFin.substring(0,1);
 
    //window.alert(codFin);
 
    if (validarCertidao(numReg, codFin, uf, periodo, trienio, ano, listarResp, anoMin))
    {
        document.getElementById(vMsg).innerHTML = "";
        var params = "nr=" + numReg + ";if=" + codFin + ";uf=" + uf + 
            ";pr=" + periodo + ";tr=" + trienio + ";an=" + ano + 
            ";lr=" + lr + ";am=" + anoMin;
        
        document.getElementById(vTxtDados).value = "ac=gc;" + params;
        document.forms["Form1"].submit();
    }
}
