// *******************************************************************************************************************************
// Classe que gerencia as listas ( de nomes à esquerda das páginas)
// *******************************************************************************************************************************
function Lista(parametros) {
for (var i in parametros) {
this[i] = parametros[i];
}
this.contNovo = 0;
// caso não seja passado o tamanho inicial da lista, coloca o padrão.
this.tamanhoPadrao = 2; // 'pequena'
this.tamanhoAtual = (this.tamanhoInicial != undefined) ? this.tamanhoInicial : this.tamanhoPadrao;
// se a instância da lista não tiver um formato para apresentar os itens, usa-se o formato padrão (só o nome)
this.formatoPadrao = function() { return cria('txt', this.nome) };
if (!this.semMudarTamanho && !this.semBotoesTamanho) this.tamanho.botoes.call(this);
if (!this.elementoBase) return;
this.idPreSel = queryString('idPreSel');
this.primeiraBusca = true;
if (this.filtros) {
this.objFiltro = new clFiltro(this, this.filtros);
this.objFiltro.funcaoBuscar = this.filtra;
this.objFiltro.funcaoMontar = this.montaListaFiltrada;
this.objFiltro.aposExibir = this.aposExibirFiltro;
this.objFiltro.aposOcultar = this.aposOcultarFiltro;
this.elementoBase.appendChild(this.objFiltro.monta());
colocaClasse(this.elementoBase, "comFiltro");
}
this.montaInicial();
if (this.tamanhoAtual != this.tamanhoPadrao) this.tamanho.muda.call(this);
if (typeof(this.dados) == "object") this.retornaLista(this.dados);
else this.buscaLista();
if (this.filtros) this.objFiltro.ajustaMonta();
}
Lista.prototype.montaInicial = function() {
//log("monta inicial");
var ulSobreAbas = $(this.elementoBase).find("ul#sobreAbas")[0];
var naoApaga = [ulSobreAbas];
if (this.objFiltro) naoApaga.push(this.objFiltro.divFiltro);
naoApaga.push((this.divBotoes) ? this.divBotoes[0] : $('div.botTamanho')[0]);
limpaConteudo(this.elementoBase, naoApaga);
this.tamanho.inicializa.call(this);
if (!this.semTotais) {
var divTotais = $("
").appendTo($(this.elementoBase));
this.divTotais = divTotais.children().first();
}
this.novoCad();
this.colocaBarrasLetras();
this.listaDom = this.elementoBase.appendChild(cria('ul', { id: 'lista' }));
this.itens = [];
if (this.paginado) this.paginacao = new clPaginacao({
"pai": this, "forma": this.paginado, "funcaoBusca": this.buscaLista,
"elementoBase": this.elementoBase, "elementoScroll": this.listaDom,
"tamPagina": this.tamPagina
});
// se a instância tiver outra visualização da lista, chama para montar e vincula o objeto
if (this.outraVisualizacao) this.outraLista = this.outraVisualizacao();
if (this.antesBuscar) this.antesBuscar.call(this);
tela.ajusta();
};
Lista.prototype.filtra = function(veioDoFiltro) {
if (veioDoFiltro) delete(this.buscaLetra);
this.montaInicial();
this.buscaLista();
tela.ajusta();
if (this.aposFiltrar) this.aposFiltrar.call(this);
};
Lista.prototype.aposExibirFiltro = function() {
colocaClasse(this.elementoBase, 'comFiltro');
// this.tamanhoAtual = this.tamanhoPadrao + 1;
// this.tamanho.muda.call(this);
};
Lista.prototype.aposOcultarFiltro = function() {
tiraClasse(this.elementoBase, 'comFiltro');
};
Lista.prototype.buscaLista = function() {
var estaLista = this;
var divCarregando = cria('div', { id: 'carregandoLista', className: 'limpaDepois' });
divCarregando.appendChild(cria('img', { src: 'img/ico_aguarde2.gif' }));
divCarregando.appendChild(cria('span', null, null, "carregando" + "..."));
// se o número da página for maior que um, muda o estilo do carregando pois ele é carregado abaixo da lista. Se o carregando for em cima, esconde o divTotais
if (this.itens.length > 0) colocaClasse(divCarregando, 'abaixoDaLista');
else {
if (this.objFiltro && this.objFiltro.divFiltro) $(divCarregando).css("top", $(this.objFiltro.divFiltro).height());
if (this.divTotais) this.divTotais.hide();
}
if (this.paginacao) this.paginacao.ajustaCarregando();
this.divCarregando = this.elementoBase.appendChild(divCarregando);
this.ajustaLetras();
var url = this.urlBase + '?' + this.buscaDados;
if (this.paginacao) {
url += this.paginacao.querystring();
if (this.idPreSel > 0) url += "&idPreSel=" + this.idPreSel + "&preInativo=" + queryString('inativo');
}
if (this.buscaLetra) url += "&buscaLetra=" + this.buscaLetra;
url += this.tamanho.complemento.call(this);
if (this.objFiltro) url += this.objFiltro.querystring();
new cnx.carrega(url, function() { estaLista.retornaLista.call(estaLista, this.resposta); });
};
Lista.prototype.retornaLista = function(retorno) {
if (typeof(retorno) == "string") retorno = jQuery.parseJSON(retorno);
if (this.objFiltro && !this.objFiltro.testaRetorno.call(this.objFiltro, retorno)) return;
this.listaCompleta = (retorno.lista) ? retorno.lista : retorno;
this.listaParaMontar = this.listaCompleta;
this.total = (retorno.total) ? retorno.total : this.listaParaMontar.length;
if (this.descontaTotal) this.total -= this.descontaTotal.call(this);
this.ultimo = retorno.ultimo;
this.complementoCarregado = retorno.complementoCarregado;
if (retorno.letras) this.letras = retorno.letras;
if (retorno.param) this.param = retorno.param;
if (this.ajustaDados) this.ajustaDados(retorno);
removeObj(this.divCarregando);
if (this.divTotais) this.divTotais.show();
// passa pelo filtraDireto para filtrar os campos já preenchidos que são javascript "JS"
if (this.objFiltro) this.objFiltro.filtraDireto();
else this.montaLista();
};
Lista.prototype.montaListaFiltrada = function() {
if (!this.paginacao) {
this.montaInicial();
this.total = this.listaParaMontar.length;
if (this.descontaTotal) this.total -= this.descontaTotal.call(this);
}
this.montaLista();
};
Lista.prototype.montaLista = function() {
if (this.paginacao) this.paginacao.habilita();
this.ajustaTotais();
if (this.listaParaMontar.length == 0) {
if (this.paginacao) this.paginacao.desabilita();
} else {
var posInicial = this.itens.length;
if (this.paginacao) posInicial -= this.paginacao.getForaLista();
for (var i = 0, t = this.listaParaMontar.length; t--; i++) this.incluiItem(this.listaParaMontar[i], posInicial + i, i);
if (this.paginacao) {
var carregouUltimo = (this.listaParaMontar[this.listaParaMontar.length-1].id == this.ultimo);
if (carregouUltimo) this.paginacao.desabilita();
}
}
// se for passado um id pré-selecionado via URL, já seleciona o item
if (this.idPreSel > 0) {
if (queryString('inativo') > "0") {
var filtroLicencas = this.objFiltro.camposID.ftLicenca;
if (filtroLicencas) {
var sel = filtroLicencas.objetoCampo.campo;
var $sel = $(sel);
if (sel && $sel.val() && $sel.val().length > 0 && $sel.val() != "|todos|") {
$sel.val("|todos|");
this.objFiltro.filtra();
}
}
}
for (var i = 0, t = this.itens.length; t--; i++) if (this.itens[i].id == this.idPreSel) this.itens[i].seleciona();
} else {
// senão, se a lista só tem um item ou se tiver itens e tiver o parametro selecPrimeiro já entra com o primeiro item selecionado
if (!this.naoAbreSoUm && (this.itens.length == 1 || (this.selecPrimeiro && this.total > 0))) this.itens[0].seleciona();
else if (!this.naoAbreComNovo && this.primeiraBusca) this.incluiNovo();
// else if ( this.dadosCarregados) this.
}
this.idPreSel = 0; // zera para buscar apenas na primeira vez (se filtrar de novo não influencia)
// inicia a página com um cadastro novo já aberto (só se ainda não tiver nenhum item selecionado e no tamanho inicial puder mostrar o conteudo)
// if (!this.comecaFechado && this.itemSelecionado == undefined && this.tamanho.parametros['nivel' + this.tamanhoAtual].largConteudo > '0') this.incluiNovo();
this.verificaCategorias();
this.ajustaLetras();
this.primeiraBusca = false;
// se a instância tiver método aposMontar, chama
if (this.aposMontar) this.aposMontar();
};
Lista.prototype.tamanho = {
parametros: function() {
var parametros = {
nivel0: { largApoio: '0', largConteudo: '98%', formato: null, dadosComplementares: null, mostraTotal: false, filtroAberto: false },
nivel1: { largApoio: '3.5%', largConteudo: (this.listaInterna) ? "96%" : '91.5%', formato: null, dadosComplementares: null, mostraTotal: false, filtroAberto: false },
nivel2: { largApoio: '24%', largConteudo: (this.listaInterna) ? "75.5%" : '71%', formato: 'formato', dadosComplementares: null, mostraTotal: true, filtroAberto: true },
nivel3: { largApoio: (this.listaInterna) ? "99.5%" : '95%', largConteudo: '0', formato: 'formatoGrande', dadosComplementares: 'acaoAberto', mostraTotal: true, filtroAberto: true }
};
return parametros;
},
inicializa: function() {
if (this.semMudarTamanho) return;
var elementoBase = $(this.elementoBase);
if (!this.tamanhoInicial) elementoBase.addClass("nivel2");
// se for para mudar tamanho inclui um div em branco para a passagem do mouse incluir a faixa à esquerda da lista
$("
").appendTo(elementoBase);
// faixa à direita que permite alterar a largura
var estaLista = this;
var divLista = $(this.elementoBase);
$("").appendTo(divLista).draggable({
axis: "x",
drag: function(event, ui) { estaLista.tamanho.mudaContinuo.call(estaLista, ui); },
start: function() { divLista.removeClass("fechaComMouse") }
});
},
mudaContinuo: function(drag) {
var posLeft = drag.position.left;
var largTela = 0.95 * tamanhoTela().largura;
var divLista = $(this.elementoBase);
drag.helper.removeClass("limiteEsq").removeClass("limiteDir");
if (posLeft <= 0.15 * largTela) {
drag.position.left = divLista.width();
drag.helper.addClass("limiteEsq");
} else if (posLeft >= 0.7 * largTela) {
drag.position.left = divLista.width();
drag.helper.addClass("limiteDir");
} else {
var largConteudo = largTela - posLeft;
var tamanhoParametro = this.tamanho.parametros.call(this);
tamanhoParametro.nivel2.largApoio = posLeft + 'px';
tamanhoParametro.nivel2.largConteudo = largConteudo + 'px';
divLista.css({ "width": posLeft }).addClass("mudouLargura");
var elementoAlvo = $(this.elementoAlvo || obj('main'));
elementoAlvo.css({ "width": largConteudo });
}
},
botoes: function() {
this.divBotoes = $("").appendTo($(this.elementoBase));
this.botAmplia = $("").appendTo(this.divBotoes);
this.botReduz = $("").appendTo(this.divBotoes);
this.tamanho.eventos.call(this);
},
eventos: function() {
var estaLista = this;
$(this.elementoBase)
.on("click", ".botTamanho a", function(e) {
estaLista.tamanho.botTamanho.call(estaLista, e, this.className);
})
.on("mouseenter", ".botTamanho", function(e) { estaLista.tamanho.naoAlteraTamanho = true; })
.on("mouseleave", ".botTamanho", function(e) { estaLista.tamanho.naoAlteraTamanho = false; })
.on("mouseover", function(e) {
if (temClasse(estaLista.elementoBase,"nivel1")) {
if (estaLista.tamanho.naoAlteraTamanho) return;
colocaClasse(this, 'abrindo');
estaLista.botAmplia.click();
}
})
.on("mouseleave", function() {
if (temClasse(estaLista.elementoBase,"fechaComMouse")) {
tiraClasse(estaLista.elementoBase, 'fechaComMouse');
estaLista.botReduz.click();
}
});
},
botTamanho: function(e, classe) {
this.tamanhoAtual += ((classe == 'menor') ? -1 : 1);
if( this.tamanhoAtual == 0) this.tamanhoAtual = 1;
if (temClasse(this.elementoBase, 'fechaComMouse') && this.tamanhoAtual > 2 ) {
tiraClasse(this.elementoBase, 'fechaComMouse');
}
this.tamanho.muda.call(this);
this.veioDoMouse = false;
if (e.preventDefault) e.preventDefault(); else return false;
},
muda: function() {
var estaLista = this;
var tamanhoParametro = this.tamanho.parametros.call(this);
// muda a classe
for (var i in tamanhoParametro) tiraClasse(this.elementoBase, i);
if (this.tamanhoAtual > 3) this.tamanhoAtual = 3;
colocaClasse(this.elementoBase, 'nivel' + this.tamanhoAtual);
// muda o tamanho (com animate)
var parametros = tamanhoParametro['nivel' + this.tamanhoAtual];
var conteudo = (this.elementoAlvo) ? $(this.elementoAlvo) : $('div#main');
var divLista = $(this.elementoBase)
.stop(true, true)
.animate({ width: parametros.largApoio }, function() {
if (temClasse(this, 'abrindo')) {
$(this).addClass('fechaComMouse');
tiraClasse(this, 'abrindo');
}
});
// se já foi mudada a largura, ajusta também o div de mudar a largura
if (divLista.hasClass("mudouLargura")) $("#mudaLargura").stop(true, true).animate({ left: parametros.largApoio });
if (parametros.largConteudo == '0') conteudo.hide();
else conteudo.show().stop(true, true)
.animate({ width: parametros.largConteudo }, function() { $(this).css("overflow", "visible") });
this.tamanho.mostraTotal.call(this);
// muda o formato
if (parametros.formato && this[parametros.formato]) {
this.tamanho.trocaFormato.call(this);
// carrega dados complementares
if (this[tamanhoParametro['nivel' + this.tamanhoAtual].dadosComplementares]) this.tamanho.carregaComplemento.call(this);
}
if (this.objFiltro && !parametros.filtroAberto) this.objFiltro.oculta.call(this.objFiltro);
if (this.aposMudaTamanho) this.aposMudaTamanho.call(this);
if (this.cadastroLista) {
for (var i = 0; i < this.itens.length; i++) {
var item = this.itens[i];
if (item.cadastroDoItem) {
if ($(item.divItemLista).find("div.principal").length == 0) $(item.divItemLista).append(item.cadastroDoItem.onde);
}
}
}
},
mudaAutomatico: function() {
// se a largura do conteudo for zerada, tem que diminuir o tamanho (até encontrar algum que mostre o conteudo)
// a não ser que seja setado o semMudarTamanho ou tamanho inicial = 3
if (this.semMudarTamanho) return;
if (this.tamanhoInicial == 3 && !this.montouPrimeiraVez) {
this.montouPrimeiraVez = true;
return;
}
var tamanhoParametro = this.tamanho.parametros.call(this);
var tamanhoAnterior = this.tamanhoAtual;
while (tamanhoParametro['nivel' + this.tamanhoAtual].largConteudo == '0') this.tamanhoAtual--;
if (this.tamanhoAtual != tamanhoAnterior) this.tamanho.muda.call(this);
},
trocaFormato: function() {
var itens = this.itens;
var formato = this.tamanho.formatoValido.call(this);
for (var i = 0, t = itens.length; t--; i++) {
itens[i].formato = formato;
itens[i].remonta.call(itens[i]);
}
},
formatoValido: function() {
var tamanhoParametro = this.tamanho.parametros.call(this);
return this[tamanhoParametro['nivel' + this.tamanhoAtual].formato] ||
this[tamanhoParametro['nivel' + this.tamanhoPadrao].formato] ||
this.formatoPadrao;
},
mostraTotal: function() {
var tamanhoParametro = this.tamanho.parametros.call(this);
if (this.divTotais) {
var itensTotais = this.divTotais.children('span.total, label.total');
if (this.labelTotal && tamanhoParametro['nivel' + this.tamanhoAtual].mostraTotal) {
itensTotais.show();
} else {
itensTotais.hide();
}
}
},
complemento: function() {
// retorna a acao (do fx) que buscara os dados complementares (se o tamanho atual tiver que buscar dados complementares)
var tamanhoParametro = this.tamanho.parametros.call(this);
var acaoComplementar = this[tamanhoParametro['nivel' + this.tamanhoAtual].dadosComplementares];
return (acaoComplementar) ? "&complemento=" + acaoComplementar : "";
},
dadosParaCarregar: function() {
var itens = this.itens;
var semComplemento = [];
for (var i = 0, t = itens.length; t--; i++) if (!itens[i].complementoCarregado) {
semComplemento.push(itens[i].id);
itens[i].carregandoComplemento.call(itens[i]);
}
return semComplemento;
},
carregaComplemento: function() {
var itens = this.tamanho.dadosParaCarregar.call(this);
if (itens.length == 0) return;
var info = 'ids=' + JSON.stringify(itens);
var tamanhoParametro = this.tamanho.parametros.call(this);
var acao = this[tamanhoParametro['nivel' + this.tamanhoAtual].dadosComplementares];
var estaLista = this;
var url = this.urlBase + '?' + acao;
new cnx.carrega(url, function() { estaLista.tamanho.complementaDados.call(estaLista, this.resposta); }, null ,'POST', info);
},
complementaDados: function(dadosAdicionais) {
var tamanhoParametro = this.tamanho.parametros.call(this);
var parametros = tamanhoParametro['nivel' + this.tamanhoAtual];
var dadosAdicionais = jQuery.parseJSON(dadosAdicionais);
var itens = this.itens;
for (var i = 0, t = itens.length; t--; i++) if (!itens[i].complementoCarregado) {
for (var iAdicional = 0, totAdicional = dadosAdicionais.length; totAdicional--; iAdicional++) {
if (itens[i].id == dadosAdicionais[iAdicional].id) {
for (campo in dadosAdicionais[iAdicional]) itens[i][campo] = dadosAdicionais[iAdicional][campo];
itens[i].complementoCarregado = true;
break;
}
}
itens[i].remonta.call(itens[i]);
}
}
};
Lista.prototype.ajustaTotais = function() {
if (this.labelTotal && this.divTotais) {
this.divTotais.children('span.total').text(this.total).show();
var label = (this.total == 0) ? this.labelTotal.nenhum : ((this.total > 1) ? this.labelTotal.plural : this.labelTotal.singular);
this.divTotais.children('label.total').text(label);
}
this.tamanho.mostraTotal.call(this);
};
Lista.prototype.inclui = function(item) {
const novoItem = this.incluiItem(item);
this.total++;
this.ajustaTotais();
this.verificaCategorias();
return novoItem;
};
Lista.prototype.encontraPosicao = function(item, posInicial) {
if (!this.ordena || this.ordena.length == 0) this.ordena = ["nome"];
// passa pelos itens, encontra onde irá incluir, coloca um novo item com a posição na lista.
var pos = -1;
// se o item sendo colocado fica abaixo do último da lista, quando carregar o "ver mais" os novos itens podem ficar fora da ordem
// por isso testa a posição para todos os itens incluidos, mas utilizando um "posInicial" para,
// no caso de colocar vários em seguida já ordenados, como no caso do montaLista, economizar tempo
if (!posInicial) posInicial = 0;
//for (var i = posInicial, t = this.itens.length - posInicial; t--; i++) {
for (var i = posInicial; i < this.itens.length - posInicial; i++) {
if (this.itens[i]) {
for (var j = 0, totOrdena = this.ordena.length; totOrdena--; j++) {
var chave = this.ordena[j];
var valorLista = (this.itens[i][chave]) ? tiracentos(this.itens[i][chave].toString().toLowerCase()) : "";
var valorNovo = (item[chave]) ? tiracentos(item[chave].toString().toLowerCase()) : "";
if(this.ordenaNumero){
valorLista = parseInt(valorLista);
valorNovo = parseInt(valorNovo);
}
if (valorLista > valorNovo) { pos = i; break; }
else if (valorLista == valorNovo) pos = i;
else { pos = -1; break; }
}
}
if (pos >= 0) break;
if (i == this.itens.length - 1 && this.paginacao) this.paginacao.incrementaForaLista(); // ficou além do final da lista
}
if (pos < 0) pos = null;
return pos;
};
Lista.prototype.encontraPosicaoListaCompleta = function(item, posInicial) {
if (!this.ordena || this.ordena.length == 0) this.ordena = ["nome"];
var pos = -1;
if (!posInicial) posInicial = 0;
for (var i = posInicial, t = this.listaCompleta.length - posInicial; t--; i++) {
for (var j = 0, totOrdena = this.ordena.length; totOrdena--; j++) {
var chave = this.ordena[j];
var valorLista = this.listaCompleta[i][chave];
if (valorLista) {
valorLista = tiracentos(this.listaCompleta[i][chave].toString().toLowerCase());
var valorNovo = (item[chave]) ? tiracentos(item[chave].toString().toLowerCase()) : "";
if(this.ordenaNumero){
valorLista = parseInt(valorLista);
valorNovo = parseInt(valorNovo);
}
if (valorLista > valorNovo) { pos = i; break; }
else if (valorLista == valorNovo) pos = i;
else { pos = -1; break; }
} else { pos = -1; break; }
}
if (pos >= 0) break;
}
if (pos < 0) pos = null;
return pos;
};
Lista.prototype.incluiItem = function(item, inicioBusca, posNaLista) {
if (this.testaJaTem(item)) return;
var pos = this.encontraPosicao(item, inicioBusca);
item.formato = this.tamanho.formatoValido.call(this);
item.complementoCarregado = this.complementoCarregado;
item.posNaLista = posNaLista;
var novoItem = new Item(this, item);
var li = novoItem.insere();
if (pos == null || isNaN(pos) || pos >= this.itens.length) { // se não for passado o pos ou se o pos for no final da lista, coloca o novo item no final da lista
this.itens.push(novoItem);
this.listaDom.appendChild(li);
} else { // se for passado o pos, insere o item na posição pos da lista (e muda o scroll da lista para mostrar)
var proximoLi = $(this.itens[pos].li);
// // se o li seguinte estiver em outra categoria, coloca em uma posição antes da divisão de categorias (se a for ordenado pelo mesmo campo que a categoria)
// if (proximoLi.prev().hasClass('categoria')) proximoLi = proximoLi.prev();
$(li).insertBefore(proximoLi);
// $(this.li).slideUp(400, function() { removeObj(this) });
this.itens.splice(pos, 0, novoItem);
}
// se for passada a posição, ajusta o scroll para mostrar o item
//if (pos != null) {
// var posLI = li.offsetTop;
// var lista = $(this.listaDom);
// if (posLI < lista.scrollTop() || posLI > lista.scrollTop() + lista.height()) li.scrollIntoView(false);
//}
// se não for a carga inicial (que vem com inicioBusca) inclui na lista Completa
if (inicioBusca == undefined) {
var posListaCompleta = this.encontraPosicaoListaCompleta(item, inicioBusca);
if (posListaCompleta == null || isNaN(posListaCompleta) || posListaCompleta >= this.itens.length) {
this.listaCompleta.push(item);
} else {
this.listaCompleta.splice(posListaCompleta, 0, item);
}
}
if (this.barraLetras) this.incluiNaBarraLetras(novoItem);
if (tip) tip.acha(li);
return novoItem;
};
Lista.prototype.testaJaTem = function(item) {
// um item retornado pelo servidor pode já estar na lista (se foi uma alteração feita após a última carga)
// por isso testa se já existe antes de incluir um item
for (var i = 0, t = this.itens.length; t--; i++) if (this.itens[i] && this.itens[i].id == item.id) return true;
return false;
};
Lista.prototype.novoCad = function() {
if (this.botaoAdd && this.permissao('incluir') && this.divTotais) {
var estaLista = this;
this.divNovo = $("").appendTo(this.divTotais).on("click", function(e) {
if (!temClasse(this, 'desabilitado')) temAlteracao.verificaAlterados(estaLista, 'incluiNovo');
//if (!temClasse(this, 'desabilitado')) estaLista.incluiNovo.call(estaLista);
if (e.preventDefault) e.preventDefault(); else return false;
});
}
};
Lista.prototype.verificaNovo = function() {
if (this.itemSelecionado && this.itemSelecionado.toString().substring(0,4) == 'novo') $(this.divNovo).addClass("desabilitado");
else $(this.divNovo).removeClass("desabilitado");
if (this.mantemHabilitado) $(this.divNovo).removeClass("desabilitado");
};
Lista.prototype.incluiNovo = function() {
if (this.botaoAdd && this.permissao('incluir')) {
var parametros = { id: 'novo' + (this.contNovo++) };
if (this.parametrosNovo) for (var i in this.parametrosNovo) parametros[i] = this.parametrosNovo[i];
this.parametrosNovo = "";
var item = new Item(this, parametros);
item.seleciona.call(item);
return item;
}
};
Lista.prototype.deseleciona = function() {
var itens = (this.itensTodos) ? this.itensTodos : this.itens;
for (var i = 0, t = itens.length; t-- ; i++) if (temClasse(itens[i].li, 'selecionado')) {
var li = itens[i].li;
tiraClasse(li, 'selecionado');
if (this.categorias && !this.categoriasNaoFecha) {
var liAnterior = li.previousSibling;
while(liAnterior) {
if (temClasse(liAnterior, "categoria")) break;
liAnterior = liAnterior.previousSibling;
}
if (liAnterior && temClasse(liAnterior, "categoria") && !temClasse(liAnterior, "aberto")) $(li).hide();
}
}
this.itemSelecionado = null;
};
Lista.prototype.permissao = function(acao) {
//se tiver o this.abaPai é pq ela é uma aba interna e tem que pegar a premissão de uma aba e nao da pagina
if (!this.abaPai) {
var acoes = ["editar|gravar", "incluir", "excluir"];
var pos = -1;
for (var i = 0, t = acoes.length; t--; i++) if (acoes[i].indexOf(acao) >= 0) pos = i;
if (pos < 0) return true;
else return (_quem[pos + 3] > 0);
} else {
if (this.abaPai.perm >= 3 ) return true;
}
};
Lista.prototype.tiraItem = function(item) {
for (var i = 0, t = this.listaCompleta.length; t--; i++) {
if (this.listaCompleta[i].id == item.id) {
this.listaCompleta.splice(i, 1);
break;
}
}
for (var i = 0, t = this.itens.length; t--; i++) {
if (this.itens[i] == item) {
this.itens.splice(i, 1);
this.total--;
this.ajustaTotais();
break;
}
}
this.verificaCategorias();
};
Lista.prototype.verificaCategorias = function() {
if (!this.categorias) return;
if (!temClasse(this.listaDom, 'comCategorias')) colocaClasse(this.listaDom, 'comCategorias');
$(this.listaDom).find("li.categoria").remove();
this.categoriasAnterior = {}; // categoriasAnterior para manter as categorias abertas ou fechadas
for (var i in this.categoriasCriadas) this.categoriasAnterior[i] = this.categoriasCriadas[i];
this.categoriasCriadas = {};
for (var i = 0, t = this.itens.length; t--; i++) this.itens[i].verificaCategoria.call(this.itens[i]);
};
Lista.prototype.colocaBarrasLetras = function() {
if (!this.barraLetras) return;
var estaLista = this;
var divApoio = $(this.elementoBase).addClass('comBarraLetras').on('click', 'a#abreBarraLetras', function(e) {
e.preventDefault();
estaLista.abreLetras.call(estaLista);
});
this.listaLetrasDom = $("
").appendTo(divApoio).on('click', 'a', function(e) {
e.preventDefault();
if (temClasse(this.parentNode, 'link')) {
var alvo = estaLista.listaLetras[this.innerText]["alvo"];
if (alvo == "busca") {
estaLista.buscaLetra = this.innerText;
estaLista.filtra();
} else {
$(estaLista.listaDom).scrollTo(estaLista.listaLetras[this.innerText]["alvo"], 300);
}
} else if (temClasse(this, 'fecha')) estaLista.fechaLetras.call(estaLista);
});
this.listaLetras = {};
for (var i = 65; i <= 90; i++) this.listaLetrasDom.append(this.incluiLetra(String.fromCharCode(i)));
};
Lista.prototype.incluiNaBarraLetras = function(objItem) {
var letra = tiracentos(objItem[this.barraLetras].substring(0, 1).toUpperCase());
// se não existe na lista de letras, inclui (no topo da lista - para caracteres que não são letras)
if (this.listaLetras[letra] == undefined) this.listaLetrasDom.children().first().after(this.incluiLetra(letra));
// se é o primeiro que aparece desta letra, grava o elemento para o clique
if (!this.listaLetras[letra]["alvo"]) {
this.listaLetras[letra]["alvo"] = objItem.li;
this.listaLetras[letra]["link"].addClass("link");
}
};
Lista.prototype.incluiLetra = function(letra) {
var li = $("
");
this.listaLetras[letra] = { "link": li };
return li;
};
Lista.prototype.ajustaLetras = function() {
if (!this.barraLetras) return;
var alturaTotal = this.listaLetrasDom.height();
var LIs = this.listaLetrasDom.children();
// arredondado para baixo com uma casa decimal
var alturaLI = Math.floor(1000 / LIs.length) / 10;
LIs.css({ "height": alturaLI + "%" });
this.alturaLinkLetra = Math.floor(10 * alturaTotal / LIs.length) / 10;
this.listaLetrasDom.find("a").css({ "line-height": this.alturaLinkLetra + "px" });
// se estiver paginado e a lista não estiver completa, muda os links das letras para incluir toda as letras que tem e buscar no servidor
if (this.paginacao && this.itens.length < this.total && this.letras) {
for (var i = 0; i < this.letras.length; i++) {
var letra = tiracentos(this.letras[i]);
if (this.listaLetras[letra]) {
this.listaLetras[letra]["alvo"] = 'busca';
this.listaLetras[letra]["link"].addClass("link");
}
}
}
};
Lista.prototype.fechaLetras = function() {
var estaLista = this;
this.listaLetrasDom.children().first().removeClass("fecha");
var largura = (temClasse(this.listaDom.parentNode, "nivel3")) ? 3 : 7;
$(this.listaDom).animate({ "width": "100%", "margin-left": 0 }, 200, function() { tiraClasse(this, "comBarraLetras") });
$("").appendTo($(estaLista.elementoBase))
.css({ "height": estaLista.alturaLinkLetra + "px", "width": largura + "%" });
this.listaLetrasDom.addClass("escondido").animate({ "width": 0 }, 200);
};
Lista.prototype.abreLetras = function() {
var estaLista = this;
this.listaLetrasDom.children().first().removeClass("fecha");
var largura = (temClasse(this.listaDom.parentNode, "nivel3")) ? 3 : 7;
var larguraLista = 100 - largura;
$(this.listaDom).addClass("comBarraLetras").animate({ "width": larguraLista + "%", "margin-left": largura + "%" }, 200);
$("#abreBarraLetras").animate({ "width": 0 }, 100, function () { removeObj(this) });
this.listaLetrasDom.removeClass("escondido").animate({ "width": largura + "%" }, 200);
};
// *******************************************************************************************************************************
// *******************************************************************************************************************************
// *******************************************************************************************************************************
// Classe que gerencia cada item da lista
// *******************************************************************************************************************************
function Item(pai, objItem) {
this.pai = pai;
for (var i in objItem) {
this[i] = objItem[i];
}
// console.log(pai);
// console.log(objItem);
this.classeOrigem = 'Item';
this.nomeItem = this.pai.nomeItem;
if (!this.naoClica) this.onclick = this.pai.onclick;
// log(this.pai);
// o elementoAlvo é onde acontecerão as ações de cliques nesse item (herda da lista)
// se não for específicado, por default é o div "main"
this.elementoAlvo = this.pai.elementoAlvo || obj('main');
}
Item.prototype.colocaEventoItem = function() {
var li = this.li;
var esteItem = this;
if (this.onclick) {
var link = li.childNodes;
$(link).click(function(e) {
if (!temClasse(esteItem.li, 'excluindo')) temAlteracao.verificaAlterados(esteItem, 'seleciona');
if (e.preventDefault) e.preventDefault(); return false;
});
}
}
Item.prototype.insere = function() {
var li = cria('li', { id: 'item' + this.id });
if (this.pai.itemSelecionado == this.id) li.className = "selecionado";
this.li = li;
var esteItem = this;
if (this.onclick) {
var link = li.appendChild(cria('a', { href: '#' }));
$(link).click(function(e) {
if (!temClasse(esteItem.li, 'excluindo')) temAlteracao.verificaAlterados(esteItem, 'seleciona');
if (e.preventDefault) e.preventDefault();
else return false;
});
} else {
var link = li;
}
if (!this.formato) this.formato = this.pai.formatoPadrao;
link.appendChild(this.formato.call(this));
if (this.pai.outraLista) this.outroItem = this.pai.insereItem.call(this);
if (this.ativo != 1 && this.pai.tipInativo) {
colocaClasse(li, 'inativo');
var div = li.firstChild.firstChild;
var title = div.getAttribute("title");
var tip = div.getAttribute("tip");
if (title && title.length) div.setAttribute("title", title + '\n' + "(" + this.pai.tipInativo + ")");
else if (tip && tip.length) div.setAttribute('tip', tip + '\n' + "(" + this.pai.tipInativo + ")");
else div.setAttribute("title", "(" + this.pai.tipInativo + ")");
}
if (this.pai.cadastroLista) {
if (!this.pai.cadastroLista.onde || this.pai.cadastroListaOnde) {
this.pai.cadastroListaOnde = true;
var ondeCadastro = $(this.divItemLista);
this.pai.cadastroLista.onde = ondeCadastro[0];
this.pai.cadastroLista.idElementoBase = "cadastroLista";
this.pai.cadastroLista.item = this;
}
this.pai.cadastroLista.dados = this;
this.cadastroDoItem = new Cadastro(this.pai.cadastroLista);
}
return li;
};
Item.prototype.seleciona = function() {
const listaPai = this.pai;
if (this.parametros) {
if (this.objParametros) this.objParametros.coloca();
else new clParametros(null, this).inicia();
}
listaPai.deseleciona();
// se for um item novo, desabilita o botão de criar novo cadastro. Senão, volta a habilitar
if (this.id && this.id.toString().substring(0,4) == 'novo' && !listaPai.abaDialog) $('a#novoCadastro').addClass('desabilitado');
else $('a#novoCadastro').removeClass('desabilitado');
if (this.li && !temClasse(this.li, 'selecionado')) {
colocaClasse(this.li, 'selecionado');
var $li = $(this.li);
$li.show();
var ulLista = $(listaPai.listaDom);
var posTop = $li.position().top;
var novaPos = posTop + ulLista.scrollTop();
if (posTop < 0 || posTop > ulLista.height()) ulLista.animate({ scrollTop: novaPos }, 300);
}
listaPai.itemSelecionado = this.id;
if (!listaPai.abaDialog) limpaConteudo(this.elementoAlvo);
if (listaPai.onclick) {
if (this.parametros) {
// se tem parametros, espera um pouco antes de chamar o click da lista (para mudar outros parâmetros)
this.temporiza();
} else {
// se nao tem parâmetros, busca direto os dados (sem esperar)
listaPai.onclick.call(this);
}
// quando seleciona, verifica se tem que mudar o tamanho
if (this.esperaParaMudarTamanho > 0) setTimeout(function() { listaPai.tamanho.mudaAutomatico.call(listaPai) }, this.esperaParaMudarTamanho);
else listaPai.tamanho.mudaAutomatico.call(listaPai);
}
listaPai.verificaNovo();
};
Item.prototype.temporiza = function() {
var esteItem = this;
clearTimeout(this.tempoBusca);
this.tempoBusca = setTimeout(function() { esteItem.pai.onclick.call(esteItem) }, 1000);
};
Item.prototype.exclui = function() {
this.pai.tiraItem.call(this.pai, this);
$(this.li).slideUp(400, function() { removeObj(this) });
};
Item.prototype.remonta = function() {
var link = this.li.childNodes[0];
limpaConteudo(link);
link.appendChild(this.formato.call(this));
};
Item.prototype.carregandoComplemento = function() {
$("
" + "carregando informações adicionais" + "...
").appendTo($(this.li).find('a'));
}
Item.prototype.verificaCategoria = function() {
var objLista = this.pai;
var valor = objLista.categorias(this);
if (!objLista.categoriasCriadas[valor]) {
objLista.categoriasCriadas[valor] = objLista.categoriasAnterior[valor] || 1;
var liCat = $("").insertBefore($(this.li));
if (objLista.categoriasCriadas[valor] == "aberto") liCat.addClass("aberto");
}
};
// *******************************************************************************************************************************
// *******************************************************************************************************************************
// *******************************************************************************************************************************
// Classe que gerencia cada Categoria que agrupa os itens da lista
// *******************************************************************************************************************************
function Categoria(pai, listaCompleta, objItem) {
this.pai = pai;
this.identificador = pai.separa.identificador;
this.total = pai.separa.total;
this.fecha = pai.separa.fecha;
for (var i in objItem) {
this[i] = objItem[i];
}
this.listaCompleta = listaCompleta;
this.lista = this.incluiItens();
}
Categoria.prototype.incluiItens = function() {
var lista = [];
for (var j = 0; j < this.listaCompleta.length; j++) {
if (this.listaCompleta[j][this.identificador] == this.id) lista.push(this.listaCompleta[j]);
}
return lista;
};
Categoria.prototype.monta = function() {
var estaCategoria = this;
var li = cria('li', { className: 'categoria' });
this.li = li;
var linhaTitulo = li.appendChild(cria('div', { className: 'titulo' }));
if (this.fecha > 0) botao.habilita(linhaTitulo.appendChild(botao.cria('ocultar', function () { estaCategoria.abreFecha.call(estaCategoria); }, true, 0)));
linhaTitulo.appendChild(cria('h7', null, null, this.label));
var ulInterno = li.appendChild(cria('ul'));
for (var j = 0; j < this.lista.length; j++) {
var cadaItem = new Item(this.pai, this.lista[j]);
pai.itens.push(cadaItem);
ulInterno.appendChild(cadaItem.insere());
}
if (this.total) linhaTitulo.appendChild(cria('label', null, null, '(' + this.lista.length + ')'));
return li;
};
Categoria.prototype.abreFecha = function() {
var listaItens = this.li.getElementsByTagName('ul')[0];
var estaCategoria = this;
// tira o botão de abre/fecha para colocar o outro no lugar
var bot;
var divs = this.li.firstChild.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) if (temClasse(divs[i], 'botao')) { bot = divs[i]; break; }
removeObj(bot);
if (temClasse(listaItens, 'some')) {
// exibir
tiraClasse(listaItens, 'some');
botao.habilita(this.li.firstChild.appendChild(botao.cria('ocultar', function () { estaCategoria.abreFecha.call(estaCategoria); }, true, 0)));
} else {
// ocultar
colocaClasse(listaItens, 'some');
botao.habilita(this.li.firstChild.appendChild(botao.cria('exibir', function () { estaCategoria.abreFecha.call(estaCategoria); }, true, 0)));
}
};
// *******************************************************************************************************************************
// *******************************************************************************************************************************