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

Revision 8021, 106.6 KB checked in by douglas, 11 years ago (diff)

Ticket #3392 - Preferencia para que a visualizacao diaria fique sem as horas

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