/*

ROTINAS DE MANIPULAÇÃO DA INTERFACE HTML

By
  Mauricio Fodra
  Jan 2010
  
*/

var Abas = null;
var CntResultados = 0;
var timer = null;
var Filtros = new Array(new Array("Legislação#0", "Civil#0", "Criminal#1", "Comercial#2", "Administrativa#3", "Trabalhista#4", "Tributária#5", "Eleitoral#6", "Geral#7", "Revista Forense#RFW"),
                        new Array("Ementários#1", "Civil#0", "Criminal#1", "Eleitoral#2", "Trabalhista#3", "Tributária#4", "Revista Forense#RFW"),
                        new Array("Acórdãos#2", "Civil#0", "Criminal#1", "Eleitoral#2", "Trabalhista#3", "Tributária#4", "Revista Forense#RFW"),
                        new Array("Súmulas/Enunciados#3", "Vinculantes#0", "STF#1", "TST#2", "STJ#3", "TRFs#4", "Orientações TST#5", "TRTs#6", "Estados (Tribunais e Colégios)#7", "AGU#8", "JEF#9", "TCU#10", "TCE#11"),
                        new Array("Doutrinas#4", "Civil#0", "Criminal#1", "Trabalhista#2", "Revista Forense#RFW"),
                        new Array("Pareceres#5", "Civil#0", "Criminal#1", "Trabalhista#2", "Revista Forense#RFW"),
                        new Array("Sentenças#6", "Civil#0", "Criminal#1", "Trabalhista#2", "Revista Forense#RFW"),
                        new Array("Prática#7", "Civil#0", "Criminal#1", "Trabalhista#2", "Tributário#3", "Eleitoral#4", "Revista Forense#RFW"));


/*

FUNÇÕES TRATADORAS DO HTML

*/
function ExibeDadosLogIn(status)
{
  var div_login = document.getElementById('div_login');
  var div_dados = document.getElementById('div_dados');
  
  div_login.style.display = (status)?'none':'block';
  div_dados.style.display = (status)?'block':'none';
  
  if (status)
  {
    document.getElementById('dados_nome').innerHTML = GetCookie('NOME');
    if (document.getElementById('linkJURID'))
    {
      document.getElementById('linkJURID').href = "http://premiumweb.jurid.com.br/?INTEGID=" + GetCookie('INTEGID') + '&IDFONTE=0';
      document.getElementById('linkBF').href = "https://secure.jurid.com.br/bibliotecaforense/?INTEGID=" + GetCookie('INTEGID') + '&IDFONTE=1';
      document.getElementById('linkBL').href = "https://secure.jurid.com.br/bibliotecaltr/?INTEGID=" + GetCookie('INTEGID') + '&IDFONTE=3';
      document.getElementById('linkRFE').href = "https://secure.jurid.com.br/revistaforense/?INTEGID=" + GetCookie('INTEGID') + '&IDFONTE=2';
    }
  }
  else
  {
    if (document.getElementById('linkJURID'))
    {
      document.getElementById('linkJURID').href = "http://premiumweb.jurid.com.br";
      document.getElementById('linkBF').href = "https://secure.jurid.com.br/bibliotecaforense";
      document.getElementById('linkBL').href = "https://secure.jurid.com.br/bibliotecaltr";
      document.getElementById('linkRFE').href = "https://secure.jurid.com.br/revistaforense";
    }
  } 
}
 
function PopulaOpcoesAreas(container)
{
  var option = null; 
  for (var i=0;i<Filtros.length;i++)
  {
    option = document.createElement('option');
    option.label = Filtros[i][0].split('#')[0];
    option.value = Filtros[i][0].split('#')[1];
    option.text = option.label;
    container.appendChild(option);
  }
}

function htmlPesquisar()
{
  var filtro = document.getElementById('filtro');
  filtro = filtro.options[filtro.selectedIndex].value;
  var modo = document.getElementById('modo').selectedIndex;
  var palavras = document.getElementById('epesquisa').value;
  
  if (palavras == "Digite aqui o assunto a pesquisar")
  {
    alert('Informe as palavras a serem pesquisadas!');
    document.getElementById('epesquisa').select();
    return;
  }
  
  PesquisarEmTudo(palavras, modo, filtro, "0");
}

