// JavaScript Document

///
/// VARIAVEIS GLOBAIS AO WEBAPP
///
var AbaPrincipal = null;
var AbaSecundaria = null;
var Frames = null;

var global_mousemoveativo = false;
var global_moveu_mouse = false;
var global_tamanho_fonte = 12;

var fPesquisa = null;
var fPesquisaAvancada = null;
var fLocalizaBanco = null;
var fPareceres = null;

var popTexto = null;
var popReferencias = null;
var TickerTimer = null;

window.onbeforeprint = windowonbeforeprint;
window.onafterprint = windowonafterprint;

/* ROTINAS GERAIS */

function fireClickEvent(control)
{
  if (document.all) control.fireEvent("onclick");
  else
  {
    var clickEvent = window.document.createEvent("MouseEvent");
    clickEvent.initEvent("click", false, true);
    control.dispatchEvent(clickEvent);
  }
}

/* ROTINAS PARA TRATAMENTO DE TELAS */

function destaca(id, cor) 
{
  document.getElementById(id).style.backgroundColor = cor;
}

function setastatusbotao(botao, status) 
{
	(status)?RetornaElementosComID(FrameAtivo().div, botao)[0].src = sprintf("/imagens/botoes/%sON.gif", botao):RetornaElementosComID(FrameAtivo().div, botao)[0].src = sprintf("/imagens/botoes/%sOFF.gif", botao);
}

function setastatusbotaomenuprincipal(botao, status) 
{
	document.getElementById(botao).src = (status)?sprintf("/imagens/principal/%sON.gif", botao):sprintf("/imagens/principal/%sOFF.gif", botao);
}

function checkar(id)
{
  if (typeof(id) == "string") id = document.getElementById(id);
   if (id.className == "checkbox_off") SetaStatusControlaEvento(id, true); else SetaStatusControlaEvento(id, false);
}

function SetaStatusControlaEvento(CheckBox, status)
{
  if (typeof(CheckBox) == "string") CheckBox = document.getElementById(CheckBox);
  
  if ((fLocalizaBanco) && (fLocalizaBanco.style.display == "block"))
  {
   if (status)
    {
     	CheckBox.className = "checkbox_on"; 
   	}
   	else
   	{
   		CheckBox.className = "checkbox_off";
   	}
    RetornaElementosComID(fLocalizaBanco, 'fLocalizaBanco_div_itens_selecionados')[0].style.display = (TemCheckBoxMarcado(localizabanco_divlist.divativo))?"block":"none";
  }
  else
  {
    CheckBox.className = (status)?"checkbox_on":"checkbox_off";
    /*
    if (status)
    {
     	CheckBox.className = "checkbox_on"; 
   	}
   	else
   	{
   		CheckBox.className = "checkbox_off";
   	}
   	*/
   	
	var divs = new Array();
	divs[0] = document.getElementById('pAreaListaBancosAbertos');
	divs[1] = document.getElementById('pAreaListaPesquisasAbertas');
	divs[2] = document.getElementById('pAreaListaBancos');

	document.getElementById('div_itens_selecionados').style.display = ((AbaPrincipal.indiceabaativa != 0) && (AbaSecundaria.indiceabaativa == 0) && (TemCheckBoxMarcado(divs[2])))?"block":"none";
	document.getElementById('div_fechar_itens_selecionados').style.display = ((AbaSecundaria.indiceabaativa == 1) && (TemCheckBoxMarcado(divs[0])))?"block":"none";
	document.getElementById('div_fechar_itens_pesquisados').style.display = ((AbaSecundaria.indiceabaativa == 2) && (TemCheckBoxMarcado(divs[1])))?"block":"none";

  }
}

/* ROTINAS PARA TRATAMENTO DOS CLICKS e DBL-CLICKS */

function ListaCheckBoxMarcados(div)
{
  var coll = null;
  if (div) coll = div.getElementsByTagName('img'); else coll = document.getElementsByTagName('img'); 
  var i = 0;
  var resultado = new Array();
  
  for (i = 0;i<coll.length;i++)
    if (coll[i].className == "checkbox_on") resultado[resultado.length] = coll[i]; 
    
  return resultado;
}

function bAbrirSelecionadosClick(div)
{
  var marcados = ListaCheckBoxMarcados(div);
  var i = 0;
  var idbanco = null;
  for (i=0;i<marcados.length;i++)
  {
    idbanco = marcados[i].id.split('_')[1];
    CriaAba(idbanco);
  } 
  
  if ((div != null) && (fLocalizaBanco != null) && (fLocalizaBanco.style.display == "block")) FechaJanela(fLocalizaBanco); 
}

function bPesquisarSelecionadosClick(div)
{
  var marcados = ListaCheckBoxMarcados(div);
  var i = 0;
  var ids = new Array();
  for (i=0;i<marcados.length;i++)
    ids[ids.length] = {banco:marcados[i].id.split('_')[1]};
  
  ExecutarPesquisaSimplesNestesBancos(ids);
}


