/** 
  * Função para Buscar os Pacientes Inline (Campo Auto-Preenchimento de acordo com o valor digitado)
  * @access public 
  * @param Object objeto
  * @param String id_conteiner
  * @param String script
  * @param String tipo
  * @param String cliente 
  * @param String mod
  * @param String sub
  * @param String pag 
  * @return Boolean 
  */ 
function buscaPaciente(event, objeto,id_conteiner,script, tipo, cliente, scriptSearchMore, prossegue, delay, minLength) {
  if (scriptSearchMore==null || scriptSearchMore==undefined) scriptSearchMore = '';
  if (prossegue==null || prossegue==undefined) prossegue = true;
  if (delay==null || delay==undefined) delay = 1700;
  if (minLength==null || minLength==undefined) minLength = (tipo=='nome') ? 7 : 3;
  tecla = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	var vStrcaract = new RegExp(/^[0-9a-zA-Z]+$/i);
	var vStrcaract = vStrcaract.test(String.fromCharCode(tecla));
  var vSetaUp = (event.keyCode==38);
  var vSetaDown = (event.keyCode==40);
  if (vSetaUp || vSetaDown) {
    if (document.getElementById(id_conteiner).style.display!='none' && trim(document.getElementById(id_conteiner).innerHTML)!='') {
      tipo = (vSetaUp?'up':'down'); 
      navegaObjetoPaciente(id_conteiner, tipo);
    }
    return true;
  }
  script += "; document.getElementById('"+id_conteiner+"').style.display='none';";
  if (event.keyCode==13) {
    if (document.getElementById(id_conteiner).style.display!='none' && trim(document.getElementById(id_conteiner).innerHTML)!='') {
      eval(script);
      return true;
    }
  }
  if (!(vStrcaract || tecla==8 || tecla==46)) return false;
  //if (app==undefined) app='';
  if (script==undefined) script='';
  if (typeof(exec)=='undefined') {
    exec = false;
  } else {
    window.clearTimeout(exec);
  }
  with(document.getElementById(id_conteiner)){
    style.display='block';
    innerHTML = '<img src="imagens/carrega.gif" />';
  }
  exec = window.setTimeout(   
    function () {
		  try{
        form = document.getElementById(objeto.form.id);
        defineCloseObject(objeto, id_conteiner);
        if (objeto.value.length < minLength){
          if (objeto.value.length > 0) {
            document.getElementById(id_conteiner).innerHTML = "<div class=\"msgInline\">Número insuficiente de caracteres para pesquisa!</div>";
          } else {
            document.getElementById(id_conteiner).style.display='none';
          }
          return false;
        }
        var str = objeto.value.replace(/'/g,'');
        var nome_alt = (document.getElementById('cliente_alt') ? document.getElementById('cliente_alt').value : "");
        var urlx = '?mode=ajax&mod=assistidos_auxiliar&p=procurarass&inline=1&cliente='+cliente+'&nome_alt='+nome_alt+'&scriptSearchMore='+escape(scriptSearchMore)+'&prossegue='+prossegue;
        urlx += '&'+tipo+'=' + str+'&id_conteiner='+id_conteiner;
        urlx += '&onclick='+script;
        var processar = form.processar.value
        form.processar.value=0;
        retorno = simple_sjax_post(urlx, id_conteiner, form.id, true,'',false);
        form.processar.value=processar;
        if (str==objeto.value.replace(/'/g,'')) {
          if(retorno.length > 0){
            document.getElementById(id_conteiner).innerHTML = retorno;
            //document.getElementById(id_conteiner).onclick=function() {eval(script);}
          }else{
            document.getElementById(id_conteiner).innerHTML = "<div class=\"msgInline\">Nenhum Paciente encontrado!</div>";
          }
        }
        return true;
      }catch(erro){alert(erro)}
      return false;
    }
    ,delay
  );
}

function navegaObjetoPaciente(id_conteiner, tipo) {
    var cliAtual = parseInt(document.getElementById('seq_paciente_inline_sel').value);
    cliOld = cliAtual;
    cliAtual = (tipo=='up'?cliAtual-1:cliAtual+1);
    if (cliAtual<=0) cliAtual = 1;
    if (document.getElementById('id_paciente_inline_'+cliAtual)==null) cliAtual = cliOld;
    highlightAssistidoLista(cliAtual);

    //document.getElementById('tr_paciente_inline_'+cliAtual).className = 'selectLine2Hover'; 
    if (document.getElementById('tr_paciente_inline_'+(cliAtual-1))!=null) document.getElementById('tr_paciente_inline_'+(cliAtual-1)).className = 'selectLine2';
    if (document.getElementById('tr_paciente_inline_'+(cliAtual+1))!=null) document.getElementById('tr_paciente_inline_'+(cliAtual+1)).className = 'selectLine2';
}

function highlightAssistidoLista(seq) {
    if (seq!=0) {
	    var seqTmp = (document.getElementById('seq_paciente_inline_sel').value);
	    if (document.getElementById('tr_paciente_inline_'+seqTmp)!=null) document.getElementById('tr_paciente_inline_'+seqTmp).className='selectLine2';
	
	    document.getElementById('seq_paciente_inline_sel').value = seq;
    }
    document.getElementById('id_paciente_inline_sel').value = document.getElementById('id_paciente_inline_'+seq).value;
    document.getElementById('nome_paciente_inline_sel').value = document.getElementById('nome_paciente_inline_'+seq).value
    document.getElementById('mat_paciente_inline_sel').value = document.getElementById('mat_paciente_inline_'+seq).value
    document.getElementById('cpf_paciente_inline_sel').value = document.getElementById('cpf_paciente_inline_'+seq).value
    document.getElementById('plano_paciente_inline_sel').value = document.getElementById('plano_paciente_inline_'+seq).value
    document.getElementById('src_paciente_inline_sel').value = document.getElementById('src_paciente_inline_'+seq).value
    document.getElementById('cliente_alt_paciente_inline_sel').value = document.getElementById('cliente_alt_paciente_inline_'+seq).value


    if (seq!=0) document.getElementById('tr_paciente_inline_'+seq).className='selectLine2Hover';
    
}

function procurarAssistidoCaptacao(id_form, tela, prossegue) {
  try {
    if (prossegue==null || prossegue==undefined) prossegue = true;
    var cliente   = '';
    var matricula = '';
    var nome      = '';
    var cpf       = '';
    var ok        = false;
    var form = document.getElementById(id_form);
    var nome_alt = document.getElementById('cliente_alt').value;
 
    try {
      if (form.cliente && form.cliente.value != '' ) {
        cliente = form.cliente.value;
      }  
      if (form.paciente && form.paciente.value != '' ) {
           nome = escape(form.paciente.value);
      }
      
      if (form.matricula && form.matricula.value != '' ) {
        matricula = form.matricula.value;
      }
      if (form.cpf && form.cpf.value != '' ) {
        cpf = form.cpf.value;
      }
	  // call procurar
	  var dir  = 'mod=assistidos_auxiliar&p=procurarass';
	  var dir2 = dir + '&cli=' + cliente + '&nome_alt='+nome_alt+ '&nome=' + nome + '&mat=' + matricula + '&cpf=' + cpf + '&id_form=' + id_form + '&tela=' + tela;
	  dir2 += '&prossegue='+prossegue;
	  dialog('Procurar Assistido',dir2,850,580);
     
    }
    catch(e1) {}
  }
  catch(e) {}
}


function carregaComboCores(id_combo,produto,id_areacor) {
    combo = document.getElementById(id_combo);
    form = combo.form;
    var mod = document.getElementById('mod').value;
    var sub = document.getElementById('sub').value;
    var pag = document.getElementById('pag').value;
    document.getElementById(id_areacor).src = '';
    var urlx = '?mode=ajax&app=cem&mod='+mod+'&sub='+sub+'&pag='+pag+'&combo=busca_cor&produto='+produto+'&id_area_cor='+id_areacor;
    retorno = simple_sjax_post(urlx, id_combo, form.id);
    combo.innerHTML = retorno;
}

function selecionaAssistidoLista(id_form, tela) {
  id_cliente = document.getElementById('id_paciente_inline_sel').value;
  nome = document.getElementById('nome_paciente_inline_sel').value ;
  matricula = document.getElementById('mat_paciente_inline_sel').value;
  cpf = document.getElementById('cpf_paciente_inline_sel').value;
  cliente_alternativo = document.getElementById('cliente_alt_paciente_inline_sel').value;
  
  cod_plano = document.getElementById('plano_paciente_inline_sel').value;
  origem = document.getElementById('src_paciente_inline_sel').value;

  nome = (nome=='') ? document.getElementById('paciente').value : nome; 
  matricula = (matricula=='') ? document.getElementById('matricula').value : matricula;
  cpf = (cpf=='') ? document.getElementById('cpf').value : cpf;

  document.getElementById('idassistido').value = id_cliente;
  document.getElementById('paciente').value = nome;
  document.getElementById('matricula').value = matricula;
  document.getElementById('cpf').value = cpf;
  //document.getElementById('alterarCliente').style.display = 'none';    
  cem_selecionar_assistido_captacao(id_form, origem, id_cliente, matricula, nome, cpf, cod_plano, tela, cliente_alternativo);
  focaCampo(origem, tela, id_cliente, matricula);
}

function focaCampo(origem, tela, id_cliente, matricula) {
  if ( origem && id_cliente && matricula && (origem != '') && !isNaN(id_cliente) && (matricula != '') ) {
    inclusao_manual = 0;
    document.getElementById('dados_responsavel').responsavel.focus();
  } else {
    document.getElementById('formDadosAssist_manual').nome_assistido_manual.focus();
    inclusao_manual = 1;
  }    
}

function cem_selecionar_assistido_captacao(id_form, origem, id_cliente, matricula, nome, cpf, cod_plano, tela, cliente_alt) { 
  var via_tela = (document.getElementById('busca_assistidos_tela')!=null);

  var form = document.getElementById(id_form); 
  var inclusao_manual = 1;
  if (cliente_alt==null || cliente_alt==undefined) cliente_alt = '';
  try {
    if ( origem && id_cliente && matricula && (origem != '') && !isNaN(id_cliente) && (matricula != '') ) {
       inclusao_manual = 0;
    
       document.formDadosAssist_manual.nome_assistido_manual.className = 'input';
       document.formDadosAssist_manual.matricula_manual.className      = 'input';
       document.formDadosAssist_manual.idade_manual.className          = 'input';
       document.formDadosAssist_manual.sexo_manual[0].className        = 'input';
       document.formDadosAssist_manual.sexo_manual[1].className        = 'input';       
    }

    // desabilitar as funcoes de busca
    if (form.cliente)   form.cliente.disabled   = true;
    if (form.matricula) form.matricula.disabled = true;
    if (form.cpf)       form.cpf.disabled       = true;
    if (form.procurar_assistido == undefined) {
      procurar_assistido = document.getElementById('procurar_assistido');
      if (procurar_assistido) procurar_assistido.disabled = true;
    } else {
      form.procurar_assistido.disabled = true;
    }
    if (form.inclui_manual == undefined) {
      inclui_manual = document.getElementById('inclui_manual');
      inclui_manual.disabled = true;
    } else {
      form.inclui_manual.disabled = true;
    }
    // preencher form com os dados do assistido
    //form.paciente.value  = nome;
    if(form.matricula)  form.matricula.value = matricula;
    if(form.cpf)        form.cpf.value       = cpf;            
    
    try {
      var but = document.getElementById('cem_proc_ass');
      if (but) {
        but.innerHTML = '';
      }

    } catch(ee) { alert(ee); }           

    closeDialog();

    document.getElementById('matricula_manual').maxLength = getMaxLenMatricula('formDadosAssist_manual',document.getElementById('cliente').value);

    var params = '&de=' + origem + '&cli=' + id_cliente + '&mat=' + escape(matricula) + '&cliente_alt='+cliente_alt+'&prod='+tela;
      
    // ocultar aba de busca
    var divbusca = document.getElementById('formCaptacao3');
    if (divbusca) { divbusca.style.display = 'none'; }    
    
    
    //Se for inclusão manual... habilita campos
    if(inclusao_manual == 1) {
      // mostrar fieldset contato
      var fieldcontato= document.getElementById('table_incl_manual');
      if (fieldcontato) { fieldcontato.style.display = ''; }
      
      // ocultar botao de completar endereco do assistido
      var botao_end_orig= document.getElementById('botao_endereco_assistido_orig_ida');
      if (botao_end_orig) { botao_end_orig.style.display = 'none'; }                                       
      var botao_end_orig= document.getElementById('botao_endereco_assistido_orig_volta');
      if (botao_end_orig) { botao_end_orig.style.display = 'none'; }                                       
      // ocultar botao de completar endereco do assistido
      var botao_end_dest= document.getElementById('botao_endereco_assistido_dest');
      if (botao_end_dest) { botao_end_dest.style.display = 'none'; }
      
      var botao_ant_orig= document.getElementById('botao_endereco_missaoant_assistido_orig_ida');
      if (botao_ant_orig) { botao_ant_orig.style.display = 'none'; }    
      
      if (via_tela) {
        document.getElementById('paciente').value = nome;
        document.getElementById('matricula').value = nome;
        document.getElementById('cpf').value = nome;
      }
      document.getElementById('nome_assistido_manual').value = nome;
      document.getElementById('matricula_manual').value = matricula;
      document.getElementById('cpf_manual').value = incluiPontuacaoCPF(cpf);
      if (matricula!='') validaMatricula('formDadosAssist_manual','matricula_manual',document.getElementById('cliente').value, document.getElementById('matricula_manual').value);
      //formataCPF(document.getElementById('cpf_manual'));
      //validaMatricula('formDadosAssist_manual','matricula_manual',document.getElementById('cliente').value, document.getElementById('matricula_manual').value);             
    } else {
      // mostrar fieldset contato
      var fieldcontato= document.getElementById('field_contato_TIT');
      if (fieldcontato) { fieldcontato.style.display = ''; }
    }
            

    // mostrar aba de atendimento TIT
    var divamt = document.getElementById('dv_atendimento_TIT');
    if (divamt) divamt.style.display = '';
    

    // mostrar aba de contato
    var div1 = document.getElementById('dv_contato_tit');
    if (div1) {
      div1.style.display = '';
      if (inclusao_manual==0) {
        var ret = simple_sjax_post('?mode=ajax&mod=atendimento&p=getcadastro' + params, 'dv_contato_tit', '');
        div1.innerHTML = ret;
      }
    }
    
    
    var fieldhist= document.getElementById('dv_historico_sup');
    if ((origem != '' || id_cliente != '' || matricula != '')&&(inclusao_manual==0)) {
      var rethist = simple_sjax_post('?mode=ajax&mod=atendimento&p=gethistorico&prod=tit' + params,'dv_historico_sup','');
      if (rethist.match('Não foram encontrados') || rethist.match('N&atilde;o foram encontrados')) {
        if (fieldhist) { fieldhist.style.display = 'none'; }
      } else {
        if (fieldhist) { fieldhist.style.display = ''; }
      }
      document.getElementById('dv_historico_sup').innerHTML = rethist;   
      //ajax_get_into('?mode=ajax&app=cem&mod=captacao&sub=novoatend&pag=gethistorico' + params, 'dv_historico', '');
    } else {
     var fieldhist= document.getElementById('dv_historico_sup');
     if (fieldhist) { fieldhist.style.display = 'none'; }
    }
    

    // mostrar fieldset Reiteracoes / Advertencias
    var auth = document.getElementById('autorizacao');
    if (auth) auth.style.display = 'block';
    

    var tr_missao = document.getElementById('trmissao');
    if (tr_missao) tr_missao.style.display = 'block';
    
    document.getElementById('tbConfirma').style.display = 'block';
    document.getElementById('spnAlertaObr').style.display = '';
    document.getElementById('trSepNum').style.display = 'none';
    document.getElementById('tdSepNum').style.display = 'none';
    //autoSave('formTIT','salvar_captacao_tit(true)')
    return true;
  }
  catch(e) {}
}

function getMaxLenMatricula(form, id_cliente) {
    document.getElementById(form).processar.value = 1;
    var ret = simple_sjax_post('?mode=ajax&mod=assistidos_auxiliar&p=getlenmatricula&id_cliente='+id_cliente,form,form,true,'',false);
    document.getElementById(form).processar.value = 0;
    return ret;
}

function validaMatricula(form, campo, id_cliente, matricula) {
    document.getElementById(form).processar.value = 1;
    matricula = trim(matricula);
    var ret = simple_sjax_post('?mode=ajax&mod=assistidos_auxiliar&p=validamatricula&id_cliente='+id_cliente+'&matricula='+matricula,form,form, true,'',false);
    if (ret==1) {
        //alert('true');
    } else {
        alert('Matrícula Inválida. Verifique!');
        document.getElementById(campo).value='';
        document.getElementById(campo).focus();
    }
    document.getElementById(form).processar.value = 0;
    return ret;
}

/** 
  * Função para Buscar os Clientes (Gerenciadores) Inline (Campo Auto-Preenchimento de acordo com o valor digitado)
  * @access public 
  * @param Object objeto
  * @param String id_conteiner
  * @param String script
  * @param String mod
  * @param String sub
  * @param String pag 
  * @return Boolean 
  */ 
function buscaCliente(event, objeto,id_conteiner,script, apagaCampo, filtroProduto, scriptSearchMore, delay) {
  if (filtroProduto==null || filtroProduto==undefined) filtroProduto = '';
  if (scriptSearchMore==null || scriptSearchMore==undefined) scriptSearchMore = '';
  if (delay==null || delay==undefined) delay = 1700;
  if (is_array(objeto)) {
    var objetos = objeto; 
    objeto = objeto[0];
  } else {
    var objetos = null;
  }
  tecla = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
  var vStrcaract = new RegExp(/^[0-9a-zA-Z]+$/i);
  var vStrcaract = vStrcaract.test(String.fromCharCode(tecla));
  var vSetaUp = (event.keyCode==38);
  var vSetaDown = (event.keyCode==40);
  if (vSetaUp || vSetaDown) {
    if (document.getElementById(id_conteiner).style.display!='none' && trim(document.getElementById(id_conteiner).innerHTML)!='') {
      tipo = (vSetaUp?'up':'down'); 
      navegaObjetoCliente(id_conteiner, tipo);
    }
    return true;
  }
  if (script==''||script==undefined||script==null) {
    if (document.getElementById('cliente')) {
      script = "selecionaClienteDef('"+objeto.id+"','cliente');";
    } else {
      script = "selecionaClienteDef('"+objeto.id+"','cliente_pesq');";
    }
  }
  script += "; document.getElementById('"+id_conteiner+"').style.display='none';";
  if (event.keyCode==13) {
    if (document.getElementById(id_conteiner).style.display!='none' && trim(document.getElementById(id_conteiner).innerHTML)!='') {
      eval(script);
      return true;
    }
  }
  if (!(vStrcaract || tecla==8 || tecla==46)) return false;
  script = (script==undefined) ? '' : script;
  //alert(script);
  apagaCampo = (apagaCampo==undefined) ? false : apagaCampo;
  if (typeof(exec)=='undefined') {
    exec = false;
  } else {
    window.clearTimeout(exec);
  }
  with(document.getElementById(id_conteiner)){
    style.display='block';
    innerHTML = '<img src="imagens/carrega.gif" />';
  }
  exec = window.setTimeout( 
    function () {
      try {
        form = document.getElementById(objeto.form.id);
        var minLength = 3;
        if (objetos==null) {
          defineCloseObject(objeto, id_conteiner, apagaCampo);
        } else {
          defineCloseObject(objetos, id_conteiner, apagaCampo);
        }
        if (objeto.value.length < minLength){
          document.getElementById(id_conteiner).style.display='none';
          return false;
        }
        var cliente = objeto.value;
        var str = objeto.value.replace(/'/g,'');
        var urlx = '?mode=ajax&mod=assistidos_auxiliar&p=buscaCliente&inline=1&cliente='+cliente+'&scriptSearchMore='+escape(scriptSearchMore)+'&onclick='+escape(script)+'&id_conteiner='+id_conteiner+'&filtroProduto='+filtroProduto;
        retorno = simple_sjax_post(urlx, id_conteiner, form.id, true, '', false );
        if (str==objeto.value.replace(/'/g,'')) {
          if(retorno.length > 0){
            document.getElementById(id_conteiner).innerHTML = retorno;
            //document.getElementById(id_conteiner).onclick=function() {eval(script);}
          }else{
            document.getElementById(id_conteiner).innerHTML = "<div class=\"msgInline\">Nenhum Cliente encontrado!</div>";
          }
        }
        document.getElementById(id_conteiner).style.display='block';
        return true;
      } catch(erro){alert(erro);}
      return false;
    }
    ,1700
  );
}

function navegaObjetoCliente(id_conteiner, tipo) {
    var cliAtual = parseInt(document.getElementById('seq_cliente_inline_sel').value);
    cliOld = cliAtual;
    cliAtual = (tipo=='up'?cliAtual-1:cliAtual+1);
    if (cliAtual<=0) cliAtual = 1;
    if (document.getElementById('id_cliente_inline_'+cliAtual)==null) cliAtual = cliOld;
    document.getElementById('seq_cliente_inline_sel').value = cliAtual;
    document.getElementById('id_cliente_inline_sel').value = document.getElementById('id_cliente_inline_'+cliAtual).value;
    document.getElementById('nome_cliente_inline_sel').value = document.getElementById('nome_cliente_inline_'+cliAtual).value;
    document.getElementById('nome_alt_cliente_inline_sel').value = document.getElementById('nome_alt_cliente_inline_'+cliAtual).value;
    document.getElementById('tr_cliente_inline_'+cliAtual).className = 'selectLine2Hover'; 
    if (document.getElementById('tr_cliente_inline_'+(cliAtual-1))!=null) document.getElementById('tr_cliente_inline_'+(cliAtual-1)).className = 'selectLine2';
    if (document.getElementById('tr_cliente_inline_'+(cliAtual+1))!=null) document.getElementById('tr_cliente_inline_'+(cliAtual+1)).className = 'selectLine2';
}

function highlightCliente(id_cliente, nome, nome_alternativo, seq) {
    document.getElementById('id_cliente_inline_sel').value=id_cliente; 
    document.getElementById('nome_cliente_inline_sel').value=nome;
    document.getElementById('nome_alt_cliente_inline_sel').value=nome_alternativo; 
    var seqTmp = (document.getElementById('seq_cliente_inline_sel').value);
    if (document.getElementById('tr_cliente_inline_'+seqTmp)!=null) document.getElementById('tr_cliente_inline_'+seqTmp).className='selectLine2';
    document.getElementById('seq_cliente_inline_sel').value=seq; 
    document.getElementById('tr_cliente_inline_'+seq).className='selectLine2Hover';
}

function selecionaClienteDef(objeto, objeto_id) {
    document.getElementById(objeto).value = document.getElementById('nome_cliente_inline_sel').value;
    document.getElementById(objeto_id).value = document.getElementById('id_cliente_inline_sel').value; 
}

function procurarClienteCaptacao(id_form, tela, filtroProduto, exibeModus) {
  try {
    var cliente   = '';
    var matricula = '';
    var nome      = '';
    var cpf       = '';
    var ok        = false;
    var form = document.getElementById(id_form);
    if (exibeModus==null || exibeModus==undefined) exibeModus = true;
    nome = form.desc_cliente.value;
    try {
       var dir  = 'mod=assistidos_auxiliar&p=procurarcli';
       var dir2 = dir + '&nome=' + nome +'&id_form=' + id_form + '&tela=' + tela+'&filtroProduto='+filtroProduto;
       dir2 += '&exibeModus=false';

       if (form.processar) {
         var proc = form.processar.value;
         form.processar.value = 0;
       }
       dialog('Procurar Cliente',dir2,850,450,id_form);
       if (form.processar) {
         form.processar.value = proc;
       }
    }
    catch(e1) {}
  }
  catch(e) {}
}

function carregarClienteCaptacao() {
    var i = 0;
    tipo = 'TIT';
  	var imprime = document.getElementById('cliente_selecionado');
		if (document.getElementById('nome_cliente_tela_sel')!=null) {
		   cliente     = document.getElementById('nome_cliente_tela_sel').value;
		   id_cliente  = document.getElementById('id_cliente_tela_sel').value;
		   cliente_alt = document.getElementById('nome_alt_cliente_tela_sel').value;
		   var inline = false;
		} else {
       cliente     = document.getElementById('nome_cliente_inline_sel').value;
       id_cliente  = document.getElementById('id_cliente_inline_sel').value;
       cliente_alt = document.getElementById('nome_alt_cliente_inline_sel').value;
       var inline = true;
		}
    
  	document.getElementById('cliente').value = id_cliente;
  	document.getElementById('desc_cliente').value = cliente;
  	document.getElementById('cliente_alt').value = cliente_alt;
  	document.getElementById('cliente_alt_desc').value = cliente_alt;
  	
  	document.getElementById('trNomeAlt').style.display = '';
  
  	document.getElementById('procurar_cliente').style.display = 'none';
  	document.getElementById('procurar_cliente').src = 'icon_lupa_gray.gif';
  	document.getElementById('alterarCliente').style.display = 'inline';
  	document.getElementById('divConteinerCli').style.display = 'none';
	
    habilitaCamposAssistido(true); 
    document.getElementById('paciente').focus();

    document.getElementById('matricula_manual').onchange = function() {validaMatricula('formDadosAssist_manual','matricula_manual',document.getElementById('cliente').value, document.getElementById('matricula_manual').value);}
    
    if (imprime!=null) {
      imprime.innerHTML  = ' <input type="hidden" name="id_cliente_manual" id="id_cliente_manual" value="'+id_cliente+'">';
      imprime.innerHTML += ' <input type="hidden" name="cliente_manual" id="cliente_manual" value="'+cliente+'">';   
      imprime.innerHTML += ' <input type="hidden" name="cliente_alternativo_manual" id="cliente_alternativo_manual" value="'+cliente+'">';   
      imprime.innerHTML += cliente;
    }
}

function reSelCliente(obj) {
    form = obj.form.id;
    
    if (document.getElementById(form).idassistido)  document.getElementById(form).idassistido.value = '';
    if (document.getElementById(form).paciente)     document.getElementById(form).paciente.value = '';
    if (document.getElementById(form).matricula)    document.getElementById(form).matricula.value = '';
    if (document.getElementById(form).cpf)          document.getElementById(form).cpf.value = '';

    habilitaCamposAssistido(false);
    
    obj.style.display = 'none'; 
    
    document.getElementById('procurar_cliente').style.display = '';
    document.getElementById('procurar_cliente').src='imagens/icon_lupa.gif';
    document.getElementById('trNomeAlt').style.display='none';
    
}

function habilitaCamposAssistido(habilita) {
    
    if (document.getElementById('paciente')) document.getElementById('paciente').disabled = (!habilita);
    if (document.getElementById('matricula')) document.getElementById('matricula').disabled = (!habilita);
    if (document.getElementById('cpf')) document.getElementById('cpf').disabled = (!habilita);
    if (document.getElementById('procurar_assistido')) document.getElementById('procurar_assistido').disabled = (!habilita);
    if (document.getElementById('inclui_manual')) document.getElementById('inclui_manual').disabled = (!habilita);
    imagem = (habilita ? 'imagens/icon_lupa.gif' : 'imagens/icon_lupa_gray.gif');
    if (document.getElementById('procurar_assistido')) document.getElementById('procurar_assistido').src = imagem;
    imagem = (habilita ? 'imagens/user_add.png' : 'imagens/user_add_gray.png');
    if (document.getElementById('inclui_manual')) document.getElementById('inclui_manual').src = imagem;
    document.getElementById('desc_cliente').readOnly = habilita;
}

function calc_idade(data, id) {
  try {
    if (data=='') {
      document.getElementById(id).value = '';
      return true;
    }  
    
    var datax = data.split("/");
    var dia = parseFloat(datax[0]);
    var mes = parseFloat(datax[1]);
    var ano = parseFloat(datax[2]);
  
    var dataAtual = new Date();
    
    ano = parseInt( ano );
    diaAtual = parseFloat( dataAtual.getDate());
    mesAtual = parseFloat( dataAtual.getMonth()+1 );
    anoAtual = parseFloat( dataAtual.getFullYear());
  
    var idade = ( anoAtual - ano );
    if (mesAtual<mes) idade--;
    else {
      if (mesAtual==mes && diaAtual<dia) idade--;
    }
    
    document.getElementById(id).value = idade;
    return true;
  } catch(erro) {loading_start("error",erro,true,true);}
}

function selecionaHomeCare(valor) {
  document.getElementById('quais_homecare').style.visibility=(valor?'visible':'hidden');
  if (valor) {
    document.getElementsByName('monitoramento')[1].checked = true;
    document.getElementById('quais_monitoramento').style.visibility='hidden';
  }
  document.getElementById('spnMonitoramento').style.display=(valor?'none':'');
  document.getElementById('spnMonitoramento2').style.display=(valor?'':'none');
}

//Visualizar Busca de Equipamentos e Medicamentos TIT
function selecionarEquipamentos() {
  try {    
    var equipamentos  = document.getElementById('equ_selecionados').value;
    var medicamentos  = (document.getElementById('med_selecionados')?document.getElementById('med_selecionados').value:'');
    equipamentos = equipamentos.replace(/#/g,'&equip_');
    equipamentos = equipamentos.replace(/:/g,'=');
    medicamentos = medicamentos.replace(/#/g,'&med_');
    medicamentos = medicamentos.replace(/:/g,'=');
    var dir  = 'mod=atendimento&p=equipamentos'+equipamentos+medicamentos;
    dialog('Selecionar Equipamentos',dir,850,500);
    //if (document.getElementById('escolha_equipamentos').elements[1]!=null) document.getElementById('escolha_equipamentos').elements[1].focus(); 
  }   
  catch(e) {}
}

//Monta os equipamentos e medicamentos selecionados
function confirmaSelecaoEquipamentos() {
  try {  
    var todos_equipamentos = '';
    var todos_medicamentos = '';        
    var imprime_equ = document.getElementById('linha_equipamentos_selecionados');
    var valor_equ, nome_equ, id_equ, obj_equ;

    //Zera a impressão caso tenha algo
    var html_equip ='';

    //Captura os equipamentos
    if (is_ie()) {
      //for( x in document.getElementById('escolha_equipamentos').elements ) {
      for( x=0;x<9999;x++ ) {
        obj_equ = document.getElementById('escolha_equipamentos').elements[x];
        if (!obj_equ) break;
        
        if(obj_equ.value > 0) {
          valor_equ = obj_equ.value;
          nome_equ  = obj_equ.title;
          id_equ    = obj_equ.name.substr(3,4);
  
          html_equip += nome_equ+': '+valor_equ+'<br/> ';
  
          //Monta string para passar por hidden
          todos_equipamentos += '#'+id_equ+':'+valor_equ;
        }         
        
      }
    } else {
      for( x in document.getElementById('escolha_equipamentos').elements ) {
        obj_equ = document.getElementById('escolha_equipamentos').elements[x];
  
        if(obj_equ.value > 0) {
          valor_equ = obj_equ.value;
          nome_equ  = obj_equ.title;
          id_equ    = obj_equ.name.substr(3,4);
  
          html_equip += nome_equ+': '+valor_equ+'<br/> ';
  
          //Monta string para passar por hidden
          todos_equipamentos += '#'+id_equ+':'+valor_equ;
        }         
      }
    }

    //imprime o hidden
    html_equip += '<input type="hidden" name="equ_selecionados" id="equ_selecionados" value="'+todos_equipamentos+'">';

    if (is_ie()) {
      innerHTML_ie('linha_equipamentos_selecionados',html_equip);
    } else {
      imprime_equ.innerHTML = html_equip;
    }
    
    closeDialog();

    //Exibir linha equipamentos
    var divquaisequip = document.getElementById('equipamentos_selecionados');
    if (divquaisequip) { divquaisequip.style.display = ''; }

    if (document.getElementsByName('acompanhante')[0]) document.getElementsByName('acompanhante')[0].focus();

  }   
  catch(e) {alert(e);}
}

function checaPreMarcado(tipo, valor) {
  var tipo_cpo = '';
  if (tipo!='') tipo_cpo  = '_'+tipo;
  if (valor) {
    for (i=1;i<=3;i++) {
      document.getElementById('div_data_missao'+tipo_cpo+'_'+i).style.visibility='visible';
    }; 
    var coll = document.getElementById('div_data_missao'+tipo_cpo+'_3').childNodes;
    for (i in coll) {
      if (coll[i]!=null) {
        try {
          if (coll[i].className!='cemTitulos') {
            coll[i].className = 'oinput';
          }
        } catch(e) {}
        var col2 = coll[i].childNodes;
        for (j in col2) {
          if (col2[j]!=null) {
            try{
              col2[j].className = 'oinput';
            } catch(e) {}
          }
        }
      }
    }
    if (tipo!='ida' && tipo!='') {
      document.getElementById('spnPrevista'+tipo_cpo+'').style.visibility='hidden';
      document.getElementById('spnMisNAcionada'+tipo_cpo).style.display = 'none';
    }    
  } else {
    for (i=1;i<=3;i++) {
      document.getElementById('div_data_missao'+tipo_cpo+'_'+i).style.visibility='hidden';
    }; 
    var coll = document.getElementById('div_data_missao'+tipo_cpo+'_3').childNodes;
    for (i in coll) {
      if (coll[i]!=null) {
        try {
          if (coll[i].className!='cemTitulos') coll[i].className = 'desc';
        } catch(e) {}
        var col2 = coll[i].childNodes;
        for (j in col2) {
          try {
            if (col2[j]!=null) col2[j].className = 'desc';
          } catch(e) {}
        }
      }
    }
    if (tipo!='ida' && tipo!='') {
      document.getElementById('spnMisNAcionada'+tipo_cpo).style.display = (document.getElementById('prevista'+tipo_cpo).checked?'':'none');
      document.getElementById('spnPrevista'+tipo_cpo).style.visibility='hidden';
    }
  }
  
}

function copiaDataMissaoTIT() {
  var form_ida = document.getElementById('formDadosMissaoIda');
  var form_volta = document.getElementById('formDadosMissaoVolta');
  if (captura_valor_radiobutton(form_ida.premarcado_ida)==1) {
    document.getElementById('dpremarcada_volta').value = document.getElementById('dpremarcada_ida').value;
  }
}

function duplicaDadosMissaoVolta(obj) {
  try {
    //if (obj==null || obj==undefined) return false;
    var id_obj = obj.id;
    var nome_obj = obj.name;
    var form_obj = obj.form.id;
    var tipo_obj = obj.type;
    var id_dest = id_obj;
    if (id_dest=="") return false;
    //alert(id_dest);
    id_dest = id_dest.replace('_ida','_volta');
    id_dest = id_dest.replace('Ida','Volta');
    if (id_dest.match('orig')) {
      id_dest = id_dest.replace('origem','destino');
      id_dest = id_dest.replace('orig','dest');
    }
    else if (id_dest.match('dest')) {
      id_dest = id_dest.replace('destino','origem');
      id_dest = id_dest.replace('dest','orig');
    }
    if (document.getElementById(id_dest)) {
	    switch(tipo_obj) {
	        case 'select-one':
	            document.getElementById(id_dest).selectedIndex = document.getElementById(id_obj).selectedIndex;
	            break; 
	        case 'text':
	            document.getElementById(id_dest).value = document.getElementById(id_obj).value;
	            break; 
	        case 'checkbox':
	            document.getElementById(id_dest).checked = document.getElementById(id_obj).checked;
	            break; 
	        case 'radio':
	            var i=0;
	            while (document.getElementsByName(id_dest)[i]!=null) {
	                document.getElementsByName(id_dest)[i].checked = document.getElementsByName(id_obj)[i].checked;
	                i++; 
	            }
	            break; 
	        case 'textarea':
	            document.getElementById(id_dest).value = document.getElementById(id_obj).value;
	            break; 
	    }
	    if (document.getElementById(id_dest).onclick!=null) {
        var exec = String(document.getElementById(id_dest).onclick);
        exec = preparaFuncaoExecucaoEval(exec);
        eval(exec);
	    }
	    if (document.getElementById(id_dest).onchange!=null) {
        var exec = String(document.getElementById(id_dest).onchange);
        exec = preparaFuncaoExecucaoEval(exec);
        eval(exec);
	    }
	    if (document.getElementById(id_dest).onblur!=null) {
        var exec = String(document.getElementById(id_dest).onblur);
        exec = preparaFuncaoExecucaoEval(exec);
        eval(exec);
	    }
    }
  } catch(e) {
    alert(e);
  } 
}

function captura_endereco_assistido(formu, local, mostraAlert, label) {
  try {
    if (mostraAlert==null || mostraAlert==undefined) mostraAlert=true;
    if (label==null || label==undefined) label='';
    var obj = document.getElementById(formu);
    
    //Divide endereço do numero
    var endereco = explode(", ",document.getElementById('endereco').innerHTML);
    
    //Se não existir endereço para o assitido...
    if( endereco[0] <= 0 || endereco[0] == "N/A") {
      erroValidacao('Não existe endereço cadastrado para o assitido.');
      return false;
    }  
    if (mostraAlert) loading_start("success",'Favor confirmar o endereço e a formatação do CEP.',true,true); 
    if (local.match('orig') || local.match('dest')) {
      if (trim(document.getElementById('cep').innerHTML)!='') {
        eval("if (obj!=null) obj.cep_"+local+".value      = trim(document.getElementById('cep').innerHTML)");
        if (label=='') label = local;
        //buscarCep(trim(document.getElementById('cep').innerHTML), label, formu, true, false,1, true, true );
        buscarCepJS(trim(document.getElementById('cep').innerHTML), local );
        eval("if (obj!=null) obj.numero_"+local+".value   = (endereco[1] > 0 ? endereco[1]:' ')");
      } else {
        eval("if (obj!=null) obj.cep_"+local+".value      = trim(document.getElementById('cep').innerHTML)");
        eval("if (obj!=null) obj.endereco_"+local+".value = trim(endereco[0])");
        eval("if (obj!=null) obj.numero_"+local+".value   = (endereco[1] > 0 ? endereco[1]:' ')");
        eval("if (obj!=null) obj.compl_"+local+".value    = trim(document.getElementById('complemento').innerHTML)");
        eval("if (obj!=null) obj.bairro_"+local+".value   = trim(document.getElementById('bairro').innerHTML)");
        //eval("if (obj!=null) obj.cidade_"+local+".value   = trim(document.getElementById('cidade').innerHTML)");
        eval("if (obj!=null) obj.uf_"+local+".value       = trim(document.getElementById('estado').innerHTML)");
      }
    } else if( local == 'cobranca') {      
      obj.nome_cobranca.value     = trim(document.getElementById('nome_assistido').textContent);
      obj.cpf_cobranca.value      = trim(document.getElementById('cpf_assistido').textContent);
      obj.cep_cobranca.value      = trim(document.getElementById('cep').innerHTML);
      obj.endereco_cobranca.value = trim(endereco[0]);
      obj.numero_cobranca.value   = (endereco[1] > 0 ? endereco[1]:" ");
      obj.compl_cobranca.value    = trim(document.getElementById('complemento').innerHTML);
      obj.bairro_cobranca.value   = trim(document.getElementById('bairro').innerHTML);
      obj.cidade_cobranca.value   = trim(document.getElementById('cidade').innerHTML);
      obj.uf_cobranca.value       = trim(document.getElementById('estado').innerHTML);
    } else {
      erroValidacao('Erro ao capturar o endereco.');
    }
  } catch(erro) {
    loading_start("error",erro,true,true);
  } 
}

function captura_endereco_missao_anterior(formu, local) {
  try {
    var obj = document.getElementById(formu);
    var obj_missao = document.getElementById('missaoAnterior');

    if (obj==null || obj_missao==null) return false;

    //Divide endereço do numero
    var endereco = obj_missao.endereco_orig_ant.value;
    //Se não existir endereço para o assitido...
    if( endereco <= 0 || endereco == "N/A") {
      erroValidacao('Não existe missão anterior com endereço residencial de origem cadastrado para este paciente.');
      return false;
    }

    eval("if (obj.origem_"+local+" != null)  obj.origem_"+local+".value     = obj_missao.local_orig_ant.value");
    eval("if (obj.destino_"+local+" != null) obj.destino_"+local+".value    = obj_missao.local_orig_ant.value");
    eval("obj.cep_"+local+".value        = obj_missao.cep_orig_ant.value");
    eval("obj.endereco_"+local+".value   = obj_missao.endereco_orig_ant.value");
    eval("obj.numero_"+local+".value     = obj_missao.numero_orig_ant.value");
    eval("obj.compl_"+local+".value      = obj_missao.compl_orig_ant.value");
    eval("obj.cod_bairro_"+local+".value = obj_missao.codbairro_orig_ant.value");    
    eval("obj.bairro_"+local+".value     = obj_missao.bairro_orig_ant.value");
    eval("obj.cod_cidade_"+local+".value = obj_missao.codcidade_orig_ant.value");    
    eval("obj.cidade_"+local+".value     = obj_missao.cidade_orig_ant.value");
    eval("if (obj.uf_"+local+" != null) obj.uf_"+local+".value              = obj_missao.uf_orig_ant.value");
    eval("if (obj.cod_uf_"+local+" != null) obj.cod_uf_"+local+".value      = obj_missao.cod_uf_orig_ant.value");
    eval("if (obj.x_uf_"+local+" != null) obj.x_uf_"+local+".value          = obj_missao.x_uf_orig_ant.value");
    eval("if (obj.pais_"+local+" != null) obj.pais_"+local+".value          = '55'");
    eval("if (obj.cod_pais_"+local+" != null) obj.cod_pais_"+local+".value  = 'BRASIL'");
    
    eval("obj.tel_"+local+".value     = formataTel(obj_missao.tel_orig_ant.value)");
    eval("obj.cel_"+local+".value     = formataTel(obj_missao.cel_orig_ant.value)");
    
    eval("if (obj.x_uf_"+local+" != null) obj.x_uf_"+local+".style.display = 'none';");
    eval("if (obj.uf_"+local+" != null) obj.uf_"+local+".style.display = '';");
    
    eval("obj.pagina_"+local+".value     = obj_missao.pag_orig_ant.value");
    eval("obj.coordenada_"+local+".value = obj_missao.coord_orig_ant.value");            
    return true;
  } catch(erro) {
    loading_start("error",erro,true,true);
  } 
}


//Salvar TIT
function salvar_captacao_tit(autoSave) {
  try {
    var objTIT = document.getElementById('formTIT');
    objTIT.percurso.value = captura_valor_radiobutton( document.getElementById('formDadosMissaoGerais').percurso );
    
    if (autoSave==null||autoSave==undefined) autoSave = false;

    if (!autoSave) {
      var formValidado = true; 
      formValidado = (validaFormulario('formAutorizacao') && formValidado);
      if (objTIT.percurso.value!='1') {
  	    formValidado = (validaFormulario('formDestino_volta') && formValidado);
  	    formValidado = (validaFormulario('formOrigem_volta') && formValidado);
  	    formValidado = (validaFormulario('formDadosMissaoVolta') && formValidado);
  	  }
      formValidado = (validaFormulario('formDestino_ida') && formValidado);
      formValidado = (validaFormulario('formOrigem_ida') && formValidado);
      formValidado = (validaFormulario('formDadosMissaoIda') && formValidado);
      formValidado = (validaFormulario('formDadosCobranca') && formValidado);
      formValidado = (validaFormulario('formDadosMissaoGerais') && formValidado);
      formValidado = (validaFormulario('form_exames') && formValidado);
      formValidado = (validaFormulario('dados_responsavel') && formValidado);
      formValidado = ((document.getElementById('formDadosAssist')!=null) ? validaFormulario('formDadosAssist') : validaFormulario('formDadosAssist_manual')) && formValidado;  
      if (!formValidado) {
        loading_start("error","Favor preencher todos os campos obrigatórios!", true, true);
        return false;
      }
      //stopAutoSave();
      objTIT.processar.value = 0;
    }

    if (document.getElementById('motivosTit').value=='00008') document.getElementById('cortit').value = '02';
    if (document.getElementById('tipoambulancia').value!='00002' && document.getElementById('cortit').value == '04') {
      loading_start("error","Para Tipos de Recurso UTI não é possível ter-se uma Guia Azul!", true, true);
      return false;     
    }
    
    if (document.getElementById('intubado').value==1 || document.getElementById('uso_equipamento').value==1) {
      if (trim(document.getElementById('equ_selecionados').value)=='') {
        loading_start("error","Os Equipamentos do Paciente não foram informados. Por favor, verifique!", true, true);
        return false;     
      }
    }
    //Dados Assistido   
    objTIT.numero_guia.value = document.getElementById('formCaptacao3').numero_guia.value;
    if (document.getElementById('formDadosAssist')!=null) {
	    objTIT.id_assistido.value = document.getElementById('formDadosAssist').id_assistido.value;   
	    objTIT.id_cliente.value   = document.getElementById('formDadosAssist').id_cliente.value;
	    objTIT.cliente.value      = document.getElementById('formDadosAssist').cliente.value;
      objTIT.cliente_alternativo.value = document.getElementById('formDadosAssist').cliente_alternativo.value;
	    objTIT.nome.value         = document.getElementById('formDadosAssist').nome.value;
	    objTIT.cpf.value          = document.getElementById('formDadosAssist').cpf.value;
	    objTIT.rg.value           = document.getElementById('formDadosAssist').rg.value;
	    objTIT.matricula.value    = document.getElementById('formDadosAssist').matricula.value;
	    objTIT.data_nasc.value    = document.getElementById('formDadosAssist').data_nasc.value;
	    objTIT.idade.value        = document.getElementById('formDadosAssist').idade.value;
	    objTIT.grupo.value        = document.getElementById('formDadosAssist').grupo.value;
	    objTIT.cod_plano.value    = document.getElementById('formDadosAssist').cod_plano.value;
	    objTIT.plano.value        = document.getElementById('formDadosAssist').plano.value;
	    objTIT.sexo.value         = document.getElementById('formDadosAssist').sexo.value;  
    } else {
	    //Dados Assistido MANUAL 
	    objTIT.id_cliente_manual.value     = document.getElementById('formDadosAssist_manual').id_cliente_manual.value;
	    objTIT.cliente_manual.value        = document.getElementById('formDadosAssist_manual').cliente_manual.value;    
      objTIT.cliente_alternativo_manual.value = document.getElementById('formDadosAssist_manual').cliente_alternativo_manual.value;    
	    objTIT.nome_assistido_manual.value = document.getElementById('formDadosAssist_manual').nome_assistido_manual.value;
	    objTIT.matricula_manual.value      = document.getElementById('formDadosAssist_manual').matricula_manual.value;
	    objTIT.rg_manual.value             = document.getElementById('formDadosAssist_manual').rg_manual.value;
	    objTIT.cpf_manual.value            = document.getElementById('formDadosAssist_manual').cpf_manual.value;
	    objTIT.datanasc_manual.value       = document.getElementById('formDadosAssist_manual').datanasc_manual.value;
	    objTIT.idade_manual.value          = document.getElementById('formDadosAssist_manual').idade_manual.value;    
	    objTIT.tipo_idade_manual.value     = captura_valor_radiobutton( document.getElementById('formDadosAssist_manual').tipo_idade_manual );
	    objTIT.plano_manual.value          = '';
	    objTIT.sexo_manual.value           = captura_valor_radiobutton( document.getElementById('formDadosAssist_manual').sexo_manual );
	    objTIT.obs_manual.value            = '';
	  }
    //Dados Responsável
    //Valida Form
    objTIT.data_inicio_captacao.value  = document.getElementById('dados_responsavel').data_inicio_captacao.value;
    objTIT.responsavel.value           = document.getElementById('dados_responsavel').responsavel.value;
    objTIT.telefone.value              = document.getElementById('dados_responsavel').telefone.value;
    objTIT.telefone2.value             = document.getElementById('dados_responsavel').telefone2.value;

    objTIT.home_care.value             = captura_valor_radiobutton( document.getElementById('dados_responsavel').home_care );
    objTIT.quais_homecare.value        = document.getElementById('dados_responsavel').quais_homecare.value;
    objTIT.quais_homecare_outros.value = document.getElementById('dados_responsavel').quais_homecare_outros.value;
    objTIT.monitoramento.value             = captura_valor_radiobutton( document.getElementById('dados_responsavel').monitoramento );
    objTIT.quais_monitoramento.value        = document.getElementById('dados_responsavel').quais_monitoramento.value;
    objTIT.quais_monitoramento_outros.value = document.getElementById('dados_responsavel').quais_monitoramento_outros.value;
    objTIT.peso.value                  = document.getElementById('dados_responsavel').peso.value;    
    objTIT.cortit.value                = document.getElementById('dados_responsavel').cortit.value;
    objTIT.motivosTit.value            = document.getElementById('dados_responsavel').motivosTit.value;
    objTIT.complementoMotivo.value     = document.getElementById('dados_responsavel').complementoMotivo.value;

    objTIT.quais_exames.value          = document.getElementById('form_exames').quais_exames.value;        
    objTIT.quais_exames_desc.value     = document.getElementById('form_exames').quais_exames_desc.value + '\n' + document.getElementById('form_exames').quais_exames_outros.value;        
    objTIT.diagnostico.value           = document.getElementById('form_exames').diagnostico.value;
    objTIT.obs.value                   = document.getElementById('form_exames').obs.value;           

    objTIT.equ_selecionados.value      = document.getElementById('formDadosMissaoGerais').equ_selecionados.value;
    objTIT.med_selecionados.value      = document.getElementById('formDadosMissaoGerais').med_selecionados.value;        
    objTIT.acompanhante.value          = captura_valor_radiobutton( document.getElementById('formDadosMissaoGerais').acompanhante );
    objTIT.nome_acompanhante.value     = document.getElementById('formDadosMissaoGerais').nome_acompanhante.value; 
    objTIT.percurso.value              = captura_valor_radiobutton( document.getElementById('formDadosMissaoGerais').percurso );        
    objTIT.tipoambulancia.value        = document.getElementById('formDadosMissaoGerais').tipoambulancia.value;
    objTIT.intubado.value              = document.getElementById('formDadosMissaoGerais').intubado.value;
    objTIT.valor.value                 = 0; //document.getElementById('formDadosMissaoGerais').valor.value;

    objTIT.nome_cobranca.value         = (document.getElementById('formDadosCobranca').nome_cobranca?document.getElementById('formDadosCobranca').nome_cobranca.value:'');    
    objTIT.cpf_cobranca.value          = (document.getElementById('formDadosCobranca').cpf_cobranca?document.getElementById('formDadosCobranca').cpf_cobranca.value:'');
    objTIT.cep_cobranca.value          = (document.getElementById('formDadosCobranca').cep_cobranca?document.getElementById('formDadosCobranca').cep_cobranca.value:'');    
    objTIT.endereco_cobranca.value     = (document.getElementById('formDadosCobranca').endereco_cobranca?document.getElementById('formDadosCobranca').endereco_cobranca.value:'');    
    objTIT.numero_cobranca.value       = (document.getElementById('formDadosCobranca').numero_cobranca?document.getElementById('formDadosCobranca').numero_cobranca.value:'');
    objTIT.compl_cobranca.value        = (document.getElementById('formDadosCobranca').compl_cobranca?document.getElementById('formDadosCobranca').compl_cobranca.value:'');    
    objTIT.bairro_cobranca.value       = (document.getElementById('formDadosCobranca').bairro_cobranca?document.getElementById('formDadosCobranca').bairro_cobranca.value:'');
    objTIT.cidade_cobranca.value       = (document.getElementById('formDadosCobranca').cidade_cobranca?document.getElementById('formDadosCobranca').cidade_cobranca.value:'');    
    objTIT.uf_cobranca.value           = (document.getElementById('formDadosCobranca').uf_cobranca?document.getElementById('formDadosCobranca').uf_cobranca.value:'');    
    objTIT.tel_cobranca.value          = (document.getElementById('formDadosCobranca').tel_cobranca?document.getElementById('formDadosCobranca').tel_cobranca.value:'');
    objTIT.obs_cobranca.value          = (document.getElementById('formDadosCobranca').obs_cobranca?document.getElementById('formDadosCobranca').obs_cobranca.value:'');

    objTIT.premarcado_ida.value         = captura_valor_radiobutton( document.getElementById('formDadosMissaoIda').premarcado_ida );
    if (document.getElementById('formDadosMissaoIda').prevista_ida!=null) {
    	objTIT.prevista_ida.value           = document.getElementById('formDadosMissaoIda').prevista_ida.checked;
    } else {
      objTIT.prevista_ida.value           = false;
    }
    
    objTIT.dpremarcada_ida.value        = document.getElementById('formDadosMissaoIda').dpremarcada_ida.value;
    objTIT.horario_premarcada_ida.value = document.getElementById('formDadosMissaoIda').horario_premarcada_ida.value;
    objTIT.local_ida.value              = captura_valor_radiobutton( document.getElementById('formDadosMissaoIda').local_ida );    

    objTIT.origem_ida.value             = document.getElementById('formOrigem_ida').origem_orig_ida.value;
    objTIT.tipo_orig_ida.value          = document.getElementById('formOrigem_ida').tipo_orig_ida.value;
    objTIT.cep_orig_ida.value           = document.getElementById('formOrigem_ida').cep_orig_ida.value;
    objTIT.endereco_orig_ida.value      = document.getElementById('formOrigem_ida').endereco_orig_ida.value;
    objTIT.numero_orig_ida.value        = document.getElementById('formOrigem_ida').numero_orig_ida.value;
    objTIT.compl_orig_ida.value         = document.getElementById('formOrigem_ida').compl_orig_ida.value;
    objTIT.cod_bairro_orig_ida.value    = document.getElementById('formOrigem_ida').cod_bairro_orig_ida.value;    
    objTIT.bairro_orig_ida.value        = document.getElementById('formOrigem_ida').bairro_orig_ida.value;
    objTIT.cod_cidade_orig_ida.value    = document.getElementById('formOrigem_ida').cod_cidade_orig_ida.value;
    objTIT.cidade_orig_ida.value        = document.getElementById('formOrigem_ida').cidade_orig_ida.value;
    objTIT.cod_uf_orig_ida.value        = document.getElementById('formOrigem_ida').uf_orig_ida.value;
    objTIT.uf_orig_ida.value            = document.getElementById('formOrigem_ida').uf_orig_ida.value;
    objTIT.pagina_orig_ida.value        = document.getElementById('formOrigem_ida').pagina_orig_ida.value;
    objTIT.coordenada_orig_ida.value    = document.getElementById('formOrigem_ida').coordenada_orig_ida.value;
    objTIT.tel_orig_ida.value           = document.getElementById('formOrigem_ida').tel_orig_ida.value;
    objTIT.cel_orig_ida.value           = document.getElementById('formOrigem_ida').cel_orig_ida.value;
    objTIT.tel_orig3_ida.value          = document.getElementById('formOrigem_ida').tel_orig3_ida.value;
    objTIT.contato_orig_ida.value       = document.getElementById('formOrigem_ida').contato_orig_ida.value;
    objTIT.crm_contato_orig_ida.value   = document.getElementById('formOrigem_ida').crm_contato_orig_ida.value;    
    objTIT.referencia_orig_ida.value    = document.getElementById('formOrigem_ida').referencia_orig_ida.value;

    objTIT.destino_ida.value            = document.getElementById('formDestino_ida').destino_dest_ida.value;
    objTIT.tipo_dest_ida.value          = document.getElementById('formDestino_ida').tipo_dest_ida.value;
    objTIT.cep_dest_ida.value           = document.getElementById('formDestino_ida').cep_dest_ida.value;
    objTIT.endereco_dest_ida.value      = document.getElementById('formDestino_ida').endereco_dest_ida.value;
    objTIT.numero_dest_ida.value        = document.getElementById('formDestino_ida').numero_dest_ida.value;
    objTIT.compl_dest_ida.value         = document.getElementById('formDestino_ida').compl_dest_ida.value;
    objTIT.cod_bairro_dest_ida.value    = document.getElementById('formDestino_ida').cod_bairro_dest_ida.value;    
    objTIT.bairro_dest_ida.value        = document.getElementById('formDestino_ida').bairro_dest_ida.value;
    objTIT.cod_cidade_dest_ida.value    = document.getElementById('formDestino_ida').cod_cidade_dest_ida.value;
    objTIT.cidade_dest_ida.value        = document.getElementById('formDestino_ida').cidade_dest_ida.value;
    objTIT.cod_uf_dest_ida.value        = document.getElementById('formDestino_ida').uf_dest_ida.value;
    objTIT.uf_dest_ida.value            = document.getElementById('formDestino_ida').uf_dest_ida.value;
    objTIT.pagina_dest_ida.value        = document.getElementById('formDestino_ida').pagina_dest_ida.value;
    objTIT.coordenada_dest_ida.value    = document.getElementById('formDestino_ida').coordenada_dest_ida.value;
    objTIT.tel_dest_ida.value           = document.getElementById('formDestino_ida').tel_dest_ida.value;
    objTIT.cel_dest_ida.value           = document.getElementById('formDestino_ida').cel_dest_ida.value;
    objTIT.tel_dest3_ida.value          = document.getElementById('formDestino_ida').tel_dest3_ida.value;
    objTIT.contato_dest_ida.value       = document.getElementById('formDestino_ida').contato_dest_ida.value;
    objTIT.crm_contato_dest_ida.value   = document.getElementById('formDestino_ida').crm_contato_dest_ida.value;    
    objTIT.referencia_dest_ida.value    = document.getElementById('formDestino_ida').referencia_dest_ida.value;

    if (objTIT.percurso.value!='1') {
	    objTIT.premarcado_volta.value         = captura_valor_radiobutton( document.getElementById('formDadosMissaoVolta').premarcado_volta );
	    objTIT.prevista_volta.value           = document.getElementById('formDadosMissaoVolta').prevista_volta.checked;
	    objTIT.dpremarcada_volta.value        = document.getElementById('formDadosMissaoVolta').dpremarcada_volta.value;
	    objTIT.horario_premarcada_volta.value = document.getElementById('formDadosMissaoVolta').horario_premarcada_volta.value;
	    objTIT.local_volta.value              = captura_valor_radiobutton( document.getElementById('formDadosMissaoVolta').local_volta );    
	
	    objTIT.origem_volta.value             = document.getElementById('formOrigem_volta').origem_orig_volta.value;
	    objTIT.tipo_orig_volta.value          = document.getElementById('formOrigem_volta').tipo_orig_volta.value;
	    objTIT.cep_orig_volta.value           = document.getElementById('formOrigem_volta').cep_orig_volta.value;
	    objTIT.endereco_orig_volta.value      = document.getElementById('formOrigem_volta').endereco_orig_volta.value;
	    objTIT.numero_orig_volta.value        = document.getElementById('formOrigem_volta').numero_orig_volta.value;
	    objTIT.compl_orig_volta.value         = document.getElementById('formOrigem_volta').compl_orig_volta.value;
	    objTIT.cod_bairro_orig_volta.value    = document.getElementById('formOrigem_volta').cod_bairro_orig_volta.value;    
	    objTIT.bairro_orig_volta.value        = document.getElementById('formOrigem_volta').bairro_orig_volta.value;
	    objTIT.cod_cidade_orig_volta.value    = document.getElementById('formOrigem_volta').cod_cidade_orig_volta.value;
	    objTIT.cidade_orig_volta.value        = document.getElementById('formOrigem_volta').cidade_orig_volta.value;
	    objTIT.cod_uf_orig_volta.value        = document.getElementById('formOrigem_volta').uf_orig_volta.value;
	    objTIT.uf_orig_volta.value            = document.getElementById('formOrigem_volta').uf_orig_volta.value;
	    objTIT.pagina_orig_volta.value        = document.getElementById('formOrigem_volta').pagina_orig_volta.value;
	    objTIT.coordenada_orig_volta.value    = document.getElementById('formOrigem_volta').coordenada_orig_volta.value;
	    objTIT.tel_orig_volta.value           = document.getElementById('formOrigem_volta').tel_orig_volta.value;
      objTIT.cel_orig_volta.value           = document.getElementById('formOrigem_volta').cel_orig_volta.value;
	    objTIT.tel_orig3_volta.value          = document.getElementById('formOrigem_volta').tel_orig3_volta.value;
	    objTIT.contato_orig_volta.value       = document.getElementById('formOrigem_volta').contato_orig_volta.value;
	    objTIT.crm_contato_orig_volta.value   = document.getElementById('formOrigem_volta').crm_contato_orig_volta.value;    
	    objTIT.referencia_orig_volta.value    = document.getElementById('formOrigem_volta').referencia_orig_volta.value;
	
	    objTIT.destino_volta.value            = document.getElementById('formDestino_volta').destino_dest_volta.value;
	    objTIT.tipo_dest_volta.value          = document.getElementById('formDestino_volta').tipo_dest_volta.value;
	    objTIT.cep_dest_volta.value           = document.getElementById('formDestino_volta').cep_dest_volta.value;
	    objTIT.endereco_dest_volta.value      = document.getElementById('formDestino_volta').endereco_dest_volta.value;
	    objTIT.numero_dest_volta.value        = document.getElementById('formDestino_volta').numero_dest_volta.value;
	    objTIT.compl_dest_volta.value         = document.getElementById('formDestino_volta').compl_dest_volta.value;
	    objTIT.cod_bairro_dest_volta.value    = document.getElementById('formDestino_volta').cod_bairro_dest_volta.value;    
	    objTIT.bairro_dest_volta.value        = document.getElementById('formDestino_volta').bairro_dest_volta.value;
	    objTIT.cod_cidade_dest_volta.value    = document.getElementById('formDestino_volta').cod_cidade_dest_volta.value;
	    objTIT.cidade_dest_volta.value        = document.getElementById('formDestino_volta').cidade_dest_volta.value;
	    objTIT.cod_uf_dest_volta.value        = document.getElementById('formDestino_volta').uf_dest_volta.value;
	    objTIT.uf_dest_volta.value            = document.getElementById('formDestino_volta').uf_dest_volta.value;
	    objTIT.pagina_dest_volta.value        = document.getElementById('formDestino_volta').pagina_dest_volta.value;
	    objTIT.coordenada_dest_volta.value    = document.getElementById('formDestino_volta').coordenada_dest_volta.value;
	    objTIT.tel_dest_volta.value           = document.getElementById('formDestino_volta').tel_dest_volta.value;
      objTIT.cel_dest_volta.value           = document.getElementById('formDestino_volta').cel_dest_volta.value;
	    objTIT.tel_dest3_volta.value          = document.getElementById('formDestino_volta').tel_dest3_volta.value;
	    objTIT.contato_dest_volta.value       = document.getElementById('formDestino_volta').contato_dest_volta.value;
	    objTIT.crm_contato_dest_volta.value   = document.getElementById('formDestino_volta').crm_contato_dest_volta.value;    
	    objTIT.referencia_dest_volta.value    = document.getElementById('formDestino_volta').referencia_dest_volta.value;
    }
    objTIT.autorizante.value           = document.getElementById('formAutorizacao').autorizante.value;
    objTIT.senha.value                 = document.getElementById('formAutorizacao').senha.value;    
    if (!autoSave) {
      var urlx  = '?mode=ajax&mod=atendimento&p=salvartit&modal=0';
      var where = 'include';
      //var postp = "if (document.getElementById('txtAdicionaObs')!=null) document.getElementById('txtAdicionaObs').focus(); ";
      ajax_post(urlx, where, 'formTIT', '');
    }
  }
  catch(e) { alert(e); } 
}

function valida_idade_captacao() {
  if (document.getElementById('formDadosAssist')!=null) {
    var idade = document.getElementById('formDadosAssist').idade.value;
    var tipo_idade = captura_valor_radiobutton(document.getElementById('formDadosAssist').tipo_idade_manual);
    var campo_idade = document.getElementById('formDadosAssist').idade;
  } else if (document.getElementById('dadosARP')!=null) {
    var idade = document.getElementById('dadosARP').idadeARP.value;
    var tipo_idade = captura_valor_radiobutton(document.getElementById('dadosARP').tipo_idadeARP);
    var campo_idade = document.getElementById('dadosARP').idadeARP;
  } else {
    var idade = document.getElementById('formDadosAssist_manual').idade_manual.value;
    var tipo_idade = captura_valor_radiobutton(document.getElementById('formDadosAssist_manual').tipo_idade_manual);
    var campo_idade = document.getElementById('formDadosAssist_manual').idade_manual;
  }
  if (tipo_idade == 2 && idade > 12) {
    erroValidacao('A idade em meses não pode ser maior que 12');
    campo_idade.value = '';
  }
  if (tipo_idade == 3 && idade > 31) {
    erroValidacao('A idade em dias não pode ser maior que 31');
    campo_idade.value = '';
  }
}

//Pesquisar uma Área Protegida
function procurarARP(formulario, destino)
{
  try {
  	document.getElementById('formEnderecoX').form_orig.value = formulario;
  	document.getElementById('formEnderecoX').destino.value = destino;
  	document.getElementById('formEnderecoX').processar.value = 1;
  	var urlx  = '?mode=ajax&mod=cadastroarp&p=main';
  	var where = 'divResultARP';
  	ajax_post(urlx, where, 'formEnderecoX', '');
    return true;
  }
  catch(e) {return false;}
}


function editaARP(id_area_protegida) {
    var id_cliente = document.getElementById('cliente_pesq').value;
    if (trim(id_area_protegida)!='') {
      dialog('Editar &Aacute;rea Protegida','mod=cadastroarp&p=edit&id_area_protegida='+id_area_protegida, 640, 450);
    } else {
      dialog('Adicionar &Aacute;rea Protegida','mod=cadastroarp&p=edit&id_cliente='+id_cliente, 640, 450);
    } 
    modalDialog.setCloseAction("ajax_post('?mode=ajax&mod=cadastroarp&p=main','divResultARP','formEnderecoX','')");
    return false;
}

function excluiARP(id_arp) {
  var retorno = simple_sjax_post('?mode=ajax&mod=cadastroarp&p=excluir&id_area_protegida='+id_arp,'formARP','formARP');
  if (retorno==true) {
    img = "imagens/omt_ok.png";
    msg = "<span><b>&Aacute;rea Protegida Excluída</b> com sucesso</span>";
  } else {
    //img = "<img src='imagens/omt_erro.png'>";
    img = "imagens/omt_erro.png";
    msg = "<span>Ocorreu um erro ao <b>Salvar a &Aacute;rea Protegida</b></span>";
    msg+= "<br>"+retorno+".";
  }
  carregaHTMLRetornoGravacao(img,msg);
  return false;
}

function salvarARP() {
  if (!validaFormulario('formARP')) return false;
  var form = document.getElementById('formARP');
  form.processar.value = 1;
  var retorno = simple_sjax_post('?mode=ajax&mod=cadastroarp&p=edit','formARP','formARP');
  form.processar.value = 0;
  if (retorno==true) {
    img = "imagens/omt_ok.png";
    msg = "<span><b>&Aacute;rea Protegida Salva</b> com sucesso</span>";
  } else {
    //img = "<img src='imagens/omt_erro.png'>";
    img = "imagens/omt_erro.png";
    msg = "<span>Ocorreu um erro ao <b>Salvar a &Aacute;rea Protegida</b></span>";
    msg+= "<br>"+retorno+".";
  }
  carregaHTMLRetornoGravacao(img,msg);
  return false;
}

function exibirGuiaRelatorio(cod_cliente, nro_guia) {
  var tela = '';
 
  try {   
    if ( isNaN(cod_cliente) ) {
      erroValidacao('Codigo de Cliente invalido!');
      return false;
    }
    if ( isNaN(nro_guia) ) {
      erroValidacao('Numero de Guia invalida!');
      return false;
    }
    
    else dir = 'mod=relcliente&p=verguia&guia='+nro_guia+ '&cli=' + cod_cliente+'&tela=' + tela + '&tipo=captacao';
    dialog('Consulta de Guia',dir,970,500);
  }
  catch(e) { alert(e); }
}

function printGuia(cod_cliente, nro_guia) {
  var tela = '';
  try {   
    if ( isNaN(cod_cliente) ) {
      erroValidacao('Codigo de Cliente invalido!');
      return false;
    }
    if ( isNaN(nro_guia) ) {
      erroValidacao('Numero de Guia invalida!');
      return false;
    }

    var dir = 'pguia.php?mod=relcliente&p=verguia&guia='+nro_guia+ '&cli=' + cod_cliente+'&tela=' + tela + '&tipo=captacao';
    popup(dir,'imp_guia',970,500);
  }
  catch(e) { alert(e); }
}

function exibirGuiaOnline(cod_cliente, nro_guia) {
  try {   
    if ( isNaN(cod_cliente) ) {
      erroValidacao('Codigo de Cliente invalido!');
      return false;
    }
    if ( isNaN(nro_guia) ) {
      erroValidacao('Numero de Guia invalida!');
      return false;
    }
    
    else dir = 'mod=online&p=verguia&guia='+nro_guia+ '&cli=' + cod_cliente;
    dialog('Consulta de Guia',dir,970,500);
  }
  catch(e) { alert(e); }
}

function copia_endereco_tit(formu, seq, tipo)
{
    var obj = document.getElementById(formu);
    tipo = "_"+tipo;
    if (formu.match('Destino')) {
        orig = 'dest';
        orig2 = 'destino';
    } else {
        orig = 'orig';
        orig2 = 'origem';
    }
    eval("obj."+orig2+"_"+orig+tipo+".value  = document.getElementById('hist_local_'+seq).value");
    eval("obj.tipo_"+orig+tipo+".value       = document.getElementById('hist_tipo_'+seq).value");
    eval("obj.cep_"+orig+tipo+".value        = document.getElementById('hist_cep_'+seq).value");
    eval("obj.endereco_"+orig+tipo+".value   = document.getElementById('hist_endereco_'+seq).value");
    eval("obj.numero_"+orig+tipo+".value     = document.getElementById('hist_numero_'+seq).value");
    eval("obj.compl_"+orig+tipo+".value      = document.getElementById('hist_complemento_'+seq).value");
    eval("obj.cod_bairro_"+orig+tipo+".value = document.getElementById('hist_cod_bairro_'+seq).value");
    eval("obj.bairro_"+orig+tipo+".value     = document.getElementById('hist_bairro_'+seq).value");
    eval("obj.cod_cidade_"+orig+tipo+".value = document.getElementById('hist_cod_cidade_'+seq).value");    
    eval("obj.cidade_"+orig+tipo+".value     = document.getElementById('hist_cidade_'+seq).value");
    eval("obj.cod_uf_"+orig+tipo+".value     = document.getElementById('hist_cod_uf_'+seq).value");
    eval("obj.uf_"+orig+tipo+".value         = document.getElementById('hist_estado_'+seq).value");
    eval("obj.pagina_"+orig+tipo+".value     = document.getElementById('hist_pag_guia_'+seq).value");
    eval("obj.coordenada_"+orig+tipo+".value = document.getElementById('hist_coordenadas_'+seq).value");   
             
    return true;
}

function copia_telefone_tit(formu, seq, tipo)
{
    var obj = document.getElementById(formu);
    tipo = "_"+tipo;
    if (formu.match('Destino')) {
        orig = 'dest';
    } else {
        orig = 'orig';
    }

    eval("obj.tel_"+orig+tipo+".value = document.getElementById('hist_telefone_'+seq).value");   
             
    return true;
}

function selecionaMotivoTIT(id_motivo) {
  switch (id_motivo) {
    case '00004':
    case '00001':
      document.getElementById('percurso_I').checked = true;
      document.getElementById('quais_exames_outros').className = 'input';
      document.getElementById('field_missao_volta').style.display='none';
      break;
    case '00002':
    case '00003':
      document.getElementById('percurso_V').checked = true;
      document.getElementById('quais_exames_outros').className = 'oinput';
      document.getElementById('field_missao_volta').style.display='';
      break;
    case '00008':
      document.getElementById('percurso_I').checked = true;
      document.getElementById('quais_exames_outros').className = 'input';
      document.getElementById('field_missao_volta').style.display='none';
      document.getElementById('cortit').value='02'; 
      eval(preparaFuncaoExecucaoEval(String(document.getElementById('cortit').options[1].onclick)));
      break;
  }
}