function htmlNovoFiltro(filtro0, filtro1)
{
  if (filtro1.indexOf("RFW") != -1)
    PlotaListaDeResultados(RP.rfw, RP.qtd_rfw, 1);
    else
    {
      var palavras = unescape(GetCookie('PALAVRAS'));
      var modo = GetCookie('MODO');
      PesquisarApenasJURID(palavras, modo, filtro0, filtro1);
    }
}

function htmlRecuperarResultado()
{
  var palavras = unescape(GetCookie('PALAVRAS'));
  var spalavras = document.getElementById('spalavras');
  spalavras.innerHTML = palavras;
  SelecionaArea();
  
  var div = document.getElementById("aguarde");
  if (!div) return;
  if (div.style.display != 'block') div.style.display = "block";  

  CntResultados = 0;
  if (Abas) Abas.enable = false;//evito que o usuário troque de aba antes de completada a carga
  ExecutaPesquisa("jurid", [0,0,0,0], [100, 10, 100, 10], true, Tratadora);
  
  if (!timer)
    timer = setInterval("Tickar()", 60000);
}

function htmlOnAreaChange()
{
  var selecionado = document.getElementById('filtro').selectedIndex;
  htmlNovoFiltro(selecionado, "0");
}

function htmlProximasOcos()
{
  var biblioteca = (Abas.abaativa.data == "RFW")?'rfw':'jurid'; 
  var ps = document.getElementById('lista_resultados').getElementsByTagName('p');
  var indices = (biblioteca == 'jurid')?[ps.length, 0, 0, 0]:[0, 0, ps.length, 0];
  ExecutaPesquisa(biblioteca, indices, [100,10,100,10], false, TratadoraProximas);
}

/*

Montagem da interface

*/

function MontaAbas()
{
  var filtro0 = GetCookie('FILTRO0');
  var filtro1 = GetCookie('FILTRO1');
  
  if (!Abas)
  {
    Abas = new Fdr_LI_Abas(document.getElementById('abas'), "ativa", "inativa");
    Abas.onabaclick = function(evento, objeto, aba) 
                      {
                        htmlNovoFiltro(GetCookie('FILTRO0'), aba.data);
                      }
    Abas.enable = false;//evito que o usuário troque de aba antes de completada a carga
  }
  else
    Abas.limpa();
    
  var iFiltro = 0;
  var j = 0;
  var codigo = 0;
  var aux = null;
  
  for (i=0; i < Filtros.length; i++)
  {
    codigo = Filtros[i][0].split('#')[1];
    if (filtro0 == codigo)//achei a área, entao monto as abas
    {
      for (j=1;j<Filtros[i].length;j++)
      {
        aux = Filtros[i][j].split('#');
        Abas.adiciona(aux[0], aux[1], aux[1] == filtro1);
      }
      break;
    }
  }
  Abas.fimlista('clear');
}

function PlotaListaDeResultados(fonte, qtd_fonte, identificador)
{
  //limpando itens...
  var i = 0;
  var qtd_resultados = document.getElementById('qtd_resultados');
  qtd_resultados.innerHTML = qtd_fonte + " documentos <small>( por relevância )</small>";
  var p = null;
  var img = null;
  var pai = document.getElementById('lista_resultados');  
  //limpando a lista...
  var ps = pai.getElementsByTagName('p');
  while (ps.length > 0) pai.removeChild(ps[0]);
  ps = pai.getElementsByTagName('img');
  while (ps.length > 0) pai.removeChild(ps[0]);
  
  if (qtd_fonte > 0)
  {
    //nova lista
    var cores = new Array('#f3f7fa', '#e2edf3');
    for (i=0;i<fonte.length;i++)
    {
      img = document.createElement('img');
      img.src = (identificador == 0)?"/img/icon_JP.gif":"/img/icon_Forense.gif";
      img.style.padding = "4px 10px 0px 4px";
      img.style.cssFloat = "left";//FF
      img.style.styleFloat = "left";//IE    
      pai.appendChild(img);
  
      p = document.createElement('p');
      p.style.background = cores[i&1];
      p.innerHTML = fonte[i].sub;
      p.onclick = MontaOnClick(identificador, fonte[i]);
      p.onselectstart = function(){return false};
      pai.appendChild(p);
    }
  }
  else
  {
      p = document.createElement('p');
      p.style.background = "#f8f2f2";
      p.style.color = "red";
      p.innerHTML = 'Nenhuma ocorrência para esta área';
      p.onselectstart = function(){return false};
      pai.appendChild(p);
  }
  //exibindo/ocultando botão de + ocos  
  document.getElementById('btn_mais_ocos').style.display = (pai.getElementsByTagName('p').length >= qtd_fonte)?"none":"block";
}