function bFecharSelecionadosClick()
{
  var marcados = ListaCheckBoxMarcados(document.getElementById('pAreaListaBancosAbertos'));
  var bancos = new Array();
  
  var i = 0;
  var j = 0;
  
  for (i=0;i<marcados.length;i++)
    bancos[bancos.length] = marcados[i].id.split('_')[1];
    
  for (i=0;i<bancos.length;i++)
    for (j=0;j < Frames.lista.length; j++)
      if (Frames.lista[j].codigobanco == bancos[i])
      {
       AbaSecundaria.RemoveAba(AbaSecundaria.abas[j + 3]);
       break;
      } 
}

function bFecharPesquisasClick()
{
  var marcados = ListaCheckBoxMarcados();
  var sid = null;
  var i = 0;
  var j = 0;
  
  for (i=0;i<marcados.length;i++)
    for (j=0;j < Frames.lista.length; j++)
    {
      sid = marcados[i].id.split('_')[1];
      if (Frames.lista[j].sid == sid)
      {
       AbaSecundaria.RemoveAba(AbaSecundaria.abas[j + 3]);
       break;
      }
    } 
}



function tratadblclick(id)
{
	// antes de mais nada, vejo se já não tenho esse banco aberto noutra aba
	if (typeof(id) == "string") id = document.getElementById(id);
	var i = 0;
	var idbanco = id.id.split('_')[1];
	
	for (i = 0; i < Frames.lista.length; i++)
	{
		if ((!Frames.lista[i].ehresultadopesquisa()) && (Frames.lista[i].codigobanco == idbanco))
		{
			//já tem esse banco aberto, vou apenas ativar a aba dele
			AbaSecundaria.SetaAbaAtiva(i + 3);
			return;
		}
	}
	
	CriaAba(idbanco);
  SetaStatusControlaEvento(id, false);//desmarcando o item
  
  if ((fLocalizaBanco != null) && (fLocalizaBanco.style.display == "block")) FechaJanela(fLocalizaBanco);
}

function CriaAba(codigobanco, sid, ResultadoPesquisa, QtdOcorrencias, PalavrasPesquisadas, EhFrase)
{
	codigobanco = Math.round(codigobanco - 0.5);
	var frame = Frames.adiciona(codigobanco, sid, ResultadoPesquisa, PalavrasPesquisadas, EhFrase, QtdOcorrencias);
	
	if (frame)
	{
 		document.getElementById('pAreaPremiumWEBHoje').style.display = "none";
 		document.getElementById('pAreaListaBancos').style.display = "none";
 		document.getElementById('pAreaListaBancosAbertos').style.display = "none";
 		document.getElementById('pAreaListaPesquisasAbertas').style.display = "none";
 		document.getElementById('pAreaBancosAbertos').style.display = "block";
 		
 		if (PalavrasPesquisadas) AbaSecundaria.AdicionaAba(sprintf("Pesquisa: \"%s\" [ %d ]", PalavrasPesquisadas, QtdOcorrencias), true); else AbaSecundaria.AdicionaAba(frame.nomebanco, true);
 		
 		AbaSecundaria.SetaAbaAtiva(AbaSecundaria.abas.length - 1);
 		SetaTamanhoFonte(global_tamanho_fonte);
	}
	return frame;
}

function CriaAbaNoCodigo(codigodoc)
{
	var codigobanco = Math.round(codigodoc/10000 - 0.5);
	var frame = CriaAba(codigobanco);
	FrameAtivo().navega_qualquer(codigodoc % 10000);
	
	return frame;
}

/* ROTINA DE TRATAMENTO DE IMPRESSAO */

function windowonbeforeprint()
{
  var Fundo = RetornaElementosComID(document, 'pFundo')[0];
  Fundo.style.display = "none";
}

function windowonafterprint()
{
  var Fundo = RetornaElementosComID(document, 'pFundo')[0];
  Fundo.style.display = "block";
}


/* ROTINA DE INICIALIZAÇÃO DOS MÓDULOS */

