source: branches/2.5/prototype/modules/mail/js/label.js @ 8232

Revision 8232, 20.4 KB checked in by douglas, 11 years ago (diff)

Ticket #0000 - Copiadas as alterações do Trunk. Versão final 2.5.1.

  • Property svn:executable set to *
Line 
1function msgCallback(msg){
2        switch(msg){
3                case '#LabelNameError':
4                        alert('Já existe um marcador com esse nome.');
5                        break;
6                case '#LabelSlotError':
7                        alert('Atingido limite de marcadores criados.');
8                        break; 
9                default:
10                        alert('Ocorreu um erro ao salvar o Marcador');
11        }
12}
13function configureLabel(event, ui){
14        var idmarkernow = $(this).find('[name="labelItemId"]').val();
15        winElement.find('.edit-label').val(idmarkernow);
16        winElement.find('.input-nome').val($(this).find("span").text());
17       
18        var colorpicker = winElement.find('.lebals-colorpicker');
19        colorpicker.find('input[name="backgroundColor"]').val(rgb2hex($(this).css("backgroundColor")))
20        .css("background-color", $(this).css("backgroundColor")).focus().end()
21        .find('input[name="fontColor"]').val(rgb2hex($(this).css("color"))).css("background-color", $(this).css("color")).focus().end()
22        .find('input[name="borderColor"]').val(rgb2hex($(this).css("border-left-color"))).css("background-color", $(this).css("border-left-color")).focus().end()
23        .find('.preview-label-outer').css({
24                'background-color':$(this).css("backgroundColor"),
25                'color':$(this).css("color"),
26                'border-color':$(this).css("border-left-color")
27        })             
28        winElement.find(".preview-label-inner").text($(this).text());
29}
30
31function editLabel(data){       
32        var conteudoSpan = $(this).parent().find(".text-list").text();
33        var span = $(this).parent().find(".text-list");
34        $(this).parent().trigger('click').unbind('click', configureLabel).find("span.text-list")
35        .html('<input name="edit-value-list" class="edit-value-list" type="text" maxlength="18" value="'+conteudoSpan+'">').find("input[name='edit-value-list']").keydown(function(event){
36                event.stopPropagation();
37                $("input.edit-value-list").keyup(function () {
38                        var value = $(this).val();
39                        winElement.find('.input-nome').val(value);
40                }).keyup();
41                if(event.keyCode == 13){
42                        event.preventDefault();
43                        var nameLabel = $(".label-list").find(".edit-value-list").val();
44                        $(span).html(conteudoSpan)
45                        .parent().find('.edit').css("display","").parents("li").click(configureLabel);
46                        save_editLabel(nameLabel, data.applyToSelectedMessages);
47                }else if( event.keyCode == 27){
48                        $(this).trigger("focusout");
49                }
50        }).focusout(function(){
51                $(span).html(conteudoSpan)
52                .parent().find('.edit').css("display","").parents("li").click(configureLabel);
53        }).focus();
54        $(this).hide();
55}
56
57function deleteLabel(event){
58        var id = $(this).parents(".label-item").attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/)[1];
59        var nameLabel = winElement.find(".input-nome").val();
60        confirmDelete(id, nameLabel);
61        event.stopImmediatePropagation();
62}
63
64function colors_suggestions(){
65        return [
66                                {name:'Padrão', border:'#3366cc', font:'#ffffff', background:'#3366cc'},
67                                {name:'Coala', border:'#123456', font:'#ffffff', background:'#385c80'},
68                                {name:'Tomate', border:'#d5130b', font:'#111111', background:'#e36d76'},
69                                {name:'Limão', border:'#32ed21', font:'#1f3f1c', background:'#b2f1ac'},
70                                {name:'Alto contraste', border:'#000000', font:'#ffffff', background:'#222222'}
71                        ]               
72}
73
74function rgb2hex(rgb){ 
75        if(!!(rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/))){
76                return "#" +
77                ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
78                ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
79                ("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
80        }else{
81                return rgb;
82        }
83}
84
85function returnLabels(msgsReference){
86        var folderIndex = {};
87   for (var i=0; i < msgsReference.length; i++) {       
88       if( folderIndex[ msgsReference[i].folderName] ){       
89           folderIndex[ msgsReference[i].folderName].push( msgsReference[i].messageNumber );         
90       }else{
91           folderIndex[ msgsReference[i].folderName] = [ msgsReference[i].messageNumber ];
92       }     
93   }
94   var labels = [];
95   for(var folder in folderIndex){
96                var currentLabes = DataLayer.get('labeled',{ filter:[
97               'AND',
98               ['=', 'folderName', folder ],
99               ['IN', 'messageNumber', folderIndex[ folder ] ]
100               ], criteria: {deepness: '2'}});
101
102                if( $.isArray( currentLabes ) )
103                        labels = labels.concat( currentLabes );
104   }
105   var labelsIndex = {};
106   $.each( labels, function(i, e){
107       if( labelsIndex[ e.messageNumber ] ){
108           labelsIndex[ e.messageNumber ][ 'labels' ].push( e.label );
109       }else{
110           labelsIndex[ e.messageNumber ] = e;
111           labelsIndex[ e.messageNumber ][ 'labels' ] = [];
112           labelsIndex[ e.messageNumber ][ 'labels' ].push( e.label );
113       }
114   });
115   return labelsIndex;
116}
117
118
119function updateMessageLabels(msgsReference){
120        var labelsIndex = returnLabels(msgsReference);
121   $.each(labelsIndex,function(index,e){
122           updateLabelsColumn({msg_number: e.messageNumber, boxname: e.folderName,labels: e.labels, forceIcon: true});
123   });
124}
125
126function confirmDelete(id,nameLabel){
127        $.Zebra_Dialog('Deseja excluir esse marcador <strong>'+nameLabel+'</strong> das conversas que está relacionado e excluí-lo sem remover as conversas?', {
128                'type':     'question',
129                'custom_class': (is_ie ? 'configure-zebra-dialog custom-zebra-filter' : 'custom-zebra-filter'),
130                'title':    'Atenção',
131                'buttons': ['Sim','Não'],               
132                'overlay_opacity': '0.5',
133                'onClose':  function(caption) {
134                        if(caption == 'Sim'){
135                                delete_label(id);
136                        }
137                }
138        });     
139        if(is_ie)
140                $(".ZebraDialogOverlay").css("z-index","1006");
141}               
142       
143function save_editLabel(nameLabel, apply){     
144
145        var lengthSpace = $.trim(nameLabel);
146       
147        if( lengthSpace.length >= 2){   
148                var qtdLi = $(".label-list-container ul").find("li").not(".empty-item").length;
149                // salvar marcador
150                if(qtdLi > 0 ){
151                        $(".save-label").button("disable");
152                        var labelEdited = {
153                                id : winElement.find(".edit-label").val(),
154                                uid: User.me.id,
155                                name : winElement.find('.input-nome').val().trim(),
156                                backgroundColor : winElement.find("input[name='backgroundColor']").val(),
157                                fontColor : winElement.find("input[name='fontColor']").val(),
158                                borderColor : winElement.find("input[name='borderColor']").val()
159                        }
160                        DataLayer.put('label', labelEdited.id, labelEdited);
161                        DataLayer.commit(false, false, function(data){
162                                var hasLabel = true;
163                                $.each(data, function(index, value) {
164                                       
165                                        hasLabel = typeof value == 'object' ? false : value;
166                                       
167                                });
168                                       
169                                        if(!hasLabel){
170                                                $(".label-list-container .label-list li").each(function(){
171                                                        var regex_match_2 = $(this).attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/);
172                                                       
173                                                         if(regex_match_2 && regex_match_2[1] && regex_match_2[1] == labelEdited.id){
174                                                           $(this).html("<input type='hidden' name='labelItemId' class='id-item-list' value='"+labelEdited.id+"'>"+"<span class='text-list'>"+labelEdited.name+"</span><div class='button close tiny' style='float: right'></div><div class='button edit tiny' style='float: right'></div>").css({
175                                                                "background" : labelEdited.backgroundColor,
176                                                                "color" : labelEdited.fontColor,
177                                                                "border-color" : labelEdited.borderColor       
178                                                           });
179                                                           $(this).trigger('click');
180                                                         }     
181                                                });
182                                               
183                                                $("#MyMarckersList .label-list li").each(function(){
184                                                        var regex_match_2 = $(this).attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/);
185                                                       
186                                                        if(regex_match_2 && regex_match_2[1] && regex_match_2[1] == labelEdited.id){
187                                                                $(this).html("<input type='hidden' name='labelItemId' class='id-item-list' value='"+labelEdited.id+"'>"+"<span>"+labelEdited.name+"</span>");
188                                                                $(this).find(".square-color").css('background', labelEdited.backgroundColor);
189                                                        }       
190                                                });
191                                       
192                                                winElement.find(".insert-label").val("");
193                                                $.Watermark.ShowAll();
194                                               
195                                                $(".label-list-container .label-list li").find('.button').button()
196                                                        .filter('.edit').button({icons:{primary:'ui-icon-pencil'}, text:false}).end()
197                                                        .filter('.close').button({icons:{primary:'ui-icon-close'}, text:false});
198                                                       
199                                                winElement.find('.edit').unbind("click").click(editLabel);                             
200                                                winElement.find('.close').click(deleteLabel);
201                        if( preferences['use_followupflags_and_labels'] == "1" )
202                                                    draw_tree_labels();
203                                                var msgsReference = DataLayer.get('labeled', {filter: ['=', 'labelId', ''+labelEdited.id]}, true);
204                                                updateMessageLabels(msgsReference);
205                               
206                                                /**
207                                                * Atualiza menu remove o menu presente em cada mensagem listada em uma pasta
208                                                * e carrega novamente para que os dados sejam atualizados
209                                                */
210                                                $.contextMenu( 'destroy', ".table_box tbody tr");
211                                                loadMenu();
212                                        }else{
213                                                msgCallback(hasLabel);
214                                        }
215                                       
216                                        $(".add-label-button").empty()
217                                        .addClass("ui-icon ui-icon-plus");
218                                        //winElement.find('.input-nome').val("").focus;
219                        });
220                // criar marcador
221                } else {
222                        var nameLabel = winElement.find(".input-nome").val();
223                        new_label(nameLabel, false, apply);                             
224                        $.Watermark.ShowAll();         
225                        $(".save-label").button("disable");     
226                }
227                //$(".label-list-container .label-list").find(".label-item-"+labelEdited.id).trigger("click");
228        } else {
229                alert("Mínimo 2 caracteres");
230        }       
231}
232
233function delete_label(id){
234        $(".label-list li").each(function () {
235                var regex_match = $(this).attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/);
236                if (regex_match && regex_match[1] && regex_match[1] == id) {   
237                        $(this).remove();
238                }
239        });
240       
241        var msgsReference = DataLayer.get('labeled', {filter: ['=', 'labelId', ''+id]}, true);
242               
243        DataLayer.remove('label', id);
244
245        DataLayer.commit(false, false, function(data){
246                $.contextMenu( 'destroy', ".table_box tbody tr");
247                loadMenu();
248                updateMessageLabels(msgsReference);     
249        });
250        winElement.find(".label-list li:first").trigger("click");
251       
252        if($(".label-list li").length == 0){
253                winElement.find(".label-list-container").html('<ul class="label-list"><li class="empty-item">'+get_lang("No labels found.")+'.</li></ul>');
254                $(".save-label").button("disable");     
255        }
256        var qtdLi = $(".label-list-container ul").find("li").not(".empty-item").length;
257        if (qtdLi == 0){
258                $(".my-labels").hide();
259                $(".label-list-container ul").find(".empty-item").css("display","");
260                winElement.find(".buttons .save-label .ui-button-text").text('Criar');
261                $(".delete-label").button("disable");   
262                $(".save-label").button("disable");     
263                               
264                winElement.find('.input-nome').val("");
265                winElement.find(".preview-label-inner").text("");
266       
267                var colorpicker = winElement.find('.lebals-colorpicker');
268                colorpicker.find('input[name="backgroundColor"]').val("#ebebeb")
269                .css("background-color", "#ebebeb").focus().end()
270                .find('input[name="fontColor"]').val("#000000").css("background-color", "#000000").focus().end()
271                .find('input[name="borderColor"]').val("#000000").css("background-color", "#000000").focus().end()
272                .find('.preview-label-outer').css({
273                        'background-color':"#ebebeb",
274                        'color':"#000000",
275                        'border-color':"#000000"
276                });
277                $(".input-nome").keyup(function () {
278                        var value = $(this).val();
279                        winElement.find('.preview-label-inner').text(value);
280                }).keyup();                             
281        }       
282}
283
284function new_label(nameLabel, isNew, apply){
285        var labelCreated = {
286                uid: User.me.id,
287                name : nameLabel.trim(),
288                backgroundColor : !!isNew ? '#ebebeb' : winElement.find("input[name='backgroundColor']").val(),
289                fontColor : !!isNew ? '#000000' : winElement.find("input[name='fontColor']").val(),
290                borderColor :!!isNew ? '#000000' : winElement.find("input[name='borderColor']").val()
291        }
292        DataLayer.put('label', labelCreated);
293       
294        $(".add-label-button").removeClass("ui-icon ui-icon-plus")
295        .html('<img alt="Carregando" title="Carregando" style="margin-left:10px;" src="../prototype/modules/mail/img/loader.gif" />');
296        var hasLabel = true;
297        var labelId;
298        DataLayer.commit(false, false, function(data){
299                $.each(data, function(index, value) {
300                        if(typeof value == 'object'){
301                                hasLabel = false;
302                                labelId = value.id;
303                        }else{
304                                hasLabel = value;
305                        }
306                });
307       
308                if(!hasLabel){
309                        newLabel = {
310                                id: labelId,
311                                name : nameLabel.trim(),
312                                uid: User.me.id,
313                                bgColor : !!isNew ? '#ebebeb' : winElement.find("input[name='backgroundColor']").val(),
314                                fontColor : !!isNew ? '#000000' : winElement.find("input[name='fontColor']").val(),
315                                borderColor : !!isNew ? '#000000' : winElement.find("input[name='borderColor']").val()
316                        };
317               
318                        /** Marca as mensagens selecionadas com o marcador criado*/
319                        if(apply){
320                                labeledMessages(newLabel.id)
321                        }
322                       
323                        $(".label-list-container ul").find(".empty-item").css("display","none");
324                        $(".label-list-container ul")
325                        .prepend(DataLayer.render("../prototype/modules/mail/templates/label_listitem.ejs", newLabel))
326                        .find("li:first")
327                        .fadeIn("slow").click(configureLabel);
328            if( preferences['use_followupflags_and_labels'] == "1" )
329                            draw_tree_labels();
330
331                        $(".label-list-container .label-list li").not(".empty-item").click(function(){
332                                $(".label-list-container .label-list li").find("img").remove();
333                                $(".label-list-container .label-list li.label-item").removeClass("selected");
334                                $(this).prepend("<img src='../prototype/modules/mail/img/triangle.png' style='margin: 0 5px 0 -5px;'>");
335                                $(this).addClass("selected");
336                        });
337                       
338                        $(".label-list-container .label-list li").find('.button').button()
339                        .filter('.edit').button({icons:{primary:'ui-icon-pencil'}, text:false}).end()
340                        .filter('.close').button({icons:{primary:'ui-icon-close'}, text:false});
341                       
342                        //posiciona para edição o label inserido                       
343                        winElement.find("ul.label-list li:first").trigger("click");                     
344                        winElement.find(".buttons .save-label .ui-button-text").text('Salvar');
345                        $(".delete-label").button("enable");
346                       
347                        winElement.find('.edit').unbind("click").click(editLabel);                             
348                        winElement.find('.close').click(deleteLabel);
349                       
350                        $(".my-labels").show();
351                       
352                        $.contextMenu( 'destroy', ".table_box tbody tr");
353                        loadMenu();
354                       
355                        $(".add-label-button").empty()
356                        .addClass("ui-icon ui-icon-plus");
357                }else{
358                        $(".add-label-button").empty()
359                        .addClass("ui-icon ui-icon-plus");
360                        msgCallback(hasLabel);
361                }
362        });
363}
364
365function SortByName(a, b){
366    var aName = a.name.toLowerCase();
367    var bName = b.name.toLowerCase();
368    return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
369}
370
371//Reduz a quantidade de requests
372function orderLabel(labels){
373
374    if(labels == "")
375        return labels;
376
377    if(!$.isArray( labels )){
378        var array = [];
379
380        for(var i in labels){
381
382            array[ array.length ] = labels[ i ];
383
384        }
385
386        labels = array;
387
388    }
389
390    return labels.sort(SortByName);
391}
392
393function init_label(data){
394
395        winElement = data.window;
396       
397        //TODO Mudar quando API abstrair atualizações no cache
398        var labels = DataLayer.get('label');
399
400    labels = orderLabel( labels );
401       
402        if(labels){
403                Label_List = winElement
404                .find(".label-list-container").html(DataLayer.render("../prototype/modules/mail/templates/label_list.ejs", {labels: labels}));
405               
406        }else{
407                //Exibe a mensagem informando o usuário de que não há nenhum marcador cadastrado.
408                Label_List = winElement
409                .find(".label-list-container").html('<ul class="label-list"><li class="empty-item">'+get_lang("No labels found.")+'.</li></ul>');
410               
411        }
412        Label_List.end()
413        .find('.button').button()
414        .filter('.edit').button({icons:{primary:'ui-icon-pencil'}, text:false}).end()
415        .filter('.close').button({icons:{primary:'ui-icon-close'}, text:false});       
416       
417        winElement.find('.edit').click(editLabel);
418        winElement.find('.close').click(deleteLabel);
419       
420        //marca 'd agua
421        winElement.find(".insert-label").Watermark(winElement.find(".insert-label").val());
422       
423        /*
424        $("input.insert-label").keyup(function () {
425                $.Watermark.HideAll();
426                var value = $(this).val();
427                winElement.find('.input-nome').val(value);
428        }).keyup();
429        */
430        if (!(labels)){
431                winElement.find(".buttons .save-label .ui-button-text").text('Criar');
432                $(".delete-label").button("disable");
433        }else{
434                winElement.find(".label-list li:first").addClass("selected").prepend("<img src='../prototype/modules/mail/img/triangle.png' style='margin: 0 5px 0 -5px;'>");
435        }
436        $(".save-label").button("disable");
437        /**
438        * seta a ação de click para os marcadores listados na tela
439        */
440        winElement.find(".label-list li").not(".empty-item").click(configureLabel);
441       
442        if (data.selectedItem)
443                winElement.find(".label-list li.label-item-"+data.selectedItem).trigger("click");
444        else
445                winElement.find(".label-list li:first").trigger("click");
446               
447        var dataColorPicker = {
448                colorsSuggestions: colors_suggestions()
449        };
450       
451        winElement.find('select.color-suggestions').change(function() {
452                $(".save-label").button("enable");
453                var colorpicker = winElement.find('.lebals-colorpicker');
454                var colors;
455                if(colors = dataColorPicker.colorsSuggestions[$(this).val()]) {
456                        colorpicker
457                        .find('input[name="fontColor"]').val(colors.font).focus().end()
458                        .find('input[name="backgroundColor"]').val(colors.background).focus().end()
459                        .find('input[name="borderColor"]').val(colors.border).focus().end()
460
461                        .find('.preview-label-outer').css({
462                                'background-color':dataColorPicker.colorsSuggestions[$(this).val()].background,
463                                'border-color':dataColorPicker.colorsSuggestions[$(this).val()].border,
464                                'color':dataColorPicker.colorsSuggestions[$(this).val()].font
465                        });
466                }                                       
467        });
468        var colorpickerPreviewChange = function(color) {
469                       
470                var pickedup = winElement.find('.colorwell-selected').val(color).css('background-color', color);
471
472                $(".save-label").button("enable");
473               
474                var colorpicker = winElement.find('.lebals-colorpicker');                       
475
476                if (pickedup.is('input[name="backgroundColor"]')) {
477                        colorpicker.find('.preview-label-outer').css('background-color',color);
478                } else if (pickedup.is('input[name="fontColor"]')) {
479                        colorpicker.find('.preview-label-outer').css('color',color);
480                } else if (pickedup.is('input[name="borderColor"]')) {
481                        colorpicker.find('.preview-label-outer').css('border-color',color);
482                }               
483        }
484               
485        var f = $.farbtastic(winElement.find('.colorpicker'), colorpickerPreviewChange);
486        var selected;
487                               
488        winElement.find('.colorwell').each(function () {
489                f.linkTo(this);
490        })
491        .focus(function() {
492                if (selected) {
493                        $(selected).removeClass('colorwell-selected');
494                }
495                $(selected = this).addClass('colorwell-selected');
496                f.linkTo(this, colorpickerPreviewChange);
497                f.linkTo(colorpickerPreviewChange);
498        });
499       
500        winElement.find(".add-label-button").click(function (event) {
501                $.Watermark.HideAll();
502                var nameLabel = winElement.find(".insert-label").val();
503               
504                var lengthSpace = $.trim(nameLabel);
505               
506                if(lengthSpace.length >= 2){
507                        new_label(nameLabel, true, data.applyToSelectedMessages);
508                        $.Watermark.ShowAll();
509                        winElement.find(".insert-label").val("");
510                        } else {
511                                alert("Mínimo 2 caracteres");
512                        }
513                event.stopImmediatePropagation();
514        });
515       
516        winElement.find('.insert-label').keydown(function(event, ui) {
517                if (event.keyCode == 13)
518                        winElement.find(".add-label-button").trigger('click');
519        });
520       
521        //excluir marcador {deve ser para o botão grande na janela de edição e nao o pequeno da lista}
522        winElement.find(".buttons .delete-label").click(function(event){
523                var id = winElement.find(".edit-label").val();         
524                var nameLabel = winElement.find(".input-nome").val();   
525                confirmDelete(id, nameLabel);
526                event.stopImmediatePropagation();
527        });
528       
529        $(".label-list-container .label-list li").not(".empty-item").click(function(){
530                $(".label-list-container .label-list li").find("img").remove();
531                $(".label-list-container .label-list li.label-item").removeClass("selected");
532                $(this).prepend("<img src='../prototype/modules/mail/img/triangle.png' style='margin: 0 5px 0 -4px;'>");
533                $(this).addClass("selected");
534        });
535               
536        //salvar/criar marcador
537        winElement.find(".buttons .save-label").click(function(){
538                var nameLabel = winElement.find(".input-nome").val();
539                save_editLabel(nameLabel, data.applyToSelectedMessages);
540        });     
541        //desfazer marcador
542        winElement.find(".buttons .undo-label").click(function(event){
543                var edit = winElement.find(".edit-label").val();               
544                $(".label-list-container .label-list li").each(function(){
545                        var regex_match_3 = $(this).attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/);
546                        if(regex_match_3 && regex_match_3[1] && regex_match_3[1] == edit){
547                                $(this).trigger("click");
548                        }
549                });
550        });
551       
552        //fechar
553        $(".button-close-window .close-window").click(function(){
554                $(".label-configure-win").dialog("close");
555        });
556       
557        winElement.find(':input').change(function(event){
558                if (event.keyCode != '27' && event.keyCode != '13' && !$(event.target).is(".edit-value-list") && !$(event.target).is(".insert-label") )
559                winElement.find(".save-label").button("enable");
560        }).keydown(function(event){
561                if (event.keyCode != '27' && event.keyCode != '13' && !$(event.target).is(".edit-value-list") && !$(event.target).is(".insert-label"))
562                winElement.find(".save-label").button("enable");
563        });     
564
565        $(".input-nome").keyup(function () {
566                                var value = $(this).val();
567                                winElement.find('.preview-label-inner').text(value);
568        }).keyup();     
569}
Note: See TracBrowser for help on using the repository browser.