function PlotaResultadoJURID()
{
  MontaAbas();
  PlotaListaDeResultados(RP.jurid, RP.qtd_jurid, 0);
}

function PlotaResultadoRFW()
{
  PlotaListaDeResultados(RP.rfw, RP.qtd_rfw, 1);
}

function AbrirJanela(endereco)
{
  if (window.navigator.userAgent.indexOf('MSIE') == -1)
    return window.open(endereco);
    else
    return window.open(endereco, null, 'width=' + screen.availWidth +  ', height=' + screen.availHeight + ',scrollbars=yes');
}

function PlotaResultadoBFW()
{
  /*
  BFW
  */
  var bloco = document.getElementById('bfw_bloco');
  bloco = RetornaElementosComId(bloco, "resultado_obras_obra_0")[0];
  var capa = RetornaElementosComId(bloco, "capa")[0];
  var titulo = RetornaElementosComId(bloco, "titulo")[0];
  var autor = RetornaElementosComId(bloco, "autor")[0];
  var visualizar = RetornaElementosComId(bloco, "botao_visualizar")[0];
  
  if (RP.qtd_bfw > 0)
  {
    bloco.style.display = "block";
//    bloco.onclick = function(){ window.open("https://secure.jurid.com.br/bibliotecaforense/?integid=" + GetCookie('INTEGID') + "&idobra=" + RP.bfw[0].idobra + "&palavra=" + GetCookie('PALAVRAS'), null, 'width=' + screen.availWidth +  ', height=' + screen.availHeight)};
    visualizar.onclick = function(){ AbrirJanela("https://secure.jurid.com.br/bibliotecaforense/?integid=" + GetCookie('INTEGID') + "&idobra=" + RP.bfw[0].idobra + "&palavra=" + unescape(GetCookie('PALAVRAS'))) };    
    capa.src = "http://secure.jurid.com.br/bibliotecaforense/cgi_obras/capas/" + RP.bfw[0].idobra + "_70x100.jpg";
    titulo.innerHTML = RP.bfw[0].titulo;
    autor.innerHTML = RP.bfw[0].autor;
  }
  else
    bloco.style.display = "none";
}

function PlotaResultadoBLW()
{
  /*
  BLW
  */
  var bloco = document.getElementById('blw_bloco');
  bloco = RetornaElementosComId(bloco, "resultado_obras_obra_0")[0];
  var capa = RetornaElementosComId(bloco, "capa")[0];
  var titulo = RetornaElementosComId(bloco, "titulo")[0];
  var autor = RetornaElementosComId(bloco, "autor")[0];
  var visualizar = RetornaElementosComId(bloco, "botao_visualizar")[0];
  
  if (RP.qtd_blw > 0)
  {
    bloco.style.display = "block";
    visualizar.onclick = function(){ AbrirJanela("https://secure.jurid.com.br/bibliotecaltr/?integid=" + GetCookie('INTEGID') + "&idobra=" + RP.blw[0].idobra + "&palavra=" + unescape(GetCookie('PALAVRAS')))};
    capa.src = "http://secure.jurid.com.br/bibliotecaltr/cgi_obras/capas/" + RP.blw[0].idobra + "_70x100.jpg";
    titulo.innerHTML = RP.blw[0].titulo;
    autor.innerHTML = RP.blw[0].autor;
  }
  else
    bloco.style.display = "none";
}

