﻿
var ajax;
var objLoad;

function selecionaEmpresa(idEmpresa)
{
    var i = 0;
    var obj = document.getElementById('lstEmpresa');
    var possui = false;
    
    for(i = 0; i < 3; i++ )
    {
        if( obj.options[i].value == idEmpresa + "*" )
        {
            possui = true;
        }
    }
    
    if(possui)
    {
        document.getElementById('lstEmpresa').value = idEmpresa + "*";
    }
    else
    {
        try 
        {
            document.getElementById('lstEmpresa').value = idEmpresa;
        }
        catch(ex2)
        {
            document.getElementById('lstEmpresa').value = "0"
        }
    }

}
function verificaCadastro(obj)
{
    if(obj.value.length == 11 )
    {
        objLoad = document.getElementById("dvLoad");
        preencheFormulario(obj.value);
    }
}
function verificaEnter(obj,evt)
{
    if ( evt.keyCode == 13 && obj.value.length == 11 )
    {
        obj.blur();
        verificaCadastro(obj);
        event.returnValue = 0;
        document.formulario.txtNome.focus();
        return false;
    }
}

function preencheFormulario(cpf)
{
    ajax = getAjax();
    
	if ( !ajax ) {
		//alert("Seu browser não possui o objeto XMLHttp para a utilização do Ajax.");
		ajax = null;
		return false;
	}


	var contentType = "application/x-www-form-urlencoded; charset=ISO-8859-1";

    if ( !ajax )
        return;
    
	ajax.open("POST", "cadastro.aspx?", true );
    ajax.setRequestHeader("Content-Type", contentType);
	ajax.onreadystatechange = ajaxStatus_Ficha;
    ajax.send( "cpfConsulta=" + encodeURIComponent(cpf) + "&dt=" + getDt() + "&idAgenda=" + encodeURIComponent(getIdAgenda()));
    
}
function getIdAgenda()
{
    return document.getElementById("idAgendaHidden").value;
}
function getDt()
{
    var d = new Date();
    return d.getDay() + "-" + d.getMonth() + "-" + d.getYear() + "-" + d.getDay() + "-" + d.getMinutes() + "-" + d.getSeconds();
}

function ajaxStatus_Ficha()
{
	if ( ajax.readyState == 4 ){
        eval(ajax.responseText);
		objLoad.style.display = "none";
	}
	else{
	    objLoad.style.display = "";
	}
}

function getAjax()
{
	var xmlhttp=false;
   /* running locally on IE5.5, IE6, IE7 */                                              ; /*@cc_on
     if(location.protocol=="file:"){
      if(!xmlhttp)try{ xmlhttp=new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){xmlhttp=false;}
      if(!xmlhttp)try{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){xmlhttp=false;}
     }                                                                                ; @cc_off @*/
   /* IE7, Firefox, Safari, Opera...  */
     if(!xmlhttp)try{ xmlhttp=new XMLHttpRequest(); }catch(e){xmlhttp=false;}
   /* IE6 */
     if(typeof ActiveXObject != "undefined"){
      if(!xmlhttp)try{ xmlhttp=new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){xmlhttp=false;}
      if(!xmlhttp)try{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){xmlhttp=false;}
     }
   /* IceBrowser */
     if(!xmlhttp)try{ xmlhttp=createRequest(); }catch(e){xmlhttp=false;}

	return xmlhttp;
}


var numFormacao = 1;

