source: branches/2.5/prototype/modules/calendar/js/helpers.js @ 7982

Revision 7982, 106.0 KB checked in by douglas, 11 years ago (diff)

Ticket #3378 - Importação automatica de eventos nos participantes

RevLine 
[5515]1function formatBytes(bytes) {
[6044]2    if (bytes >= 1000000000) {
3        return (bytes / 1000000000).toFixed(2) + ' GB';
4    }
5    if (bytes >= 1000000) {
6        return (bytes / 1000000).toFixed(2) + ' MB';
7    }
8    if (bytes >= 1000) {
9        return (bytes / 1000).toFixed(2) + ' KB';
10    }
11    return bytes + ' B';
[5515]12};
13
[5341]14function validDateEvent(){
[6444]15       
16        var errors = {
17                'emptyInitData': 'Por favor, informe uma data inicial',
18                'emptyEndData': 'Por favor, informe uma data final',
19                'emptyInitHour': 'Por favor, informe uma hora inicial',
20                'emptyEndHour': 'Por favor, informe uma hora final',
21               
22                'invalidInitData' : 'Data inicial inválida',
23                'invalidEndData' : 'Data final inválida',
24               
25                'equalData' : 'Hora inicial igual a final',
[6552]26                'theirData' : 'Data final menor que a inicial',         
27                'theirHour' : 'Hora final menor que a inicial',
[6444]28               
29                'emptyOcurrence' : 'Por favor, informe o número de ocorrências',
30                'invalidOcurrence' : 'Por favor, informe um valor válido para a quantidade de ocorrências',
31               
32                'emptyInterval' : 'Por favor, informe o intervalo',
33                'invalidInterval' : 'Por favor informe um valor válido para o intervalo'
34        };
35
[6044]36    var start_date = $(".new-event-win.active .start-date").val();
37    var end_date   = $(".new-event-win.active .end-date").val();
38    var start_time = $(".new-event-win.active .start-time").val();
39    var end_time   = $(".new-event-win.active .end-time").val();
40    var isAllDay   = $('.new-event-win.active input[name="allDay"]').is(':checked');
[6077]41    var customDate = $(".endRepeat").val() == "customDate";
42    var occurrences = $(".endRepeat").val() == "occurrences";
[6087]43    var eventInterval = $('.eventInterval').val();
44   
[6044]45    if(start_date == "")
[6444]46                return errors['emptyInitData'];
[6044]47    else if(end_date == "")
[6444]48                return errors['emptyEndData'];
[6044]49    else if(!isAllDay && start_time == "")
[6444]50                return errors['emptyInitHour'];
[6044]51    else if(!isAllDay && end_time == "")
[6444]52                return errors['emptyEndHour'];
[5341]53       
[6444]54    var formatString = User.preferences.dateFormat + " " + User.preferences.hourFormat;
[5409]55               
[6444]56    var startDate = Date.parseExact( start_date + " " + $.trim(start_time) , formatString );
57    var endDate = Date.parseExact( end_date + " " + $.trim(end_time) , formatString );
[5510]58
[6044]59    if(startDate == null || startDate.getTime() < 0 )
[6444]60                return errors['invalidInitData'];
[6044]61    if(endDate == null || endDate.getTime() < 0)
[6444]62                return errors['invalidEndData'];
[5341]63       
[6444]64        if(isAllDay){
65                startDate.clearTime();
66                endDate.clearTime();
67                if(endDate.compareTo(startDate) == -1)
68                        return errors['theirData'];
69        }else{
[6552]70                var condition = endDate.compareTo(startDate);
71                if(condition != 1){
72                        if(condition < 0){
73                                startDate.clearTime();
74                                endDate.clearTime();
75                                condition = endDate.compareTo(startDate);                               
76                                return (errors[ condition == 0 ? 'theirHour' : 'theirData'] );
77                        }
78                        else
79                                return errors['equalData'];
80                }
[6444]81        }
[6077]82   
[6444]83    if (customDate)   
84                if ( !($('.new-event-win.active .customDateEnd').val().length) )
85                   return errors['emptyEndData'];
86
[6077]87    if (occurrences){
[6444]88                if ( !($('.occurrencesEnd').val().length) )
89                   return errors['emptyOcurrence'];
90                else if (parseInt($('.occurrencesEnd').val(),10) <= 0 || parseInt($('.occurrencesEnd').val(),10).toString() == "NaN")
91                   return errors['invalidOcurrence'];
92        }
[6087]93
94    if (!($('.new-event-win.active p.input-group.finish_event.repeat-in').hasClass('hidden'))){
95        if (!eventInterval.length)
[6444]96            return errors['emptyInterval'];
[6346]97        else if (parseInt(eventInterval,10) < 1 || parseInt(eventInterval,10).toString() == "NaN")
[6444]98            return errors['invalidInterval'];
[6087]99    }   
[6044]100    return false;
[5341]101}
102
[6996]103function printNow(){
[7022]104        if($("#calendar").fullCalendar('getView').name == "agendaWeek" || $("#calendar").fullCalendar('getView').name == "basicWeek" || $("#calendar").fullCalendar('getView').name == "year")
105                alert('A tela de impressão será melhor visualizada com a preferência "Paisagem" do seu browser selecionada.');
106               
[6996]107        var window_print = window.open('','ExpressoCalendar','width=800,height=600,scrollbars=yes');       
108        window_print.document.open();
109
110        var start = $("#calendar").fullCalendar('getView').visStart.getTime()/1000;
111        var end = $("#calendar").fullCalendar('getView').visEnd.getTime()/1000;
112        var criteria = DataLayer.criteria("schedulable:calendar", {'start':start, 'end':end} );
113       
114        var data = DataLayer.get("schedulable:print", criteria);       
115
116        if($("#calendar").fullCalendar('getView').name == "month"){                             
117                window_print.document.write(DataLayer.render('templates/calendar_month_print.ejs', {
118                        'InfoPage' : $("#calendar").fullCalendar('getView').title,
119                        'days' : data
120                } ));
121        }
[7022]122        if($("#calendar").fullCalendar('getView').name == "agendaDay" || $("#calendar").fullCalendar('getView').name == "basicDay"){                           
[6996]123                window_print.document.write(DataLayer.render('templates/calendar_day_print.ejs', {
124                        'InfoPage' : $("#calendar").fullCalendar('getView').title,
125                        'days' : data
126                } ));
127        }
[7022]128        if($("#calendar").fullCalendar('getView').name == "agendaWeek" || $("#calendar").fullCalendar('getView').name == "basicWeek"){
[6996]129                window_print.document.write(DataLayer.render('templates/calendar_week_print.ejs', {
130                        'InfoPage' : $("#calendar").fullCalendar('getView').title,
131                        'days' : data
132                }));
133               
134                var aux = 0;
135                setTimeout(function(){$(window_print.document).find(".all-day").each(function(){
136                        if($(this).height() > aux)
137                                aux = $(this).height();
138                });
139                $(window_print.document).find(".all-day").each(function(){
140                        $(this).height(aux);
141                });
142                $(window_print.document).find(".all-day-line .write").height(aux);
143                aux = 0;
144                },20);
145        }
146        if($("#calendar").fullCalendar('getView').name == "year"){     
147                window_print.document.write(DataLayer.render('templates/calendar_year_print.ejs', {
148                        'html' : $('#calendar .fc-content').html(),
149                        'header': $('#calendar').find('.fc-header-center h2').text()
150                } ));
151        }               
152        window_print.document.close();
[7022]153        window_print.print();
[6996]154}
155
156function printEvents(){
157        //var html = DataLayer.render( path + 'templates/attendee_permissions.ejs', {} );
158        var print = $('.fc-header-right').find('.fc-button.fc-button-agendaDay').clone();
159
[5341]160        $('.fc-header-right').find('.fc-button-year').toggleClass('fc-corner-right');
[6996]161        print.addClass('fc-corner-right');
162        print.addClass('fc-button-print');
163        print.removeClass('fc-button-agendaDay');
164        print.removeClass('fc-corner-left');
165        print.find('.fc-button-content').html('Imprimir');
166        $('.fc-header-right').append(print);
167        $('.fc-button-print').click(function(){
168            printNow();
169        });
[5341]170}
[5514]171
[5746]172/*
173 * TODO - repeat foi adicionado pois melhorias devem ser feitas no rollback do
174 *DataLayer, repeat somente é usado quando se trata da criação de um evento
175 *pela edição de uma ocorrência.
176 */
177
178function eventDetails( objEvent, decoded, path, isMail, repeat)
[5341]179{
[6996]180
181    $('.qtip.qtip-blue').remove();
182
[6044]183    attendees = {};
[5937]184       
[6044]185    if(path == undefined)
186        path = "";
[5389]187               
[6044]188    if( !decoded )
189        objEvent = DataLayer.decode( "schedulable:calendar", objEvent );
[5341]190
[6044]191    if(!isMail)
192        objEvent = DataLayer.encode( "schedulable:preview", objEvent );
[5341]193       
[6044]194    if(typeof(objEvent.id) == 'undefined'){
195        objEvent.alarms = Calendar.signatureOf[User.preferences.defaultCalendar || Calendar.calendarIds[0]].defaultAlarms || false;
196        objEvent.useAlarmDefault = 1;
197    }
[5341]198       
[6044]199    /**
[5341]200         * canDiscardEventDialog deve ser true se não houver alterações no evento
201         */
[6044]202    canDiscardEventDialog = true;
203    /**
[5341]204         * zebraDiscardEventDialog é uma flag indicando que uma janela de confirmação (Zebra_Dialog)
205         * já está aberta na tela, uma vez que não é possivel acessar o evento ESC utilizado para fechá-la
206         */
[6044]207    zebraDiscardEventDialog = false;
[5341]208       
[6044]209    /**
[5514]210                ACLs do participant
211        */
[6044]212    acl_names = {
213        'w': 'acl-white',
214        'i': 'acl-invite-guests',
215        'p': 'acl-participation-required'
216    };
[6103]217
218    var dependsDelegate = function(reference, inverse){
219        if(inverse){
220            if(reference.find('input[name="attendee[]"]').val() == blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val())
221                blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val(blkAddAtendee.find('.me input[name="attendee[]"]').val());
222        }else{
223            if(blkAddAtendee.find('.me input[name="attendee[]"]').val() == blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val())
224                blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val(reference.find('input[name="attendee[]"]').val());
225        }
[5636]226       
[6103]227    };
228   
229    var removeOthers = function(){
230        var other = blkAddAtendee.find('.delegate.attendee-permissions-change-button');
231        if(other.lenght){
232            dependsDelegate(other.parents('li'), true);
233        }
234        blkAddAtendee.find('.delegate').removeClass('attendee-permissions-change-button');
235        blkAddAtendee.find('.ui-icon-transferthick-e-w').removeClass('attendee-permissions-change');
236       
237    };
238
[6044]239    var callbackAttendee = function(){
240        //Cria qtip de permissões pelo click do checkbox
241        var checked = false;
242        blkAddAtendee.find("li.not-attendee").addClass('hidden');
[5514]243       
[6044]244        blkAddAtendee.find("li .button").filter(".close.new").button({
245            icons: {
246                primary: "ui-icon-close"
247            },
248            text: false
249        }).click(function () {
250            DataLayer.remove('participant', $(this).parents('li').find('[type=checkbox]').val());
251            if($(this).parent().find('.button.delegate').hasClass('attendee-permissions-change-button')){
[6103]252                removeOthers();
[6044]253                blkAddAtendee.find('.request-update').addClass('hidden');
254                blkAddAtendee.find('.status option').toggleClass('hidden');
[5530]255                               
[6044]256                blkAddAtendee.find('option[value=1]').attr('selected','selected').trigger('change');
257            }
[5530]258                       
[6044]259            $(this).parents('li').remove();
[5530]260                       
[6044]261            if(blkAddAtendee.find(".attendee-list li").length == 1)
262                blkAddAtendee.find("li.not-attendee").removeClass('hidden');
263        })
264        .addClass('tiny disable ui-button-disabled ui-state-disabled')
265        .removeClass('new').end()
[5514]266       
[6044]267        .filter(".delegate.new").button({
268            icons: {
269                primary: "ui-icon-transferthick-e-w"
270            },
271            text: false
272        }).click(function () {
[6103]273            var me = $(this).parents('li');
[6044]274            if($(this).hasClass('attendee-permissions-change-button')){
275                $(this).removeClass('attendee-permissions-change-button')   
[6103]276                    .find('.ui-icon-transferthick-e-w').removeClass('attendee-permissions-change').end();               
277               
278                me.find('input[name="delegatedFrom[]"]').val('');
279                dependsDelegate(me, true);
[5514]280                               
[6044]281                blkAddAtendee.find('.request-update').addClass('hidden');
282                blkAddAtendee.find('.status option').toggleClass('hidden');
[6103]283
[6044]284                blkAddAtendee.find('option[value=1]').attr('selected','selected').trigger('change');
[5514]285                               
[6044]286            }else{
[6103]287                removeOthers();
[5514]288                       
[6044]289                $(this).addClass('attendee-permissions-change-button')   
290                .find('.ui-icon-transferthick-e-w').addClass('attendee-permissions-change').end();               
[6103]291               
292                me.find('input[name="delegatedFrom[]"]').val(blkAddAtendee.find('.me input[name="attendee[]"]').val());
293               
294                dependsDelegate(me, false);
[5514]295                       
[6044]296                blkAddAtendee.find('.request-update').removeClass('hidden');
297                if(blkAddAtendee.find('.status option.hidden').length == 1)
298                    blkAddAtendee.find('.status option').toggleClass('hidden');
[5514]299                       
[6044]300                blkAddAtendee.find('option[value=5]').attr('selected','selected').trigger('change');
301            }
302        })
303        .addClass('tiny disable ui-button-disabled ui-state-disabled')
304        .removeClass('new').end()
[5514]305               
[6044]306        .filter(".edit.new").button({
307            icons: {
308                primary: "ui-icon-key"
309            },
310            text: false
311        }).click(function() {
[5514]312                       
[6044]313            if(!!!checked)
314                $(this).parents('li').find('[type=checkbox]').attr('checked', (!$(this).parent().find('[type=checkbox]').is(':checked'))).end();
[5514]315                       
[6044]316            var aclsParticipant =  $(this).parents('li').find('input[name="attendeeAcl[]"]').val();
317            checked = false;
[5514]318                       
[6044]319            if( $('.qtip.qtip-blue.qtip-active').val() !== ''){
320                blkAddAtendee.find('dd.attendee-list').qtip({
321                    show: {
322                    ready: true,
323            solo: true,
324            when: {
325                    event: 'click'
326                    }
327                },
328                hide: false,
329                content: {
[6718]330                text: $('<div></div>').html( DataLayer.render( path + 'templates/attendee_permissions.ejs', {} ) ),
[6044]331                title: {
332                text:'Permissões',
333                button: '<a class="button close" href="#">close</a>'
334                }
335                },
336                style: {
337                name: 'blue',
338            tip: {
339                corner: 'leftMiddle'
340                },
341            border: {
342                width: 4,
343            radius: 8
344                },
345            width: {
346                min: 230,
347            max:230
348                }
349            },
350            position: {
351            corner: {
352            target: 'rightMiddle',
353            tooltip: 'leftMiddle'
354            },
355            adjust: {
356            x:0,
357            y:0
358            }
359            }
360            })
361        .qtip("api").onShow = function(arg0) {
362            $('.qtip-active .button.close').button({
363                icons: {
364                    primary: "ui-icon-close"
365                },
366                text: false
367            })
368            .click(function(){
369                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
370            });
[5514]371                                       
[6044]372            $('.qtip-active .button.save').button().click(function(){
[5514]373                                               
[6044]374                var acl = '';
375                $('.qtip-active').find('[type=checkbox]:checked').each(function(i, obj) {
376                    acl+= obj.value;
377                });
[5514]378
[6044]379                blkAddAtendee.find('dd.attendee-list [type=checkbox]:checked').siblings('input[name="attendeeAcl[]"]').each(function(i, obj) {
380                    obj.value = 'r'+acl;
381                }).parents('li').find('.button.edit').addClass('attendee-permissions-change-button')   
382                .find('.ui-icon-key').addClass('attendee-permissions-change');               
[5514]383                                               
[6044]384                blkAddAtendee.find('dd.attendee-list [type=checkbox]').attr('checked', false);
[5514]385                                               
[6044]386                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
[5514]387                                       
[6044]388            });
389            $('.qtip-active .button.cancel').button().click(function(){
390                blkAddAtendee.find('dd.attendee-list [type=checkbox]').attr('checked', false);
391                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
392            });
[5514]393                                       
[6044]394            if(aclsParticipant)
395                for(var i = 1; i < aclsParticipant.length; i++){
396                    $('.qtip-active').find('input[name="'+acl_names[aclsParticipant.charAt(i)]+'"]').attr('checked', true);
397                }
[6718]398                                                       
399            $('.qtip .button').button();
[5514]400                                       
[6044]401        };
402        }else{
403            if(!$('.new-event-win dd.attendee-list').find('[type=checkbox]:checked').length){
404                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
405            }else{
406                $('.qtip-active .button.save .ui-button-text').html('Aplicar a todos')
407            }
[5514]408                       
[6044]409        };                     
410    })
411.addClass('tiny disable ui-button-disabled ui-state-disabled')
412.removeClass('new').end()
[5514]413               
[6044]414.filter(".open-delegate.new").click(function(){
415    if($(this).hasClass('ui-icon-triangle-1-e')){
416        $(this).removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
417        $(this).parents('li').find('.list-delegates').removeClass('hidden');
418    }else{
419        $(this).removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
420        $(this).parents('li').find('.list-delegates').addClass('hidden');
421    }
[5514]422               
[6044]423}).removeClass('new');
[5514]424       
425       
[6044]426blkAddAtendee.find("li input[type=checkbox].new").click(function(){
427    if(!$('.new-event-win dd.attendee-list').find('[type=checkbox]:checked').length){
428        blkAddAtendee.find('dd.attendee-list').qtip('destroy');
429    }else{
430        checked = true;
431        $(this).parents('li').find('.button.edit').click();
432    }
433}).removeClass('new');
[5514]434       
[6044]435UI.dialogs.addEvent.find('.attendees-list li').hover(
436    function () {
437        $(this).addClass("hover-attendee");
438        $(this).find('.button').removeClass('disable ui-button-disabled ui-state-disabled').end()
439        .find('.attendee-options').addClass('hover-attendee');
440    },
441    function () {
442        $(this).removeClass("hover-attendee");
443        $(this).find('.button').addClass('disable ui-button-disabled ui-state-disabled').end()
444        .find('.attendee-options').removeClass('hover-attendee');;
445    }
446    );
[5514]447       
448               
[6044]449}
[5937]450
[6044]451var html = DataLayer.render( path+'templates/event_add.ejs', {
452    event:objEvent
453});     
[5341]454               
[6044]455if (!UI.dialogs.addEvent) {
456    UI.dialogs.addEvent = jQuery('#sandbox').append('<div title="Criar Evento" class="new-event-win active"> <div>').find('.new-event-win.active').html(html).dialog({
457        resizable: false,
458        modal:true,
459        autoOpen: false,
[7864]460        width:"auto",
[6044]461        position: 'center',
462        close: function(event, ui) {
[6683]463                /**
[6412]464                 * Remove tooltip possivelmente existente
465                 */
[6683]466                if ($('.qtip.qtip-blue.qtip-active').length)
467                        $('.qtip.qtip-blue.qtip-active').qtip('destroy');                                               
468                attendees  = {};
[6044]469        },
470        beforeClose: function(event, ui) {
[5341]471
[6044]472            if (!canDiscardEventDialog && !zebraDiscardEventDialog) {
473                zebraDiscardEventDialog = true;
474                window.setTimeout(function() {
475                    $.Zebra_Dialog('Suas alterações no evento não foram salvas. Deseja descartar as alterações?', {
476                        'type':     'question',
477                        'overlay_opacity': '0.5',
478                        'buttons':  ['Descartar alterações', 'Continuar editando'],
479                        'onClose':  function(clicked) {
480                            if(clicked == 'Descartar alterações') {
481                                canDiscardEventDialog = true;
482                                /**
[6412]483                                *Remoção dos anexos do eventos caso seja cancelado a edição
484                                */
485                                DataLayer.rollback();
486
487                                var ids = false;
[6044]488                                $.each($('.attachment-list input'), function (i, input) {
[6412]489                                    DataLayer.put('attachment', {id: ''+input.value});
490                                    DataLayer.remove('attachment', ''+input.value);
491                                        ids = true;
[6044]492                                });
[6412]493                                if(ids)
494                                        DataLayer.commit();
495                       
496                               
[5746]497                                                                               
[6044]498                                UI.dialogs.addEvent.dialog('close');
499                            }else{
500                                zebraDiscardEventDialog = false;
501                            }
[5341]502                                                                       
[6044]503                            /**
[6476]504                            * Uma vez aberta uma janela de confirmação (Zebra_Dialog), ao fechá-la
505                            * com ESC, para que o evento ESC não seja propagado para fechamento da
506                            * janela de edição de eventos, deve ser setada uma flag indicando que
507                            * já existe uma janela de confirmação aberta.
508                            */
[6044]509                            if (!clicked) {
510                                window.setTimeout(function() {
511                                    zebraDiscardEventDialog = false;
512                                }, 200);
513                            }
514                        }
515                    });
[5341]516                                                       
[6044]517                }, 300);
[5341]518
[6044]519            }
[6412]520            //DataLayer.rollback();
[6044]521            return canDiscardEventDialog;
[6683]522        },
523        dragStart: function(event, ui) {
524                if ($('.qtip.qtip-blue.qtip-active').length)
525                        $('.qtip.qtip-blue.qtip-active').qtip('destroy');
[6044]526        }
527    });
[5341]528                       
[6044]529} else {
530    UI.dialogs.addEvent.html(html);
531}
[5341]532               
[6683]533var tabs = UI.dialogs.addEvent.children('.content').tabs({
534        select: function(event, ui) {
535                if ($('.qtip.qtip-blue.qtip-active').length)
536                        $('.qtip.qtip-blue.qtip-active').qtip('destroy');
537        }       
538        });
[6044]539var calendar = DataLayer.get('calendar', objEvent.calendar);
[5381]540                               
[7597]541if ( (calendar.timezone != objEvent.timezone) && objEvent.id){
[6044]542    UI.dialogs.addEvent.find('.calendar-addevent-details-txt-timezone').find('option[value="'+objEvent.timezone+'"]').attr('selected','selected').trigger('change');
543    UI.dialogs.addEvent.find('.calendar_addevent_details_lnk_timezone').addClass('hidden');
544    $('.calendar-addevent-details-txt-timezone').removeClass('hidden');
[5341]545                       
[6044]546}
[5715]547
[6044]548DataLayer.render( path+'templates/event_repeat.ejs', {
549    event:objEvent
550}, function( repeatHtml ){
[5715]551
[6044]552    UI.dialogs.addEvent.find('#calendar_addevent_details3').html(repeatHtml);
[6444]553    $(".date").datepicker({
554                dateFormat: User.preferences.dateFormat.replace(/M/g, 'm').replace(/yyyy/g, 'yy')
555                });
[5715]556                 
[6044]557    if(objEvent.repeat)
558    {
559        if( objEvent.repeat['id'] )
560        {
561            $("[name='repeatId']:last").val( objEvent.repeat['id'] );
562        }
[5715]563
[6044]564        if( objEvent.repeat['frequency'] !== 'none' )
565        {
566            if( objEvent.repeat['startTime'] && objEvent.repeat['startTime'] !== "0" )
567            {
568                $("[name='startOptions'] [value='customDate']:last").attr( 'selected', 'selected' );
569                $("[name='start']:last").val(new Date( parseInt(objEvent.repeat['startTime']) ).toString( User.preferences.dateFormat ) );
570            }
571            else
572            {
573                $("[name='start']:last").val($("[name='startDate']:last").val());     
574                $("[name='start']:last").readOnly=true;
575                $("[name='start']:last").datepicker("disable");
576            }
[5715]577                             
[6044]578            $(".finish_event").removeClass("hidden");
[5715]579
[6044]580            if(objEvent.repeat['endTime'] && objEvent.repeat['endTime'] !== "0" )
581            {
582                //$("[name='occurrences']").addClass("hidden");
583                $(".customDateEnd").removeClass("hidden");
584                $(".endRepeat option[value='customDate']").attr('selected', 'selected')                                         
585                $(".customDateEnd").val( new Date( parseInt(objEvent.repeat['endTime']) )/*.setTimezoneOffset( Timezone.timezone( objEvent.timezone ) )*/.toString( User.preferences.dateFormat ) ); 
586            }
587            else if (objEvent.repeat['count'] && objEvent.repeat['count'] !== "0" ) {
588                $(".endRepeat option[value='occurrences']").attr('selected', 'selected');                                               
589                $(".occurrencesEnd").removeClass("hidden");
590                $(".occurrencesEnd").val(objEvent.repeat['count']);                                             
591            }
[5715]592                             
[6044]593            switch ( objEvent.repeat['frequency'] )
594            {
595                case "daily":
[6209]596                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Dia(s)")
[6346]597                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
[6044]598                    $(".frequency option[value='daily']").attr('selected', 'selected');
599                    break;
600                case "weekly":
[6209]601                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Semana(s)")
[6346]602                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
[7602]603                   
[6044]604                    $(".frequency option[value='weekly']").attr('selected', 'selected');
[5715]605                                           
[6044]606                    $(".event-repeat-weekly").removeClass("hidden");
[5715]607                                           
[6044]608                    var day = [];
[5715]609                                           
[6044]610                    if( objEvent.repeat.byday )
611                        day = objEvent.repeat.byday.split(',');
[5715]612                                           
[6044]613                    for(i=0; i<day.length; i++)
614                        $(".event-repeat-weekly [value='" + day[i] + "']").attr("checked","checked");
[5715]615                                           
[6044]616                    break;
617                case "monthly":
[6209]618                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Mes(s)")
[6346]619                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
[7602]620                   
[6044]621                    $(".frequency option[value='monthly']").attr('selected', 'selected')
[7602]622                   
[6044]623                    $(".event-repeat-monthly:last").removeClass("hidden").find("input[type=radio][name=repeatmonthyType]").click(function(){
[7602]624                                if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
625                                    $(".event-repeat-weekly:last").removeClass("hidden");
626                                else
627                                    $(".event-repeat-weekly:last").addClass("hidden");
[6044]628                    });
[7602]629                   
630                                           
631                        if( objEvent.repeat && objEvent.repeat.bymonthday != ''){
632
633                                $("input[type=radio][name=repeatmonthyType][value=0]").attr('checked', 'checked');
634
635                        }else if(objEvent.repeat){
636
637                                $("input[type=radio][name=repeatmonthyType][value=1]").attr('checked', 'checked');
638
639                                var days = objEvent.repeat.byday.split(',');
640
641                                $.each(days, function(i, e){
642                                        $(".event-repeat-weekly:last").find('input[name="repeatweekly[]"][value="'+e+'"]').attr('checked', 'checked');
643                                });
644
645                        }
646
647
[6044]648                    if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
[7602]649                                $(".event-repeat-weekly:last").removeClass("hidden");
[6044]650                    else
[7602]651                                $(".event-repeat-weekly:last").addClass("hidden");
[6044]652                    break;
653                case "yearly":
[6209]654                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Ano(s)")
[6346]655                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
[6044]656                    $(".frequency option[value='yearly']").attr('selected', 'selected')
657                    break;     
658            }
659        }
660    }
661    else {
662        $(".endRepeat option[value='never']").attr('selected', 'selected');
663    }
[5715]664
665
[6044]666    $(".event-repeat-container:last").find(".repeat-in").find("[name=startOptions]").change(function(){                                       
[5715]667
[6044]668        if($(this).find("option:selected").val() == "Today"){
669            $("[name='start']:last").val($("[name='startDate']:last").val());
670            $("[name='start']:last").readOnly=true;
671            $("[name='start']:last").datepicker("disable");
672        }
673        else{
674            $("[name='start']:last").readOnly=false;
675            $("[name='start']:last").datepicker("enable");
676        }
677    });
678    $(".event-repeat-container:last").find(".repeat-in").find("[name=endOptions]").change(function(){                                       
679        if($(this).find("option:selected").val() == "never"){
680            $("[name='occurrences']").addClass("hidden");
681            $("[name='end']:last").addClass("hidden");
682        }
683        else if($(this).find("option:selected").val() == "customDate"){
684            $("[name='occurrences']").addClass("hidden");
685            $("[name='end']:last").removeClass("hidden");   
686        }
687        else{
688            $("[name='end']:last").addClass("hidden");
689            $("[name='occurrences']").removeClass("hidden");                                       
690        }
691    });
[5715]692                       
[6044]693    $("[name='frequency']:last").change(function () {
694        $(".frequency-option").addClass("hidden");
695        if($(this).val() == "none"){
696            $(".repeat-in").addClass("hidden");
697            return;
698        }else{
699            $(".repeat-in").removeClass("hidden");
700            $("[name='start']:last").val($("[name='startDate']:last").val());
701        }
[5715]702                 
703                                 
[6044]704        switch($(this).val()){
705            case "daily":
706                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Dia(s)");
707                break;
708            case "weekly":
709                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Semana(s)");
710                $(".event-repeat-weekly:last").removeClass("hidden");
711                break;
712            case "monthly":
713                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Mes(s)");
714                $(".event-repeat-monthly:last").removeClass("hidden").find("input[type=radio][name=repeatmonthyType]").click(function(){
715                    if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
716                        $(".event-repeat-weekly:last").removeClass("hidden");
717                    else
718                        $(".event-repeat-weekly:last").addClass("hidden");
719                });
720                if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
721                    $(".event-repeat-weekly:last").removeClass("hidden");
722                else
723                    $(".event-repeat-weekly:last").addClass("hidden");
724                break;
725            default:
726                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Ano(s)");
727                break;
728        }
[5715]729                               
[6044]730    });
731});
[5715]732
[6044]733UI.dialogs.addEvent.find('.calendar_addevent_details_lnk_timezone').click(function(e){
734    $(this).addClass('hidden');
735    $('.calendar-addevent-details-txt-timezone').removeClass('hidden');
736    e.preventDefault();
737});
[5341]738               
[6044]739UI.dialogs.addEvent.find('.button.remove').button({
740    text:false,
741    icons:{
742        primary:'ui-icon-close'
743    }
744}).click(function(el){
745    var id;
746    if( id = $(this).parent().find('input[name="alarmId[]"]').val())
747        DataLayer.remove('alarm', id);
748    $(this).parent().remove().find('li').is(':empty');
749});
[5937]750
[6331]751var myCalendar = function(){
752        for(var i in Calendar.signatures)
753            if(Calendar.signatures[i].isOwner == "1")
754                return Calendar.signatures[i].calendar.id;
755}
[6476]756
757/*Seleciona a agenda padrão para visualização/edição de um evento*/
758if(objEvent.id)
759    UI.dialogs.addEvent.find('option[value="'+objEvent.calendar+'"]').attr('selected','selected').trigger('change');
760
[6044]761/*Adicionar alarms padrões, quando alterado a agenda do usuário*/               
762UI.dialogs.addEvent.find('select[name="calendar"]').change(function(){
763    if((typeof($('input[name = "idEvent"]').val()) == 'undefined') || (!!!$('input[name = "idEvent"]').val())) {
764        $('input[name = "isDefaultAlarm[]"]').parent().remove();
765        UI.dialogs.addEvent.find('input[name="defaultAlarm"]').parent().removeClass('hidden');
766        var calendarSelected = Calendar.signatureOf[$(this).val()];
767        calendarSelected.useAlarmDefault = 1;
768        if(calendarSelected.defaultAlarms != ""){
769            var li_attach = DataLayer.render(path+'templates/alarms_add_itemlist.ejs', {
770                alarm:calendarSelected
771            });
772            jQuery('.event-alarms-list').append(li_attach).find('.button.remove').button({
773                text:false,
774                icons:{
775                    primary:'ui-icon-close'
776                }
777            }).click(function(el) {
778            $(this).parent().remove().find('li').is(':empty');
779        });
[6476]780
[6044]781    }else{
782        UI.dialogs.addEvent.find('input[name="defaultAlarm"]').parent().addClass('hidden');
783    }
784}
[5947]785
[6476]786    var participant =  UI.dialogs.addEvent.find('dd.me input[name="attendee[]"]').val();
787    var calendar = $(this).val();
788   
789    if( !parseInt(Calendar.signatureOf[calendar].isOwner) ){
790        var signature = Calendar.signatureOf[calendar];
[6044]791        var organizer = DataLayer.get('calendarSignature', {
792            filter: ['AND', ['=','calendar',signature.calendar.id], ['=','isOwner','1']],
793            criteria: {
794                deepness: 2
795            }
796        });
[5947]797                           
[6044]798    if($.isArray(organizer))
799        organizer = organizer[0];
800    DataLayer.put('participant', {
801        id: participant,
802        user: organizer.user.id,
803        mail: organizer.user.mail
804        });
[5947]805                           
[6044]806    UI.dialogs.addEvent.find('dt.me').html(organizer.user.name);
807    UI.dialogs.addEvent.find('li.organizer input[name="attendee_organizer"]').val(participant);
808    UI.dialogs.addEvent.find('li.organizer label').filter('.name').html(organizer.user.name).end()
809    .filter('.mail').html(organizer.user.mail).attr('title',organizer.user.mail);
[5947]810
[6044]811}else{
812    UI.dialogs.addEvent.find('dt.me').html(User.me.name);
813    DataLayer.put('participant', {
814        id: participant,
815        user: User.me.id,
816        mail: User.me.mail
817        });
818    UI.dialogs.addEvent.find('li.organizer input[name="attendee_organizer"]').val(participant);
819    UI.dialogs.addEvent.find('li.organizer label').filter('.name').html(User.me.name).end()
820    .filter('.mail').html(User.me.mail).attr('title',User.me.mail);
821}
[6476]822
[6044]823});
[6331]824
[6044]825/*Checkbox adicionar alarms padrões*/
826UI.dialogs.addEvent.find('input[name="defaultAlarm"]').click(function(){
827    if($(this).attr("checked")){
828        $('input[name="isDefaultAlarm[]"]').parent().remove();
829        var calendarSelected = Calendar.signatureOf[$('select[name="calendar"]').val()];
830        calendarSelected.useAlarmDefault = 1;
831        if(calendarSelected.defaultAlarms != ""){
832            var li_attach = DataLayer.render(path+'templates/alarms_add_itemlist.ejs', {
833                alarm:calendarSelected
[5341]834            });
[6044]835            jQuery('.event-alarms-list').append(li_attach).find('.button.remove').button({
836                text:false,
837                icons:{
838                    primary:'ui-icon-close'
839                }
840            }).click(function(el) {
841            var id;
842            if( id = $(this).parent().find('input[name="alarmId[]"]').val())
843                DataLayer.remove('alarm', id);
844            $(this).parent().remove().find('li').is(':empty')
845        });
846    }
847} else {
848    $('input[name="isDefaultAlarm[]"]').parent().remove();
849}
850});
851/* Checkbox allday */
852UI.dialogs.addEvent.find('input[name="allDay"]').click(function(){
853    $(this).attr("checked") ?
854    UI.dialogs.addEvent.find('.start-time, .end-time').addClass('hidden') :
855    UI.dialogs.addEvent.find('.start-time, .end-time').removeClass('hidden');
856    updateMap(true);
857});
[5341]858
[6044]859UI.dialogs.addEvent.find('.button').button();
860UI.dialogs.addEvent.find('.button.add').button({
861    icons: {
862        secondary: "ui-icon-plus"
863    }
864});
[5341]865
[6044]866// ==== validation events ====
867UI.dialogs.addEvent.find(".input-group .h1").Watermark("Evento sem título");
868if(User.preferences.hourFormat.length == 5) {
869    UI.dialogs.addEvent.find(".end-time, .start-time").mask("99:99", {
870        completed: function(){
871            updateMap();
872        }
873    });
874} else {
875    $.mask.definitions['{']='[ap]';
876    $.mask.definitions['}']='[m]';
877    UI.dialogs.addEvent.find(".end-time, .start-time").mask("99:99 {}", {
878        completed:function(){
879            $(this).val(date.Calendar.defaultToAmPm($(this).val()));
880            $(this).timepicker("refresh");
881            $(this).val($(this).val().replace(/[\.]/gi, ""));
882            updateMap();
883        }
884    });
885}
886UI.dialogs.addEvent.find(".number").numeric();
887User.preferences.dateFormat.indexOf('-') > 0 ?
888UI.dialogs.addEvent.find(".date").mask("99-99-9999", {
889    completed:function(){
890        updateMap();
891    }
892}) :
893UI.dialogs.addEvent.find(".date").mask("99/99/9999", {
894    completed:function(){
895        updateMap();
896    }
897});
[5341]898
[6044]899UI.dialogs.addEvent.find(".menu-addevent")
900.children(".delete").click(function(){
901    $.Zebra_Dialog('Tem certeza que deseja excluir o evento?', {
902        'type':     'question',
903        'overlay_opacity': '0.5',
904        'buttons':  ['Sim', 'Não'],
905        'onClose':  function(clicked) {
906            if(clicked == 'Sim'){
907                canDiscardEventDialog = true;
[6286]908                /* Remove por filtro */
[6331]909                DataLayer.removeFilter('schedulable', {filter: ['AND', ['=', 'id', objEvent.id], ['=', 'calendar', objEvent.calendar], ['=','user',(objEvent.me.user ? objEvent.me.user.id : objEvent.me.id)]]});
[6286]910                Calendar.rerenderView(true);
911                /********************/
[6044]912                UI.dialogs.addEvent.dialog("close");
913            }
914        }
915    });
916}).end()
[5341]917           
[6044]918.children(".cancel").click(function(){
919    UI.dialogs.addEvent.dialog("close");
920}).end()
[5341]921           
[6044]922.children(".save").click(function(){
923    /* Validação */
924    var msg = false;                   
925    if(msg = validDateEvent()){
926        $(".new-event-win.active").find('.messages-validation').removeClass('hidden').find('.message label').html(msg);
927        return false;
928    }
[5341]929                       
[6044]930    canDiscardEventDialog = true;
[5341]931                       
[6044]932    var exit = function(event){
933        if(event)
934            DataLayer.remove('schedulable', event, false);
[5752]935
[6044]936        UI.dialogs.addEvent.children().find('form.form-addevent').submit();
937        UI.dialogs.addEvent.dialog("close");
938    }
[5746]939                       
[6044]940    if(repeat){
941        DataLayer.remove('repeat', false);
942        DataLayer.put('repeat', repeat);
943        DataLayer.commit('repeat', false, exit(repeat.schedulable));
944    }else
945        exit();
946}).end()
[5341]947               
[6044]948.children(".export").click(function(){
949    UI.dialogs.addEvent.children().find(".form-export").submit();
950});
[5341]951
[6044]952var dates = UI.dialogs.addEvent.find('input.date').datepicker({
[6444]953    dateFormat: User.preferences.dateFormat.replace(/M/g, 'm').replace(/yyyy/g, 'yy'),
[6044]954    onSelect : function( selectedDate ){
955        updateMap();
956    }
957});
958//if(path == ""){
959UI.dialogs.addEvent.find('input.time').timepicker({
960    closeText: 'Ok',
961    hourGrid: 4,
962    minuteGrid: 10,
963    ampm : ((User.preferences.hourFormat.length > 5) ? true: false),
964    timeFormat: "hh:mm tt",
965    onSelect: function (selectedDateTime){
[7102]966        if ((selectedDateTime.value == '__:__') || (selectedDateTime.value == '__:__ __'))
967                          selectedDateTime.value = "";
968                if(!(User.preferences.hourFormat.length == 5))
969                $(this).val(selectedDateTime.replace(/[\.]/gi, ""));                                                           
970                updateMap();
[6044]971    },
972    onClose : function (selectedDateTime){
973        if(!(User.preferences.hourFormat.length == 5))
974            $(this).val(selectedDateTime.replace(/[\.]/gi, ""));
[7102]975    },
976    beforeShow: function (selectedDateTime) {
977                if ((selectedDateTime.value == '__:__') || (selectedDateTime.value == '__:__ __'))
978                        selectedDateTime.value = "";
[6044]979    }
980});
981//}
[5341]982
[6044]983UI.dialogs.addEvent.find('.button-add-alarms').click(function(){
984    var li_attach = DataLayer.render(path+'templates/alarms_add_itemlist.ejs', {});
[5341]985
[6044]986    jQuery('.event-alarms-list').append(li_attach).find('.button.remove').button({
987        text:false,
988        icons:{
989            primary:'ui-icon-close'
990        }
991    }).click(function(el) {
992    $(this).parent().remove().find('li').is(':empty')
993});
994// valicacao de campos numericos
995$('.number').numeric();
996});
[5341]997           
[5514]998                 
[6044]999UI.dialogs.addEvent.find('.button.suggestion-hours').button({
1000    icons: {
1001        primary: "ui-icon-clock"
1002    },
1003    text: 'Sugerir horário'
1004}).click(function () {
1005    $(this).siblings('input').removeAttr('disabled')
1006    .end().parents().find('input[name="allDay"]').removeAttr('disabled');               
1007});
[5514]1008
1009
[6044]1010if(!repeat)
1011    if(objEvent.me.id == User.me.id){
1012        objEvent.me.id = DataLayer.put('participant', {
1013            user: objEvent.me.id,
1014            mail: objEvent.me.mail
1015            });
1016        objEvent.organizer.id = objEvent.me.id;
1017    }
[5746]1018
[6044]1019var attendeeHtml = DataLayer.render( path+'templates/attendee_add.ejs', {
1020    event:objEvent
1021});             
[5341]1022       
[6044]1023// load template of attendees
1024var blkAddAtendee = UI.dialogs.addEvent.find('#calendar_addevent_details6').append(attendeeHtml);
[6996]1025if(objEvent.attendee.length)
1026                callbackAttendee();
[6044]1027/**
[6996]1028Opções de delegação do participante/organizer
1029*/             
[6044]1030blkAddAtendee.find(".button.participant-delegate").button({
1031    icons: {
1032        primary: "ui-icon-transferthick-e-w"
1033    },
1034    text: false
1035}).click(function () {
1036    if($(this).hasClass('attendee-permissions-change-button')){
1037        if(!$(this).hasClass('disable')){
1038            $(this).removeClass('attendee-permissions-change-button')   
1039            .find('.ui-icon-transferthick-e-w').removeClass('attendee-permissions-change').end();               
1040            blkAddAtendee.find('.block-add-attendee.search').addClass('hidden');
1041            blkAddAtendee.find('.block-add-attendee.search dt').html('Adicionar outros contatos');
1042        }
1043    }else{                                                                     
1044        $(this).addClass('attendee-permissions-change-button')   
1045        .find('.ui-icon-transferthick-e-w').addClass('attendee-permissions-change').end();               
1046        blkAddAtendee.find('.block-add-attendee.search dt').html('Delegar participação para');
1047        blkAddAtendee.find('.block-add-attendee.search').removeClass('hidden');
1048        blkAddAtendee.find('.block-add-attendee.search input.search').focus();
1049    }
1050})
1051.addClass('tiny');             
[5341]1052                       
[6044]1053//show or hidden permissions attendees
1054//blkAddAtendee.find('.block-attendee-list #attendees-users li').click(show_permissions_attendees);
[5341]1055
[6044]1056UI.dialogs.addEvent.find(".attendee-list-add .add-attendee-input input").Watermark("digite um email para convidar");
[6996]1057/*
1058 * Trata a edição de um novo participante adicionado
1059 */
[6044]1060var hasNewAttendee = false;
[5641]1061                       
[6044]1062blkAddAtendee.find('.attendee-list-add .add-attendee-input span').click(function(data){
1063    blkAddAtendee.find('.attendee-list-add .add-attendee-input input').keydown();
1064});
[5641]1065                       
[6044]1066blkAddAtendee.find('.attendee-list-add .add-attendee-input input').keydown(function(event) {
1067    if (event.keyCode == '13' && $(this).val() != '' || (event.keyCode == undefined && $(this).val() != '')) {
1068        Encoder.EncodeType = "entity";
1069        $(this).val(Encoder.htmlEncode($(this).val()));
[5341]1070                                       
[6044]1071        newAttendeeEmail = false;
1072        newAttendeeName  = false;
1073        skipAddNewLine   = false;
[5341]1074
[6044]1075        var info = $(this).val();
[5341]1076
[6044]1077        /**
[6996]1078        * email válido?
1079        */
[6044]1080        info.match(/^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/) ?
1081        newAttendeeEmail = info : newAttendeeName = info;
[5341]1082
[6044]1083        /**
[6996]1084        * 1) busca no banco para saber se o usuário já existe
1085        *               1.1) se existe, atualiza as info na lista de participantes e nao abre o tooltip
1086        *               1.2) se não existe
1087        *                       a) salva como novo usuario externo no banco (apenas com email)
1088        *                       b) exibe tooltip pedindo o nome
1089        *                       c) se o usuário preenche tooltip e salva, atualiza com o nome o usuário recém criado
1090        *                       d) se o usuário cancela o tooltip, fica o usuário salvo apenas com email e sem nome
1091        */
[5341]1092
[6044]1093        var user = DataLayer.get('user', ["=", "mail", $(this).val()]);
1094        if(!!user && user[0].id)
1095            attendees[user[0].id] = {
1096                name: user[0].name
1097                };
[5353]1098                                       
[6044]1099        /**
[6996]1100        * guarda o último tooltip aberto referente à lista de participantes
1101        */
[6044]1102        lastEditAttendeeToolTip = [];
[5354]1103
[6044]1104        /**
[6996]1105        * Valida email e salva um participante externo
1106        */
[6044]1107        var saveContact = function() {
1108            Encoder.EncodeType = "entity";
[5354]1109
[6044]1110            var currentTip = $('.qtip-active');
1111            newAttendeeName  = currentTip.find('input[name="name"]').val();
1112            newAttendeeEmail = currentTip.find('input[name="mail"]').val();
[5354]1113
[6044]1114            if (!(!!newAttendeeEmail.match(/^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/))) {
1115                currentTip.find('.messages').removeClass('hidden').find('.message label').html('Email inválido.');
1116                return false;
1117            }
[5354]1118
[6044]1119            DataLayer.put('user', {
1120                id:userId,
1121                name:newAttendeeName,
1122                mail:newAttendeeEmail,
1123                isExternal:isExternal
1124            });
[5354]1125
[6044]1126            lastEditAttendeeToolTip.find('label')
1127            .filter('.name').html(Encoder.htmlEncode(newAttendeeName)).attr('title', Encoder.htmlEncode(newAttendeeName)).end()
1128            .filter('.mail').html(Encoder.htmlEncode(newAttendeeEmail)).attr('title', Encoder.htmlEncode(newAttendeeEmail));
[5354]1129
[6044]1130            blkAddAtendee.find('.attendee-list-add .add-attendee-input input').val('');
1131            return true;
1132        }
[5354]1133                                               
[6044]1134        /**
[5354]1135                                         * Formata e adequa um tootip abert para edição de um participante na lista
1136                                         */
[6044]1137        var onShowToolTip = function(arg0) {
1138            $('.qtip-active .button.close').button({
1139                icons: {
1140                    primary: "ui-icon-close"
1141                },
1142                text: false
1143            });
1144            $('.qtip-active .button').button()
1145            .filter('.save').click(function(event, ui) {
1146                if(saveContact())
1147                    lastEditAttendeeToolTip.qtip("destroy");
1148                else
1149                    return false;
1150            }).end()
1151            .filter('.cancel').click(function(event, ui) {
1152                lastEditAttendeeToolTip.qtip("destroy");
1153            })
[5353]1154
[6044]1155            /**
[5353]1156                                                 * Trata o ENTER no campo da tooltip, equivalente a salvar
1157                                                 * o novo convidado.
1158                                                 */
[6044]1159            $('.qtip-active input').keydown(function(event) {
1160                if (event.keyCode == '13') {                                           
1161                    if (saveContact())                                         
1162                        lastEditAttendeeToolTip.qtip("destroy");
[5409]1163                       
[6044]1164                    lastEditAttendeeToolTip.qtip("destroy");
1165                    event.preventDefault();
1166                }
1167            })
1168            .filter('[name="name"]').Watermark("informe o nome do contato").end()
1169            .filter('[name="mail"]').Watermark("informe o email do contato");
1170        }
[5353]1171                                       
[6044]1172        /**
[5354]1173                                         * Se o email digitado já foi adicionado na lista,
1174                                         * o usuário deve ser avisado e um botão de edição deve ser exibido
1175                                         */
[6044]1176        if(blkAddAtendee.find('label.mail[title="' + newAttendeeEmail + '"]').length) {
1177            hasNewAttendee  = false;
1178            newAttendeeName = blkAddAtendee.find('label.mail[title="' + newAttendeeEmail + '"]').parents('li').find('label.name').attr('title');
[5354]1179
[6044]1180            blkAddAtendee.find('.email-validation').removeClass('hidden')
1181            .find('.message label').html("O usuário acima já foi adicionado! <a class=\"small button\">Editar</a>")
1182            .find(".button").button().click(function () {
1183                /**
[5354]1184                                                         * Se o usuário optar por editar o participante anteriormente adicionado,
1185                                                         * uma tooltip deve ser aberta para este participante, viabilizando a edição
1186                                                         */
[6044]1187                blkAddAtendee.find("ul.attendee-list").scrollTo('label.mail[title="' + newAttendeeEmail + '"]');
1188                /**
[5354]1189                                                         * Remove tooltip possivelmente existente
1190                                                         */
[6044]1191                if (lastEditAttendeeToolTip.length && lastEditAttendeeToolTip.data('qtip'))
1192                    lastEditAttendeeToolTip.qtip('destroy');
[5354]1193                                       
[6044]1194                lastEditAttendeeToolTip = blkAddAtendee.find('label.mail[title="' + newAttendeeEmail + '"]').parents('li');
1195                lastEditAttendeeToolTip.qtip({
1196                    show: {
1197                        ready: true,
1198                        solo: true,
1199                        when: {
1200                            event: 'click'
1201                        }
1202                    },
1203                hide: false,
1204                content: {
1205                    text: $('<div></div>').html( DataLayer.render( path+'templates/attendee_quick_edit.ejs', {
1206                        attendee:{
1207                            name:newAttendeeName,
1208                            mail:newAttendeeEmail
1209                        }
1210                    } ) ),
1211                title: {
1212                    text:'Detalhes do participante',
1213                    button: '<a class="button close" href="#">close</a>'
1214                }
1215                },
1216                style: {
1217                    name: 'blue',
1218                    tip: {
1219                        corner: 'leftMiddle'
1220                    },
1221                    border: {
1222                        width: 4,
1223                        radius: 8
1224                    },
1225                    width: {
1226                        min: 230,
1227                        max:230
1228                    }
1229                },
1230            position: {
1231                corner: {
1232                    target: 'rightMiddle',
1233                    tooltip: 'leftMiddle'
1234                },
1235                adjust: {
1236                    x:0,
1237                    y:0
1238                }
1239            }
1240            });
1241        lastEditAttendeeToolTip.qtip("api").onShow = onShowToolTip;
1242    });
1243skipAddNewLine = true;
1244} else {
1245    hasNewAttendee  = true;
1246    blkAddAtendee.find('.email-validation').addClass('hidden');
1247}
[5353]1248                                       
1249                                       
[6044]1250var isExternal = (!!user && !(!!user.isExternal)) ? 0 : 1;
[5341]1251
[6044]1252/**
[5341]1253                                         * Remove tooltip possivelmente existente
1254                                         */
[6044]1255if (lastEditAttendeeToolTip.length && lastEditAttendeeToolTip.data('qtip'))
1256    lastEditAttendeeToolTip.qtip('destroy');
[5341]1257
[6044]1258userId = '';
1259var newAttendeeId = '';
[5341]1260
[6044]1261if (user){
1262    if (!skipAddNewLine) {
1263        user[0].id =  DataLayer.put('participant', {
1264            user: user[0].id,
1265            isExternal: isExternal,
1266            acl: 'r'
1267        });
[6203]1268        user[0].acl = objEvent.acl;
1269        user[0].isDirty = !!!objEvent.id;
[7377]1270        user[0].isDelegate = (objEvent.id && (objEvent.me.status == '5'));
[5592]1271
[6044]1272        blkAddAtendee.find('dd.attendee-list ul.attendee-list').append(
1273            DataLayer.render(path+'templates/participants_add_itemlist.ejs', user)
1274            )
1275        .scrollTo('max');
1276        callbackAttendee();
1277    }
[5349]1278                                               
[6044]1279    $(this).val('');
[5341]1280
[6996]1281} else if (!skipAddNewLine) {
[6044]1282    /**
[6996]1283     * a) salva como novo usuario externo no banco (apenas com email) e...
1284     * adiciona novo contato externo à lista de convidados
1285     */
[5341]1286
[6044]1287    userId = DataLayer.put('user', {
1288        name: newAttendeeName,
1289        mail: newAttendeeEmail,
1290        isExternal: isExternal
1291    });
1292    newAttendeeId = DataLayer.put('participant', {
1293        user: userId,
1294        isExternal: isExternal
1295    });
[5341]1296
[5354]1297                                                 
[6044]1298    blkAddAtendee.find('dd.attendee-list ul.attendee-list').append(
1299        DataLayer.render(path+'templates/participants_add_itemlist.ejs', [{
1300            id:newAttendeeId,
1301            name: newAttendeeName,
1302            mail: newAttendeeEmail,
1303            isExternal: 1,
[6203]1304            acl: objEvent.acl,
[7377]1305            isDirty: !!!objEvent.id,
1306        isDelegate: (objEvent.id && (objEvent.me.status == '5'))
[6044]1307            }])
1308        ).scrollTo('max');
1309    callbackAttendee();
[5341]1310
[6044]1311    /**
[5341]1312                                                 * Adiciona tootip para atualização dos dados do contato externo
1313                                                 * recém adicionado.
1314                                                 */
[6044]1315    lastEditAttendeeToolTip = blkAddAtendee.find('dd.attendee-list li:last');
1316    lastEditAttendeeToolTip.qtip({
1317        show: {
1318            ready: true,
1319            solo: true,
1320            when: {
1321                event: 'click'
1322            }
1323        },
1324    hide: false,
1325    content: {
1326        text: $('<div></div>').html( DataLayer.render( path+'templates/attendee_quick_edit.ejs', {
1327            attendee:{
1328                name:newAttendeeName,
1329                mail:newAttendeeEmail
1330            }
1331        } ) ),
1332    title: {
1333        text:'Detalhes do participante',
1334        button: '<a class="button close" href="#">close</a>'
1335    }
1336    },
1337    style: {
1338        name: 'blue',
1339        tip: {
1340            corner: 'leftMiddle'
1341        },
1342        border: {
1343            width: 4,
1344            radius: 8
1345        },
1346        width: {
1347            min: 230,
1348            max:230
1349        }
1350    },
1351position: {
1352    corner: {
1353        target: 'rightMiddle',
1354        tooltip: 'leftMiddle'
1355    },
1356    adjust: {
1357        x:0,
1358        y:0
1359    }
1360}
1361});
[5341]1362                       
[6044]1363lastEditAttendeeToolTip.qtip("api").onShow = onShowToolTip;
[5341]1364
[6044]1365$(this).val('');
[5341]1366
[5353]1367                                               
[6044]1368}
1369event.preventDefault();
1370}
[5354]1371                               
[6044]1372});
[5341]1373
[6044]1374/**
[6996]1375* Trata a busca de usuários para adição de participantes
1376*/
[6044]1377blkAddAtendee.find('.add-attendee-search .ui-icon-search').click(function(event) {
1378    blkAddAtendee.find('.add-attendee-search input').keydown();
1379});
[5592]1380                       
1381                       
[6044]1382blkAddAtendee.find('.add-attendee-search input').keydown(function(event) {
[5341]1383
[6044]1384    if(event.keyCode == '13' || typeof(event.keyCode) == 'undefined') {                 
1385        var result = DataLayer.get('user', ["*", "name", $(this).val()], true);
[5341]1386
[6044]1387        /**
[6371]1388        * TODO: trocar por template
1389        */
[6044]1390        blkAddAtendee.find('ul.search-result-list').empty().css('overflow', 'hidden');
1391        if (!result) {
1392            blkAddAtendee.find('ul.search-result-list').append('<li><label class="empty">Nenhum resultado encontrado.</label></li>');
1393        }
[5341]1394
[6044]1395        for(i=0; i<result.length; i++)
1396            result[i].enabled = (blkAddAtendee.find('dd.attendee-list ul.attendee-list label.mail[title="' +  result[i].mail + '"]').length) ? false : true;
[5363]1397                                                                                       
[6044]1398        blkAddAtendee.find('ul.search-result-list').append(DataLayer.render( path+'templates/participants_search_itemlist.ejs', result));
[5341]1399
[6044]1400        blkAddAtendee.find('ul.search-result-list li').click(function(event, ui){
1401            if ($(event.target).is('input')) {
1402                old_item = $(event.target).parents('li');
1403                newAttendeeId = DataLayer.put('participant', {
1404                    user: old_item.find('.id').html(),
[6371]1405                    isExternal: old_item.find('.isExternal').html()
[6044]1406                });
[5636]1407                                                       
[6044]1408                attendees[old_item.find('.id').html()] = old_item.find('.name').html();
[5636]1409                                                       
[6044]1410                blkAddAtendee.find('dd.attendee-list ul.attendee-list')
1411                .append(DataLayer.render(path+'templates/participants_add_itemlist.ejs', [{
1412                    id: newAttendeeId,
1413                    name: old_item.find('.name').html(),
1414                    mail: old_item.find('.mail').html(),
[6371]1415                    isExternal: old_item.find('.isExternal').html(),
[6203]1416                    acl: objEvent.acl,
[7377]1417                    isDirty: !!!objEvent.id,
1418            isDelegate: (objEvent.id && (objEvent.me.status == '5'))
[6044]1419                    }]))
1420                .scrollTo('max');
1421                /**
[5514]1422                                                        * Delegação de participação de um participante com permissão apenas de leitura
1423                                                        *
1424                                                        */
[6044]1425                if(!objEvent.acl.organization && !objEvent.acl.write && !objEvent.acl.inviteGuests && objEvent.acl.read ){
[5514]1426                                                               
[6044]1427                    blkAddAtendee.find('.block-add-attendee.search').addClass('hidden');
1428                    blkAddAtendee.find('.block-add-attendee.search dt').html('Adicionar outros contatos');
[5514]1429                                                               
[6044]1430                    blkAddAtendee.find('.status option').toggleClass('hidden');
1431                    blkAddAtendee.find('option[value=5]').attr('selected','selected').trigger('change');
1432                    blkAddAtendee.find('.request-update').removeClass('hidden');
[5341]1433
[6044]1434                    blkAddAtendee.find('dd.attendee-list ul.attendee-list li .button.close').parents('li').find('input[name="delegatedFrom[]"]').val(blkAddAtendee.find('.me input[name="attendee[]"]').val());
[5514]1435                                                               
[6044]1436                    blkAddAtendee.find('.me .participant-delegate').addClass('disable ui-button-disabled ui-state-disabled');
1437                    blkAddAtendee.find(".button.close").button({
1438                        icons: {
1439                            primary: "ui-icon-close"
1440                        },
1441                        text: false
1442                    }).click(function () {
[5514]1443                                                                       
[6044]1444                        $(this).parents('li').find('input[name="delegatedFrom[]"]').val('');
1445                        blkAddAtendee.find('.request-update').addClass('hidden');
1446                        blkAddAtendee.find('.status option').toggleClass('hidden');
1447                        blkAddAtendee.find('option[value=1]').attr('selected','selected').trigger('change');                   
1448                        blkAddAtendee.find('.me .participant-delegate').removeClass('disable ui-button-disabled ui-state-disabled attendee-permissions-change-button')
1449                        .find('.ui-icon-person').removeClass('attendee-permissions-change').end();                     
[5514]1450                                                                       
[6044]1451                        DataLayer.remove('participant', $(this).parents('li').find('[type=checkbox]').val());
1452                        $(this).parents('li').remove();
1453                    })
1454                    .addClass('tiny');
1455                }else{
1456                    callbackAttendee();
1457                    old_item.remove();
1458                }
1459            }
1460        });
[5341]1461
[6044]1462        event.preventDefault();
1463    }
1464});
[6996]1465
[6044]1466//$('.block-add-attendee .search-result-list').selectable();
[5341]1467
[6044]1468UI.dialogs.addEvent.find('.row.fileupload-buttonbar .button').filter('.delete').button({
1469    icons: {
1470        primary: "ui-icon-close"
1471    },
1472    text: 'Excluir'
1473}).click(function () {
[6369]1474    $.Zebra_Dialog('Tem certeza que deseja excluir todos anexos?', {
1475        'type':     'question',
1476        'overlay_opacity': '0.5',
1477        'buttons':  ['Sim', 'Não'],
1478        'onClose':  function(clicked) {
1479            if(clicked == 'Sim'){
1480               
1481                var ids = [];
1482                $.each($('.attachment-list input'), function (i, input) {
1483                     DataLayer.remove('schedulableToAttachment', {
1484                        filter: ['=', 'id', ''+input.value]
1485                        });
1486                });
[6996]1487                $('div.new-event-win .attachment-list input').remove();
1488                $('div.new-event-win .row.fileupload-buttonbar .attachments-list p').remove();
1489                $('div.new-event-win .btn-danger.delete').addClass('hidden');
[6369]1490            }
1491        }});
[6044]1492}).end()
1493.filter('.close').button({
1494    icons: {
1495        primary: "ui-icon-close"
1496    },
1497    text: false
1498}).click(function () {
[6369]1499    DataLayer.remove('schedulableToAttachment', $(this).parents('p').find('input[name="fileId[]"]').val());
[6044]1500    $(this).parents('p').remove();
1501}).end()
1502.filter('.downlaod-archive').button({
1503    icons: {
1504        primary: "ui-icon-arrowthickstop-1-s"
1505    },
1506    text: false
1507});
1508
[6996]1509extendsFileupload('event', path);
[5592]1510       
[6044]1511if(objEvent.isShared){
[5514]1512               
[6044]1513    var acls = Calendar.signatureOf[objEvent.calendar].permission.acl;
[5514]1514               
[6044]1515    if(!acls.write){
1516        UI.dialogs.addEvent.find(':input').attr('disabled', 'disabled');
1517        UI.dialogs.addEvent.find('.button').hide();
1518    }
[5592]1519               
[6044]1520    if(acls.remove)
1521        UI.dialogs.addEvent.find('.button.remove').show();
[6476]1522   
1523    UI.dialogs.addEvent.find('.button.cancel').show(); 
[6044]1524}
[5636]1525
[6996]1526disponibily(objEvent, path, attendees, 'event');
[6331]1527
1528/*Seleciona a agenda padrão para criação de um evento*/
[6476]1529if(!objEvent.id){
1530    var selectedCalendar = (objEvent.calendar != undefined) ? objEvent.calendar : (User.preferences.defaultCalendar ? User.preferences.defaultCalendar : myCalendar());
1531    UI.dialogs.addEvent.find('option[value="'+selectedCalendar+'"]').attr('selected','selected').trigger('change');
1532}
[6044]1533UI.dialogs.addEvent.find(':input').change(function(event){
1534    if (event.keyCode != '27' && event.keyCode != '13')
1535        canDiscardEventDialog = false;
1536}).keydown(function(event){
1537    if (event.keyCode != '27' && event.keyCode != '13')
1538        canDiscardEventDialog = false;
1539});     
[5636]1540
[6044]1541UI.dialogs.addEvent.dialog('open');
[6996]1542
[5341]1543}
1544
[5353]1545
1546
[5341]1547function add_tab_preferences()
1548{
[6044]1549    if(!(document.getElementById('preference_tab')))
1550    {
1551        var tab_title = "Preferencias";
1552        $tabs.tabs( "add", "#preference_tab", tab_title );
[5341]1553               
[6044]1554        /*
[5341]1555                DataLayer.render( 'templates/timezone_list.ejs', {}, function( timezones_options ){
1556                        tabPrefCalendar.find('select[name="timezone"]').html(timezones_options).find('option[value="'+User.preferences.timezone+'"]').attr('selected','selected').trigger('change');
1557                });
1558                */
[6044]1559        DataLayer.render( 'templates/preferences_calendar.ejs', {
1560            preferences:User.preferences,
[7982]1561            calendars: Calendar.calendars,
1562        signatureOf : Calendar.signatureOf
[6044]1563            }, function( template ){
1564            var tabPrefCalendar = jQuery('#preference_tab').html( template ).find('.preferences-win');
[5341]1565               
[7982]1566            tabPrefCalendar.find('select[name="defaultCalendar"] option[value="'+User.preferences.defaultCalendar+'"]').attr('selected','selected').trigger('change');
1567        tabPrefCalendar.find('select[name="dafaultImportCalendar"] option[value="'+User.preferences.dafaultImportCalendar+'"]').attr('selected','selected').trigger('change');
1568 
1569        DataLayer.render( 'templates/timezone_list.ejs', {}, function( timezones_options ){
1570
[6044]1571                tabPrefCalendar.find('select[name="timezone"]').html(timezones_options).find('option[value="'+User.preferences.timezone+'"]').attr('selected','selected').trigger('change');
1572            });
[5341]1573               
[6044]1574            tabPrefCalendar.find('.button').button()
1575            .filter('.save').click(function(evt){
1576                tabPrefCalendar.find('form').submit();
1577                $('#calendar').fullCalendar('render');
1578                $('.block-vertical-toolbox .mini-calendar').datepicker( "refresh" );
1579                $tabs.tabs( "remove", "#preference_tab");
1580            }).end().filter('.cancel').click(function(evt){
1581                $tabs.tabs( "remove", "#preference_tab");
1582            });
[5341]1583                       
[6044]1584            tabPrefCalendar.find('.number').numeric();
[5510]1585                       
[6044]1586            tabPrefCalendar.find('input.time').timepicker({
1587                closeText: 'Ok',
1588                hourGrid: 4,
1589                minuteGrid: 10,
1590                ampm : (parseInt($("select[name=hourFormat] option:selected").val().length) > 5 ? true : false), //((User.preferences.hourFormat.length > 5) ? true: false),
1591                timeFormat: "hh:mm tt",
1592                onSelect: function (selectedDateTime){
1593                    if(!(User.preferences.hourFormat.length == 5)) {
1594                        $(this).val(selectedDateTime.replace(/[\.]/gi, ""));
1595                    }
1596                },
1597                onClose : function (selectedDateTime){
1598                    if(!(User.preferences.hourFormat.length == 5)) {
1599                        $(this).val(selectedDateTime.replace(/[\.]/gi, ""));
1600                    }
1601                }
1602            });
[5510]1603                       
[6044]1604            $.mask.definitions['{']='[ap]';
1605            $.mask.definitions['}']='[m]';
1606            tabPrefCalendar.find("input.time").mask( ((User.preferences.hourFormat.length > 5) ? "99:99 {}" : "99:99"), {
1607                completed:function(){
1608                    $(this).val(dateCalendar.defaultToAmPm($(this).val()));
1609                    $(this).timepicker("refresh");
1610                    $(this).val($(this).val().replace(/[\.]/gi, ""));                                   
1611                }
1612            });
[5510]1613                                                           
[6044]1614            tabPrefCalendar.find("select[name=hourFormat]").change( function() { // evento ao selecionar formato de hora
[5510]1615               
[6044]1616                tabPrefCalendar.find("input.time").timepicker("destroy");
[5510]1617
[6044]1618                tabPrefCalendar.find('input.time').timepicker({
1619                    closeText: 'Ok',
1620                    hourGrid: 4,
1621                    minuteGrid: 10,
1622                    ampm : (parseInt($("select[name=hourFormat] option:selected").val().length) > 5 ? true : false),
1623                    timeFormat: "hh:mm tt",
1624                    onSelect: function (selectedDateTime){
1625                        if(!(User.preferences.hourFormat.length == 5)) {
1626                            $(this).val(selectedDateTime.replace(/[\.]/gi, ""));
1627                        }                                                       
1628                    },
1629                    onClose : function (selectedDateTime){
1630                        if(!(User.preferences.hourFormat.length == 5)) {
1631                            $(this).val(selectedDateTime.replace(/[\.]/gi, ""));
1632                        }
1633                    }
1634                });
[5510]1635                               
[6044]1636                var defaultStartHour = tabPrefCalendar.find("input[name=defaultStartHour]").val().trim();
1637                var defaultEndHour = tabPrefCalendar.find("input[name=defaultEndHour]").val().trim();
[5510]1638               
[6044]1639                tabPrefCalendar.find("input.time").mask( (($("select[name=hourFormat] option:selected").val().trim().length > 5) ? "99:99 {}" : "99:99") );
[5510]1640               
[6044]1641                if (parseInt($("select[name=hourFormat] option:selected").val().length) > 5) { // am/pm
1642                    tabPrefCalendar.find("input[name=defaultStartHour]").val(dateCalendar.defaultToAmPm(defaultStartHour));
1643                    tabPrefCalendar.find("input[name=defaultEndHour]").val(dateCalendar.defaultToAmPm(defaultEndHour))
[5510]1644                                       
[6044]1645                } else { //24h
1646                    tabPrefCalendar.find("input[name=defaultStartHour]").val(dateCalendar.AmPmTo24(defaultStartHour));
1647                    tabPrefCalendar.find("input[name=defaultEndHour]").val(dateCalendar.AmPmTo24(defaultEndHour));
1648                }
1649            });                 
[5510]1650                       
1651                       
1652                       
[6044]1653        });             
1654    } else {
1655        $tabs.tabs("select", "#preference_tab");
[5341]1656               
[6044]1657        return true;
1658    }
[5341]1659}
1660
1661
[6996]1662function add_tab_configure_calendar(calendar, type)
[5341]1663{
[6996]1664    $('.qtip.qtip-blue').remove();
1665
[6044]1666    var calendars = [];
1667    var signatures = [];
1668    var previewActiveCalendarConf = 0;
[6498]1669        var calendarAlarms = [];
1670       
[6996]1671        for (var i=0; i<Calendar.signatures.length; i++) {
1672                if(parseInt(Calendar.signatures[i].calendar.type) == type){
1673                   calendars.push(Calendar.signatures[i].calendar);
1674                   signatures.push(Calendar.signatures[i]);
1675                   length = signatures.length - 1;
1676                   signatures[length].numberDefaultAlarm = signatures[length].defaultAlarms != '' ?  signatures[length].defaultAlarms.length: 0;
1677                   if (calendar && calendars[length].id == calendar)
1678                           previewActiveCalendarConf = length;
1679                }
1680   }
1681        var tab_selector = ['configure_tab', 'configure_tab_group'];   
1682    if(!(document.getElementById(tab_selector[type])))
[6044]1683    {
1684        $('.positionHelper').css('display', 'none');
[6696]1685        $('.cal-list-options-btn').removeClass('fg-menu-open ui-state-active');
[6996]1686        if(type == 0){
1687                var tab_title = "Configurações de agendas";
1688        }else{
1689                var tab_title = "Configurações de Grupos";
1690        }
1691        $tabs.tabs( "add", "#"+tab_selector[type], tab_title );
[5341]1692               
[6044]1693        var dataColorPicker = {
1694            colorsSuggestions: colors_suggestions()
1695        };
[5341]1696               
1697               
1698               
[6044]1699        var populateAccordionOnActive = function(event, ui) {
1700            var nowActive = (typeof(event) == 'number') ? event : $(event.target).accordion( "option", "active" );
[6696]1701            if (nowActive === false)
1702                        return;
[6044]1703            dataColorPicker.colorsDefined = {
1704                border: '#'+signatures[nowActive].borderColor,
1705                font:'#'+signatures[nowActive].fontColor,
1706                background:'#'+signatures[nowActive].backgroundColor
1707            };
1708            if (!jQuery('.accordion-user-calendars .ui-accordion-content').eq(nowActive).has('form')) {
1709                return true;
1710            }
[5341]1711
[6044]1712            DataLayer.render( 'templates/configure_calendars_itemlist.ejs', {
1713                user:User,
[6996]1714                type:0,
[6044]1715                calendar:calendars[nowActive],
1716                signature:signatures[nowActive]
1717                }, function( form_template ){
[6996]1718                var form_content = jQuery('#'+tab_selector[type]+' .accordion-user-calendars .ui-accordion-content').eq(nowActive).html( form_template ).find('form');
[6044]1719                form_content.find('.preferences-alarms-list .button').button({
1720                    text:false,
1721                    icons:{
1722                        primary:'ui-icon-close'
1723                    }
1724                });
1725            form_content.find('.button').button();
[6498]1726            jQuery('.preferences-alarms-list').find('.button.remove').click(function(el){
1727                        calendarAlarms[calendarAlarms.length] = $(this).parent('li').find('input[name="alarmId[]"]').val();
1728                        $(this).parent().remove();
1729                });
1730       
[6044]1731                DataLayer.render( 'templates/timezone_list.ejs', {}, function( timezones_options ){
1732                    var valueTimeZone = calendars[nowActive].timezone;
1733                    form_content.find('select[name="timezone"]').html(timezones_options).find('option[value="'+valueTimeZone+'"]').attr('selected','selected').trigger('change');
1734                });
[5341]1735
[6044]1736                form_content.find('.button-add-alarms').click(function(){
[7405]1737                    DataLayer.render( 'templates/alarms_add_itemlist.ejs', {type: (parseInt(type) == 1 ? '4' : type) }, function( template ){
[6044]1738                        jQuery('.preferences-alarms-list').append(template)
1739                        .find('li:last label:eq(0)').remove().end()
1740                        .find('.number').numeric().end()
1741                        .find('.button.remove').button({
1742                            text:false,
1743                            icons:{
1744                                primary:'ui-icon-close'
1745                            }
1746                        }).click(function(el) {
1747                        $(this).parent().remove();
1748                    });   
1749                    });
1750                });
[5341]1751
1752
[6044]1753            /**
[5341]1754                                 * Set color picker
1755                                 */
[6044]1756            DataLayer.render( 'templates/calendar_colorpicker.ejs', dataColorPicker, function( template ){
1757                form_content.find('.calendar-colorpicker').html( template );
[5341]1758
[6044]1759                var f = $.farbtastic(form_content.find('.colorpicker'), colorpickerPreviewChange);
1760                var selected;
1761                var colorpicker = form_content.find('.calendar-colorpicker');
[5341]1762                                       
[6044]1763                var colorpickerPreviewChange = function(color) {
1764                    var pickedup = form_content.find('.colorwell-selected').val(color).css('background-color', color);
[5341]1765
[6044]1766                    var colorpicker = form_content.find('.calendar-colorpicker');
[5341]1767
[6044]1768                    if (pickedup.is('input[name="backgroundColor"]')) {
1769                        colorpicker.find('.fc-event-skin').css('background-color',color);
1770                    } else if (pickedup.is('input[name="fontColor"]')) {
1771                        colorpicker.find('.fc-event-skin').css('color',color);
1772                    } else if (pickedup.is('input[name="borderColor"]')) {
1773                        colorpicker.find('.fc-event-skin').css('border-color',color);
1774                    }
1775                }
[5341]1776                                       
[6044]1777                form_content.find('.colorwell').each(function () {
1778                    f.linkTo(this);
[5341]1779
[6044]1780                    if ($(this).is('input[name="backgroundColor"]')) {
1781                        colorpicker.find('.fc-event-skin').css('background-color', $(this).val());
1782                    } else if ($(this).is('input[name="fontColor"]')) {
1783                        colorpicker.find('.fc-event-skin').css('color', $(this).val());
1784                    } else if ($(this).is('input[name="borderColor"]')) {
1785                        colorpicker.find('.fc-event-skin').css('border-color', $(this).val());
1786                    }
1787                })
1788                .focus(function() {
1789                    if (selected) {
1790                        $(selected).removeClass('colorwell-selected');
1791                    }
[5341]1792
[6044]1793                    $(selected = this).addClass('colorwell-selected');
1794                    f.linkTo(this, colorpickerPreviewChange);
1795                    f.linkTo(colorpickerPreviewChange);
[5341]1796
[6044]1797                });
[5341]1798
[6044]1799                form_content.find('select.color-suggestions').change(function() {
1800                    var colors;
[5341]1801
[6044]1802                    if(colors = dataColorPicker.colorsSuggestions[$(this).val()]) {     
1803                        colorpicker
1804                        .find('input[name="fontColor"]').val(colors.font).focus().end()
1805                        .find('input[name="backgroundColor"]').val(colors.background).focus().end()
1806                        .find('input[name="borderColor"]').val(colors.border).focus().end()
[5341]1807
[6044]1808                        .find('.fc-event-skin').css({
1809                            'background-color':dataColorPicker.colorsSuggestions[$(this).val()].background,
1810                            'border-color':dataColorPicker.colorsSuggestions[$(this).val()].border,
1811                            'color':dataColorPicker.colorsSuggestions[$(this).val()].font
1812                        });
1813                    }
1814                });
[5341]1815
[6044]1816                /**
[5341]1817                                         * Trata a mudança dos valores dos campos de cores.
1818                                         * Se mudar um conjunto de cores sugerido,
1819                                         * este vira um conjunto de cores personalizado.
1820                                         */
[6044]1821                form_content.find('.colorwell').change(function (element, ui) {
1822                    if (true) {
1823                        form_content.find('select.color-suggestions')
1824                        .find('option:selected').removeAttr('selected').end()
1825                        .find('option[value="custom"]').attr('selected', 'selected').trigger('change');
1826                    }
1827                });
1828            }); //END set colorpicker
[5341]1829
[6044]1830            form_content.find('.phone').mask("+99 (99) 9999-9999");
1831            form_content.find('.number').numeric();
[5341]1832
[6044]1833        }); //END DataLayer.render( 'templates/configure_calendars_itemlist.ejs' ...
[5341]1834
[6044]1835// === validations preferences ====
[5341]1836
1837                       
[6044]1838} //END populateAccordionOnActive(event, ui)
[5341]1839               
1840
[6044]1841DataLayer.render( 'templates/configure_calendars.ejs', {
1842    user:User,
[7259]1843        type: type,
[6044]1844    calendars:calendars,
1845    signatures:signatures
1846}, function( template ){
[6996]1847    var template_content = jQuery('#'+tab_selector[type]).html( template ).find('.configure-calendars-win');
[6044]1848    template_content.find('.button').button().filter('.save').click(function(evt){
[6498]1849        if(calendarAlarms.length)
1850                DataLayer.removeFilter('calendarSignatureAlarm', {filter: ['IN','id', calendarAlarms]});       
[6044]1851        template_content.find('form').submit();
[6996]1852        $tabs.tabs( "remove", "#"+tab_selector[type]);
[6044]1853        DataLayer.commit( false, false, function( received ){
1854            delete Calendar.currentViewKey;
1855            Calendar.load();
1856            refresh_calendars();
1857        });
[6498]1858        if(calendarAlarms.length)
1859                Calendar.load();
[6044]1860    }).end().filter('.cancel').click(function(evt){
[6996]1861        $tabs.tabs( "remove", "#"+tab_selector[type]);
[6044]1862    });
[5341]1863
[6044]1864    /**
[5341]1865                         * Muda a estrutura do template para a aplicação do plugin accordion
1866                         */
[6044]1867    template_content.find('.header-menu-container').after('<div class="accordion-user-calendars"></div>').end().find('.accordion-user-calendars')
1868    .append(template_content.children('fieldset'));
[5341]1869                       
[6044]1870    template_content.find('.accordion-user-calendars').children('fieldset').each(function(index) {
1871        $(this).before($('<h3></h3>').html($(this).children('legend')));
1872    });
[5341]1873                       
[6044]1874    template_content.find('.accordion-user-calendars').accordion({
1875        autoHeight: false,
1876        collapsible: true,
1877        clearStyle: true,
1878        active: previewActiveCalendarConf,
1879        changestart: populateAccordionOnActive
1880    });
1881    populateAccordionOnActive(previewActiveCalendarConf);
1882});
[5341]1883
[6044]1884} else {
[6696]1885        $('.positionHelper').css('display','none');
1886    $('.cal-list-options-btn').removeClass('fg-menu-open ui-state-active');
[6996]1887    $tabs.tabs("select", "#"+tab_selector[type]);
[6044]1888    $('.accordion-user-calendars').accordion( "activate" , previewActiveCalendarConf );
[5341]1889               
[6044]1890    return true;
1891}
[5341]1892
1893}
1894
[6996]1895function getSelectedCalendars( reverse, type ){
[7970]1896    var selector = !!type ? "div.my-groups-task .calendar-view" : "div.my-calendars .calendar-view, div.signed-calendars .calendar-view";
1897    var returns = [];
1898 
1899    $.each( $(selector), function(i , c){
1900 
1901        if( reverse ? !c.checked : c.checked )
1902            returns.push( c.value );
1903 
[6044]1904    });
[7970]1905 
1906    if (!returns.length)
1907            return false;
1908 
1909    return returns;
[5341]1910}
1911
1912/**
1913 * TODO - transformar em preferência do módulo e criar telas de adição e exclusão de conjunto de cores
1914 */
1915function colors_suggestions(){
[6044]1916    return [
1917    {
1918        name:'Padrão',
1919        border:'#3366cc',
1920        font:'#ffffff',
1921        background:'#3366cc'
1922    },
1923
1924    {
1925        name:'Coala',
1926        border:'#123456',
1927        font:'#ffffff',
1928        background:'#385c80'
1929    },
1930
1931    {
1932        name:'Tomate',
1933        border:'#d5130b',
1934        font:'#111111',
1935        background:'#e36d76'
1936    },
1937
1938    {
1939        name:'Limão',
1940        border:'#32ed21',
1941        font:'#1f3f1c',
1942        background:'#b2f1ac'
1943    },
1944
1945    {
1946        name:'Alto contraste',
1947        border:'#000000',
1948        font:'#ffffff',
1949        background:'#222222'
1950    }
1951    ]           
[5341]1952}
1953
[7017]1954function remove_event(eventId, idCalendar, type){
[6996]1955    $.Zebra_Dialog('Tem certeza que deseja excluir?', {
[6044]1956        'type':     'question',
1957        'overlay_opacity': '0.5',
1958        'buttons':  ['Sim', 'Não'],
1959        'onClose':  function(clicked) {
1960            if(clicked == 'Sim'){
[6331]1961
[7702]1962                var schedulable = getSchedulable( eventId, '');
[6359]1963                schedulable.calendar = ''+idCalendar;
[6331]1964                var schudableDecode = DataLayer.encode( "schedulable:preview", schedulable);
1965                var me = schudableDecode.me.user ? schudableDecode.me.user.id : schudableDecode.me.id;
1966
[7017]1967        var filter = {filter: ['AND', ['=','id',eventId], ['=','calendar',idCalendar], ['=','user', me]]};
1968
1969        if(type)
1970            filter.filter.push(['=','type',type]);
1971
1972                DataLayer.removeFilter('schedulable', filter);
[6286]1973                Calendar.rerenderView(true);
[6044]1974            }
1975        }
1976    });
[5592]1977}
1978
[7965]1979function mount_exception(eventID, exception){
[5592]1980
[7702]1981    getSchedulable( eventID.toString() , '');
1982    var schedulable = DataLayer.get('schedulable', eventID.toString() )
1983    var edit = { repeat: (DataLayer.get('repeat', schedulable.repeat)) };
1984
[5746]1985    edit.repeat.startTime = new Date(parseInt(edit.repeat.startTime)).toString('yyyy-MM-dd HH:mm:00');
[5752]1986    edit.repeat.endTime = parseInt(edit.repeat.count) > 0 ? '0' : new Date(parseInt(edit.repeat.endTime)).toString('yyyy-MM-dd HH:mm:00');
[5746]1987   
[7965]1988    edit.repeat.exceptions = ( exception );
[5746]1989   
1990    return edit.repeat;
1991}
1992
1993function remove_ocurrence(eventId, idRecurrence){
[6044]1994    $.Zebra_Dialog('Tem certeza que deseja excluir esta ocorrência?', {
1995        'type':     'question',
1996        'overlay_opacity': '0.5',
1997        'buttons':  ['Sim', 'Não'],
1998        'onClose':  function(clicked) {
1999            if(clicked == 'Sim'){
2000                var repeat = mount_exception(eventId, idRecurrence);
2001                DataLayer.remove('repeat', false);
2002                DataLayer.put('repeat', repeat);
2003                DataLayer.commit(false, false, function(data){
2004                    Calendar.rerenderView(true);
2005                });
2006            }
2007        }
2008    });
[5746]2009}
2010
2011
[6996]2012function remove_calendar(type){
[6044]2013    /* Pode ser assim $('.cal-list-options-btn.ui-state-active').attr('class').replace(/[a-zA-Z-]+/g, ''); */
[6996]2014        if(!!parseInt(type))
2015                var title = 'Todas as tarefas deste grupo serão removidas. Deseja prosseguir com a operação?';
2016        else
2017                var title = 'Todos os eventos desta agenda serão removidos. Deseja prosseguir com a operação?';
2018    $.Zebra_Dialog(title, {
[6044]2019        'type':     'question',
2020        'overlay_opacity': '0.5',
2021        'buttons':  ['Sim', 'Não'],
2022        'onClose':  function(clicked) {
2023            if(clicked == 'Sim'){
2024                var idCalendar =  $('.cal-list-options-btn.ui-state-active').attr('class').match(/[0-9]+/g);
[5592]2025                               
[6044]2026                DataLayer.remove('calendarSignature', Calendar.signatureOf[idCalendar[0]].id );
[5592]2027                               
[6044]2028                if(idCalendar == User.preferences.defaultCalendar)
2029                    DataLayer.remove( 'modulePreference', User.preferenceIds['defaultCalendar']);
[5636]2030                       
[6044]2031                DataLayer.commit( false, false, function( received ){
2032                    delete Calendar.currentViewKey;
2033                    Calendar.load();
[6996]2034                    refresh_calendars(type);
[6044]2035                });
2036            }
2037            $('.positionHelper').css('display', 'none');
[5409]2038       
[6044]2039        }
2040    });
[5341]2041}
2042
[6996]2043function refresh_calendars(type){
[5341]2044
[6044]2045    var colorsSuggestions = colors_suggestions();
2046    var buttons_colors = "";
2047    for(var i = 0; i < colorsSuggestions.length; i++){
2048        buttons_colors += "<a class=\"cal-colors-options-btn ui-icon ui-button-icon-primary signed-cal-colors-options-btn-"+i+"\"  style=\"background-color:"+colorsSuggestions[i]['background']+"; border-color:"+colorsSuggestions[i]['border']+"; color:"+colorsSuggestions[i]['font']+"\">&bull;</a>";
2049    }
[5341]2050
[6044]2051    //DataLayer.render( 'templates/calendar_list.ejs', 'calendar:list', ["IN", "id", Calendar.calendarIds], function( html ){
2052    DataLayer.render( 'templates/calendar_list.ejs', Calendar, function( html ){
[5341]2053       
[6044]2054        var meu_container = $(".calendars-list").html( html );
[5341]2055       
[6674]2056        var doMenu = function(){
2057                $('ul.list-calendars .cal-list-options-btn').each(function(){
2058                        $(this).menu({   
2059                        content: $(this).next().html(),
2060                        width: '120',
2061                        positionOpts: {
2062                                posX: 'left', 
2063                                posY: 'bottom',
2064                                offsetX: 0,
2065                                offsetY: 0,
2066                                directionH: 'right',
2067                                directionV: 'down', 
2068                                detectH: true, // do horizontal collision detection   
2069                                detectV: true, // do vertical collision detection
2070                                linkToFront: false
2071                        },
2072                        flyOut: true,
2073                        showSpeed: 100,
2074                        crumbDefaultText: '>'
2075                        });
2076                });
2077        }
[6996]2078       
[6674]2079        doMenu();
[6996]2080        var currentToolTip = null;
[6674]2081        $('#divAppbox').on('scroll',function(){
2082                if ($('.cal-list-options-btn.fg-menu-open.ui-state-active')){                   
2083                        var offset = $('.cal-list-options-btn.fg-menu-open.ui-state-active').offset();
2084                        if (offset)
[6996]2085                            $('.positionHelper').css('top',offset.top);
[6674]2086                }
[6996]2087
[6956]2088                if ($('.button.config-menu.fg-menu-open')){
2089                        var offset = $('.button.config-menu.fg-menu-open').offset();
2090                        if (offset)
[6996]2091                            $('.positionHelper').css('top',offset.top);
[6956]2092                }               
[6996]2093
2094               
2095                if ($(".new-group.qtip-active").length || $(".new-calendar.qtip-active").length)                       
2096                    $('.qtip-active').css('top',currentToolTip.offset().top - 50);
2097               
[6674]2098        });
[7938]2099 
2100     $('ul.list-calendars .cal-list-options-btn').on('click',function(){doMenu();});         
[6996]2101       
2102
2103    /***************************************New Calendar***************************************/
[5592]2104        meu_container.find(".button.new-calendar").button({
[6044]2105            icons: {
2106                primary: "ui-icon-plus"
2107            },
2108            text: false
2109        }).click(function () {
[6996]2110                currentToolTip = $(this);
2111        var typeCalendar = !!parseInt($(this).attr('class').match(/[0-9]+/g)) ?
2112            {type: 'new-group', title: 'Novo Grupo', typeValue: 1, prompt: 'Nome do grupo'} :
2113            {type: 'new-calendar', title: 'Nova Agenda', typeValue: 0, prompt: 'Nome da agenda'}
[5341]2114               
[6996]2115            if(!$('.qtip.qtip-blue.qtip-active.'+typeCalendar.type).length){
2116
2117            $('.qtip.qtip-blue').remove();
2118
2119                $(this).qtip({
2120                                show: {
2121                       ready: true,
2122                   solo: true,
2123                   when: {
2124                          event: 'click'
2125                       }
2126                    },
2127                  hide: false,
2128                  content: {
2129                          text: $('<div></div>').html( DataLayer.render( 'templates/calendar_quick_add.ejs', {} ) ),
2130                          title: {
2131                              text: typeCalendar.title,
2132                              button: '<a class="button close" href="#">close</a>'
2133                          }
2134                        },
2135                  style: {
2136                          name: 'blue',
2137                      tip: {
2138                              corner: 'leftMiddle'
2139                          },
2140                   border: {
2141                           width: 4,
2142                           radius: 8
2143                          },
2144                      width: {
2145                              min: 230,
2146                          max:230
2147                          }
2148                    },
2149               position: {
2150                       corner: {
2151                           target: 'rightMiddle',
2152                           tooltip: 'leftMiddle'
2153                       },
2154                       adjust: {
2155                            x:0,
2156                            y: -12
2157                                               
2158                       }
2159                    }
2160            })
2161                .qtip("api").onShow = function(arg0) {
[5341]2162                               
[6996]2163                    $('.qtip-active .button.close').button({
[7457]2164                          icons: { primary: "ui-icon-close" },
[6996]2165                          text: false
2166                    })
2167                    .click(function(){
[7457]2168                                $('.qtip.qtip-blue').remove();
[6996]2169                    });
2170                   
[7457]2171                $('.qtip-active').addClass(typeCalendar.type);
[6996]2172
[7457]2173                    $('.qtip-active .button.cancel').button().click(function(){
2174                                $('.qtip.qtip-blue').remove();
2175                    });
2176                               
2177
[6996]2178                    $('.qtip-active .button.save').button().click(function(){
2179                    if(!typeCalendar.typeValue)
2180                                for(var i = 0; i < Calendar.calendars.length; i++){
2181                                    if(Calendar.calendars[i].location == ( User.me.uid + '/' + $('.qtip-active input').val())){
2182                                        $.Zebra_Dialog('O nome desta agenda já está sendo utilizada em uma Url de outra agenda. Por favor, informe outro nome para agenda.',{
2183                                            'overlay_opacity': '0.5',
2184                                            'type': 'warning'
2185                                        });
2186                                        $('.qtip.qtip-blue').remove();
2187                                        return;
2188                                    }
2189                                }
2190                                       
2191                        var selected;
2192                        var color = $('.cal-colors-options-btn').each(function(index){
2193                            if ($(this).is('.color-selected'))
2194                                 selected = index;
2195                        });
2196                        DataLayer.put( "calendarSignature", {
2197                            user: User.me.id,
2198                            calendar: {
2199                                name: Encoder.htmlEncode($('.qtip-active input').val()),
2200                                timezone: User.preferences.timezone,
2201                        type: typeCalendar.typeValue                   
2202                            },
2203                            isOwner: 1,
2204                            fontColor: colorsSuggestions[selected]['font'].substring(1) ,
2205                            backgroundColor: colorsSuggestions[selected]['background'].substring(1) ,
2206                            borderColor: colorsSuggestions[selected]['border'].substring(1)
2207                        });
2208                        DataLayer.commit( false, false, function( received ){
2209                            delete Calendar.currentViewKey;
2210                            Calendar.load();
2211                            refresh_calendars();
2212                        });
2213                        $('.qtip.qtip-blue').remove();
2214                    });
[7457]2215       
[6996]2216                    $(".qtip-active input").Watermark(typeCalendar.prompt);
2217                               
2218                    $('.qtip-active').keydown(function(event) {
2219                            if (event.keyCode == '27')
2220                              meu_container.find(".button.new").qtip('destroy');
2221                    });
2222                               
2223                    $('.colors-options').prepend(buttons_colors);
2224                    $('.colors-options .signed-cal-colors-options-btn-0').addClass('color-selected');
2225                                               
2226                    var buttons = $('.cal-colors-options-btn').button();
2227                               
2228                    buttons.click(function(){
2229                        buttons.removeClass('color-selected');
2230                        $(this).addClass('color-selected');
2231                    });
2232                }                               
2233           }
[6044]2234    });
[6996]2235
[6044]2236    $("img.cal-list-img").click(function(evt) {
[6996]2237           $(".cal-list-options_1").toggleClass( "hidden" );
[6044]2238    });
[5341]2239
[6996]2240    $(".my-groups-task a.title-my-calendars").click(function() {
2241        $(".my-groups-task ul.my-list-calendars").toggleClass("hidden")
2242        $('.my-groups-task .status-list').toggleClass("ui-icon-triangle-1-s");
2243        $('.my-groups-task .status-list').toggleClass("ui-icon-triangle-1-e");
2244    });
2245
[6044]2246    $(".my-calendars a.title-my-calendars").click(function() {
[6996]2247        $(".my-calendars ul.my-list-calendars").toggleClass("hidden")
2248        $('.my-calendars .status-list').toggleClass("ui-icon-triangle-1-s");
2249        $('.my-calendars .status-list').toggleClass("ui-icon-triangle-1-e");
[6044]2250    });
[5381]2251               
[6044]2252    $(".signed-calendars a.title-signed-calendars").click(function() {
[6996]2253           $(".signed-calendars ul.signed-list-calendars").toggleClass( "hidden");
[6044]2254    });
[5341]2255
[6044]2256    $("ul li.list-calendars-item").click(function(evt) {
[5341]2257       
[6044]2258        });   
[5341]2259
[6044]2260    $("ul li.list-calendars-item .ui-corner-all").click(function(evt) {
2261        //alert('teste');
2262        });   
[5341]2263       
[6044]2264    meu_container.find(".button.new-calendar-shared").button({
2265        icons: {
2266            primary: "ui-icon-plus"
2267        },
2268        text: false
2269    }).click(function (event) {
2270        show_modal_search_shared();
2271    });
[7938]2272       
2273       
[6044]2274    meu_container.find('.title-signed-calendars').click(function(evt){
2275        var status = $(this).parent().find('.status-list-shared');
[5592]2276                       
[6044]2277        if(status.hasClass('ui-icon-triangle-1-s'))
2278            status.removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
2279        else
2280            status.removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
2281    });
[5592]2282               
[6044]2283    $('.calendar-view').click(function(evt){
[7938]2284 
[7970]2285        var checkBox = $(this);
2286        var calendarId = $(this).val();
[7938]2287 
[7970]2288        Calendar.signatureOf[ calendarId ].hidden =  (checkBox.is(':checked') ? 0 : 1 );
[7938]2289 
[7970]2290        DataLayer.put('calendarSignature', {id: Calendar.signatureOf[ calendarId ].id , hidden: Calendar.signatureOf[ calendarId ].hidden }  );
2291        DataLayer.commit();
[7938]2292 
2293 
[7970]2294         if($tabs.tabs('option' ,'selected') == 0){
2295 
2296             if(Calendar.currentView && !!Calendar.currentView[ calendarId ]){
2297 
2298                 Calendar.currentView[ calendarId ].hidden = !checkBox.is(':checked');
2299                 $('#calendar').fullCalendar( 'refetchEvents' );
2300             }
2301 
2302         }else{
2303             type = $tabs.tabs('option' ,'selected');
2304             type = type > 2 ? 2 : (type - 1)
2305 
2306             pageselectCallback('', 0, false, type);
2307         }
[6044]2308    });
2309});
[5341]2310}
2311
[6996]2312function add_events_list(keyword, type)
[5341]2313{
[7423]2314    if ($.trim(keyword) == "") return;
[6044]2315    var tab_title = "";
2316    if (keyword){
[6996]2317                type = 2;
2318                if(keyword.length < 10)
2319                        tab_title = keyword;
2320                else
2321                        tab_title = keyword.substr(0,10) + '..."';
[6044]2322    }else{
[6996]2323                if(type){
2324                        if(!!parseInt(type))
2325                                tab_title = "Lista de tarefas";
2326                        else
2327                                tab_title = "Lista de eventos";
2328                }
[6044]2329    }
[6996]2330        var tab_selector = ['tab_events_list_', 'tab_tasks_list_', 'tab_all_list_'];
[6044]2331    keyword = ( keyword || '' ).replace( /\s+/g, "_" );
[5341]2332       
[6996]2333    if(!(document.getElementById(tab_selector[type] + (Base64.encode(keyword)).replace(/[^\w\s]/gi, "") )))     
[6044]2334    {
2335        Encoder.EncodeType = "entity";
[6996]2336        $tabs.tabs( "add", "#"+tab_selector[type] + (Base64.encode(keyword)).replace(/[^\w\s]/gi, ""), Encoder.htmlEncode(tab_title) );
[6044]2337    }
2338    else /* Tab already opened */
2339    {
[6996]2340                //$tabs.tabs("option", "selected", 2);
2341        }
[5341]2342       
[6996]2343    pageselectCallback(keyword, 0, false, type); // load page 1 and insert data on event_list.ejs
[5341]2344       
[6044]2345    $('.preferences-win.active .button.save, .preferences-win.active .button.cancel, .preferences-win.active .button.import, .preferences-win.active .button.export').button();
[5341]2346}
2347
2348function paginatorSearch(currentView){
[6044]2349    $(currentView+' .header-paginator .fc-header-left .fc-button').hover(
2350        function(){
2351            $(this).addClass('fc-state-hover');
2352        },
2353        function(){
2354            $(this).removeClass('fc-state-hover');
2355        }).mousedown(function(){
2356        $(this).addClass('fc-state-down');
2357    }).mouseup(function(){
2358        $(this).removeClass('fc-state-down');
2359        $('.events-list.events-list-win.active').removeClass('active');
2360        var paginator = $(this).attr('class');
2361        if(paginator.indexOf('next') > 0){
2362            if(parseInt($(currentView+' [name = results]').val()) > 25)
[6996]2363                pageselectCallback($(currentView+' [name = keyword]').val(), ((parseInt($(currentView+' [name = page_index]').val())) +1), false,  2);
[6044]2364        }else{
2365            if(parseInt($(currentView+' [name = page_index]').val()) > 0)
[6996]2366                pageselectCallback($(currentView+' [name = keyword]').val(), ((parseInt($(currentView+' [name = page_index]').val())) -1), false, 2);
[6044]2367        }
2368    });
[5341]2369}
2370
2371function mountTitleList(page_index ,view){
[6044]2372    switch (view){
2373        case 'agendaDay':
2374        case 'basicDay':
2375            var date = new Date().add({
2376                days: page_index
2377            });
2378            return (dateCalendar.dayNames[date.getDay()])+", "+(date.toString('dd MMM yyyy'));
2379        case 'agendaWeek':
2380            var dateStart = new Date().moveToDayOfWeek(dateCalendar.dayOfWeek[User.preferences.weekStart]);
2381            dateStart.add({
2382                days: (7 * page_index)
2383                });
2384            var dateEnd = new Date().moveToDayOfWeek(dateCalendar.dayOfWeek[User.preferences.weekStart]);
2385            dateEnd.add({
2386                days: (page_index * 7)+7
2387                });
2388            if(dateStart.toString('MM') != dateEnd.toString('MM'))
2389                return dateStart.toString('dd')+' de '+dateCalendar.monthNamesShort[dateStart.getMonth()]+' a '+dateEnd.toString('dd')+' de '+dateCalendar.monthNames[dateEnd.getMonth()]+' - '+dateEnd.toString('yyyy');
2390            return +dateStart.toString("dd")+" a "+dateEnd.toString("dd")+" de "+dateCalendar.monthNames[dateEnd.getMonth()]+" - "+dateEnd.toString('yyyy');
2391        case 'month':
2392            var date = new Date().add({
2393                months: page_index
2394            })
2395            return dateCalendar.monthNames[date.getMonth()]+" "+date.toString("yyyy");
2396        case 'year':
2397            var date = new Date().add({
2398                years: page_index
2399            });
2400            return date.toString("yyyy");
2401    }
[5341]2402}
2403
[6996]2404function paginatorList(currentView, view, type){
2405    $(currentView+' .events-list.events-list-win.active .list-events-paginator .fc-header-title').html('<h2>'+mountTitleList( parseInt($(currentView+' [name = page_index]').val()),view)+'</h2>');
[6044]2406    $(currentView+' .events-list.events-list-win.active .header-paginator .fc-header-right .fc-button').removeClass('fc-state-active')
2407    if(view == 'basicDay')
2408        $(currentView+' .events-list.events-list-win.active .header-paginator .fc-header-right .fc-button-agendaDay').addClass('fc-state-active');
2409    else
2410        $(currentView+' .events-list.events-list-win.active .header-paginator .fc-header-right .fc-button-'+view).addClass('fc-state-active');
2411    $(currentView+' .events-list.events-list-win.active .header-paginator .fc-header-right').addClass('list-right');
[5381]2412               
[6044]2413    $(currentView+' .header-paginator .fc-header-right .fc-button').hover(
2414        function(){
2415            $(this).addClass('fc-state-hover');
2416        },
2417        function(){
2418            $(this).removeClass('fc-state-hover');
2419        }).mousedown(function(){
2420        $(currentView+' .events-list.events-list-win.active .header-paginator .fc-header-right .fc-button').removeClass('fc-state-active')
2421        $(this).addClass('fc-state-active');
2422    }).mouseup(function(){
2423        var goView = $(this).attr('class');
2424        if(goView.indexOf('agendaDay') > 0)
[6996]2425            pageselectCallback($(currentView+' [name = keyword]').val(), 0, 'agendaDay', type);
[6044]2426        else if(goView.indexOf('month') > 0)
[6996]2427            pageselectCallback($(currentView+' [name = keyword]').val(), 0, 'month', type);
[6044]2428        else if(goView.indexOf('year') > 0)
[6996]2429            pageselectCallback($(currentView+' [name = keyword]').val(), 0, 'year', type);
[6044]2430        else if(goView.indexOf('agendaWeek') > 0)
[6996]2431            pageselectCallback($(currentView+' [name = keyword]').val(), 0, 'agendaWeek', type);
[5381]2432
[6044]2433    });
[5381]2434
[6044]2435    $(currentView+' .header-paginator .fc-header-left .fc-button').hover(
2436        function(){
2437            $(this).addClass('fc-state-hover');
2438        },
2439        function(){
2440            $(this).removeClass('fc-state-hover');
2441        }).mousedown(function(){
2442        $(this).addClass('fc-state-down');
2443    }).mouseup(function(){
2444        $(this).removeClass('fc-state-down');
2445        var paginator = $(this).attr('class');
2446        if(paginator.indexOf('next') > 0)
[6996]2447            pageselectCallback($(currentView+' [name = keyword]').val(), ((parseInt($(currentView+' [name = page_index]').val())) +1), view, type);
[6044]2448        else
[6996]2449            pageselectCallback($(currentView+' [name = keyword]').val(), ((parseInt($(currentView+' [name = page_index]').val())) -1), view, type);
[6044]2450    });
[5341]2451}
2452
[6996]2453function printEventList(view){
2454        $('.fc-button-print.print-list-events').click(function(){
2455                var window_print = window.open('','ExpressoCalendar','width=800,height=600,scrollbars=yes');
2456                var listEvents = $(view).clone();
2457                listEvents.find('.fc-button').remove();
2458                listEvents.find('.details-event-list').remove();
[7022]2459                listEvents.find('.list-events-paginator').remove();
[6996]2460                listEvents = listEvents.html();
2461                type = $(this).parents('.ui-tabs-panel').attr("id").split("_")[1];
[7022]2462
[6996]2463                var data = {
2464                        type : type == "tasks" ? "task-list" : ( type == "events" ? "event-list" : "search"),
[7022]2465                        html : listEvents,
2466                        InfoPage : $(this).parents('table.header-paginator').find( '.fc-header-title' ).text()
[6996]2467                }
2468                window_print.document.open();           
2469                window_print.document.write(DataLayer.render('templates/calendar_list_print.ejs', data));
2470                window_print.document.close();
2471                window_print.print();
2472        });
2473}
2474
2475function paginatorListEvent(currentView, typeView, view, type){
[6044]2476    if(!!$(currentView).find('.fc-calendar').length)
2477        return;
[6190]2478    $(currentView+' .events-list.events-list-win.active').prepend($('.fc-header:first').clone());
[6044]2479    //Remove contudo nao utilizado
2480    $(currentView+' .events-list.events-list-win.active .fc-header .fc-button-today').remove();
2481    $(currentView+' .events-list.events-list-win.active .fc-header .fc-button-basicWeek').remove();
2482    $(currentView+' .events-list.events-list-win.active .fc-header .fc-button-basicDay').remove();                     
[5341]2483               
[6044]2484    //Adiciona e remove as classes para esta visualizacao
2485    $(currentView+' .events-list.events-list-win.active .fc-header .fc-header-center').addClass('list-events-paginator');
2486    $(currentView+' .events-list.events-list-win.active .fc-header .list-events-paginator').removeClass('fc-header-center');           
[6996]2487               
[6044]2488    //Adicionar class no header padronizar com a tela principal
[6996]2489        $(currentView+' .events-list.events-list-win.active .fc-header .fc-button-print').addClass('print-list-events');               
2490        $(currentView+' .events-list.events-list-win.active .fc-header').addClass('header-paginator');
2491    $(currentView+' .events-list.events-list-win.active .header-paginator').removeClass('fc-header');   
2492       
2493        printEventList(currentView);
2494       
[6044]2495    if(typeView == 'search'){
[6996]2496        $(currentView+' .events-list.events-list-win.active .header-paginator .fc-header-right span.fc-button:not(.fc-button-print)').remove();
[6044]2497        $(currentView+' .events-list.events-list-win.active .list-events-paginator .fc-header-title').html('<h2>Resultados para: '+$(currentView+' [name = keyword]').val()+'</h2>');
2498        if((parseInt($(currentView+' [name = page_index]').val()) == 0) && (parseInt($(currentView+' [name = results]').val()) <= 25))
2499            return;
2500        paginatorSearch(currentView);
2501    }else
[6996]2502        paginatorList(currentView, view, type);
[5341]2503}
2504
2505function mountCriteriaList(view, page_index, calerdars_selecteds){
[6044]2506    var rangeStart , rangeEnd;
2507    switch (view){
2508        case 'basicDay':
2509        case 'agendaDay':
[7702]2510            rangeStart = new Date.today().add({ days: page_index }).getTime();
[6996]2511            rangeEnd = rangeStart + 86400000;
[6044]2512            break;
2513        case 'agendaWeek':
2514            var dateStart = new Date().moveToDayOfWeek(dateCalendar.dayOfWeek[User.preferences.weekStart]);
[7835]2515            var dateEnd = new Date().moveToDayOfWeek(dateCalendar.dayOfWeek[User.preferences.weekStart]);
2516            dateEnd.setHours(0,0,0);
2517            dateStart.setHours(0,0,0); 
[7702]2518            rangeStart = dateStart.add({ days: (7 * page_index) }).getTime();
2519            rangeEnd = dateEnd.add({ days: (7 * page_index)+7 }).getTime();
[6044]2520            break;
2521        case 'month':
[7702]2522            var date = Date.today().add({ months: page_index })
[6044]2523            rangeStart = date.moveToFirstDayOfMonth().getTime();
[7835]2524            rangeEnd = date.moveToLastDayOfMonth().getTime() + 86400000;
[6044]2525            break;
2526        case 'year':
[7702]2527            var dateStart = new Date().add({ years: page_index });
2528            var dateEnd = new Date().add({ years: page_index });
[7835]2529            dateEnd.setHours(0,0,0);
2530            dateStart.setHours(0,0,0);
[6044]2531            if(dateStart.getMonth() != 0)
[7702]2532                    dateStart.moveToMonth(0, -1)
[6044]2533            if(dateEnd.getMonth() != 11)
[7702]2534            dateEnd.moveToMonth(11)
2535
2536        rangeStart = dateStart.moveToFirstDayOfMonth().getTime();
[7835]2537        rangeEnd = dateEnd.moveToLastDayOfMonth().getTime() + 86400000;
[6044]2538            break; 
2539    }
[5641]2540                       
[6044]2541    var timezone = {};
2542    for(var i in Calendar.signatureOf)
[7702]2543            timezone[i] = Calendar.signatureOf[i].calendar.timezone;
[5641]2544       
[7702]2545    return  {
2546        rangeStart: rangeStart,
2547        rangeEnd: rangeEnd,
[6044]2548            order: 'startTime',
[7702]2549            timezones: timezone,
2550        calendar: calerdars_selecteds
2551        };
[5341]2552}
2553
[6996]2554function pageselectCallback(keyword, page_index, view, type){
2555    $('.qtip.qtip-blue').remove();
2556        var tab_selector = ['tab_events_list_', 'tab_tasks_list_', 'tab_all_list_'];
2557        var tab_title = ['Lista de eventos', 'Lista de tarefas'];
2558        var label_noselect_calendar = ['Por favor selecione ao menos uma agenda.', 'Por favor selecione ao menos um grupo.', 'Por favor selecione ao menos uma agenda ou grupo.'];
2559        var label_nofound_search = ['Não foi encontrado nenhum evento correspondente à sua pesquisa.', 'Não foi encontrado nenhuma tarefa ou atividade correspondente à sua pesquisa.', 'Não foi encontrado nenhum evento ou tarefa ou atividade correspondente à sua pesquisa.'];
2560        var label_nofound = ['Não foram encontrados eventos neste intervalo.', 'Não foram encontradas tarefas ou atividades neste intervalo.', 'Não foram encontrados eventos ou tarefas ou atividades neste intervalo.'];
2561        var selecteds = getSelectedCalendars(false, type);
2562   
2563        if(!selecteds && (keyword != '' && keyword != null)){   
[7702]2564        jQuery('#'+tab_selector[type] + ((Base64.encode(keyword)).replace(/[^\w\s]/gi, "")|| '')).html(
2565            '<div title="'+tab_title[type]+'" class="events-list events-list-win active empty">' +
2566            '<label>'+label_noselect_calendar[type]+'</label>' +
2567            '</div>'
2568        );
[6044]2569    }else{
[7702]2570        var criteria = null;
2571        if(keyword == '' || keyword == null){
2572
2573            criteria = mountCriteriaList(!!view ? view : User.preferences.defaultCalView, page_index, selecteds);
2574
2575        }else{
2576
2577            var timezone = {};
2578            for(var i in Calendar.signatureOf)
2579                timezone[i] = Calendar.signatureOf[i].calendar.timezone;
2580
2581            criteria =  {
2582
2583                searchEvent: true,
2584                order: 'startTime',
2585                offset: (25 * page_index),
2586                limit: (((25 * page_index) + 25) + 1),
2587                summary: keyword,
2588                description: keyword,
2589                calendar: selecteds,
2590                timezones: timezone
2591
2592            };
2593        }
[7835]2594         
[7702]2595        var results = DataLayer.encode('schedulable:list', DataLayer.dispatch('modules/calendar/schedules', criteria));
2596        //var results = DataLayer.get('schedulable:detail', criteria);
2597        keyword = ( keyword || '' ).replace( /\s+/g, "_" );
[6996]2598        }
[6044]2599// não há resultados   
[6444]2600
[6996]2601var currentView = '#'+tab_selector[type] + ((Base64.encode(keyword)).replace(/[^\w\s]/gi, "") || '');
[6444]2602
[6044]2603if ((((typeof(results) == 'undefined') || (!results.events_list )) && selecteds) &&(keyword != '' && keyword != null)) {
[6444]2604    $(currentView).html(
[6996]2605                '<div title="'+title+'" class="events-list events-list-win active empty">' +
2606                '<label>'+label_nofound_search[type]+'</label>' +
[6444]2607                '</div>'
[6044]2608        );
2609// há resultados e Agendas Selecionadas
2610} else{
2611    if(typeof(results) != 'undefined'){
[6444]2612                results['page_index'] = page_index;
2613                results['keyword'] = keyword;
[6996]2614                results['tab_title'] = tab_title[type];
[6444]2615                DataLayer.render( 'templates/event_list.ejs', results, function( html ){
[5341]2616                       
[6444]2617                        $(currentView).html( html );
2618                        $('.events-list-win .menu-container .button').button();
2619                                                                                                                       
[6996]2620                        $(".event-details-item").parent().click(function(event){
2621                        event.stopImmediatePropagation();
[7702]2622            var container = $(this).siblings("div.details-event-list");
2623
2624
2625            //lazy data
2626            if( container.hasClass('hidden') ){
2627
2628                //only first click
2629                if(!container.find('fieldset').length){
2630
2631                   $(this).append( '<span style="width: 20px;" class="load-event-detail"><img style="width: 20px;" src="'+DataLayer.dispatchPath+'/modules/calendar/img/loading.gif"></img></span>');
2632
2633                    var schedulable = container.find('input[name="eventid"]').val();
2634                    schedulable = DataLayer.encode('schedulable:detail', [getSchedulable( schedulable, '' )]);
2635
2636                    schedulable = $.isArray( schedulable ) ? schedulable[0] : schedulable;
2637
2638                    container.prepend( DataLayer.render( 'templates/event_detail_list.ejs', {'_event': schedulable}));
2639
2640                    $(this).find('span.load-event-detail').remove();
2641                }
2642            }
2643
2644            container.toggleClass("hidden")
[6996]2645                        .find('.button.delete').click(function(event){
[6444]2646                                var eventId = $(this).siblings('[name="eventid"]').val();
2647                                var calendarId = $(this).siblings('[name="calendarid"]').val();
[7017]2648                                remove_event(eventId, calendarId, 2);
[6996]2649                                event.stopImmediatePropagation()
[6444]2650                        })
[7010]2651                        .end().find('.button.edit').click(function(event){
[7702]2652
2653                var schedulable = $(this).siblings('[name="eventid"]').val();
[7010]2654                switch($(this).siblings('[name="eventtype"]').val()){
[7702]2655
[7010]2656                    case '1':
[7702]2657                        eventDetails( getSchedulable( schedulable, '' ), true );
[7010]2658                    break;
2659                    case '2':
[7702]2660                        taskDetails( getSchedulable( schedulable, '' ), true );
[7010]2661                    break;
2662                    case '3':
[7702]2663                        activityDetails( getSchedulable( schedulable, '' ), true );
[7010]2664                    break;
2665                }
[6996]2666                                event.stopImmediatePropagation()
2667                        })
2668                        .end().find('.button.print').click(function(event){     
2669                                var window_print = window.open('','ExpressoCalendar','width=800,height=600,scrollbars=yes');
2670                                var html = $(this).parents("td:first").clone();
2671                                html.find(".menu-container.footer-container").remove();
[7022]2672                                html.find(".fc-header-title").remove();
[6996]2673                                var html = html.html();
2674                                var data = {
2675                                        type : $(this).parents('.details-event-list').hasClass("details-event") ? "event-detail" : "task-detail",
[7022]2676                                        html : html,
2677                                        InfoPage : 'Detalhes: '+$(this).parents('tr.start-date').find('td span a').text()
[6996]2678                                }
2679                                window_print.document.open();           
2680                                window_print.document.write(DataLayer.render('templates/calendar_list_print.ejs', data));
2681                                window_print.document.close();
2682                                window_print.print();
2683                               
2684                                event.stopImmediatePropagation()
[6444]2685                        });
2686
2687                        });
[6996]2688                        paginatorListEvent(currentView, (keyword == '' || keyword == null) ? 'list' : 'search',  !!view ? view : User.preferences.defaultCalView, type);
[6044]2689                });
2690    }else{
[6444]2691                $(currentView).html(
[6996]2692                        '<div title="'+title+'" class="events-list events-list-win active empty">' +
[6444]2693                        '<input type="hidden" name="page_index" value="'+page_index+'"></inpunt>'+
2694                        '<input type="hidden" name="keyword" value="'+keyword+'"></inpunt>'+
[6996]2695                        '<label class="empty-result">'+label_nofound[type]+'</label>' +
[6444]2696                        '</div>'
2697                        );
[6996]2698                paginatorListEvent(currentView, 'list', !!view ? view : User.preferences.defaultCalView, type);
[6044]2699    }
2700}
[6996]2701        if(currentView != '#'+tab_selector[type])
[6476]2702            $tabs.tabs("select", currentView);
[5341]2703}
2704
[6996]2705function show_modal_import_export(tab, calendarId, typeView){
2706    $('.qtip.qtip-blue').remove();
[6044]2707    DataLayer.render( 'templates/import_export.ejs', {
[6996]2708        calendars: typeView == 0 ? Calendar.calendars : Calendar.groups,
2709        owner: User.me.id,
2710        typeView: typeView
[6044]2711        }, function( html ){
[5341]2712
[6044]2713        if (!UI.dialogs.importCalendar) {
2714            UI.dialogs.importCalendar = jQuery('#div-import-export-calendar')
[6996]2715            .append('<div title="Importar e Exportar "' + (typeView == 0 ? 'Eventos' : 'Tarefas') + '" class="import-export import-export-win active"> <div>')
[6044]2716            .find('.import-export-win.active').html(html).dialog({
2717                resizable: false,
2718                modal:true,
2719                width:500,
2720                position: 'center'
2721            });
[5341]2722                       
[6044]2723        } else {
2724            UI.dialogs.importCalendar.html(html);
2725        }
[5341]2726               
[6044]2727        var tabsImportExport = UI.dialogs.importCalendar.find(".tabs-import-export").tabs({
2728            selected: tab
2729        });
[5341]2730       
[6044]2731        UI.dialogs.importCalendar.find('.button').button();
[5341]2732
[6044]2733        tabsImportExport.find('option[value="'+calendarId+'"]').attr('selected','selected').trigger('change');
[5381]2734               
[6044]2735        var form = false;
2736        $('.import-event-form').fileupload({
2737            sequentialUploads: true,
2738            add: function (e, data) {
[7661]2739            form = data
2740            var name = form.files[0].name;
2741            $('.import-event-form').find('input[type="file"]').hide();
2742            $('.import-event-form').find('span.file-add').removeClass('hidden');
2743            $('.import-event-form').find('span.file-add').append('<span>'+ name +'</span><a class="button remove-attachment tiny"></a>');
2744            $('.import-event-form').find('.button.remove-attachment').button({
2745                icons: {
2746                primary: "ui-icon-close"
2747                },
2748                text: false
2749            }).click(function (event){
2750                $('.import-event-form').find('input[type="file"]').show();
2751                $('.import-event-form').find('span.file-add').addClass('hidden').html('');
2752                form = false;
2753            });
2754
[6044]2755            },
[7661]2756        submit:function(e, data){
2757
2758            $('div.import-export').find('a.button').button('option', 'disabled', true)
2759            $('.import-event-form').find('span.file-add').append('<img src="../prototype/modules/calendar/img/ajax-loader.gif">');
2760
2761        },
[6044]2762            done: function(e, data){
[7661]2763            var msg = '';
2764            var type = '';
[5901]2765
[7661]2766            if(!!data.result && data.result == '[][""]' || data.result.indexOf('Error') >= 0 ){
2767                msg = 'Erro ao realizar a importação, por favor verifique o arquivo .ics';
2768                type = 'warning';
[7394]2769
[7661]2770                $('div.import-export').find('a.button').button('option', 'disabled', false)
2771                $('.import-event-form').find('span.file-add img ').remove();
[5901]2772
[7394]2773            }else{
2774
[7661]2775                if(data.result.indexOf('schedulable') >= 0){
[7394]2776                    msg = 'Importação realizada com sucesso!';
2777                    type = 'confirmation';
2778                    Calendar.rerenderView(true);
2779                }else{
[7661]2780                    var res = JSON.parse(data.result);
2781                    var asData = false;
2782
2783                    for(var i = 0; i < res.length; i++)
2784                        if(res[i].length > 0)
2785                            asData = true;
2786
2787                    if(asData){
2788                        msg = 'Importação realizada com sucesso!';
2789                        type = 'confirmation';
2790                        Calendar.rerenderView(true);
2791                    }else{
2792                        msg = 'Não foram encontrados novos eventos na importação!';
2793                        type = 'information';
2794                    }
[7394]2795                }
[7661]2796
2797                UI.dialogs.importCalendar.dialog("close");
[7394]2798            }
2799
[7661]2800            $.Zebra_Dialog(msg, {
2801                'type':     type,
2802                'overlay_opacity': '0.5',
2803                'buttons':  ['Fechar']
2804            });
[6044]2805            }
2806        });
[5901]2807
[6044]2808        UI.dialogs.importCalendar.find(".menu-import-event")       
[7661]2809            .children(".import").click(function(data){
2810            $('.import-event-form fieldset.import-calendar', UI.dialogs.importCalendar).append(
2811                '<input type="hidden" name="params[calendar_timezone]" value="'+
2812                Calendar.signatureOf[$('.import-event-form option:selected').val()].calendar.timezone
2813                +'"/>')
2814            if(form)
2815                form.submit();
[6044]2816        });
[5341]2817           
[6044]2818        UI.dialogs.importCalendar.find(".menu-export-event")       
2819        .children(".export").click(function(){
[5341]2820             
[6044]2821            $('.export-event-form', UI.dialogs.importCalendar).submit();
2822            UI.dialogs.importCalendar.dialog("close");
2823        /**
[5341]2824                         * TODO - implementar ação de exportação
2825                         */
[6044]2826        });
[5341]2827       
[6044]2828        UI.dialogs.importCalendar.find(".menu-container")
2829        .children(".cancel").click(function(){
2830            UI.dialogs.importCalendar.dialog("close");
2831        });   
[5341]2832               
[6044]2833        UI.dialogs.importCalendar.dialog("open");
[5341]2834    });
[5592]2835}
2836
[5746]2837function copyAndMoveTo(calendar, event, idRecurrence, type, evt){
2838    /*
2839     * Types
2840     * 0 = Move
2841     * 1 = Copy Event end Repet
2842     * 2 = Copy Ocurrence
2843     * 3 = Copy to edit ocurrence
2844     *
2845     **/
2846    if(!type)
[6044]2847        type = $('.calendar-copy-move input[name="typeEvent"]').val();
[5592]2848
[7702]2849    getSchedulable(event,'');
2850    var schedulable = DataLayer.get('schedulable', event.toString());
[7106]2851    schedulable['class'] = '1';
[6331]2852       
[6044]2853    calendar = !!calendar ? calendar : schedulable.calendar;
[7357]2854
2855    owner = decodeOwnerCalendar(calendar);
[5746]2856       
[6044]2857    if(typeof(schedulable) == "array")
2858        schedulable = schedulable[0];
[5592]2859       
[6044]2860    //Move eventos entre agendas
2861    if(parseInt(type) == 0){
[5592]2862               
[6331]2863        schedulable.lastCalendar = schedulable.calendar;
[7702]2864    schedulable.calendar = calendar;
[6044]2865        DataLayer.put('schedulable', schedulable);
[5592]2866       
[6044]2867        DataLayer.commit();
2868    //copia eventos entre agendas
2869    }else{
[5592]2870       
[6044]2871        var newSchedulable = schedulable;
[5592]2872       
[6044]2873        delete newSchedulable.id;
2874        delete newSchedulable.uid;
2875        delete newSchedulable.sequence;
2876        delete newSchedulable.dtstamp;
[5746]2877               
[6044]2878        delete schedulable.DayLigth;
2879        delete schedulable.rangeStart
2880        delete schedulable.rangeEnd;
2881        delete schedulable.lastUpdate;
[5746]2882               
[6044]2883        delete schedulable.calendar;
[5746]2884               
[6044]2885        if(schedulable.repeat && type == "1" ){
2886            var repeat = DataLayer.get('repeat', schedulable.repeat);
2887            delete repeat.schedulable;
2888            delete repeat.id;
[7702]2889            repeat.startTime = repeat.startTime == '' ? '' : new Date(parseInt(repeat.startTime)).toString('yyyy-MM-dd HH:mm:00');
2890            repeat.endTime = repeat.endTime == '' ? '' : new Date(parseInt(repeat.endTime)).toString('yyyy-MM-dd HH:mm:00');
[5746]2891                   
[6044]2892            var exceptions = DataLayer.get('repeatOccurrence', {
2893                filter: ['AND', ['=','repeat', schedulable.repeat], ['=','exception','1']]
2894                }, true);
2895            if(exceptions){
2896                repeat.exceptions = '';
2897                for(var i in exceptions )
2898                    repeat.exceptions += exceptions[i].occurrence + ((exceptions.length -1) == parseInt(i) ? '' : ',');
[5746]2899                           
[6044]2900            }
[5746]2901                   
2902                   
[6044]2903            schedulable.repeat = repeat;
2904        }else{
2905            if(!!idRecurrence){
2906                newSchedulable.endTime = parseInt(schedulable.occurrences[idRecurrence]) + (parseInt(newSchedulable.endTime) - parseInt(newSchedulable.startTime));
2907                newSchedulable.startTime = schedulable.occurrences[idRecurrence];
2908            }
2909            delete schedulable.repeat;
2910        }
2911        delete schedulable.occurrences;
[5746]2912               
[7702]2913        schedulable.calendar = DataLayer.copy(calendar);
[5592]2914               
[6044]2915        var participants = DataLayer.copy(schedulable.participants);
2916        delete schedulable.participants;
[7357]2917
2918    if(schedulable['type'] == '2')
2919        delete schedulable['historic'];
2920
[6044]2921        schedulable.participants =  $.map( participants, function( attendee, i ){
[5592]2922                       
[6044]2923            var participant = DataLayer.get('participant', attendee, false);
[5592]2924                       
[6044]2925            if(typeof(participant) == 'array')
[7357]2926                    participant = participant[0];
2927
2928        if(owner.id != participant.user)
2929            delete participant.status;
[5592]2930       
[6044]2931            delete participant.delegatedFrom;
2932            delete participant.id;
2933            delete participant.schedulable;
[5746]2934                       
[6044]2935            participant.id = DataLayer.put('participant', participant);
[5592]2936                       
[6044]2937            return participant ;
2938        });
2939        //Edit ocurrence
2940        if(parseInt(type) == 3){
2941            newSchedulable.endTime = !!evt.end  ? evt.end.getTime() :  ((evt.start).getTime() + 86400000);
2942            newSchedulable.startTime = evt.start.getTime();
[5746]2943                   
[6044]2944            return newSchedulable;
2945        }
[7702]2946        newSchedulable.endTime = new Date(parseInt(newSchedulable.endTime) - (parseInt(newSchedulable.allDay) ? 86400000 : 0)).toString('yyyy-MM-dd HH:mm:00');
2947        newSchedulable.startTime = new Date(parseInt(newSchedulable.startTime)).toString('yyyy-MM-dd HH:mm:00');
[5592]2948       
[6044]2949        DataLayer.put('schedulable', newSchedulable);
[5636]2950
[6044]2951    }
[6476]2952}
[5592]2953
[6476]2954function messageHelper(msg, isShow){
2955    if(isShow)
2956        new $.Zebra_Dialog('<span style="width: 50px; height: 50px;">'+
2957                            '<img src="'+DataLayer.dispatchPath+'/modules/calendar/img/loading.gif"></img>'+
2958                        '</span><label class="messagesHelpers"> '+ msg +' </label>' , {
2959                        'buttons':  false,
2960                        'modal': true,
2961                        'overlay_opacity': '0.5',
2962                        'keyboard': false,
2963                        'overlay_close': false,
2964                        'type': false,
2965                        'custom_class': 'messagesHelpersExpressoCalendar'
2966                        }
2967                    );
2968    else{
2969        $('.messagesHelpersExpressoCalendar').remove();
2970        $('.ZebraDialogOverlay').remove();
2971    }
[6498]2972}
[6996]2973
2974function extendsFileupload(view, path){
2975    var viewName = 'div.new-'+view+'-win';
2976   
2977    path = !!path ? path : '';
2978   
2979    var maxSizeFile = 2000000;
2980    $('#fileupload'+view).fileupload({
2981        sequentialUploads: true,
2982        add: function (e, data) {
2983            if(data.files[0].size < maxSizeFile)
2984                data.submit();
2985        },
2986        change: function (e, data) {
2987            $.each(data.files, function (index, file) {
2988                var attach = {};
2989                attach.fileName = file.name;
2990                var ext = file.name.split('.');
2991                if(file.name.length > 10)
2992                    attach.fileName = ext.length == 1 ? file.name.substr(0, 10) :  file.name.substr(0, 6) + '.' + ext[ext.length -1];
2993                attach.fileSize = formatBytes(file.size);
2994                if(file.size > maxSizeFile)
2995                    attach.error = 'Tamanho de arquivo nao permitido!!'
2996                               
2997                $(viewName+' .attachments-list').append(DataLayer.render(path+'templates/attachment_add_itemlist.ejs', {
2998                    file : attach
2999                }));
3000                               
3001                if(file.size < maxSizeFile){
3002                    $(viewName+' .fileinput-button.new').append(data.fileInput[0]).removeClass('new');
3003                    $(viewName+' .attachments-list').find('[type=file]').addClass('hidden');
3004                                       
3005                }else
3006                    $(viewName+' .fileinput-button.new').removeClass('new');
3007                               
3008                               
3009                $(viewName+' .attachments-list').find('.button.close').button({
3010                    icons: {
3011                        primary: "ui-icon-close"
3012                    },
3013                    text: false
3014                }).click(function(){
3015                    var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
3016                    $(viewName+' .attachment-list').find('input[value="'+idAttach+'"]').remove();
3017                    $(this).parent().remove();
3018               
3019                    if(!$(viewName+' .attachment-list input').length)
3020                        $(viewName+' .btn-danger.delete').addClass('hidden');
3021               
3022                });     
3023                               
3024            })
3025        },
3026        done: function(e, data){
3027            var currentUpload = $(viewName+' .progress.after-upload:first').removeClass('after-upload').addClass('on-complete').hide();
3028
3029            if(!!data.result && data.result != "[]"){
3030                $(viewName+' .btn-danger.delete').removeClass('hidden');
3031                var newAttach = (attch = jQuery.parseJSON(data.result)) ? attch : jQuery.parseJSON(data.result[0].activeElement.childNodes[0].data);
3032                $(viewName+' .attachment-list').append('<input tyepe="hidden" name="attachment[]" value="'+newAttach['attachment'][0][0].id+'"/>');
3033                currentUpload.removeClass('on-complete').parents('p')
3034                .append('<input type="hidden" name="fileId[]" value="'+newAttach['attachment'][0][0].id+'"/>')
3035                .find('.status-upload').addClass('ui-icon ui-icon-check');
3036            }else
3037                currentUpload.removeClass('on-complete').parents('p').find('.status-upload').addClass('ui-icon ui-icon-cancel');
3038        }
3039    });
3040    $('.attachments-list .button').button();   
3041
3042    if(!!window.FormData)                       
3043        $('#fileupload'+view).bind('fileuploadstart', function () {
3044            var widget = $(this),
3045            progressElement = $('#fileupload-progress-'+view).fadeIn(),
3046            interval = 500,
3047            total = 0,
3048            loaded = 0,
3049            loadedBefore = 0,
3050            progressTimer,
3051            progressHandler = function (e, data) {
3052                loaded = data.loaded;
3053                total = data.total;
3054            },
3055            stopHandler = function () {
3056                widget
3057                .unbind('fileuploadprogressall', progressHandler)
3058                .unbind('fileuploadstop', stopHandler);
3059                window.clearInterval(progressTimer);
3060                progressElement.fadeOut(function () {
3061                    progressElement.html('');
3062                });
3063            },
3064            formatTime = function (seconds) {
3065                var date = new Date(seconds * 1000);
3066                return ('0' + date.getUTCHours()).slice(-2) + ':' +
3067                ('0' + date.getUTCMinutes()).slice(-2) + ':' +
3068                ('0' + date.getUTCSeconds()).slice(-2);
3069            },
3070            /* formatBytes = function (bytes) {
3071            if (bytes >= 1000000000) {
3072                return (bytes / 1000000000).toFixed(2) + ' GB';
3073            }
3074            if (bytes >= 1000000) {
3075                return (bytes / 1000000).toFixed(2) + ' MB';
3076            }
3077            if (bytes >= 1000) {
3078                return (bytes / 1000).toFixed(2) + ' KB';
3079            }
3080            return bytes + ' B';
3081        },*/
3082            formatPercentage = function (floatValue) {
3083                return (floatValue * 100).toFixed(2) + ' %';
3084            },
3085            updateProgressElement = function (loaded, total, bps) {
3086                progressElement.html(
3087                    formatBytes(bps) + 'ps | ' +
3088                    formatTime((total - loaded) / bps) + ' | ' +
3089                    formatPercentage(loaded / total) + ' | ' +
3090                    formatBytes(loaded) + ' / ' + formatBytes(total)
3091                    );
3092            },
3093            intervalHandler = function () {
3094                var diff = loaded - loadedBefore;
3095                if (!diff) {
3096                    return;
3097                }
3098                loadedBefore = loaded;
3099                updateProgressElement(
3100                    loaded,
3101                    total,
3102                    diff * (1000 / interval)
3103                    );
3104            };
3105            widget
3106            .bind('fileuploadprogressall', progressHandler)
3107            .bind('fileuploadstop', stopHandler);
3108            progressTimer = window.setInterval(intervalHandler, interval);
3109        });
3110   
[7835]3111}
Note: See TracBrowser for help on using the repository browser.