function MontaOnClick(identificador, item)
{
  return function (evento)
  {
    switch (identificador)
    {
      case 0:
//        window.open('http://premiumweb.jurid.com.br/?INTEGID=' + GetCookie('INTEGID') + '&CODDOC=' + item.iddoc + '&PALAVRAS=' + GetCookie('PALAVRAS'), null, 'width=' + screen.availWidth + ', height=' + screen.availHeight);
        AbrirJanela('http://premiumweb.jurid.com.br/?INTEGID=' + GetCookie('INTEGID') + '&CODDOC=' + item.iddoc + '&PALAVRAS=' + unescape(GetCookie('PALAVRAS')));
        break;
      case 1:
//        window.open('https://secure.jurid.com.br/revistaforense/?INTEGID=' + GetCookie('INTEGID') + '&IDOBRA=' + (parseInt(parseInt(item.idsecao)/10000)) + '&NPAG=' + item.pag +  '&PALAVRA=' + GetCookie('PALAVRAS'), null, 'width=' + screen.availWidth + ', height=' + screen.availHeight);
        AbrirJanela('https://secure.jurid.com.br/revistaforense/?INTEGID=' + GetCookie('INTEGID') + '&IDOBRA=' + (parseInt(parseInt(item.idsecao)/10000)) + '&NPAG=' + item.pag +  '&PALAVRA=' + unescape(GetCookie('PALAVRAS')));
        break;
    }
  }
}

function SelecionaArea()
{
  var filtro0 = GetCookie('FILTRO0');
  
  var filtros = document.getElementById('filtro');
  for (var i = 0; i < filtros.options.length; i++)
  {
    if (filtros.options[i].value == filtro0)
    {
      filtros.selectedIndex = i;
      return;
    }
  }
}

function GeraHTMLCelula(caminho, container, idobra, titulo, autor, posicao)
{
  var celula =  "<div id=\"blocoObra_" + idobra + "\">" + 
                "    <img id=\"capa_" + idobra + "\" src=\"http://secure.jurid.com.br/" + caminho + "/cgi_obras/capas/" + idobra + "_70x100.jpg\" alt=\"capa\" class=\"fleft capa\" style=\"cursor:pointer\" />" +
                "    <p class=\"fleft titulo-autor\">" +
                "      <span style=\"font-weight:bold\">" + titulo + "</span>" +
                "      <br />" +
                "      <span>" + autor + "</span>" +
                "      <br />" +
//                "      <img src=\"img/btn_visualizar.gif\" alt=\"Visualizar Obra\" onclick=\"window.open('https://secure.jurid.com.br/" + caminho + "/?integid=" + GetCookie('INTEGID') + "&idobra=" + idobra + "&palavra=" + GetCookie('PALAVRAS') + "', null, 'width=screen.availWidth, height=screen.availHeight')\";/>" +
                ((window.navigator.userAgent.indexOf('MSIE') == -1)?("<img src=\"img/btn_visualizar.gif\" alt=\"Visualizar Obra\" onclick=\"window.open('https://secure.jurid.com.br/" + caminho + "/?integid=" + GetCookie('INTEGID') + "&idobra=" + idobra + "&palavra=" + unescape(GetCookie('PALAVRAS')) + "')\";/>"):("<img src=\"img/btn_visualizar.gif\" alt=\"Visualizar Obra\" onclick=\"window.open('https://secure.jurid.com.br/" + caminho + "/?integid=" + GetCookie('INTEGID') + "&idobra=" + idobra + "&palavra=" + unescape(GetCookie('PALAVRAS')) + "', null, 'width=' + screen.availWidth + ', height=' + screen.availHeight + ',scrollbars=yes')\";/>")) + 
                "    </p>" +
                "    <br class=\"clear\" />" +
                "</div>";
              
  var div = RetornaElementosComId(container, "resultado_obras_obra_" + posicao);
  div[0].innerHTML = celula;
}