function InicializaEstruturas(containerFrameList)
{
	/* abas principal e secundária */
	
	AbaPrincipal = new FdrAbas(document.getElementById('abasprincipais'),
                              ["/imagens/aba_principal/aba_inativa_1.jpg", 
                               "/imagens/aba_principal/aba_inativa_2.jpg",
                               "/imagens/aba_principal/aba_inativa_3.jpg",
                               "/imagens/aba_principal/aba_inativa_3.jpg"],
                               ["/imagens/aba_principal/aba_ativa_1.jpg", 
                                "/imagens/aba_principal/aba_ativa_2.jpg", 
                                "/imagens/aba_principal/aba_ativa_3.jpg",
                                "/imagens/aba_principal/aba_ativa_3.jpg"]);
                                

  AbaPrincipal.AdicionaAba("JURID Hoje");
	AbaPrincipal.AdicionaAba("Civil");
	AbaPrincipal.AdicionaAba("Penal");
	AbaPrincipal.AdicionaAba("Comercial");
	AbaPrincipal.AdicionaAba("Administrativa");
	AbaPrincipal.AdicionaAba("Trabalhista");
	AbaPrincipal.AdicionaAba("Tributária");
	AbaPrincipal.AdicionaAba("Eleitoral");
	AbaPrincipal.AdicionaAba("Geral");
	AbaPrincipal.AdicionaAba("Jurisprudência");
	
  AbaPrincipal.onclick = TrataClickAbaPrincipal;	
	
	
  AbaSecundaria = new FdrAbas(document.getElementById('abassecundarias'),
                              ["/imagens/aba_secundaria/aba_inativa_1.jpg", 
                               "/imagens/aba_secundaria/aba_inativa_2.jpg",
                               "/imagens/aba_secundaria/aba_inativa_3.jpg",
                               "/imagens/aba_secundaria/aba_inativa_3_x.jpg"],
                               ["/imagens/aba_secundaria/aba_ativa_1.jpg", 
                                "/imagens/aba_secundaria/aba_ativa_2.jpg", 
                                "/imagens/aba_secundaria/aba_ativa_3.jpg",
                                "/imagens/aba_secundaria/aba_ativa_3_x.jpg"]);
                                
            
	AbaSecundaria.AdicionaAba("JURID Hoje");
	AbaSecundaria.AdicionaAba("Bancos abertos");
	AbaSecundaria.AdicionaAba("Pesquisas abertas");
	AbaPrincipal.SetaAbaAtiva(0);
	
  AbaSecundaria.onclick = TrataClickAbaSecundaria;
	AbaSecundaria.onremovida = TrataRemoveAba;

	/* FrameList */

	Frames = new FrameList(containerFrameList, "0px", "0px", "0px", "0px");
	CarregaJuridWebHoje();
	
	var QP = new FdrQueryParams();
	if (QP.valor('INTEGID'))
	  ExecutaLogInPorINTEGID(QP.valor('INTEGID'));

  if (QP.valor('PALAVRAS'))
    SetCookie('PALAVRAS', QP.valor('PALAVRAS'));
    
  if (QP.valor('CODDOC'))
    CriaAbaNoCodigo(parseInt(QP.valor('CODDOC')));

  if (QP.valor('PALAVRAS'))
    MarcaPalavrasTexto(QP.valor('PALAVRAS'), false, true);
}


/* TRATADOR DAS ABAS */


function TrataClickAbaPrincipal(Obj, Aba)
{
	document.getElementById('pAreaBancosAbertos').style.display = "none";	
	document.getElementById('pAreaListaBancosAbertos').style.display = "none";
	document.getElementById('pAreaListaPesquisasAbertas').style.display = "none";
  document.getElementById('div_itens_selecionados').style.display = "none";
  document.getElementById('div_fechar_itens_selecionados').style.display = "none";
  document.getElementById('div_fechar_itens_pesquisados').style.display = "none";
	
	if (Obj.indiceabaativa == 0)
	{	
		document.getElementById('pAreaPremiumWEBHoje').style.display = "block";
		document.getElementById('pAreaListaBancos').style.display = "none";
		AbaSecundaria.AlteraCaptionAba(0, "JURID Hoje");
		AtualizaBancosAcessados();
	}
	else
	{
		document.getElementById('pAreaPremiumWEBHoje').style.display = "none";
		document.getElementById('pAreaListaBancos').style.display = "block";
		PopulaListaBancos(Obj.indiceabaativa, document.getElementById('lista_bancos'));
		AbaSecundaria.AlteraCaptionAba(0, sprintf("Todos os Bancos [ %s ]", Aba.captionaba));
	}
	AbaSecundaria.SetaAbaAtiva(0);
}

function TemCheckBoxMarcado(div)
{
  var coll = null;
  if (div) coll = div.getElementsByTagName('img'); else return false; 
  
  for (i = 0;i<coll.length;i++)
    if (coll[i].className == "checkbox_on") return true;
    
  return false;
}