function incluiFormacao(){
  for (var i=1; i<=numFormacao; i++){

    if (document.formulario['DAFormacao'+i].value==''){
      alert('Antes de incluir uma nova formação preencha os dados das anteriores.');
      document.formulario['DAFormacao'+i].focus();
      return false;
    }
    if (document.formulario['DAInstituicao'+i].value==''){
      alert('Antes de incluir uma nova formação preencha os dados das anteriores.');
      document.formulario['DAInstituicao'+i].focus();
      return false;
    }
    if (document.formulario['DACidade'+i].value==''){
      alert('Antes de incluir uma nova formação preencha os dados das anteriores.');
      document.formulario['DACidade'+i].focus();
      return false;
    }
    if (document.formulario['DAUF'+i].value==''){
      alert('Antes de incluir uma nova formação preencha os dados das anteriores.');
      document.formulario['DAUF'+i].focus();
      return false;
    }
  
  }

  numFormacao++;
  var objFormacao = document.getElementById('dadosAcademicos');
  var newHtml = objFormacao.innerHTML;

  newHtml = newHtml.replace('(1)','('+numFormacao+')');
  newHtml = newHtml.replace('DAFormacao1','DAFormacao'+numFormacao);
  newHtml = newHtml.replace('DAInstituicao1','DAInstituicao'+numFormacao);
  newHtml = newHtml.replace('DACidade1','DACidade'+numFormacao);
  newHtml = newHtml.replace('DAUF1','DAUF'+numFormacao);
  newHtml = newHtml.replace('\<TBODY\>','\<TABLE cellpadding=\"0\" cellspacing=\"0\"\>');
  newHtml = newHtml.replace('\</TBODY\>','\</TABLE\>');

  objFormacao.parentNode.insertAdjacentHTML('beforeEnd',newHtml);

  document.formulario['DAFormacao'+numFormacao].value='';
  document.formulario['DAInstituicao'+numFormacao].value='';
  document.formulario['DACidade'+numFormacao].value='';
  document.formulario['DAUF'+numFormacao].value='';

  document.formulario['DAFormacao'+numFormacao].focus();

}
function validaOutros()
{
    //indicado por
    var oTextbox = document.getElementById("tbIndicado");
    var oDiv = oTextbox.parentElement;    
    if (oDiv.style.display == "block" && oTextbox.value == "")        
    {
        alert("Favor preencher o campo Indicado por");    
        return false;
    }   
   
    //revista
    var oTextbox = document.getElementById("tbQualRevista");
    var oDiv = oTextbox.parentElement;    
    if (oDiv.style.display == "block" && oTextbox.value == "")        
    {
        alert("Favor preencher o campo Qual revista");  
        return false;
    }
    
    //jornal
    var oTextbox = document.getElementById("tbQualJornal");
    var oDiv = oTextbox.parentElement;    
    if (oDiv.style.display == "block" && oTextbox.value == "")
    {
        alert("Favor preencher o campo Qual jornal");  
        return false;
    }
        
    //outros
    var oTextbox = document.getElementById("tbOutroQual");
    var oDiv = oTextbox.parentElement;    
    if (oDiv.style.display == "block" && oTextbox.value == "")        
    {
        alert("Favor preencher o campo Outros. Qual");       
        return false;
    }
    return true;           
}

function validaForm(){

    //validacao de campos outros conhecimento do curso
    if (!validaOutros())
    {
        return false;
    }
    
    var f = document.forms[0];
    for( i = 0 ; i < f.elements.length; i++)
    {
        obj = f.elements[i];
        if ( obj.tagName == "INPUT" )
        {
            if ( obj.type )
            {
                var t = obj.type.toUpperCase();
                if ( t == "TEXT" )
                {
                    if ( obj.value == "" && obj.style.display != "none" )
                    {
                        if ( obj.className )
                            if ( obj.className == "naoObrigatorio" )
                                continue;

                        alert("Favor preencher todos os campos antes de continuar!");
                        return false;

                    }
                }
//                if ( t == "CHECKBOX" )
//                {
//                    if ( obj.value == "" && obj.style.display != "none" )
//                    {
//                        if ( obj.className )
//                            if ( obj.className == "naoObrigatorio" )
//                                continue;

//                        alert("Favor preencher todos os campos antes de continuar!");
//                        return false;

//                    }
//                }
            }
        }
    }
    return true;
}
function showCoop()
{
    document.getElementById("trCoop").style.display="";
    var vlr = document.getElementById("ihvalor").value;
    var desc = document.getElementById("ihdesconto").value;
    var num_parc = document.getElementById("ihparcela").value;
        
    if ( (vlr != "") && (desc != ""))
    {
        var calculo = vlr - (vlr*desc/100); 
        var resultado = calculo.toString();                       
        document.getElementById("div_valor").innerHTML = num_parc + " Parcelas de R$ " + resultado.replace(".",",") + " (Com desconto para Mantededor)";
    }    
}
function hideCoop()
{
    document.getElementById("trCoop").style.display="none";
    var vlr = document.getElementById("ihvalor").value;
    var num_parc = document.getElementById("ihparcela").value;
    var resultado = vlr.toString();  
    document.getElementById("div_valor").innerHTML = num_parc + " Parcelas de R$ " + resultado.replace(".",",") ;
}

function selCooperativa(id){
    if( id == -1 ){
        document.getElementById("divOutraCooperativa").style.display = "";
        document.getElementById("txtOutraCooperativa").style.display = "";
    }
    else{
        document.getElementById("divOutraCooperativa").style.display = "none";
        document.getElementById("txtOutraCooperativa").style.display = "none";
    }
}
function selEmpResp(id){
    if( id == -1 ){
        document.getElementById("divOutraEmpResp").style.display = "";
        document.getElementById("txtOutraEmpResp").style.display = "";
    }
    else{
        document.getElementById("divOutraEmpResp").style.display = "none";
        document.getElementById("txtOutraEmpResp").style.display = "none";
    }
}
function selSecEmp(id){
    if( id == -1 ){
        document.getElementById("divOutraSecEmp").style.display = "";
        document.getElementById("txtOutraSecEmp").style.display = "";
    }
    else{
        document.getElementById("divOutraSecEmp").style.display = "none";
        document.getElementById("txtOutraSecEmp").style.display = "none";
    }
}

