source: trunk/prototype/modules/calendar/js/helpers.js @ 7991

Revision 7991, 106.4 KB checked in by cristiano, 11 years ago (diff)

Ticket #3382 - Travamento do navegador ao carregar repetições com muitos participantes

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