function TrataClickAbaSecundaria(obj, aba)
{
 	document.getElementById('barra_navegador').style.display = (obj.indiceabaativa > 2)?"block":"none";
	document.getElementById('div_localiza_texto').style.display = (obj.indiceabaativa > 2)?"block":"none";
	document.getElementById('div_acessibilidade').style.display = (obj.indiceabaativa > 2)?"block":"none";
 	
 	
 	if (obj.indiceabaativa > 2) RetornaElementosComID(document.getElementById('barra_navegador'), 'evaipara')[0].value = '';
	var divs = new Array();
	var i = 0;
	
	divs[0] = document.getElementById('pAreaPremiumWEBHoje');
	divs[1] = document.getElementById('pAreaListaBancosAbertos');
	divs[2] = document.getElementById('pAreaListaPesquisasAbertas');
	divs[3] = document.getElementById('pAreaBancosAbertos');
	divs[4] = document.getElementById('pAreaListaBancos');
	
	document.getElementById('div_itens_selecionados').style.display = ((AbaPrincipal.indiceabaativa != 0) && (obj.indiceabaativa == 0) && (TemCheckBoxMarcado(divs[4])))?"block":"none";
	document.getElementById('div_fechar_itens_selecionados').style.display = ((obj.indiceabaativa == 1) && (TemCheckBoxMarcado(divs[1])))?"block":"none";
	document.getElementById('div_fechar_itens_pesquisados').style.display = ((obj.indiceabaativa == 2) && (TemCheckBoxMarcado(divs[2])))?"block":"none";
	
	for (i = 0; i < divs.length; i++) divs[i].style.display = ((i == obj.indiceabaativa) && (i < 4))?"block":"none";
	
	if ((obj.indiceabaativa == 0) && (AbaPrincipal.indiceabaativa == 0))
	{
	   AtualizaBancosAcessados();
  }
  else
	if ((obj.indiceabaativa == 0) && (AbaPrincipal.indiceabaativa != 0))
	{
	  AtualizaBancosAcessados();
		document.getElementById('pAreaPremiumWEBHoje').style.display = "none";
		document.getElementById('pAreaListaBancos').style.display = "block";
	}
	else
	if (obj.indiceabaativa == 1)
	{
		PopulaAreaListaBancosAbertos(document.getElementById('lista_bancos_abertos'));
	}
	else
	if (obj.indiceabaativa == 2)
	{
		PopulaAreaListaPesquisasAbertas(document.getElementById('lista_pesquisas_abertas'));
	}
	else
	if (obj.indiceabaativa > 2)
	{
		document.getElementById('pAreaBancosAbertos').style.display = "block";
		Frames.seta_indiceframeativo(obj.indiceabaativa - 3);
		
		RetornaElementosComID(document, 'lTipoStr')[0].innerHTML = FrameAtivo().tipostr;
	}
	
	if (Frames)
	{
		if (Frames.qtdframesbanco() > 0) AbaSecundaria.AlteraCaptionAba(1, "Bancos abertos [ " +  Frames.qtdframesbanco() + " ]"); else AbaSecundaria.AlteraCaptionAba(1, "Bancos abertos");
		if (Frames.qtdframespesquisa() > 0) AbaSecundaria.AlteraCaptionAba(2, "Pesquisas abertas [ " + Frames.qtdframespesquisa() + " ]"); else AbaSecundaria.AlteraCaptionAba(2, "Pesquisas abertas");
	}
	
	if ((obj.indiceabaativa > 2) && (FrameAtivo() != null) && (FrameAtivo().destacadorpalavras.qtdocos > 0))
  {
    ExibeNavegadorOcorrencias(true);
    document.getElementById('eLocalizaTexto').value = FrameAtivo().destacadorpalavras.palavrasdestacadas;
  }
  else
  {
    document.getElementById('barra_navegador_ocorrencias').style.display = "none";
    document.getElementById('eLocalizaTexto').value = "";
  }
}

function TrataRemoveAba(indice)
{
	Frames.remove(indice - 3);
}

/* Eventos do FrameBanco */

function FrameAtivo()
{
  return Frames.frameativo;
}

function tratamousedownsplitter(evento)
{
	global_mousemoveativo = true;
}

function tratamouseupsplitter(evento)
{
	global_mousemoveativo = false;
}

function tratamousemovesplitter(evento)
{
  var e=(evento)?evento:window.event;
  
	if ((global_mousemoveativo) && (e.button <= 1))
	{
	  RetornaElementosComID(FrameAtivo().div, "pEsquerda")[0].style.width = e.clientX  - 16 + "px";
 	  document.getElementById('barra_navegador').style.width = parseInt(RetornaElementosComID(FrameAtivo().div, 'pSplitter')[0].offsetLeft) + 9 + "px";   
 	  document.getElementById('barra_navegador_ocorrencias').style.left = parseInt(RetornaElementosComID(FrameAtivo().div, 'pSplitter')[0].offsetLeft) - parseInt(document.getElementById('barra_navegador_ocorrencias').clientWidth) + "px";
	}
}

function tratamousedownimgsplitter(evento)
{
	global_mousemoveativo = true;
	global_moveu_mouse = false;
}

function tratamouseupimgsplitter(evento)
{
  var e=(evento)?evento:window.event;
	global_mousemoveativo = false;
	if (!global_moveu_mouse) 
  {
    ExecutaRecolheExpandePainelDireito();
    e.cancelBubble = true;
  }
}

function tratamousemoveimgsplitter(evento)
{
  var e=(evento)?evento:window.event;
  
	if ((global_mousemoveativo) && (e.button <= 1))
	{
	  RetornaElementosComID(Frames.frameativo.div, "pEsquerda")[0].width = e.x - 2 + "px";
	  document.getElementById('barra_navegador').style.width = e.x + 11 + "px";
	  document.getElementById('barra_navegador_ocorrencias').style.left = e.x - parseInt(document.getElementById('barra_navegador_ocorrencias').clientWidth) + "px";
    
    global_moveu_mouse = true; 
	}
}