function showEmpResp()
{
    document.getElementById("trEmpResp").style.display="";
}
function hideEmpResp()
{
    document.getElementById("trEmpResp").style.display="none";
}


function check()
{
    var obj = document.getElementsByName("COOPERADO");
    if ( obj[1] ) {
        if ( obj[1].checked )
            showCoop();
    }
}

var nPessoas = 0;
function selAcompanhantes()
{
    
    var obj = document.getElementById("pnlPessoas");
    var txtInicial = document.getElementById("pessoa_0");
    
    if ( document.forms[0].chkAcompanhantes[0].checked )
	{
	    txtInicial.style.display = "";
        obj.style.display = "";
	}
    else
	{
	    txtInicial.style.display = "none";
        obj.style.display = "none";
	}
        
}

function addPessoa()
{

	// verifica
	var oldtxt = document.getElementById("pessoa_" + nPessoas);
	if ( oldtxt.value == "" )
	{
		alert("Preencha o último campo de pessoa adicionado antes de incluir outra pessoa!");
		oldtxt.focus();
		return;
	}

	// ultimo botao
	document.getElementById("addPessoa_" + nPessoas).style.display = "none";
	var oldrem = document.getElementById("remPessoa_" + nPessoas);
	if (oldrem)
	{
		oldrem.style.display = "none";
	}


	// proximo
	nPessoas++;

	// conteudo
	var conteudo = document.getElementById("pnlPessoas");

	// texto
	var txt = document.createElement("input");
	txt.setAttribute("type","text");
	txt.id  = "pessoa_" + nPessoas;
	txt.name = "pessoa_" + nPessoas;
	txt.maxlength = 255;
	txt.size = 50;
	txt.style.marginRight = "10px";

	// botao++
	var btnadd = document.createElement("input");
	btnadd.type = "button";
	btnadd.id  = "addPessoa_" + nPessoas;
	btnadd.value = "( + ) Adicionar pessoa";
	btnadd.onclick = addPessoa

	// botao--
	var btnrem = document.createElement("input");
	btnrem.type = "button";
	btnrem.id  = "remPessoa_" + nPessoas;
	btnrem.value = "( - ) Remover pessoa";
	btnrem.onclick = remPessoa;

	// label
	var	nome = document.createElement("span");
	nome.id = "label_" + nPessoas;
	nome.innerHTML = "Nome : ";

	// quebra
	var	quebra = document.createElement("br");
	quebra.id = "quebra_" + nPessoas;

	// adiciona
	conteudo.appendChild(btnrem);
	conteudo.appendChild(quebra);
	conteudo.appendChild(nome);
	conteudo.appendChild(txt);
	conteudo.appendChild(btnadd);

}
function remPessoa(){
	
	// conteudo
	var conteudo = document.getElementById("pnlPessoas");

	// remove
	conteudo.removeChild(document.getElementById("addPessoa_" + nPessoas))
	conteudo.removeChild(document.getElementById("remPessoa_" + nPessoas))
	conteudo.removeChild(document.getElementById("pessoa_" + nPessoas))
	conteudo.removeChild(document.getElementById("label_" + nPessoas))
	conteudo.removeChild(document.getElementById("quebra_" + nPessoas))

	// ultimo botao
	nPessoas--;
	document.getElementById("addPessoa_" + nPessoas).style.display = "";
	var btnrem = document.getElementById("remPessoa_" + nPessoas);
	if (btnrem)
	{
		btnrem.style.display = "";

		if(nPessoas == 0)
		{
			btnrem.style.display = "none";
		}
	}

}
function restauraEstado(){
    if ( document.forms[0].COOPERADO[0].checked )
    {
        showCoop();
    }
    if ( document.forms[0].EMP_RESP[0].checked )
    {
        showEmpResp();
    }
    if ( document.forms[0].chkAcompanhantes ) 
    {
        if ( document.forms[0].chkAcompanhantes[0].checked )
        {
            selAcompanhantes();
        }
    }
}

function verificaAcesso(codCfo)
{
    if ( codCfo.substring(codCfo.length -1 , codCfo.length) == "*" )
    {
        alert(msgGeralRestrito);
        return false;
    }
    else
    {
        return true;
    }
}

function checkCPF(obj)
{
    if( !valida_cpf(obj.value))
    {
        alert("CPF inválido! Verifique novamente antes de continuar.");
        obj.select();
        return false;
    }
    return true;
}

function valida_cpf(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;
  }


