PageSourceSearch

https://faculdadecienciasdavida.com.br/siginscricoes/www//js/sig.js

js faculdadecienciasdavida.com.br collected 2026-10-05 09:45:21 UTC 68,983 bytes, 1,580 lines download raw bytes

1/**
2 * Copyright (c) StharParanet Telecomunicações & Informática Ltda CNPJ:07023709/0001-51
3 * Endereço: Rua Major Castranheira, 293, - Centro - Sete Lagoas - MG
4 * Todos os direitos reservados.
5 *
6 * Este código está protegido pelas leis de propriedade intelectual, sua redistribuição ou uso
7 * sem expressa autorização é crime.
8 * Em caso de dúvidas entre em contato com [email protected] para maiores esclarecimentos.
9 * @author fabio
10 */
11
12$(document).ready(function(){
13    sig.start();
14    window.setInterval("sig.isOnline()", (60 * 2000 ));
15    //Foi a solução aceita para que o onchange não ficasse em loop enviando o mesmo arquivo várias vezes.
16    $(".novoUploadArquivo").live('change',function(){
17        idUpload = $(this).attr("id");
18        sig.ged.selecionarArquivo($("#"+idUpload));
19    });
20});
21
22var _DiasDaSemna = Array('Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado');
23var _Meses = Array('','Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro');
24/******************************************************************************/
25
26var sig ={
27    /**
28     * Variável para alocar qualquer função anônima para callback
29     */
30    funcaoAnonima: null,
31    /**
32     *Enquanto estiver conectado à internet esta variável será true
33     **/
34    online:true,
35    /**
36     * Verifica se o popup está bloqueado
37     */
38    verificaPopup   :   function(){
39        var result = false;
40        try{
41            var w = window.open('','SIG','status=0,resizeable=0,width=10,height=10,top=0,left=' + screen.width + 100);
42            w.document.write("<script>window.close();</script>");
43        }
44        catch (err) {
45            return true;
46        }
47        try {
48            if (typeof w == 'undefined') {
49                result = true;
50            }else if (w && w.closed) {
51                result = false;
52            }else if (w && w.test) {
53                result = false;
54            }else {
55                result = true;
56            }
57        } catch (err) {}
58        return result;
59    },
60   /** Função para subtotalizar e Totalizar todas as operações do SIG2, referente à (quantidade * valor - desconto)
61     *  Por padrão os Ids dos campos devem ter o mesmo nome das classes concatenando '_' mais o código do registro
62     * @param {type} classQtd       Classe do campo Quantidade
63     * @param {type} classValor     Classe do campo Valor
64     * @param {type} classDesconto  Classe do campo Desconto
65     * @param {type} classSubtotal  Classe do campo Subtotal
66     * @param {type} IdTotal        Id do Total Geral
67     * @param {type} casasDecimais
68     * @param {type} casasDecimaisTotal
69     * @returns {html}
70     */
71    subtotalizar: function(classQtd, classValor, classDesconto, classSubtotal, IdTotal,casasDecimais,casasDecimaisTotal) {
72        valorTotal = 0;
73        //Vamos percorrer todo o laço em procura das quantidades, valores e descontos
74        $('.' + classQtd).each(function() {
75            var idClass1 = $(this).attr("id");
76            codigoReg   = idClass1.split('_', 2);//Todos ID deve ser separado por "_" para que possamos percorrer o laço a procura dos valores
77            qtd         = parseFloat($('#' + classQtd + '_' + codigoReg[1]).val().replace(/[.]/g, '').replace(',', '.'));
78            valor       = parseFloat($('#' + classValor + '_' + codigoReg[1]).val().replace(/[.]/g, '').replace(',', '.'));
79            subtotal    = qtd * valor;
80            if (classDesconto != '') {
81                desconto = parseFloat($('#' + classDesconto + '_' + codigoReg[1]).val().replace(/[.]/g, '').replace(',', '.'));
82                if (desconto > 0) {
83                    subtotal = (1 - desconto / 100) * subtotal;
84                }
85            }
86            if (IdTotal) {
87                valorTotal += subtotal;
88            }
89            //subtotal = sig.formataMoeda(String(subtotal).replace('.',','),casasDecimais);
90            $('#' + classSubtotal + '_' + codigoReg[1]).val(sig.formataMoeda(String(subtotal).replace('.',','),casasDecimais));
91        });
92        if (IdTotal) {
93            $('#' + IdTotal).val(sig.formataMoeda(String(valorTotal).replace('.',','),casasDecimaisTotal));
94        }
95
96    },
97    toggleDivs : function(idDiv) {
98        idDiv           = $('#'+idDiv).attr("id");
99        idDivQuebrado   = idDiv.split('_');
100        moreExibicao    = 'More_'+idDivQuebrado[1];
101        imgExibicao     = 'img_'+idDivQuebrado[1];
102        hidden_Exibicao = 'hidden_'+idDivQuebrado[1];
103
104        // A logica é invertida pelo fato de analisar a situação atual, quer dizer que se está oculto será exibido e vice-versa
105        if($('#' + moreExibicao).css('display') === 'none'){
106            $('#' + imgExibicao).attr('src', 'images/icons/collapse.png');
107            $('#' + hidden_Exibicao).val('1');
108        } else {
109            $('#' + imgExibicao).attr('src', 'images/icons/expand.png');
110            $('#' + hidden_Exibicao).val('0');
111        }
112        $('#'+moreExibicao).slideToggle();
113    },
114    /**
115     * Verifica se o usuário está usando um navegador bom
116     **/
117    verificaNavegadorAtualizado:function(){
118        return true;
119    },
120    validaData:function (data){
121	tmp = data.split('/', 3);
122	if (tmp.length != 3) {
123		return false;
124	}
125	dia = parseInt(tmp[0], 10);
126	mes = parseInt(tmp[1], 10);
127	ano = parseInt(tmp[2], 10);
128	anoAtual = new Date().getFullYear();
129	if (isNaN(dia) || !(dia >= 1 && dia <= 31)) {
130            return false;
131	}
132	if (isNaN(mes) || !(mes >=1 && mes <= 12)) {
133            return false;
134	}
135	if (isNaN(ano) || ano < 1900 || ano > (anoAtual + 20)) {
136            return false;
137	}
138    if (mes == 2 && (((ano % 4) != 0 && dia > 28) || ((ano % 4) == 0 && dia > 29))) { //fevereiro
139            return false;
140	}
141    if ((mes == 4 || mes == 6 || mes == 9 || mes == 11 ) && dia > 30) {
142            return false;
143	}
144	return true;
145    },
146    /*
147     * Retorna a Data Atual no formato dos parametros
148     */
149    dataAtual: function(formato,separador){
150        var dataAtual = new Date();
151        var dia = dataAtual.getDate();
152        var mes = dataAtual.getMonth()+1;
153        var ano = dataAtual.getFullYear();
154        var hora = dataAtual.getHours();
155        var minuto = dataAtual.getMinutes();
156        var segundo = dataAtual.getSeconds();
157        var diaSemana = sig.getDiaExtenso(dataAtual.getDay());
158        var mesExtenso = sig.getMesExtenso(dataAtual.getMonth());
159
160        if (formato == ('dmY')){
161            return dia + separador + mes + separador + ano;
162        } else if (formato == ('Ymd')){
163            return ano + separador + mes + separador + dia;
164        }
165        return false;
166    },
167    getMesExtenso:function (mes){
168        return _Meses[mes];
169    },
170    getDiaExtenso: function (dia){
171        return _DiasDaSemna[dia];
172    },
173    /*
174     * Calcula a diferença entre duas datas
175     */
176    diffDate: function(date1,date2,interval) {
177        var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
178        date1 = new Date(date1);
179        date2 = new Date(date2);
180        var timediff = date2 - date1;
181        if (isNaN(timediff)) return NaN;
182        switch (interval) {
183            case "years": return date2.getFullYear() - date1.getFullYear();
184            case "months": return (
185                ( date2.getFullYear() * 12 + date2.getMonth() )
186                -
187                ( date1.getFullYear() * 12 + date1.getMonth() )
188            );
189            case "weeks"  : return Math.floor(timediff / week);
190            case "days"   : return Math.floor(timediff / day);
191            case "hours"  : return Math.floor(timediff / hour);
192            case "minutes": return Math.floor(timediff / minute);
193            case "seconds": return Math.floor(timediff / second);
194            default: return undefined;
195        }
196    },
197    toggle:function(idDiv){
198        idDiv = $(idDiv).attr("id");
199        if($('#'+idDiv).css('display') === 'none'){
200            $('.'+idDiv).attr('src', 'images/icons/expand.png');
201        } else {
202            $('.'+idDiv).attr('src', 'images/icons/collapse.png');
203        }
204        $('#'+idDiv).slideToggle(1000);
205    },
206    /** http://phpjs.org/functions/stristr:538
207     *
208      * @param {type} haystack
209      * @param {type} needle
210      * @param {type} bool
211      * @returns {@exp;haystack@call;substr|Boolean|@exp;haystack@call;slice}
212     */
213     stristr:function (haystack, needle, bool) {
214        // Finds first occurrence of a string within another, case insensitive
215        //
216        // version: 1109.2015
217        // discuss at: http://phpjs.org/functions/stristr
218        // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
219        // +   bugfxied by: Onno Marsman
220        // *     example 1: stristr('Kevin van Zonneveld', 'Van');
221        // *     returns 1: 'van Zonneveld'
222        // *     example 2: stristr('Kevin van Zonneveld', 'VAN', true);
223        // *     returns 2: 'Kevin '
224        var pos = 0;
225
226        haystack += '';
227        pos = haystack.toLowerCase().indexOf((needle + '').toLowerCase());
228        if (pos == -1) {
229            return false;
230        } else {
231            if (bool) {
232                return haystack.substr(0, pos);
233            } else {
234                return haystack.slice(pos);
235            }
236        }
237    },
238    formataMoeda:function (num,casasDecimais){
239        num = num.toString().replace(/[^0-9,]/g,'');
240        num = num.toString().replace(',','.');
241        if( parseInt(num) > 0 || parseFloat(num) > 0){
242            parseFloat(num);
243            if(isNaN(num)){
244                num = 0;
245            }else{
246                var x = new Number(num);
247                if (casasDecimais>0){
248                    num=x.toFixed(casasDecimais);
249                } else {
250                    num=x.toFixed(2);
251                }
252            };
253            numFormatado=num.toString();
254            return numFormatado.replace(/[.]/g,',');
255        }else{
256            return '0,00';
257        }
258    },
259    formataDecimal:function (num,decimal){
260        num = num.toString().replace(/[^0-9,]/g,'');
261        num = num.toString().replace(',','.');
262        if( parseInt(num) > 0 || parseFloat(num) > 0){
263            parseFloat(num);
264            if(isNaN(num)){
265                num = 0;
266            }else{
267                var x = new Number(num);
268                num=x.toFixed(decimal);
269            };
270            numFormatado=num.toString();
271            return numFormatado.replace(/[.]/g,',');
272        }else{
273            return '0,00';
274        }
275    },
276     /** Selecionar todos os itens de um select
277      *
278      * @param {type} id - ID CSS
279      * @returns {undefined}
280     */
281    selecionaTodos : function(id){
282        $("#" + id  +" option").each(function(){
283            $(this).attr("selected",true);
284        });
285        $("#" + id).trigger("change");
286        if($("#" + id).hasClass("chosen")){
287            $("#" + id).trigger("liszt:updated");
288        }
289    },
290     /** Retorna todos os itens que estão selecionadados de um select
291      *
292      * @param {type} id
293      * @returns string (1,2,8,9)
294     */
295    getValoresSelect : function(id){
296        itens = '';
297        $("#" + id  +" option:selected").each(function() {
298            itens += ($(this).val()) + ',';
299        });
300        itens = itens.substring(0,itens.length - 1);
301        return itens;
302    },
303     /** Retorna quantos itens estão selecionados no select
304      *
305      * @param {type} id
306      * @returns {Number}
307     */
308    contaQuantosValoresSelect : function(id){
309        selecteds = 0;
310        $("#" + id  +" option:selected").each(function() {
311            selecteds +=1;
312        });
313        return selecteds;
314    },
315    submitFormulario : function(){
316        $('<img/>').src = "images/icons/saveSubmit.gif";
317        $(".validarFormulario").submit(function(){
318            var validator = $(".validarFormulario").validate();
319            if (validator.errorList.length == 0){
320                $('input[type="submit"]').attr('disabled', 'disabled');
321                $('input[type="button"]').attr('disabled', 'disabled');
322                setTimeout(function(){
323                    if ($('#formPesquisa').length) {
324                        if ($('#formPesquisa').val() == 1){
325                            $('input[type="submit"]').before('<span class="submitFormulario">Pesquisando...</span>');
326                        }
327                    } else {
328                        $('input[type="submit"]').before('<span class="submitFormulario">Salvando...</span>');
329                    }
330                }, 100);
331            }
332        });
333    },
334    /** Marca todos os checkbox da class (parametro)
335     *
336     * @param {type} nomeClass - Nome da classe dos checkbox no qual serão marcados para serem removidos.
337     * @param {type} idCheck - [Opcional] Deve ser passado quando se tem abas e usam a opção todosCheckBox em mais de uma aba, para saber qual id analisar para selecionar.
338     * @returns {undefined}
339     */
340    marcarDesmarcarTodosCheckbox : function(nomeClass,idCheck){
341        idChecar =  idCheck ? idCheck : 'todosCheckBox';
342       if ($("#"+idChecar).attr("checked")){
343          $('.'+nomeClass).each(
344             function(){
345                if (!$(this).attr('disabled')){
346                    $(this).attr("checked", true);
347                }
348             }
349          );
350       } else {
351          $('.'+nomeClass).each(
352             function(){
353                $(this).attr("checked", false);
354             }
355          );
356       }
357    },
358    /**
359     * Busca o endereço pelo CEP
360     * @param string cep número do cep
361     * @param array campos na ordem => logradouro|bairro|cidade|uf
362     * @param str foco Campo a ser focado depois da busca
363     */
364    /** Busca o endereço pelo CEP
365     *
366     * @param {string} cep número do cep
367     * @param {array} campos na ordem => logradouro|bairro|cidade|uf
368     * @param {string} foco Campo a ser focado depois da busca
369     * @param {type} seletor
370     * @returns {undefined}
371     */
372    preencheCep : function(cep,campos,foco,seletor){
373        if (cep.length > 0){
374            $('#respostaCep').html('Cep não encontrado.');
375            $("body").css("cursor","wait");
376            $.ajax({
377                url: "https://cep.paranet.com.br/endereco/"+cep,
378                dataType: "jsonp",
379                success: function(resposta) {
380                    if (!jQuery.isEmptyObject(resposta)) {
381                        if(!seletor){
382                            $("." + campos[0]).val(sig.capitalize(resposta.logradouro));
383                            $("." + campos[1]).val(sig.capitalize(resposta.bairro));
384                            $("." + campos[2]).val(sig.capitalize(resposta.cidade));
385                            $("." + campos[3]).val(resposta.uf);
386                            if($("." + campos[3]).hasClass("chosen")){
387                                $("." + campos[3]).trigger("liszt:updated");
388                            }
389                            $("." + campos[3]).change();
390                            $("." + foco).focus();
391                        } else {
392                            $(seletor).find("." + campos[0]).val(sig.capitalize(resposta.logradouro));
393                            $(seletor).find("." + campos[1]).val(sig.capitalize(resposta.bairro));
394                            $(seletor).find("." + campos[2]).val(sig.capitalize(resposta.cidade));
395                            $(seletor).find("." + campos[3]).val(resposta.uf);
396                            if($(seletor).find("." + campos[3]).hasClass("chosen")){
397                                $(seletor).find("." + campos[3]).trigger("liszt:updated");
398                            }
399                            $(seletor).find("." + campos[3]).change();
400                            $(seletor).find("." + foco).focus();
401                        }
402                    } else {
403                        $('#respostaCep').html('Cep não encontrado.');
404                    }
405                    $("body").css("cursor","default");
406                },
407                error: function () {
408                    $('#respostaCep').html('Erro ao tentar buscar cep,serviço indisponível.');
409                }
410            });
411        }
412    },
413    /**
414     * Criar uma div sobrepondo toda a tela para que o usuário aguarde
415     */
416    carregando : function(){
417        if(!$("#divSigCarregando").length){
418            $('body').append("<div id='divSigCarregando'><div class='img'><img src='images/icons/ajax-loader-bar.gif' alt='aguarde'>Carregando</div></div></div>");
419        }
420        $("#divSigCarregando").width($(window).width());
421        $("#divSigCarregando").height($(window).height());
422        $("#divSigCarregando").show();
423    },
424    fecharCarregando : function(){
425        setTimeout(
426            '$("#divSigCarregando").hide("slow")',500
427            );
428    },
429     /** Capitalizar uma string
430      *
431      * @param {type} str
432      * @param {type} forcarlower
433      * @returns {@exp;partes@call;join}
434     */
435    capitalize: function (str, forcarlower ) {
436
437        forcarlower = !! forcarlower;
438        if(!forcarlower){
439            forcarlower = new Array("da","de","do","ou");
440        }
441
442        var partes = str.split(" ");
443        for(var i = 0 ; i < partes.length; i++){
444            if(in_array(partes[i].toLowerCase(), forcarlower)){
445                partes[i] = partes[i].toLowerCase() ;
446            } else {
447                partes[i] = partes[i][0].toUpperCase() + partes[i].substr(1).toLowerCase();
448            }
449        }
450        return partes.join(" ");
451    },
452     /**
453      * Clonar um no
454      *
455      * @param {type} seletor
456      * @param {type} obj
457      * @param {type} callback //função que será usada na opção de remover o clone, se deseja executar algo após o clone deve executa-lo na sua própria função.
458      * @returns {unresolved}
459      */
460    clonar: function (seletor,obj,callback){
461        var clone = $(seletor).clone();
462
463        $(obj).find("img").attr("src","images/icons/publish_r.png");
464        $(obj).unbind("click");
465        $(obj).attr("onclick","return false;");
466
467
468        /**
469         * Gambiarra para funcionar no IE8, se não usar setTimeout, ele enfileira o evento no click e executa após encerrar essa função
470         */
471        setTimeout(
472            function(){
473                $(obj).bind('click',function(){
474                    sig.removerClone(this,callback);
475                });
476            },10);
477
478        clone.find("select:first").val(clone.find("select:first option:first").val());
479        clone.find("input").val("");
480        //incrementar todos os ids
481        clone.find("*").each(function(){
482            if(typeof $(this).attr("id") == "string"){
483                var id = $(this).attr("id");
484                var novoid = id + "_0";
485                var partes = id.split("_");
486                //se a última parte for um número incrementa
487
488                if(partes.length>1){
489                    var uparte = partes.pop();
490                    if(!isNaN(uparte)){
491                        novoid = partes.join("_") + "_" +  (parseFloat(uparte) + 1);
492                    }
493                }
494                $(this).attr("id",novoid);
495            }
496        });
497        $(clone).insertAfter($(seletor));
498
499        //atualizar chosen
500        $(clone).find(".chzn-container").remove();
501        $(clone).find(".chosen").removeClass("chzn-done");
502        $(clone).find(".chosen").css("display","");
503        $(clone).find(".chosen").chosen({
504            no_results_text: "Nada encontrado",
505            disable_search_threshold: 10
506        });
507        $(clone).find(".telefone").focus(function(){
508            sig.notificar("Informar 9 ou ESPAÇO para o Nono digíto do telefone.");
509        });
510        $(clone? $(clone).find(".txtAutocomplete") : ".txtAutocomplete").each(function(){
511            var data = $(this).data();
512            sig.autocomplete($(this).attr("name"), data.source, $(this).attr("id"), data.callback?eval(data.callback):null, data.strictmatch);
513        });
514
515        $(clone).find('.data').mask('99/99/9999');
516
517        $(clone).find('.calendario').removeClass('hasDatepicker');
518        $(clone).find('.calendario').datepicker({
519            dateFormat: "dd/mm/yy",
520            dayNames : ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'],
521            dayNamesShort : ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb'],
522            dayNamesMin : ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb'],
523            monthNames : ['janeiro', 'fevereiro', 'mar&ccedil;o', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'],
524            monthNamesShort : ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'],
525            currentText : "Hoje",
526            nextText : "Próximo",
527            prevText : "Anterior"
528        });
529        return clone;
530    },
531     /**
532      * Clonar um no
533      *
534      * @param {type} seletor
535      * @param {type} obj
536      * @param {type} callback //função que será usada na opção de remover o clone, se deseja executar algo após o clone deve executa-lo na sua própria função.
537      * @returns {unresolved}
538      */
539    clonarSemApagar: function (seletor,obj,callback){
540        var clone = $(seletor).clone();
541
542        $(obj).find("img").attr("src","images/icons/publish_r.png");
543        $(obj).unbind("click");
544        $(obj).attr("onclick","return false;");
545
546
547        /**
548         * Gambiarra para funcionar no IE8, se não usar setTimeout, ele enfileira o evento no click e executa após encerrar essa função
549         */
550        setTimeout(
551            function(){
552                $(obj).bind('click',function(){
553                    sig.removerClone(this,callback);
554                });
555            },10);
556
557        clone.find("select:first").val(clone.find("select:first option:first").val());
558        //clone.find("input").val("");
559        //incrementar todos os ids
560        clone.find("*").each(function(){
561            if(typeof $(this).attr("id") == "string"){
562                var id = $(this).attr("id");
563                var novoid = id + "_0";
564                var partes = id.split("_");
565                //se a última parte for um número incrementa
566
567                if(partes.length>1){
568                    var uparte = partes.pop();
569                    if(!isNaN(uparte)){
570                        novoid = partes.join("_") + "_" +  (parseFloat(uparte) + 1);
571                    }
572                }
573                $(this).attr("id",novoid);
574            }
575        });
576        $(clone).insertAfter($(seletor));
577
578        //atualizar chosen
579        $(clone).find(".chzn-container").remove();
580        $(clone).find(".chosen").removeClass("chzn-done");
581        $(clone).find(".chosen").css("display","");
582        $(clone).find(".chosen").chosen({
583            no_results_text: "Nada encontrado",
584            disable_search_threshold: 10
585        });
586
587        $(clone).find(".telefone").focus(function(){
588            sig.notificar("Informar 9 ou ESPAÇO para o Nono digíto do telefone.");
589        });
590        $(clone? $(clone).find(".txtAutocomplete") : ".txtAutocomplete").each(function(){
591            var data = $(this).data();
592            sig.autocomplete($(this).attr("name"), data.source, $(this).attr("id"), data.callback?eval(data.callback):null, data.strictmatch);
593        });
594
595        $(clone).find('.data').mask('99/99/9999');
596
597        $(clone).find('.calendario').removeClass('hasDatepicker');
598        $(clone).find('.calendario').datepicker({
599            dateFormat: "dd/mm/yy",
600            dayNames : ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'],
601            dayNamesShort : ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb'],
602            dayNamesMin : ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb'],
603            monthNames : ['janeiro', 'fevereiro', 'mar&ccedil;o', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'],
604            monthNamesShort : ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'],
605            currentText : "Hoje",
606            nextText : "Próximo",
607            prevText : "Anterior"
608        });
609
610        return clone;
611    },
612    /** Clonar o elemento mantendo a ordem de inserção do usuário e mantendo os 2 botões.
613     *
614     * @param {type} clonar - Elemento a ser Clonado
615     * @param {type} indexCampo - Index do elemento a ser clonado
616     * @param {type} obj - obja a ser clonado
617     * @returns {undefined}
618     */
619    clonarCampo: function (clonar,indexCampo,obj){
620        var clone = sig.clonarEspecial('.'+clonar+':eq('+indexCampo+')',obj);
621    },
622    /** A função é praticamente a mesma clonar. A diferença que é possível clonar elementos internos e mantem 2 botões de exclusão e inclusão.
623     *
624     * @param {type} seletor
625     * @param {type} obj
626     * @returns {unresolved}
627     */
628    clonarEspecial: function (seletor,obj){
629        var clone = $(seletor).clone();
630
631        //$(obj).find("img").attr("src","images/icons/publish_r.png");
632        //$(obj).unbind("click");
633        //$(obj).attr("onclick","return false;");
634
635
636        /**
637         * Gambiarra para funcionar no IE8, se não usar setTimeout, ele enfileira o evento no click e executa após encerrar essa função
638         */
639        /*
640        setTimeout(
641            function(){
642                $(obj).bind('click',function(){
643                    sig.removerClone(this);
644                })
645            },10);
646        */
647        clone.find("select:first").val(clone.find("select:first option:first").val());
648        clone.find("input").val("");
649        //incrementar todos os ids
650        clone.find("*").each(function(){
651            if(typeof $(this).attr("id") == "string"){
652                var id = $(this).attr("id");
653                var novoid = id + "_0";
654                var partes = id.split("_");
655                //se a última parte for um número incrementa
656
657                if(partes.length>1){
658                    var uparte = partes.pop();
659                    if(!isNaN(uparte)){
660                        novoid = partes.join("_") + "_" +  (parseFloat(uparte) + 1);
661                    }
662                }
663                $(this).attr("id",novoid);
664            }
665        });
666        $(clone).insertAfter($(seletor));
667
668        //atualizar chosen
669        $(clone).find(".chzn-container").remove();
670        $(clone).find(".chosen").removeClass("chzn-done");
671        $(clone).find(".chosen").css("display","");
672        $(clone).find(".chosen").chosen({
673            no_results_text: "Nada encontrado",
674            disable_search_threshold: 10
675        });
676
677        return clone;
678    },
679    removerClone:function(obj,callback){
680        $(obj).parent().remove();
681         if(typeof(callback)=="function"){
682            callback.call();
683         }
684    },
685    ckeditor: function(seletor){
686
687        if($( seletor ? $(seletor).find("textarea.ckeditor") : "textarea.ckeditor").length > 0 || $( seletor ? $(seletor).find("textarea.ckeditorMinimum") :  "textarea.ckeditorMinimum").length > 0){
688            $.cachedScript("https://cdn.paranet.com.br/ckeditor/3.6/ckeditor.js", function(data) {
689                $.cachedScript("https://cdn.paranet.com.br/ckeditor/3.6/adapters/jquery.js", function(data) {
690                    $( seletor ? $(seletor).find("textarea.ckeditorMinimum") :  "textarea.ckeditorMinimum" ).each(function(){
691                        /*if($(this).ckeditorGet()){
692                                $(this).ckeditorGet().destroy(true);
693                            }*/
694                        if(CKEDITOR.instances[$(this).attr("id")]){
695                            CKEDITOR.instances[$(this).attr("id")].destroy(true);
696                        }
697                        $(this).ckeditor({
698                            toolbar : [['Bold', 'Italic', 'Underline','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock', '-', 'NumberedList', 'BulletedList', 'Outdent','Indent', '-', 'Link', 'Unlink', 'Table']],
699                            uiColor : "#9FC8F4",
700                            language : "pt-br",
701                            width:$(this).css("width"),
702                            height:$(this).css("height")
703                        });
704
705                    });
706                });
707            });
708        }
709    },
710    start: function(seletor){
711        /**Por problemas encontrados em formulários onde ao usar o enter o formulário estava tendo comportamento estranhos Submetendo ou execuando uma função onclick, geralmente da clonagem de objetos.
712         * http://codigofonte.uol.com.br/codigos/desabilitar-a-tecla-enter-para-enviar-formulario
713         * @param {type} e
714         * @returns {undefined}
715         */
716        $('input').keypress(function (e) {
717            var code = null;
718            code = (e.keyCode ? e.keyCode : e.which);
719            return (code == 13) ? false : true;
720       });
721        $("#menu").find("li").click(function(){
722            $(this).find(">ul>li").show();
723            setTimeout(function(){
724                $(this).find(">ul>li").hide();
725            },
726            3000);
727        });
728        jQuery.cachedScript = function(url, callback, options) {
729            options = $.extend(options || {}, {
730                dataType: "script",
731                cache: true,
732                url: url
733            });
734            return jQuery.ajax(options).done(callback);
735        };
736        $(".reservaLivro").click(function() {
737            var idClass = $(this).attr("id");
738            codigoReg   = idClass.split('_');
739            livro       = codigoReg[1];
740            favorecido  = codigoReg[2];
741            aluno       = codigoReg[3];
742            $.ajax({
743                type: "POST",
744                dataType: "jsonp",
745                url: "json/livros/reservarLivroJson",
746                data : {
747                    livro           : livro,
748                    tp_favorecido   : favorecido,
749                    favorecido      : aluno
750                },
751                success: function (resposta) {
752                    if(resposta.emprestimo == true){
753                        sig.notificar("Livro Reservado com sucesso. Quando o livro estiver disponível, você será comunicado via email.");
754                    } else if(resposta.emprestimo == 'jaReservado'){
755                        sig.notificar("Livro já estava reservado.");
756                    } else if(resposta.emprestimo == 'emprestado'){
757                        sig.notificar("Existe um emprésitimo em seu nome não é possível efetuar a reserva.");
758                    }
759                },
760                error: function () {
761                    sig.notificar("Não foi possível registrar a reserva.");
762            }
763            });
764        });
765
766        if(typeof jQuery('body').validate == "function"){
767            $(seletor? $(seletor).find(".validarFormulario"): ".validarFormulario").validate({
768                ignore: ''
769            });
770        }
771
772        //Mascara de Moeda
773        $(".moeda").maskMoney({
774              symbol:'R$', // Simbolo
775              decimal:',', // Separador do decimal
776              precision:2, // Precisão
777              thousands:'', // Separador para os milhares
778              allowZero:true, // Permite que o digito 0 seja o primeiro caractere
779              showSymbol:false // Exibe/Oculta o símbolo
780            });
781
782        $(".moedaNegativa").maskMoney({
783              symbol:'R$', // Simbolo
784              decimal:',', // Separador do decimal
785              precision:2, // Precisão
786              thousands:'.', // Separador para os milhares
787              allowZero:true, // Permite que o digito 0 seja o primeiro caractere
788              showSymbol:false, // Exibe/Oculta o símbolo
789              allowNegative : true
790            });
791
792        //Mascara de Percentual
793        $(".percentual6").maskMoney({
794              symbol:'R$', // Simbolo
795              decimal:',', // Separador do decimal
796              precision:6, // Precisão
797              thousands:'', // Separador para os milhares
798              allowZero:true, // Permite que o digito 0 seja o primeiro caractere
799              showSymbol:false // Exibe/Oculta o símbolo
800            });
801
802        if(typeof jQuery.mask == "object"){
803            $(seletor? $(seletor).find("input.cep") : "input.cep").mask("99.999-999");
804            $(seletor? $(seletor).find("input.data") : "input.data").mask("99/99/9999");
805            $(seletor? $(seletor).find("input.hora") : "input.hora").mask("99:99");
806            $(seletor? $(seletor).find("input.calendario") : "input.calendario").datepicker({
807                dateFormat: "dd/mm/yy",
808                dayNames : ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'],
809                dayNamesShort : ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb'],
810                dayNamesMin : ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb'],
811                monthNames : ['janeiro', 'fevereiro', 'mar&ccedil;o', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'],
812                monthNamesShort : ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'],
813                currentText : "Hoje",
814                nextText : "Próximo",
815                prevText : "Anterior"
816            });
817            $(seletor? $(seletor).find("input.calendario") : "input.calendario").datepicker('option', 'onSelect', function() {
818                $(this).blur();
819                $(this).focus();
820            });
821            $('input.calendario').bind('onSelect', function() {
822                $(this).focus();
823            });
824            $(seletor? $(seletor).find("input.calendario") : "input.calendario").each(function(){
825                if($(this).hasClass("dataMinimaHoje")){
826                    $(this).datepicker( "option", "minDate", new Date());
827                }
828                if($(this).hasClass("dataMaximaHoje")){
829                    $(this).datepicker( "option", "maxDate", new Date());
830                }
831            });
832            $(seletor? $(seletor).find("input.cpf") : "input.cpf").mask("999.999.999-99");
833            $(seletor? $(seletor).find("input.cnpj") : "input.cnpj").mask("99.999.999/9999-99");
834            $.mask.definitions['~']='[9 ]';//Solução Momentanea
835            $(seletor? $(seletor).find("input.telefone") : "input.telefone").mask("(99) ~9999-9999");
836            $(seletor? $(seletor).find("input.celular") : "input.celular").mask("(99) ~9999-9999");
837            $(seletor? $(seletor).find("input.placa") : "input.placa").mask("aaa-9999");
838            $(seletor? $(seletor).find("input.coordenadas") : "input.coordenadas").mask("a 99º99\"99,9'");
839            $(seletor? $(seletor).find("input.mascaraDiaMes") : "input.mascaraDiaMes").mask("99/99");
840            $('.telefone').focus(function(){sig.notificar("Informar 9 ou espaço para o Nono digíto do telefone.");});
841        }
842
843        $(seletor? $(seletor).find("select.chosen") : "select.chosen").each(function(){
844            $(this).chosen({
845                no_results_text: "Nada encontrado",
846                disable_search_threshold: $(this).data("threshold")?$(this).data("threshold"):10
847            });
848        });
849
850        $(seletor? $(seletor).find(".txtAutocomplete") : ".txtAutocomplete").each(function(){
851            var data = $(this).data();
852            sig.autocomplete($(this).attr("name"), data.source, $(this).attr("id"), data.callback?eval(data.callback):null, data.strictmatch);
853        });
854
855        $(seletor? $(seletor).find(".jquery_slider") : ".jquery_slider").each(function(){
856            $( this ).width( $( this ).data("width") );
857            $( this ).slider({
858                range: $(this).data("range"),
859                value: $(this).data("value"),
860                min: $(this).data("min"),
861                max: $(this).data("max"),
862                slide: function( event, ui ) {
863                    $( "#" + $(this).data("destino") ).val( ui.value );
864                    $( "#spn_" + $(this).data("destino") ).html( ui.value );
865                }
866            });
867            $( "#" + $(this).data("destino") ).val( $( this ).slider( "value" ) );
868            $( "#spn_" + $(this).data("destino") ).html( $( this ).slider( "value" ) );
869        });
870        if($.browser.msie){
871            $(seletor? $(seletor).find(".noIe") : ".noIe").hide();
872        }
873
874        sig.ckeditor(seletor ? seletor : null);
875        sig.submitFormulario();
876    },
877    novoRequerimento : function(idTaxa){
878        sig.carregando();
879        $.ajax({
880            type    : "POST",
881            dataType: 'html',
882            url     : "json/requerimentoNovo/" + idTaxa + "",
883            success : function(data){
884                sig.notificar("Dados o requerimento carregado com sucesso");
885                $("#ajax_Requerimento").html(data);
886                sig.fecharCarregando();
887                //atualizar chosen
888                $(".chzn-container").remove();
889                $(".chosen").removeClass("chzn-done");
890                $(".chosen").css("display","");
891                $(".chosen").chosen({
892                    no_results_text: "Nada encontrado",
893                    disable_search_threshold: 10
894                });
895                //bind #pai
896            },
897            error: function () {
898                sig.alert(data.msg,"Erro",{
899                    Ok: function(){
900                        $(this).dialog("close");
901                    }
902                });
903            }
904        });
905    },
906    posicionarItemSelect : function(select, direcao) {
907        $("#"+select+" option:selected").each(function() {
908            if (direcao == "up") {
909                var val = $(this).prev().val();
910                var tex = $(this).prev().text();
911                var cla = $(this).prev().attr("class");
912                var sel = $(this).prev().attr("selected");
913                var idx = ($(this).index());
914                if(idx>0 && sel != 'selected'){
915                    $(this).prev().remove();
916                    if (val && tex) {
917                        $(this).after("<option value='"+val+"' class='"+cla+"'>"+tex+"</option>");
918                    }
919                }
920            } else if (direcao == "down") {
921                var val = $(this).next().val();
922                var tex = $(this).next().text();
923                var cla = $(this).next().attr("class");
924                $(this).next().remove();
925                if (val && tex) {
926                    $(this).before("<option value='"+val+"' class='"+cla+"'>"+tex+"</option>");
927                }
928            }
929        });
930    },
931    autocomplete : function (nome, source, id, callback, _strictMatch){
932        $('#label_'+id).autocomplete({
933                source:function(request, response){
934                    $.ajax({
935                        url: 'json/' + source,
936                        dataType: 'json',
937                        cache: true,
938                        data: {
939                        term: request.term
940                        },
941                        success: function(data ) {
942                            response($.map(data, function(item) {
943                            return {
944                                id: item.value ,
945                                value: item.label, // invertido, pois no evento automplete, o valor preenchido no campo é o exibido aqui e o que vai pra caixa oculta é o id
946                                outros: item
947                            };
948                        }));
949                    }
950                });
951                },
952                minLength:2,
953                select: function(event, ui){
954                    if(ui.item.id == "__NADA_ENCONTRADO__"){
955                        $(this).val('');
956                        return false;
957                    }
958                    $('#' + id).val(ui.item.id);
959                    $(this).blur();
960                    if(typeof callback == 'function') callback(ui.item.outros,this);
961                },
962                change: function (event, ui){
963                    if(!ui.item && _strictMatch){
964                      $(this).val('');
965                      $('#' + id).val('');
966                      sig.notificar('Você deve selecionar um item clicando na lista.');
967                      }
968                    }
969        }).data('autocomplete')._renderItem = function (ul, item) {
970        return $('<li class=\'result\'></li>')
971                .data('item.autocomplete', item)
972                .append('<a><span class=\'name\'>' + item.label + '</span><span class=\'type\'></span></a>')
973                .appendTo(ul);};
974    },
975    browseImage: function(pasta,callback){
976        if(!$("#browseImage").length){
977            $('body').append("<div id='browseImage'></div>");
978        }
979        $("#browseImage").html("<img src='images/icons/lightbox-ico-loading.gif' style='margin:30% 0 0 50%' alt='Carregando...' />").dialog({
980            modal: true,
981            width: 670,
982            height: 500,
983            resizable: false,
984            draggable: false,
985            title: 'Selecione uma imagem',
986            open: function(){
987                $.getJSON( "json/ged/browse/" + pasta,  function(arquivos){
988
989                    if(arquivos.length==0){
990                        $("#browseImage").html("Nada encontrado");
991                    } else {
992                        $("#browseImage").html("");
993                    }
994                    for(var i=0; i< arquivos.length; i++){
995                        if(arquivos[i].mime.indexOf("image")>-1){
996                            var div = document.createElement("div");
997                            var a = document.createElement("a");
998                            var img = document.createElement("img");
999
1000                            div.className = "arquivo";
1001                            a.href= "#";
1002                            $(a).data("url", arquivos[i].URL);
1003                            $(a).bind('click',function(){
1004                                $("#browseImage").dialog('close');
1005                                callback($(this).data("url"));
1006                                return false;
1007                            });
1008                            //img.src = arquivos[i].URL;
1009                            img.src = arquivos[i].URL + "?w=130&h=120&redimensionar=1";
1010                            a.appendChild(img);
1011                            div.appendChild(a);
1012                            $("#browseImage").append(div);
1013                        }
1014                    }
1015                });
1016            }
1017        });
1018
1019    },
1020    /**
1021     * Verifica se o sistema está online
1022     */
1023    isOnline: function(){
1024        $.getJSON("json/isOnline")
1025        .success(function(data){
1026            sig.online = data;
1027            $("#statusConexao").attr("title","Sua conexão está online");
1028            $("#statusConexao div").removeClass("offline").addClass("online");
1029            sig.localStorage.set('offLine',parseInt(0));//Definir que a tentativa foi válida e vamos zerar o contador offLine
1030            sig.removeAlertOffLine();
1031        })
1032        .error(function (data){
1033            sig.online = false;
1034            $("#statusConexao").attr("title","Você não está conectado na internet");
1035            $("#statusConexao div").removeClass("online").addClass("offline");
1036            sig.localStorage.set('offLine',parseInt(sig.localStorage.get('offLine'))+1);
1037            if (parseInt(sig.localStorage.get('offLine'))>=3){//Aguardar mais de 3 tentativas off para definir a exibição da tela de off.
1038            sig.alertOffLine("Perda de conexão com Host.\n Verifique conexões internas e se há sinal de internet.","OFF LINE",{
1039                    Ok: function(){
1040                        $(this).dialog('close');
1041                    }
1042                //retirado os botões para não permitir que o usuário feche a janela e fique tentando envi
1042ar enquanto está off line.
1043            });
1044            }
1045        });
1046    },
1047    /**
1048     * Adicionar uma mensagem na tela
1049     * @param msg Mensagem a ser exibida
1050     * @param classe Classe css
1051     * @example sig.addMsg("teste","alerta");
1052     */
1053    addMsg : function(msg,classe){
1054        if(!$("#msgs").length){
1055            $("<a name='msgs'></a><ul id='msgs'></ul>").insertBefore($("#principal"));
1056        }
1057        location.href= location.href + '#msgs';
1058        classe = classe ? classe : "info";
1059        var html = "<li class='"+classe+"'><span></span>"+msg+"</li>";
1060        $("#msgs").append(html);
1061    },
1062    /**
1063     * Exibe uma notificação na tela pro usuário
1064     * @param msg Mensagem a exibir
1065     * @example sig.notificar('Mensagem');
1066     */
1067    notificar : function (msg) {
1068        if(!$("#msgsNotificar").length){
1069            $("body").prepend("<ul id='msgsNotificar'></ul>");
1070        }
1071        var li = document.createElement("li");
1072        var span = document.createElement("span");
1073        var txt = document.createTextNode(msg);
1074        var d = new Date();
1075        li.id = "li_" + d.getTime() + (Math.random() * 10000).toFixed(0);
1076        li.appendChild(span);
1077        li.appendChild(txt);
1078        li.innerHTML = li.innerHTML.replace(/\n/g,"<br/>");
1079        $("#msgsNotificar").prepend(li);
1080        /*
1081     $('#'+li.id).hover(function(){
1082            if($(this).css("margin-right").replace("px","") > 200){
1083                $(this).animate({
1084                marginRight:"0px"
1085            },200);
1086            }
1087            else{
1088                $(this).animate({
1089                    marginRight:"300px"
1090                },500);
1091                }
1092        });*/
1093        setTimeout("$('#"+li.id+"').hide('slow')",15000);
1094        //Deixar que o usuário possa ocultar, para não ter que ficar esperando para clicar o que está abaixo.
1095        $("#"+li.id).click(function(){
1096            $("#"+li.id).hide('slow');
1097        });
1098    },
1099    /**
1100     * Exibe uma notificação na tela pro usuário mais rápida
1101     * @param msg Mensagem a exibir
1102     * @example sig.notificar('Mensagem');
1103     */
1104    notificarR : function (msg) {
1105        if(!$("#msgsNotificar").length){
1106            $("body").prepend("<ul id='msgsNotificar'></ul>");
1107        }
1108        var li = document.createElement("li");
1109        var span = document.createElement("span");
1110        var txt = document.createTextNode(msg);
1111        var d = new Date();
1112        li.id = "li_" + d.getTime() + (Math.random() * 10000).toFixed(0);
1113        li.appendChild(span);
1114        li.appendChild(txt);
1115        li.innerHTML = li.innerHTML.replace(/\n/g,"<br/>");
1116        $("#msgsNotificar").prepend(li);
1117        setTimeout("$('#"+li.id+"').hide('slow')",3000);
1118        //Deixar que o usuário possa ocultar, para não ter que ficar esperando para clicar o que está abaixo.
1119        $("#"+li.id).click(function(){
1120            $("#"+li.id).hide('slow');
1121        });
1122    },
1123    /**
1124     * Exibir um alerta na tela
1125     * @param msg Mensagem a ser exibida
1126     * @param titulo Título a ser exibido
1127     * @param btns Botões a serem exibidos => O objeto deve ter o seguinte formato <br/> <pre> { nomedobotao : function(){ escopo da função a ser executada ao clicar}}</pre>
1128    */
1129    alert : function(msg,titulo,btns){
1130        if(!$("#divSigMsgs").length){
1131            $("body").append("<div id='divSigMsgs'></div>");
1132        }
1133        $("#divSigMsgs").html(msg).dialog({
1134            draggable:false,
1135            modal : true,
1136            buttons: btns,
1137            title : titulo ? titulo : "Atençao"
1138        });
1139    },
1140    alertOffLine : function(msg,titulo,btns){
1141        if(!$("#divSigOFF").length){
1142            $("body").append("<div id='divSigOFF'></div>");
1143        }
1144        $("#divSigOFF").html(msg).dialog({
1145            draggable:false,
1146            modal : true,
1147            buttons: btns,
1148            title : titulo ? titulo : "Atençao"
1149        });
1150    },
1151    /** remove a msg do alert
1152     *
1153     * @returns {undefined}
1154     */
1155    removeAlertOffLine : function(){
1156        if($("#divSigOFF").length){
1157            $("#divSigOFF").remove();
1158        }
1159    },
1160    dragEnter : function(div,e){
1161        $(div).addClass("dragOver");
1162        $(div).html("Solte");
1163        return true;
1164    },
1165    dragLeave : function(div,e){
1166        $(div).removeClass("dragOver");
1167        $(div).html("Arraste e solte o arquivo aqui...");
1168        return true;
1169    },
1170    drop : function(div,e){
1171        e.preventDefault();
1172        console.log("Nao implementado");
1173        return false;
1174    },
1175    /**
1176         * Gerar um id único
1177         */
1178    uniqid : function(){
1179        var d = new Date();
1180        var id =  d.getTime() + (Math.random() * 10000).toFixed(0);
1181        return id;
1182    },
1183    ged : {
1184        funcaoAnonima : null,
1185        /** Selecionar um arquivo para upload no GED
1186         *
1187         * @param {type} inputFile
1188         * @returns {undefined}
1189         */
1190        selecionarArquivo : function(inputFile){
1191            sig.carregando();
1192            try {
1193                if(typeof $.ajaxFileUpload == "undefined"){
1194                    throw "O plugin AjaxFileUpload não foi carregado";
1195                }
1196                var d = $(inputFile).data();
1197                sig.ged.funcaoAnonima = eval(d.callback);
1198
1199                $.ajaxFileUpload({
1200                    url:'json/gedUpload',
1201                    secureuri:false,
1202                    fileElementId: $(inputFile).attr("id")  ,
1203                    contentType :  "application / json; charset = UTF-8" ,
1204                    dataType: 'json',
1205                    data:{
1206                        ged: d.destino,
1207                        id : $(inputFile).attr("id"),
1208                        tiposPermitidos : d.tipos,
1209                        limite_tamanho : d.limite_tamanho,
1210                        destino : d.destino ,
1211                        modulo: d.modulo,
1212                        idModulo: d.idmodulo
1213                    },
1214                    success: function (data, status){
1215                        sig.fecharCarregando();
1216                        if(typeof(data.erro) != 'undefined') {
1217                            if(data.erro != ''){
1218                                alert(data.msg);
1219                            } else {
1220                                if(data.erro==1){
1221                                    sig.alert(data.msg,"Erro",{
1222                                        Ok: function(){
1223                                            $(this).dialog("close");
1224                                        }
1225                                    });
1226                                } else {
1227                                    //console.log(data);
1228                                    var img = "", zip = "";
1229                                    if(data.tipo.indexOf("image/") >= 0){
1230                                        img = "<img align='absmiddle' src='openged/"+data.path+"?redimensionar=1&w=50&h=50'/>";
1231                                    }
1232                                    if((data.nome.split(".").pop()).indexOf("zip") >=0){
1233                                        zip = "<button style='float:right' onclick='sig.ged.descompactar(\""+data.id+"\",this.parentNode.parentNode.parentNode,\""+d.modulo+"\",\""+d.idmodulo+"\",this.parentNode.parentNode);return false' class='img' title='Descompactar'><img src='images/icons/zip.png' /></button>";
1234                                    }
1235                                    $("#ged_" + d.hash).append("<tr><td style='text-align:left' > "+zip+" <a href='openged/"+data.path+"?download=1' target='_blank'>"+img+" &nbsp; "+data.nome+"</a></td><td></td><td></td><td><input type='text' size='40' name='descricao_"+data.id+"' onchange='sig.ged.descricao(\""+data.id+"\",this.value);' onkeypress='$(\"#img_ged_reload_"+data.id+"\").show(\"slow\");' /> &nbsp; <img style='display:none' id='img_ged_reload_"+data.id+"' src='images/icons/captcha-reload.gif' alt='atualizar' title='Clique aqui para atualizar a descrição do arquivo' align='absmiddle' /></td><td></td><td><button class='img' onclick='return sig.ged.removerArquivo(\""+data.id+"\",this.parentNode.parentNode);'><img src='images/icons/publish_r.png' alt='remover' /></button></td></tr>");
1236                                    if(typeof sig.ged.funcaoAnonima == "function"){
1237                                        sig.ged.funcaoAnonima(data.path);
1238                                    }
1239                                }
1240                            }
1241                        }
1242                    },
1243                    error: function (data, status, e) {
1244                        alert(e);
1245                        sig.fecharCarregando();
1246                    }
1247                });
1248            } catch (exception) {
1249                sig.fecharCarregando();
1250                sig.alert(exception, "Erro", {
1251                    Ok: function() {
1252                        $( this ).dialog( "close" );
1253                    }
1254                });
1255            }
1256        },
1257        drop : function(div,e){
1258            e.preventDefault();
1259            var f = e.dataTransfer.files;
1260            var d = $(div).data();
1261            var tipos = d.tipos.split("|");
1262            sig.ged.funcaoAnonima = eval(d.callback);
1263            try {
1264                if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
1265                    throw "Seu navegador não permite fazer upload direto, utilize o formulário para enviar um arquivo";
1266                }
1267                if(f.length<=0){
1268                    throw "Isso não é um arquivo";
1269                }
1270                if(f.length > d.limite_upload){
1271                    throw "Só é permitido enviar " + d.limite_upload + " arquivo(s) de cada vez";
1272                }
1273
1274                for(var i=0;i<f.length;i++){
1275                    var extensao = f[i].name.split(".").pop();
1276                    extensao = extensao.toLowerCase();//Necessário colocar a extensão em minusculo para comparação.
1277                    try{
1278                        if(f[i].size > (d.limite_tamanho * 1024 * 1024)){
1279                            throw "O arquivo " + f[i].name  + " excede o tamanho limite de " + d.limite_tamanho + " MB" ;
1280                        }
1281                        if(!in_array(extensao, tipos)){
1282                            throw "O tipo do arquivo " + f[i].name  + " não é permitido " ;
1283                        }
1284
1285                        var nome = f[i].name;
1286                        var tipo = f[i].type;
1287                        var progressId = sig.uniqid();
1288                        $("<div id='"+progressId+"'>Enviando o arquivo " + nome + " <br/> <div class='progress' style='width:300px'></div></div>").insertAfter(div);
1289                        $("#" + progressId).find(".progress:first").progressbar({
1290                            value: 0
1291                        });
1292
1293                        //<img align='absmiddle' src='images/icons/ajax-loader.gif' alt='...' />
1294                        var reader = new FileReader();
1295                        reader.readAsDataURL(f[i]);
1296                        reader.modulo = d.modulo;
1297                        reader.idmodulo = d.idmodulo;
1298                        reader.hash = d.hash;
1299                        reader.nome = nome;
1300                        reader.tipo = tipo;
1301                        reader.progressId = progressId;
1302                        reader.onload = function (event) {
1303                            var xhr, provider;
1304                            var progressId = this.progressId;
1305                            var _modulo = this.modulo;
1306                            var _idmodulo = this.idmodulo;
1307                            xhr = jQuery.ajaxSettings.xhr();
1308                            if (xhr.upload) {
1309                                xhr.upload.addEventListener('progress', function (e) {
1310                                    var complete = (e.loaded / e.total * 100 | 0);
1311                                    $("#" + progressId).find(".progress:first").progressbar("option","value", complete);
1312                                }, false);
1313                            }
1314                            provider = function () {
1315                                return xhr;
1316                            };
1317
1318                            var conteudoArquivo = this.result.split(";base64,")[1];
1319                            var tipo = this.tipo;
1320                            var nome = this.nome;
1321                            var hash = this.hash;
1322                            $.ajax({
1323                                url: "json/gedUpload64",
1324                                dataType: 'json',
1325                                xhr: provider,
1326                                type: 'POST',
1327                                data:{
1328                                    destino : d.destino ,
1329                                    nome : this.nome ,
1330                                    tipo : this.tipo ,
1331                                    modulo: this.modulo,
1332                                    idModulo: this.idmodulo,
1333                                    arquivo : conteudoArquivo
1334                                },
1335                                success: function(data){
1336                                    $("#" + progressId).find(".progress:first").progressbar("option","value", 100);
1337                                    if(data.erro==1){
1338                                        $("<div style='color:red;font-weight:bold;'><img align='absmiddle' src='images/icons/publish_r.png' alt='erro' /> "+data.msg+"</div>").insertAfter(div);
1339                                        $("#" + progressId).hide('slow');
1340                                    } else {
1341                                        $("#" + progressId).html("<img src='images/icons/tick.png' align='absmiddle' /> Enviado " + nome);
1342                                        var img = "", zip = "";
1343                                        if(tipo.indexOf("image/") >= 0){
1344                                            img = "<img align='absmiddle' src='openged/"+data.path+"?redimensionar=1&w=50&h=50'/>";
1345                                        }
1346                                        if((nome.split(".").pop()).indexOf("zip") >=0){
1347                                            zip = "<button style='float:right' onclick='sig.ged.descompactar(\""+data.id+"\",this.parentNode.parentNode.parentNode,\""+_modulo+"\",\""+_idmodulo+"\",this.parentNode.parentNode);return false' class='img' title='Descompactar'><img src='images/icons/zip.png' /></button>";
1348                                        }
1349                                        $("#ged_" + hash).append("<tr><td style='text-align:left' > "+zip+" <a href='openged/"+data.path+"?download=1' target='_blank'>"+img+" &nbsp; "+nome+"</a></td><td></td><td></td><td><input type='text' size='40' name='descricao_"+data.id+"' onchange='sig.ged.descricao(\""+data.id+"\",this.value);' onkeypress='$(\"#img_ged_reload_"+data.id+"\").show(\"slow\");' /> &nbsp; <img style='display:none' id='img_ged_reload_"+data.id+"' src='images/icons/captcha-reload.gif' alt='atualizar' title='Clique aqui para atualizar a descrição do arquivo' align='absmiddle' /></td><td></td><td><button class='img' onclick='return sig.ged.removerArquivo(\""+data.id+"\",this.parentNode.parentNode);'><img src='images/icons/publish_r.png' alt='remover' /></button></td></tr>");
1350                                        if(typeof sig.ged.funcaoAnonima == "function"){
1351                                            sig.ged.funcaoAnonima(data.path);
1352                                        }
1353                                    }
1354                                }
1355                            });
1356                        };
1357                    }
1358                    catch (exception) {
1359                        $("<div style='color:red;font-weight:bold;'><img align='absmiddle' src='images/icons/publish_r.png' alt='erro' /> "+exception+"</div>").insertAfter(div);
1360                    }
1361                }
1362            } catch (exception) {
1363                $(div).removeClass("dragOver");
1364                $(div).html("Arraste e solte o arquivo aqui...");
1365                alert(exception);
1366            }
1367
1368            $(div).removeClass("dragOver");
1369            $(div).html("Arraste e solte o arquivo aqui...");
1370
1371            return false;
1372        },
1373
1374        upload: function(path){
1375        //console.log(path);
1376        },
1377        removerArquivo : function (id,tr){
1378            if(confirm("Deseja remover este arquivo?")){
1379                $.getJSON("json/ged/excluirArquivo/" + id , function(data){
1380                    if(data.retorno.erro){
1381                        sig.notificar("Erro: " + data.retorno.erro);
1382                    }else{
1383                        sig.notificar("O arquivo " + data.nome + " foi excluído com sucesso");
1384                        if(typeof tr == "object"){
1385                            $(tr).hide('slow');
1386                        }
1387                        return true;
1388                    }
1389                });
1390            }
1391            return false;
1392        },
1393        descricao : function(id, descricao){
1394            $.getJSON("json/ged/descricaoArquivo/" + id + "/" + escape(descricao) , function(data){
1395                sig.notificar("A descrição do arquivo \n"+ data.nome+" foi atualizada para \n"  + data.comentario);
1396                $("#img_ged_reload_"+id).hide("slow");
1397            });
1398        },
1399        vizualizacao : function(id, novaVisualizacao){
1400            $.getJSON("json/ged/visualizacao/" + id + "/" + novaVisualizacao , function(data){
1401                sig.notificar("A visualização do arquivo \n"+ data.nome+" foi alterada para \n"  + data.visualizacao);
1402            });
1403        },
1404        descompactar : function(id,tabelaRetorno,modulo,idModulo,trZip){
1405            sig.notificar("Descompactando o arquivo");
1406            $.getJSON("json/ged/descompactarArquivo/" + id  + "/" + modulo + "/" + idModulo , function(data){
1407                $(trZip).hide("slow");
1408                for(var i = 0; i< data.length; i++){
1409                    if(data[i].erro){
1410                        sig.addMsg(data[i].erro, "erro");
1411                    }
1412
1413                    var nome = data[i].nome;
1414                    var tipo = data[i].tipo;
1415                    sig.notificar("Descompactando o arquivo " + nome);
1416                    var img = "", zip = "";
1417                    if(tipo.indexOf("image/") >= 0){
1418                        img = "<img align='absmiddle' src='openged/"+data[i].caminho+"?redimensionar=1&w=50&h=50'/>";
1419                    }
1420                    if((nome.split(".").pop()).indexOf("zip") >=0){
1421                        zip = "<button style='float:right' onclick='sig.ged.descompactar(\""+data[i].id+"\",this.parentNode.parentNode.parentNode,\""+modulo+"\",\""+idModulo+"\",this.parentNode.parentNode);return false' class='img' title='Descompactar'><img src='images/icons/zip.png' /></button>";
1422                    }
1423                    $(tabelaRetorno).append("<tr><td style='text-align:left' > "+zip+" <a href='openged/"+data[i].caminho+"?download=1' target='_blank'>"+img+" &nbsp; "+nome+"</a></td><td></td><td></td><td><input type='text' size='40' name='descricao_"+data[i].id+"' onchange='sig.ged.descricao(\""+data[i].id+"\",this.value);' onkeypress='$(\"#img_ged_reload_"+data[i].id+"\").show(\"slow\");' /> &nbsp; <img style='display:none' id='img_ged_reload_"+data[i].id+"' src='images/icons/captcha-reload.gif' alt='atualizar' title='Clique aqui para atualizar a descrição do arquivo' align='absmiddle' /></td><td></td><td><button class='img' onclick='return sig.ged.removerArquivo(\""+data[i].id+"\",this.parentNode.parentNode);'><img src='images/icons/publish_r.png' alt='remover' /></button></td></tr>");
1424
1425                }
1426            });
1427        }
1428    },
1429    grade :{
1430        /** Verificar se existe alguma palavra chave buscada anteriormente
1431         *
1432         * @param {type} idBusca
1433         * @returns {undefined}
1434         */
1435        verificaBusca : function(idBusca){
1436            if(sig.sessionStorage.get("buscaGrade_" + idBusca)){
1437                var form = $("#grade_" + idBusca).find("form:first");
1438                form.find("input[name=_campoBuscaGrade_"+idBusca+"]").val(sig.sessionStorage.get("buscaGrade_" + idBusca));
1439                form.submit();
1440            }
1441        },
1442        busca : function(f,idBusca){
1443            var idBusca = f.idBusca.value;
1444            var termo = f.elements["_campoBuscaGrade_" + idBusca].value;
1445            sig.sessionStorage.set("buscaGrade_" + idBusca, termo );
1446            var dados = $(f).serialize();
1447            $("#grade_" + idBusca).html("<img src='images/icons/ajax-loader.gif' alt='Carregando' />");
1448            $.ajax({
1449                type    : "POST",
1450                dataType: 'html',
1451                url     :  "json/sig/buscaGrade",
1452                data    : dados,
1453                success : function(data){
1454                    $("#grade_" + idBusca).html($(data).html());
1455                }
1456            });
1457        }
1458    },
1459
1460    /**
1461     * Redicionar para uma URL<br/>
1462     * O problema de usar location.href diretamente é que o IE ignora a tag base, direcionando para o endereço incorreto
1463     * @param url Link da página
1464     */
1465    redirecionar : function(url){
1466        var base = "";
1467        if(!url.indexOf("http")>=0){
1468            base = $("base").attr("href");
1469        }
1470        location.href = base + url;
1471    },
1472    /**
1473     * Redicionar para uma URL - Abrindo Nova Janela<br/>
1474     * @param url Link da página
1475     */
1476    redirecionarBlank : function(url){
1477        var base = "";
1478        if(!url.indexOf("http")>=0){
1479            base = $("base").attr("href");
1480        }
1481        window.open(base + url);
1482    },
1483    sessionStorage : {
1484        set : function(chave, valor){
1485            if(typeof sessionStorage != "undefined"){
1486                window.sessionStorage.setItem(chave,valor);
1487            }
1488        },
1489        get: function(chave){
1490            if(typeof sessionStorage != "undefined"){
1491                return window.sessionStorage.getItem(chave);
1492            }
1493        },
1494        remove : function(chave){
1495            if(typeof sessionStorage != "undefined"){
1496                window.sessionStorage.removeItem(chave);
1497            }
1498        }
1499    },
1500    localStorage : {
1501        set : function(chave, valor){
1502            if(typeof localStorage != "undefined"){
1503                window.localStorage.setItem(chave,valor);
1504            }
1505        },
1506        get: function(chave){
1507            if(typeof localStorage != "undefined"){
1508                return window.localStorage.getItem(chave);
1509            }
1510        },
1511        remove : function(chave){
1512            if(typeof localStorage != "undefined"){
1513                window.localStorage.removeItem(chave);
1514            }
1515        }
1516    },
1517    duploClick : function(){
1518        var tr = $('table tr');
1519        tr.dblclick(function() {
1520            var self = this;
1521            tr.each(function(){
1522                if(this == self){
1523                    $(this).toggleClass('marcar');
1524                }
1525            });
1526        });
1527    },
1528    aplicarNovaTagSalaVirtual : function (selTag, idSala){
1529        var idTag = $(selTag).val();
1530        if(confirm("Deseja aplicar esta Tag")) {
1531            sig.carregando();
1532            $.ajax({
1533                type    : "POST",
1534                dataType: 'json',
1535                url     :  "alunoSalaVirtual/aplicarHashTag",
1536                data    : {
1537                    idTag   : idTag,
1538                    idSala  : idSala
1539                },
1540                success : function(data){
1541                    if(data.erro == false){
1542                        sig.notificar("Tag aplicada com sucesso");
1543                        sig.fecharCarregando();
1544                    } else {
1545                        sig.notificar("Erro: " + data.erro);
1546                        sig.fecharCarregando();
1547                    }
1548                }
1549            });
1550        }
1551    }    
1552
1553};
1554
1555//se houver um click duplo na linha, vamos selecionar a linha
1556$("body").dblclick(function() {
1557    sig.duploClick();
1558});
1559
1560/** Oculta/Exibe as TRs com a class classTR e altera o botão da div conforme oculta ou exibe as TRs
1561 *
1562 * @param {type} idDiv
1563 * @param {type} classTR
1564 * @returns {undefined}
1565 */
1566function toggleTRSubTotal(idDiv,classTR){
1567    // A logica é invertida pelo fato de analisar a situação atual, quer dizer que se está oculto será exibido e vice-versa
1568    if($('.'+idDiv).css('display') === 'none'){
1569        $('#'+idDiv).attr('src', 'images/icons/collapse.png');
1570        if(classTR != ''){
1571            $('.'+classTR).attr('src', 'images/icons/collapse.png');
1572        }
1573    } else {
1574        $('#'+idDiv).attr('src', 'images/icons/expand.png');
1575        if(classTR != ''){
1576            $('.'+classTR).attr('src', 'images/icons/expand.png');
1577        }
1578    }
1579    $('.'+idDiv).slideToggle();
1580}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.