function setastatusbotaosplitter(status)
{
  var splitter = RetornaElementosComID(FrameAtivo().div, 'imgSplitter')[0]; 
  
  if (splitter.recolhido == "true")
    splitter.src = (status)?"http://premiumweb.jurid.com.br/imagens/botoes/imgSplitter02ON.gif":"http://premiumweb.jurid.com.br/imagens/botoes/imgSplitter02OFF.gif";
      else
    splitter.src = (status)?"http://premiumweb.jurid.com.br/imagens/botoes/imgSplitter01ON.gif":"http://premiumweb.jurid.com.br/imagens/botoes/imgSplitter01OFF.gif";
}

function ExecutaRecolheExpandePainelDireito()
{
  var status = (RetornaElementosComID(FrameAtivo().div, 'pDireita')[0].style.display == "none");
  FrameAtivo().exibeocultarelacionais(status);
  RetornaElementosComID(FrameAtivo().div, 'imgSplitter')[0].recolhido = (status)?"false":"true";
}

function trataclickindice(sender, no)
{
  if (!no) return;
	
	if (no.data != FrameAtivo().codigoexibido)
	{
	  if (!FrameAtivo().navegoupeloindice) FrameAtivo().navegoupeloindice = true;
	  FrameAtivo().codigoexibido = no.data;
	  FrameAtivo().exibecodigo(no.data);
		// destaque das palavras
	  if ((FrameAtivo().palavraspesquisadas) && (FrameAtivo().palavraspesquisadas != ""))
    {
      MarcaPalavrasTexto(FrameAtivo().palavraspesquisadas, FrameAtivo().ehfrase, true);
      nav_oco_primeira();
    }
    var i = 0;
    var nos = FrameAtivo().tvanalitico.nosemvetor;
    
    if (nos == null) return;
    
    var ok = false;
    // mesmo o  exibecodigo já cuidando no nó, prefiro fazer a busca aqui pelo nó exato, pois tenho essa informação do nó
    for (i = 0; i < nos.length ; i++) 
    {
      if (nos[i] == no)
      {
        FrameAtivo().tvanalitico.nosemvetorindice = i;
        return;
      }
    }
	}
}

function trataantesexpandirtvpesquisa(no)
{
	if (!no) return false;
	var pilha = new Array();
	var i = 0;

	pilha[no.nivel] = no;
	
	var codigodoc = Math.round(no.data/10000 - 0.5);
	
	if ((no.filhos.length) && (no.filhos[0].texto == "TEMP"))
	{
		FrameAtivo().tvpesquisa.removeno(no.filhos[0]);
		var resultado = ajax_completaitempesquisa(FrameAtivo().sid, codigodoc);

		var ResultadoPesquisa = new ListaResultadoPesquisa();
		ResultadoPesquisa.parseialista(retornavalor(resultado, "RESULTADO"));
		
		for ( i = 0; i < ResultadoPesquisa.qtd(); i++)
		{
			pilha[ResultadoPesquisa.item(i).nivel] = FrameAtivo().tvpesquisa.adicionafilho(pilha[ResultadoPesquisa.item(i).nivel - 1]	, ResultadoPesquisa.item(i).descricao);
			pilha[ResultadoPesquisa.item(i).nivel].data = ResultadoPesquisa.item(i).codigo;
		}
		
	}
	return true;
}

function navega_primeiro()
{
	FrameAtivo().navega_primeiro();
}

function navega_anterior()
{
	FrameAtivo().navega_anterior();
}

function navega_proximo()
{
	FrameAtivo().navega_proximo();
}

function navega_ultimo()
{
	FrameAtivo().navega_ultimo();
}

function nav_oco_primeira()
{
  FrameAtivo().destacadorpalavras.indiceoco = 0;
  FrameAtivo().destacadorpalavras.rolarateoco(RetornaElementosComID(FrameAtivo().div, 'pTextoDoc')[0]);
  ExibeNavegadorOcorrencias(true);
}

function nav_oco_anterior()
{
  if (FrameAtivo().destacadorpalavras.indiceoco > 0)
  {
    FrameAtivo().destacadorpalavras.indiceoco--;
    FrameAtivo().destacadorpalavras.rolarateoco(RetornaElementosComID(FrameAtivo().div, 'pTextoDoc')[0]);
    ExibeNavegadorOcorrencias(true);
  }
}

function nav_oco_proxima()
{
  if (FrameAtivo().destacadorpalavras.indiceoco < FrameAtivo().destacadorpalavras.qtdocos - 1)
  {
    FrameAtivo().destacadorpalavras.indiceoco++;
    FrameAtivo().destacadorpalavras.rolarateoco(RetornaElementosComID(FrameAtivo().div, 'pTextoDoc')[0]);
    ExibeNavegadorOcorrencias(true);
  }
}

function nav_oco_ultima()
{
  FrameAtivo().destacadorpalavras.indiceoco = FrameAtivo().destacadorpalavras.qtdocos - 1;
  FrameAtivo().destacadorpalavras.rolarateoco(RetornaElementosComID(FrameAtivo().div, 'pTextoDoc')[0]);
  ExibeNavegadorOcorrencias(true);
}