/*
// monta a celula no formato BF nova
function GeraHTMLCelula(caminho, container, idobra, posicao, resultado)
{
  var aux = retornavalor(resultado, "RESULTADO").split('#');
  var titulo = aux[0];
  var autor = aux[1];
  
  var celula = "<div id=\"blocoObra_" + idobra + "\" style=\"float:left; margin:06px 6px 0 7px; padding:3px; border:1px solid #b5b5b5; z-index:1; cursor:pointer;\" onmouseout=\"document.getElementById('capa_" + idobra + "').style.display='block';\" onclick=\"alert('uia uia, abrindo obra de código " + idobra + "');\">" + 
               "<img id=\"capa_" + idobra + "\" src=\"http://secure.jurid.com.br/" + caminho + "/cgi_obras/capas/" + idobra + "_135x193.jpg\" alt=\"\" style=\"position: absolute; width: 135px; height: 193px; z-index: 3; display: block; \" onmouseover=\"this.style.display='none';\">" +      
               "<div id=\"infoObra\" style=\"width:133px; height:191px; border:1px solid #c8c8c8; z-index:2;\" onmouseover=\"document.getElementById('capa_" + idobra + "').style.display='none';\">" +
               "<div style=\"height:140px;\">" +
               "<p class=\"blocoObraNome\">" + titulo + "</p>" +
               "<p id=\"autor\" class=\"blocoObraAutor\">" + autor + "</p>" +
               "</div>" +
               "<p style=\"font-family:verdana; font-size:0.8em; padding:3px 8px 0 8px;\">" +
               "<span id=\"valor\" style=\"color:#4f8326;\"><!-- VALOR NÃO EXIBIDO --></span>" +
               "<img src=\"http://secure.jurid.com.br/" + caminho + "/images/btn_visualizar.png\" alt=\"\" border=\"0\" style=\"margin-top:5px;\"></p>" +
               "</div>" +
               "</div>";
               
               
  var div = RetornaElementosComId(container, "resultado_obras_obra_" + posicao);
  
  div[0].innerHTML = celula;
}
*/

function MontaRetornoGeraHTML(caminho, container, idobra, posicao)
{
  return function(resultado)
  {
    GeraHTMLCelula(caminho, container, idobra, posicao, resultado);
  }
}

function MontaListaObrasBiblioteca(nomedabibliotecaporextenso, biblioteca, caminho, container, fonte, qtd)
{
  container.style.display = "block";
  for (var i=1;i<fonte.length;i++)//pulo a primeira, pois já está exibida
    GeraHTMLCelula(caminho, container, fonte[i].idobra, fonte[i].titulo, fonte[i].autor, i);
}


// function MontaListaObrasBiblioteca(nomedabibliotecaporextenso, biblioteca, caminho, container, fonte, qtd)
// {
//   container.style.display = "block";
//   for (var i=1;i<fonte.length;i++)//pulo a primeira, pois já está exibida
//     TituloAutorDaObraAssincrono(biblioteca, fonte[i].idobra, MontaRetornoGeraHTML(caminho, container, fonte[i].idobra, i));
// }


function ExibeOcultaObrasBFW()
{
  var botao = document.getElementById('btn_mais_forense');
  if (botao.src.indexOf('btn_VisObrasForense') != -1)
  {
    MontaListaObrasBiblioteca('Biblioteca Forense WEB', 'bfw', 'bibliotecaforense', RetornaElementosComId(document.getElementById('bfw_bloco'), 'bloco_maisobras')[0], RP.bfw, RP.qtd_bfw);
    botao.src = "/img/btn_OcultarObrasForense.gif";
  }
  else
  {
    RetornaElementosComId(document.getElementById('bfw_bloco'), 'bloco_maisobras')[0].style.display = "none";
    botao.src = "/img/btn_VisObrasForense.gif";
  }
  event.cancelBubble=true;
}

function ExibeOcultaObrasBLW()
{
  var botao = document.getElementById('btn_mais_ltr');
  if (botao.src.indexOf('btn_VisObrasLtr') != -1)
  {
    MontaListaObrasBiblioteca('Biblioteca LTr Digital', 'blw', 'bibliotecaltr', RetornaElementosComId(document.getElementById('blw_bloco'), 'bloco_maisobras')[0], RP.blw, RP.qtd_blw);
    botao.src = "/img/btn_OcultarObrasLtr.gif";
  }
  else
  {
    RetornaElementosComId(document.getElementById('blw_bloco'), 'bloco_maisobras')[0].style.display = "none";
    botao.src = "/img/btn_VisObrasLtr.gif";
  }
  event.cancelBubble=true;
}