function nav_ref_primeira()
{
  var frame = FrameAtivo();
  
  switch(frame.abarelacionalativa)
  {
    case 0: frame.indice_referencias = 0; break;
    case 1: frame.indice_remissoes = 0; break;
    case 2: frame.indice_doutrinas = 0; break;
    case 3: frame.indice_sumulas = 0; break;
    case 4: frame.indice_vinculantes = 0; break;
    case 5: frame.indice_modelos = 0; break;
    case 6: frame.indice_sentencas = 0; break;
    case 7: frame.indice_mps = 0; break;
    case 8: frame.tvanalitico.nosemvetorindice = 0;break;
  }
  
  frame.atualizaconteudoindice();
}

function nav_ref_anterior()
{
  var frame = FrameAtivo();
  
  switch(frame.abarelacionalativa)
  {
    case 0: if (frame.indice_referencias > 0) frame.indice_referencias--; break;
    case 1: if (frame.indice_remissoes > 0) frame.indice_remissoes--; break;
    case 2: if (frame.indice_doutrinas > 0) frame.indice_doutrinas--; break;
    case 3: if (frame.indice_sumulas > 0) frame.indice_sumulas--; break;
    case 4: if (frame.indice_vinculantes > 0) frame.indice_vinculantes--; break;
    case 5: if (frame.indice_modelos > 0) frame.indice_modelos--; break;
    case 6: if (frame.indice_sentencas > 0) frame.indice_sentencas--; break;
    case 7: if (frame.indice_mps > 0) frame.indice_mps--; break;
    case 8: if (frame.tvanalitico.nosemvetorindice > 0) frame.tvanalitico.nosemvetorindice--;break; 
  }
  
  frame.atualizaconteudoindice();
}

function nav_ref_proxima()
{
  var frame = FrameAtivo();
  
  switch(frame.abarelacionalativa)
  {
    case 0: if (frame.indice_referencias < frame.qtd_referencias - 1) frame.indice_referencias++; break;
    case 1: if (frame.indice_remissoes < frame.qtd_remissoes - 1) frame.indice_remissoes++; break;
    case 2: if (frame.indice_doutrinas < frame.qtd_doutrinas - 1) frame.indice_doutrinas++; break;
    case 3: if (frame.indice_sumulas < frame.qtd_sumulas - 1) frame.indice_sumulas++; break;
    case 4: if (frame.indice_vinculantes < frame.qtd_vinculantes - 1) frame.indice_vinculantes++; break;
    case 5: if (frame.indice_modelos < frame.qtd_modelos - 1) frame.indice_modelos++; break;
    case 6: if (frame.indice_sentencas < frame.qtd_sentencas - 1) frame.indice_sentencas++; break;
    case 7: if (frame.indice_mps < frame.qtd_mps - 1) frame.indice_mps++; break;
    case 8: if (frame.tvanalitico.nosemvetorindice < frame.tvanalitico.nosemvetor.length - 1) frame.tvanalitico.nosemvetorindice++;break;
  }
  
  frame.atualizaconteudoindice();
}

function nav_ref_ultima()
{
  var frame = FrameAtivo();
  
  switch(frame.abarelacionalativa)
  {
    case 0: if (frame.indice_referencias < frame.qtd_referencias - 1) frame.indice_referencias = frame.qtd_referencias - 1; break;
    case 1: if (frame.indice_remissoes < frame.qtd_remissoes - 1) frame.indice_remissoes = frame.qtd_remissoes - 1; break;
    case 2: if (frame.indice_doutrinas < frame.qtd_doutrinas - 1) frame.indice_doutrinas = frame.qtd_doutrinas - 1; break;
    case 3: if (frame.indice_sumulas < frame.qtd_sumulas - 1) frame.indice_sumulas = frame.qtd_sumulas - 1; break;
    case 4: if (frame.indice_vinculantes < frame.qtd_vinculantes - 1) frame.indice_vinculantes = frame.qtd_vinculantes - 1; break;
    case 5: if (frame.indice_modelos < frame.qtd_modelos - 1) frame.indice_modelos = frame.qtd_modelos - 1; break;
    case 6: if (frame.indice_sentencas < frame.qtd_sentencas - 1) frame.indice_sentencas = frame.qtd_sentencas - 1; break;
    case 7: if (frame.indice_mps < frame.qtd_mps - 1) frame.indice_mps = frame.qtd_mps - 1; break;
    case 8: if (frame.tvanalitico.nosemvetorindice < frame.tvanalitico.nosemvetor.length - 1) frame.tvanalitico.nosemvetorindice = frame.tvanalitico.nosemvetor.length - 1;break;
  }
  
  frame.atualizaconteudoindice();
}

function trataevaiparakeypress(evento)
{
  var e=(evento)?evento:event;
	if (e.keyCode == 13)
	{
		FrameAtivo().navega_qualquer(RetornaElementosComID(document, "evaipara")[0].value);
		RetornaElementosComID(document, "evaipara")[0].value = "";
	}
}

function exibeabaindice(indice)
{
	FrameAtivo().navegoupeloindice = false;
	FrameAtivo().exibeindices(indice);
}


function copiaconteudoframeativo(popup, item, texto)
{
  if (popup.browsermodo == POPUP_IE) popup.range.execCommand('copy', false);
                                      else
                                      alert("Prezado Usuário\r\n\r\nEste navegador apresenta limitações de acesso automático à \"Área de Transferencia\" do Windows.\r\n\r\nDessa forma, para executar operações como a Cópia, tecle a combinação Ctrl + C.");
}

function copiaconteudoframeativosempopup()
{
  if (document.selection) document.selection.createRange().execCommand('copy', false);
    else
    alert("Prezado Usuário\r\n\r\nEste navegador apresenta limitações de acesso automático à \"Área de Transferencia\" do Windows.\r\n\r\nDessa forma, para executar operações como a Cópia, tecle a combinação Ctrl + C.");
}

function imprimeconteudoframeativo()
{
  ImprimirConteudoDIV(RetornaElementosComID(FrameAtivo().div, 'pTextoDoc')[0]);
}

function pesquisarnobancoaberto()
{
  var marcados = new Array();
  marcados[0] = {banco:(Math.round(FrameAtivo().codigoexibido / 10000))};//é assim por causa da interface usada no "ExecutarPesquisaSimples..."
  ExecutarPesquisaSimplesNestesBancos(marcados);
}

function selecionartudoreferencias(indice)
{
  SelecionarElemento(RetornaElementosComID(FrameAtivo().div, 'pTextoIndices')[indice]);
}

function copiaconteudoreferencias(indice)
{
  CopiarConteudoDIV(RetornaElementosComID(FrameAtivo().div, 'pTextoIndices')[indice]);
}

function imprimeconteudoreferencias(indice)
{
  ImprimirConteudoDIV(RetornaElementosComID(FrameAtivo().div, 'pTextoIndices')[indice]);
}

function pesquisarnobancoabertoreferencias()
{
  var marcados = new Array();
  marcados[0] = {banco:(Math.round(FrameAtivo().codigorelacionalexibido/ 10000))};//é assim por causa da interface usada no "ExecutarPesquisaSimples..."
  ExecutarPesquisaSimplesNestesBancos(marcados);
}

/* FUNÇÕES QUE TRATAM O TAMANHO DA FONTE */

function SetaTamanhoFonte(tamanho)
{
  global_tamanho_fonte = tamanho;
  var i = 0;
  var j = 0;
  var coll = null;
  for (i = 0; i < Frames.lista.length; i++)
  {
    RetornaElementosComID(Frames.lista[i].div, 'pTextoDoc')[0].style.fontSize = global_tamanho_fonte + "pt";
    coll = RetornaElementosComID(Frames.lista[i].div, 'pTextoIndices');
    for (j = 0; j < coll.length; j++)
      coll[j].style.fontSize = global_tamanho_fonte + "pt";
  }
}

function AumentarFonte()
{
  SetaTamanhoFonte(++global_tamanho_fonte); 
}

function DiminuirFonte()
{
  SetaTamanhoFonte(--global_tamanho_fonte); 
}

/* FUNÇÕES DE TRATAMENTO DE JANELAS */

function CriaJanela(arquivohtml)
{
	var div = document.createElement('div');
	var resultado = ajax_carregapagina(arquivohtml);
	var htmljanela = retornavalor(resultado, "RESULTADO");
	
	document.body.appendChild(div);
	
	div.style.position = "absolute";
	div.style.top = '0';
	div.style.left = '0';
	div.style.width = "100%";
	div.style.height = "100%";
	div.style.zIndex = "1001";
	div.style.display = "none";
	div.innerHTML = htmljanela;
	
	return div;
}

function ExibeJanela(janela, largura, altura)
{
  //<gambi>
  document.getElementById('listarelatoriosatz').style.display = "none";
  //</gambi>
  
  var div_esmaecimento = document.getElementById('div_esmaecimento');
  

  div_esmaecimento.style.height = parseInt(document.documentElement.clientHeight) + "px";
  div_esmaecimento.style.width = parseInt(document.documentElement.clientWidth) + "px";
  div_esmaecimento.style.display = "block";
  
  janela.style.display = "block";
  
  RetornaElementosComID(janela, 'fundo')[0].style.left = (largura)?((parseInt(document.documentElement.clientWidth) - largura) / 2) + "px":((parseInt(document.documentElement.clientWidth) - parseInt(RetornaElementosComID(janela, 'fundo')[0].clientWidth)) / 2) + "px";
  RetornaElementosComID(janela, 'fundo')[0].style.top  = (altura)?((parseInt(document.documentElement.clientHeight) - altura) / 2) + "px":((parseInt(document.documentElement.clientHeight) - parseInt(RetornaElementosComID(janela, 'fundo')[0].clientHeight)) / 2) + "px";
}

function FechaJanela(janela)
{
  if (!janela) alert("Opa, faltou identificar a janela!")
  else
  {
    //<gambi>
    document.getElementById('listarelatoriosatz').style.display = "block";
    //</gambi>

	  document.getElementById('div_esmaecimento').style.display = "none";	
	  janela.style.display = "none";
  }
}

/* FUNÇÕES PARA DESTAQUE DE PALAVRAS */

function MarcaPalavrasTexto(palavras, ehfrase, naoexibiraviso)
{
	RetornaElementosComID(FrameAtivo().div, 'pTextoDoc')[0].innerHTML = FrameAtivo().textooriginaldodoc;
	ExibeNavegadorOcorrencias(false);
	FrameAtivo().destacadorpalavras.destacarpalavras(palavras, RetornaElementosComID(FrameAtivo().div, 'pTextoDoc')[0], ehfrase);
	if (FrameAtivo().destacadorpalavras.qtdocos == 0)
  {
    if (!naoexibiraviso) alert("Nenhuma ocorrência de " + palavras + " localizada neste texto.");
  }
	else
	ExibeNavegadorOcorrencias(true);
}

function ExibeNavegadorOcorrencias(status)
{
  document.getElementById('barra_navegador_ocorrencias').style.display = (status)?"block":"none";
  document.getElementById('barra_navegador_ocorrencias').style.left = parseInt(RetornaElementosComID(FrameAtivo().div, "pEsquerda")[0].clientWidth) + 2 - parseInt(document.getElementById('barra_navegador_ocorrencias').clientWidth) + "px";
  
  document.getElementById('barra_navegador').style.width = parseInt(RetornaElementosComID(FrameAtivo().div, "pEsquerda")[0].clientWidth) + 14 + "px";
  
  if (status) RetornaElementosComID(document.getElementById('barra_navegador_ocorrencias'), "ocotaldetanto")[0].innerHTML = sprintf("%d de %d", FrameAtivo().destacadorpalavras.indiceoco + 1, FrameAtivo().destacadorpalavras.qtdocos);
}

function bLocalizaTextoClick()
{
  var texto = document.getElementById('eLocalizaTexto').value;
  var ehfrase = (texto.indexOf('\"') != -1);
  
  texto = texto.replace(/\"/g, '');
  
	MarcaPalavrasTexto(texto, ehfrase);
}

/* FUNÇÕES PARA EXIBIÇÃO DE POPMENUS */

function ExibePopupMenuTexto(evento)
{
  if (!evento) var evento = window.event;
  
  if (!popTexto)
  {
    popTexto = new PopUpMenu();
    popTexto.adiciona("Selecionar Tudo", function(){SelecionarElemento(RetornaElementosComID(FrameAtivo().div, 'pTextoDoc')[0])});
    popTexto.adiciona("Copiar", copiaconteudoframeativo);
    popTexto.adiciona("Imprimir", imprimeconteudoframeativo);
    popTexto.adiciona("Pesquisar neste banco", pesquisarnobancoaberto);
  }
  popTexto.exibe(evento.clientX + "px", evento.clientY + "px");
  
  if (evento.preventDefault) evento.preventDefault(); else evento.returnValue = false;
  
  return false;
}

function ExibePopupReferencias(evento, indice)
{
  if (!evento) var evento = event;
  
  if (popReferencias)
  {
    document.body.removeChild(popReferencias.div);
    popReferencias = null;
  }
  
  popReferencias = new PopUpMenu();
  
  popReferencias.adiciona("Selecionar Tudo", function (){selecionartudoreferencias(indice)});
  popReferencias.adiciona("Copiar", function (){copiaconteudoreferencias(indice)});
  popReferencias.adiciona("Imprimir", function (){imprimeconteudoreferencias(indice)});
  popReferencias.adiciona("Pesquisar neste banco", pesquisarnobancoabertoreferencias);
  
  popReferencias.exibe(evento.clientX +"px", evento.clientY + "px");
  
  if (evento.preventDefault) evento.preventDefault(); else evento.returnValue = false;
    
  return false;
}
///
/// Selecionar TUDO
///

function SelecionarElemento(elemento) 
{ 
  var selection, range, doc, win; 
  if ((doc = elemento.ownerDocument) 
       && 
       (win = doc.defaultView) 
       && 
       (typeof(win.getSelection) != 'undefined')
       && 
       (typeof(doc.createRange) != 'undefined')
       && 
       (selection = window.getSelection()) 
       && 
       (typeof(selection.removeAllRanges) != 'undefined')) 
       {
          //mozila life-style 
          range = doc.createRange(); 
          range.selectNode(elemento); 
          selection.removeAllRanges(); 
          selection.addRange(range); 
        }
        else 
        if ((document.body) 
            &&
            (typeof(document.body.createTextRange) != 'undefined') 
            && 
            (range = document.body.createTextRange()))
            {
              //IE life-style 
              range.moveToElementText(elemento); 
              range.select(); 
            } 
}
    
    

