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

Revision 7985, 106.4 KB checked in by douglas, 11 years ago (diff)

Ticket #3379 - Problema ao remover um participante e verificar disponibilidade

Line 
1function formatBytes(bytes) {
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';
12};
13
14function validDateEvent(){
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',
26                'theirData' : 'Data final menor que a inicial',         
27                'theirHour' : 'Hora final menor que a inicial',
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
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');
41    var customDate = $(".endRepeat").val() == "customDate";
42    var occurrences = $(".endRepeat").val() == "occurrences";
43    var eventInterval = $('.eventInterval').val();
44   
45    if(start_date == "")
46                return errors['emptyInitData'];
47    else if(end_date == "")
48                return errors['emptyEndData'];
49    else if(!isAllDay && start_time == "")
50                return errors['emptyInitHour'];
51    else if(!isAllDay && end_time == "")
52                return errors['emptyEndHour'];
53       
54    var formatString = User.preferences.dateFormat + " " + User.preferences.hourFormat;
55               
56    var startDate = Date.parseExact( start_date + " " + $.trim(start_time) , formatString );
57    var endDate = Date.parseExact( end_date + " " + $.trim(end_time) , formatString );
58
59    if(startDate == null || startDate.getTime() < 0 )
60                return errors['invalidInitData'];
61    if(endDate == null || endDate.getTime() < 0)
62                return errors['invalidEndData'];
63       
64        if(isAllDay){
65                startDate.clearTime();
66                endDate.clearTime();
67                if(endDate.compareTo(startDate) == -1)
68                        return errors['theirData'];
69        }else{
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                }
81        }
82   
83    if (customDate)   
84                if ( !($('.new-event-win.active .customDateEnd').val().length) )
85                   return errors['emptyEndData'];
86
87    if (occurrences){
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        }
93
94    if (!($('.new-event-win.active p.input-group.finish_event.repeat-in').hasClass('hidden'))){
95        if (!eventInterval.length)
96            return errors['emptyInterval'];
97        else if (parseInt(eventInterval,10) < 1 || parseInt(eventInterval,10).toString() == "NaN")
98            return errors['invalidInterval'];
99    }   
100    return false;
101}
102
103function printNow(){
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               
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        }
122        if($("#calendar").fullCalendar('getView').name == "agendaDay" || $("#calendar").fullCalendar('getView').name == "basicDay"){                           
123                window_print.document.write(DataLayer.render('templates/calendar_day_print.ejs', {
124                        'InfoPage' : $("#calendar").fullCalendar('getView').title,
125                        'days' : data
126                } ));
127        }
128        if($("#calendar").fullCalendar('getView').name == "agendaWeek" || $("#calendar").fullCalendar('getView').name == "basicWeek"){
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();
153        window_print.print();
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
160        $('.fc-header-right').find('.fc-button-year').toggleClass('fc-corner-right');
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        });
170}
171
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)
179{
180
181    $('.qtip.qtip-blue').remove();
182
183    attendees = {};
184 
185    if(!!objEvent.participants)
186    {
187        $.each(objEvent.participants ,function(index, value) {
188            var part = DataLayer.get('participant' , value );
189            var user = DataLayer.get('user' , part.user );
190 
191            attendees[part.user] = user.name;
192        });
193    }
194 
195    if(path == undefined)
196        path = "";
197               
198    if( !decoded )
199        objEvent = DataLayer.decode( "schedulable:calendar", objEvent );
200
201    if(!isMail)
202        objEvent = DataLayer.encode( "schedulable:preview", objEvent );
203       
204    if(typeof(objEvent.id) == 'undefined'){
205        objEvent.alarms = Calendar.signatureOf[User.preferences.defaultCalendar || Calendar.calendarIds[0]].defaultAlarms || false;
206        objEvent.useAlarmDefault = 1;
207    }
208       
209    /**
210         * canDiscardEventDialog deve ser true se não houver alterações no evento
211         */
212    canDiscardEventDialog = true;
213    /**
214         * zebraDiscardEventDialog é uma flag indicando que uma janela de confirmação (Zebra_Dialog)
215         * já está aberta na tela, uma vez que não é possivel acessar o evento ESC utilizado para fechá-la
216         */
217    zebraDiscardEventDialog = false;
218       
219    /**
220                ACLs do participant
221        */
222    acl_names = {
223        'w': 'acl-white',
224        'i': 'acl-invite-guests',
225        'p': 'acl-participation-required'
226    };
227
228    var dependsDelegate = function(reference, inverse){
229        if(inverse){
230            if(reference.find('input[name="attendee[]"]').val() == blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val())
231                blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val(blkAddAtendee.find('.me input[name="attendee[]"]').val());
232        }else{
233            if(blkAddAtendee.find('.me input[name="attendee[]"]').val() == blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val())
234                blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val(reference.find('input[name="attendee[]"]').val());
235        }
236       
237    };
238   
239    var removeOthers = function(){
240        var other = blkAddAtendee.find('.delegate.attendee-permissions-change-button');
241        if(other.lenght){
242            dependsDelegate(other.parents('li'), true);
243        }
244        blkAddAtendee.find('.delegate').removeClass('attendee-permissions-change-button');
245        blkAddAtendee.find('.ui-icon-transferthick-e-w').removeClass('attendee-permissions-change');
246       
247    };
248
249    var callbackAttendee = function(){
250        //Cria qtip de permissões pelo click do checkbox
251        var checked = false;
252        blkAddAtendee.find("li.not-attendee").addClass('hidden');
253       
254        blkAddAtendee.find("li .button").filter(".close.new").button({
255            icons: {
256                primary: "ui-icon-close"
257            },
258            text: false
259        }).click(function () {
260        var participant = DataLayer.get('participant' , $(this).parents('li').find('[type=checkbox]').val());
261            DataLayer.remove('participant', participant.id);
262            if($(this).parent().find('.button.delegate').hasClass('attendee-permissions-change-button')){
263                removeOthers();
264                blkAddAtendee.find('.request-update').addClass('hidden');
265                blkAddAtendee.find('.status option').toggleClass('hidden');
266                               
267                blkAddAtendee.find('option[value=1]').attr('selected','selected').trigger('change');
268            }
269            $(this).parents('li').remove();
270                       
271            if(blkAddAtendee.find(".attendee-list li").length == 1)
272                blkAddAtendee.find("li.not-attendee").removeClass('hidden');
273        delete attendees[participant.user];
274        })
275        .addClass('tiny disable ui-button-disabled ui-state-disabled')
276        .removeClass('new').end()
277       
278        .filter(".delegate.new").button({
279            icons: {
280                primary: "ui-icon-transferthick-e-w"
281            },
282            text: false
283        }).click(function () {
284            var me = $(this).parents('li');
285            if($(this).hasClass('attendee-permissions-change-button')){
286                $(this).removeClass('attendee-permissions-change-button')   
287                    .find('.ui-icon-transferthick-e-w').removeClass('attendee-permissions-change').end();               
288               
289                me.find('input[name="delegatedFrom[]"]').val('');
290                dependsDelegate(me, true);
291                               
292                blkAddAtendee.find('.request-update').addClass('hidden');
293                blkAddAtendee.find('.status option').toggleClass('hidden');
294
295                blkAddAtendee.find('option[value=1]').attr('selected','selected').trigger('change');
296                               
297            }else{
298                removeOthers();
299                       
300                $(this).addClass('attendee-permissions-change-button')   
301                .find('.ui-icon-transferthick-e-w').addClass('attendee-permissions-change').end();               
302               
303                me.find('input[name="delegatedFrom[]"]').val(blkAddAtendee.find('.me input[name="attendee[]"]').val());
304               
305                dependsDelegate(me, false);
306                       
307                blkAddAtendee.find('.request-update').removeClass('hidden');
308                if(blkAddAtendee.find('.status option.hidden').length == 1)
309                    blkAddAtendee.find('.status option').toggleClass('hidden');
310                       
311                blkAddAtendee.find('option[value=5]').attr('selected','selected').trigger('change');
312            }
313        })
314        .addClass('tiny disable ui-button-disabled ui-state-disabled')
315        .removeClass('new').end()
316               
317        .filter(".edit.new").button({
318            icons: {
319                primary: "ui-icon-key"
320            },
321            text: false
322        }).click(function() {
323                       
324            if(!!!checked)
325                $(this).parents('li').find('[type=checkbox]').attr('checked', (!$(this).parent().find('[type=checkbox]').is(':checked'))).end();
326                       
327            var aclsParticipant =  $(this).parents('li').find('input[name="attendeeAcl[]"]').val();
328            checked = false;
329                       
330            if( $('.qtip.qtip-blue.qtip-active').val() !== ''){
331                blkAddAtendee.find('dd.attendee-list').qtip({
332                    show: {
333                    ready: true,
334            solo: true,
335            when: {
336                    event: 'click'
337                    }
338                },
339                hide: false,
340                content: {
341                text: $('<div></div>').html( DataLayer.render( path + 'templates/attendee_permissions.ejs', {} ) ),
342                title: {
343                text:'Permissões',
344                button: '<a class="button close" href="#">close</a>'
345                }
346                },
347                style: {
348                name: 'blue',
349            tip: {
350                corner: 'leftMiddle'
351                },
352            border: {
353                width: 4,
354            radius: 8
355                },
356            width: {
357                min: 230,
358            max:230
359                }
360            },
361            position: {
362            corner: {
363            target: 'rightMiddle',
364            tooltip: 'leftMiddle'
365            },
366            adjust: {
367            x:0,
368            y:0
369            }
370            }
371            })
372        .qtip("api").onShow = function(arg0) {
373            $('.qtip-active .button.close').button({
374                icons: {
375                    primary: "ui-icon-close"
376                },
377                text: false
378            })
379            .click(function(){
380                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
381            });
382                                       
383            $('.qtip-active .button.save').button().click(function(){
384                                               
385                var acl = '';
386                $('.qtip-active').find('[type=checkbox]:checked').each(function(i, obj) {
387                    acl+= obj.value;
388                });
389
390                blkAddAtendee.find('dd.attendee-list [type=checkbox]:checked').siblings('input[name="attendeeAcl[]"]').each(function(i, obj) {
391                    obj.value = 'r'+acl;
392                }).parents('li').find('.button.edit').addClass('attendee-permissions-change-button')   
393                .find('.ui-icon-key').addClass('attendee-permissions-change');               
394                                               
395                blkAddAtendee.find('dd.attendee-list [type=checkbox]').attr('checked', false);
396                                               
397                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
398                                       
399            });
400            $('.qtip-active .button.cancel').button().click(function(){
401                blkAddAtendee.find('dd.attendee-list [type=checkbox]').attr('checked', false);
402                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
403            });
404                                       
405            if(aclsParticipant)
406                for(var i = 1; i < aclsParticipant.length; i++){
407                    $('.qtip-active').find('input[name="'+acl_names[aclsParticipant.charAt(i)]+'"]').attr('checked', true);
408                }
409                                                       
410            $('.qtip .button').button();
411                                       
412        };
413        }else{
414            if(!$('.new-event-win dd.attendee-list').find('[type=checkbox]:checked').length){
415                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
416            }else{
417                $('.qtip-active .button.save .ui-button-text').html('Aplicar a todos')
418            }
419                       
420        };                     
421    })
422.addClass('tiny disable ui-button-disabled ui-state-disabled')
423.removeClass('new').end()
424               
425.filter(".open-delegate.new").click(function(){
426    if($(this).hasClass('ui-icon-triangle-1-e')){
427        $(this).removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
428        $(this).parents('li').find('.list-delegates').removeClass('hidden');
429    }else{
430        $(this).removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
431        $(this).parents('li').find('.list-delegates').addClass('hidden');
432    }
433               
434}).removeClass('new');
435       
436       
437blkAddAtendee.find("li input[type=checkbox].new").click(function(){
438    if(!$('.new-event-win dd.attendee-list').find('[type=checkbox]:checked').length){
439        blkAddAtendee.find('dd.attendee-list').qtip('destroy');
440    }else{
441        checked = true;
442        $(this).parents('li').find('.button.edit').click();
443    }
444}).removeClass('new');
445       
446UI.dialogs.addEvent.find('.attendees-list li').hover(
447    function () {
448        $(this).addClass("hover-attendee");
449        $(this).find('.button').removeClass('disable ui-button-disabled ui-state-disabled').end()
450        .find('.attendee-options').addClass('hover-attendee');
451    },
452    function () {
453        $(this).removeClass("hover-attendee");
454        $(this).find('.button').addClass('disable ui-button-disabled ui-state-disabled').end()
455        .find('.attendee-options').removeClass('hover-attendee');;
456    }
457    );
458}
459
460var html = DataLayer.render( path+'templates/event_add.ejs', {
461    event:objEvent
462});     
463               
464if (!UI.dialogs.addEvent) {
465    UI.dialogs.addEvent = jQuery('#sandbox').append('<div title="Criar Evento" class="new-event-win active"> <div>').find('.new-event-win.active').html(html).dialog({
466        resizable: false,
467        modal:true,
468        autoOpen: false,
469        width:"auto",
470        position: 'center',
471        close: function(event, ui) {
472                /**
473                 * Remove tooltip possivelmente existente
474                 */
475                if ($('.qtip.qtip-blue.qtip-active').length)
476                        $('.qtip.qtip-blue.qtip-active').qtip('destroy');                                               
477                attendees  = {};
478        },
479        beforeClose: function(event, ui) {
480
481            if (!canDiscardEventDialog && !zebraDiscardEventDialog) {
482                zebraDiscardEventDialog = true;
483                window.setTimeout(function() {
484                    $.Zebra_Dialog('Suas alterações no evento não foram salvas. Deseja descartar as alterações?', {
485                        'type':     'question',
486                        'overlay_opacity': '0.5',
487                        'buttons':  ['Descartar alterações', 'Continuar editando'],
488                        'onClose':  function(clicked) {
489                            if(clicked == 'Descartar alterações') {
490                                canDiscardEventDialog = true;
491                                /**
492                                *Remoção dos anexos do eventos caso seja cancelado a edição
493                                */
494                                DataLayer.rollback();
495
496                                var ids = false;
497                                $.each($('.attachment-list input'), function (i, input) {
498                                    DataLayer.put('attachment', {id: ''+input.value});
499                                    DataLayer.remove('attachment', ''+input.value);
500                                        ids = true;
501                                });
502                                if(ids)
503                                        DataLayer.commit();
504                       
505                               
506                                                                               
507                                UI.dialogs.addEvent.dialog('close');
508                            }else{
509                                zebraDiscardEventDialog = false;
510                            }
511                                                                       
512                            /**
513                            * Uma vez aberta uma janela de confirmação (Zebra_Dialog), ao fechá-la
514                            * com ESC, para que o evento ESC não seja propagado para fechamento da
515                            * janela de edição de eventos, deve ser setada uma flag indicando que
516                            * já existe uma janela de confirmação aberta.
517                            */
518                            if (!clicked) {
519                                window.setTimeout(function() {
520                                    zebraDiscardEventDialog = false;
521                                }, 200);
522                            }
523                        }
524                    });
525                                                       
526                }, 300);
527
528            }
529            //DataLayer.rollback();
530            return canDiscardEventDialog;
531        },
532        dragStart: function(event, ui) {
533                if ($('.qtip.qtip-blue.qtip-active').length)
534                        $('.qtip.qtip-blue.qtip-active').qtip('destroy');
535        }
536    });
537                       
538} else {
539    UI.dialogs.addEvent.html(html);
540}
541               
542var tabs = UI.dialogs.addEvent.children('.content').tabs({
543        select: function(event, ui) {
544                if ($('.qtip.qtip-blue.qtip-active').length)
545                        $('.qtip.qtip-blue.qtip-active').qtip('destroy');
546        }       
547        });
548var calendar = DataLayer.get('calendar', objEvent.calendar);
549                               
550if ( (calendar.timezone != objEvent.timezone) && objEvent.id){
551    UI.dialogs.addEvent.find('.calendar-addevent-details-txt-timezone').find('option[value="'+objEvent.timezone+'"]').attr('selected','selected').trigger('change');
552    UI.dialogs.addEvent.find('.calendar_addevent_details_lnk_timezone').addClass('hidden');
553    $('.calendar-addevent-details-txt-timezone').removeClass('hidden');
554                       
555}
556
557DataLayer.render( path+'templates/event_repeat.ejs', {
558    event:objEvent
559}, function( repeatHtml ){
560
561    UI.dialogs.addEvent.find('#calendar_addevent_details3').html(repeatHtml);
562    $(".date").datepicker({
563                dateFormat: User.preferences.dateFormat.replace(/M/g, 'm').replace(/yyyy/g, 'yy')
564                });
565                 
566    if(objEvent.repeat)
567    {
568        if( objEvent.repeat['id'] )
569        {
570            $("[name='repeatId']:last").val( objEvent.repeat['id'] );
571        }
572
573        if( objEvent.repeat['frequency'] !== 'none' )
574        {
575            if( objEvent.repeat['startTime'] && objEvent.repeat['startTime'] !== "0" )
576            {
577                $("[name='startOptions'] [value='customDate']:last").attr( 'selected', 'selected' );
578                $("[name='start']:last").val(new Date( parseInt(objEvent.repeat['startTime']) ).toString( User.preferences.dateFormat ) );
579            }
580            else
581            {
582                $("[name='start']:last").val($("[name='startDate']:last").val());     
583                $("[name='start']:last").readOnly=true;
584                $("[name='start']:last").datepicker("disable");
585            }
586                             
587            $(".finish_event").removeClass("hidden");
588
589            if(objEvent.repeat['endTime'] && objEvent.repeat['endTime'] !== "0" )
590            {
591                //$("[name='occurrences']").addClass("hidden");
592                $(".customDateEnd").removeClass("hidden");
593                $(".endRepeat option[value='customDate']").attr('selected', 'selected')                                         
594                $(".customDateEnd").val( new Date( parseInt(objEvent.repeat['endTime']) )/*.setTimezoneOffset( Timezone.timezone( objEvent.timezone ) )*/.toString( User.preferences.dateFormat ) ); 
595            }
596            else if (objEvent.repeat['count'] && objEvent.repeat['count'] !== "0" ) {
597                $(".endRepeat option[value='occurrences']").attr('selected', 'selected');                                               
598                $(".occurrencesEnd").removeClass("hidden");
599                $(".occurrencesEnd").val(objEvent.repeat['count']);                                             
600            }
601                             
602            switch ( objEvent.repeat['frequency'] )
603            {
604                case "daily":
605                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Dia(s)")
606                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
607                    $(".frequency option[value='daily']").attr('selected', 'selected');
608                    break;
609                case "weekly":
610                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Semana(s)")
611                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
612                   
613                    $(".frequency option[value='weekly']").attr('selected', 'selected');
614                                           
615                    $(".event-repeat-weekly").removeClass("hidden");
616                                           
617                    var day = [];
618                                           
619                    if( objEvent.repeat.byday )
620                        day = objEvent.repeat.byday.split(',');
621                                           
622                    for(i=0; i<day.length; i++)
623                        $(".event-repeat-weekly [value='" + day[i] + "']").attr("checked","checked");
624                                           
625                    break;
626                case "monthly":
627                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Mes(s)")
628                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
629                   
630                    $(".frequency option[value='monthly']").attr('selected', 'selected')
631                   
632                    $(".event-repeat-monthly:last").removeClass("hidden").find("input[type=radio][name=repeatmonthyType]").click(function(){
633                                if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
634                                    $(".event-repeat-weekly:last").removeClass("hidden");
635                                else
636                                    $(".event-repeat-weekly:last").addClass("hidden");
637                    });
638                   
639                                           
640                        if( objEvent.repeat && objEvent.repeat.bymonthday != ''){
641
642                                $("input[type=radio][name=repeatmonthyType][value=0]").attr('checked', 'checked');
643
644                        }else if(objEvent.repeat){
645
646                                $("input[type=radio][name=repeatmonthyType][value=1]").attr('checked', 'checked');
647
648                                var days = objEvent.repeat.byday.split(',');
649
650                                $.each(days, function(i, e){
651                                        $(".event-repeat-weekly:last").find('input[name="repeatweekly[]"][value="'+e+'"]').attr('checked', 'checked');
652                                });
653
654                        }
655
656
657                    if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
658                                $(".event-repeat-weekly:last").removeClass("hidden");
659                    else
660                                $(".event-repeat-weekly:last").addClass("hidden");
661                    break;
662                case "yearly":
663                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Ano(s)")
664                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
665                    $(".frequency option[value='yearly']").attr('selected', 'selected')
666                    break;     
667            }
668        }
669    }
670    else {
671        $(".endRepeat option[value='never']").attr('selected', 'selected');
672    }
673
674
675    $(".event-repeat-container:last").find(".repeat-in").find("[name=startOptions]").change(function(){                                       
676
677        if($(this).find("option:selected").val() == "Today"){
678            $("[name='start']:last").val($("[name='startDate']:last").val());
679            $("[name='start']:last").readOnly=true;
680            $("[name='start']:last").datepicker("disable");
681        }
682        else{
683            $("[name='start']:last").readOnly=false;
684            $("[name='start']:last").datepicker("enable");
685        }
686    });
687    $(".event-repeat-container:last").find(".repeat-in").find("[name=endOptions]").change(function(){                                       
688        if($(this).find("option:selected").val() == "never"){
689            $("[name='occurrences']").addClass("hidden");
690            $("[name='end']:last").addClass("hidden");
691        }
692        else if($(this).find("option:selected").val() == "customDate"){
693            $("[name='occurrences']").addClass("hidden");
694            $("[name='end']:last").removeClass("hidden");   
695        }
696        else{
697            $("[name='end']:last").addClass("hidden");
698            $("[name='occurrences']").removeClass("hidden");                                       
699        }
700    });
701                       
702    $("[name='frequency']:last").change(function () {
703        $(".frequency-option").addClass("hidden");
704        if($(this).val() == "none"){
705            $(".repeat-in").addClass("hidden");
706            return;
707        }else{
708            $(".repeat-in").removeClass("hidden");
709            $("[name='start']:last").val($("[name='startDate']:last").val());
710        }
711                 
712                                 
713        switch($(this).val()){
714            case "daily":
715                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Dia(s)");
716                break;
717            case "weekly":
718                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Semana(s)");
719                $(".event-repeat-weekly:last").removeClass("hidden");
720                break;
721            case "monthly":
722                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Mes(s)");
723                $(".event-repeat-monthly:last").removeClass("hidden").find("input[type=radio][name=repeatmonthyType]").click(function(){
724                    if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
725                        $(".event-repeat-weekly:last").removeClass("hidden");
726                    else
727                        $(".event-repeat-weekly:last").addClass("hidden");
728                });
729                if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
730                    $(".event-repeat-weekly:last").removeClass("hidden");
731                else
732                    $(".event-repeat-weekly:last").addClass("hidden");
733                break;
734            default:
735                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Ano(s)");
736                break;
737        }
738                               
739    });
740});
741
742UI.dialogs.addEvent.find('.calendar_addevent_details_lnk_timezone').click(function(e){
743    $(this).addClass('hidden');
744    $('.calendar-addevent-details-txt-timezone').removeClass('hidden');
745    e.preventDefault();
746});
747               
748UI.dialogs.addEvent.find('.button.remove').button({
749    text:false,
750    icons:{
751        primary:'ui-icon-close'
752    }
753}).click(function(el){
754    var id;
755    if( id = $(this).parent().find('input[name="alarmId[]"]').val())
756        DataLayer.remove('alarm', id);
757    $(this).parent().remove().find('li').is(':empty');
758});
759
760var myCalendar = function(){
761        for(var i in Calendar.signatures)
762            if(Calendar.signatures[i].isOwner == "1")
763                return Calendar.signatures[i].calendar.id;
764}
765
766/*Seleciona a agenda padrão para visualização/edição de um evento*/
767if(objEvent.id)
768    UI.dialogs.addEvent.find('option[value="'+objEvent.calendar+'"]').attr('selected','selected').trigger('change');
769
770/*Adicionar alarms padrões, quando alterado a agenda do usuário*/               
771UI.dialogs.addEvent.find('select[name="calendar"]').change(function(){
772    if((typeof($('input[name = "idEvent"]').val()) == 'undefined') || (!!!$('input[name = "idEvent"]').val())) {
773        $('input[name = "isDefaultAlarm[]"]').parent().remove();
774        UI.dialogs.addEvent.find('input[name="defaultAlarm"]').parent().removeClass('hidden');
775        var calendarSelected = Calendar.signatureOf[$(this).val()];
776        calendarSelected.useAlarmDefault = 1;
777        if(calendarSelected.defaultAlarms != ""){
778            var li_attach = DataLayer.render(path+'templates/alarms_add_itemlist.ejs', {
779                alarm:calendarSelected
780            });
781            jQuery('.event-alarms-list').append(li_attach).find('.button.remove').button({
782                text:false,
783                icons:{
784                    primary:'ui-icon-close'
785                }
786            }).click(function(el) {
787            $(this).parent().remove().find('li').is(':empty');
788        });
789
790    }else{
791        UI.dialogs.addEvent.find('input[name="defaultAlarm"]').parent().addClass('hidden');
792    }
793}
794
795    var participant =  UI.dialogs.addEvent.find('dd.me input[name="attendee[]"]').val();
796    var calendar = $(this).val();
797   
798    if( !parseInt(Calendar.signatureOf[calendar].isOwner) ){
799        var signature = Calendar.signatureOf[calendar];
800        var organizer = DataLayer.get('calendarSignature', {
801            filter: ['AND', ['=','calendar',signature.calendar.id], ['=','isOwner','1']],
802            criteria: {
803                deepness: 2
804            }
805        });
806                           
807    if($.isArray(organizer))
808        organizer = organizer[0];
809    DataLayer.put('participant', {
810        id: participant,
811        user: organizer.user.id,
812        mail: organizer.user.mail
813        });
814                           
815    UI.dialogs.addEvent.find('dt.me').html(organizer.user.name);
816    UI.dialogs.addEvent.find('li.organizer input[name="attendee_organizer"]').val(participant);
817    UI.dialogs.addEvent.find('li.organizer label').filter('.name').html(organizer.user.name).end()
818    .filter('.mail').html(organizer.user.mail).attr('title',organizer.user.mail);
819
820}else{
821    UI.dialogs.addEvent.find('dt.me').html(User.me.name);
822    DataLayer.put('participant', {
823        id: participant,
824        user: User.me.id,
825        mail: User.me.mail
826        });
827    UI.dialogs.addEvent.find('li.organizer input[name="attendee_organizer"]').val(participant);
828    UI.dialogs.addEvent.find('li.organizer label').filter('.name').html(User.me.name).end()
829    .filter('.mail').html(User.me.mail).attr('title',User.me.mail);
830}
831
832});
833
834/*Checkbox adicionar alarms padrões*/
835UI.dialogs.addEvent.find('input[name="defaultAlarm"]').click(function(){
836    if($(this).attr("checked")){
837        $('input[name="isDefaultAlarm[]"]').parent().remove();
838        var calendarSelected = Calendar.signatureOf[$('select[name="calendar"]').val()];
839        calendarSelected.useAlarmDefault = 1;
840        if(calendarSelected.defaultAlarms != ""){
841            var li_attach = DataLayer.render(path+'templates/alarms_add_itemlist.ejs', {
842                alarm:calendarSelected
843            });
844            jQuery('.event-alarms-list').append(li_attach).find('.button.remove').button({
845                text:false,
846                icons:{
847                    primary:'ui-icon-close'
848                }
849            }).click(function(el) {
850            var id;
851            if( id = $(this).parent().find('input[name="alarmId[]"]').val())
852                DataLayer.remove('alarm', id);
853            $(this).parent().remove().find('li').is(':empty')
854        });
855    }
856} else {
857    $('input[name="isDefaultAlarm[]"]').parent().remove();
858}
859});
860/* Checkbox allday */
861UI.dialogs.addEvent.find('input[name="allDay"]').click(function(){
862    $(this).attr("checked") ?
863    UI.dialogs.addEvent.find('.start-time, .end-time').addClass('hidden') :
864    UI.dialogs.addEvent.find('.start-time, .end-time').removeClass('hidden');
865    updateMap(true);
866});
867
868UI.dialogs.addEvent.find('.button').button();
869UI.dialogs.addEvent.find('.button.add').button({
870    icons: {
871        secondary: "ui-icon-plus"
872    }
873});
874
875// ==== validation events ====
876UI.dialogs.addEvent.find(".input-group .h1").Watermark("Evento sem título");
877if(User.preferences.hourFormat.length == 5) {
878    UI.dialogs.addEvent.find(".end-time, .start-time").mask("99:99", {
879        completed: function(){
880            updateMap();
881        }
882    });
883} else {
884    $.mask.definitions['{']='[ap]';
885    $.mask.definitions['}']='[m]';
886    UI.dialogs.addEvent.find(".end-time, .start-time").mask("99:99 {}", {
887        completed:function(){
888            $(this).val(date.Calendar.defaultToAmPm($(this).val()));
889            $(this).timepicker("refresh");
890            $(this).val($(this).val().replace(/[\.]/gi, ""));
891            updateMap();
892        }
893    });
894}
895UI.dialogs.addEvent.find(".number").numeric();
896User.preferences.dateFormat.indexOf('-') > 0 ?
897UI.dialogs.addEvent.find(".date").mask("99-99-9999", {
898    completed:function(){
899        updateMap();
900    }
901}) :
902UI.dialogs.addEvent.find(".date").mask("99/99/9999", {
903    completed:function(){
904        updateMap();
905    }
906});
907
908UI.dialogs.addEvent.find(".menu-addevent")
909.children(".delete").click(function(){
910    $.Zebra_Dialog('Tem certeza que deseja excluir o evento?', {
911        'type':     'question',
912        'overlay_opacity': '0.5',
913        'buttons':  ['Sim', 'Não'],
914        'onClose':  function(clicked) {
915            if(clicked == 'Sim'){
916                canDiscardEventDialog = true;
917                /* Remove por filtro */
918                DataLayer.removeFilter('schedulable', {filter: ['AND', ['=', 'id', objEvent.id], ['=', 'calendar', objEvent.calendar], ['=','user',(objEvent.me.user ? objEvent.me.user.id : objEvent.me.id)]]});
919                Calendar.rerenderView(true);
920                /********************/
921                UI.dialogs.addEvent.dialog("close");
922            }
923        }
924    });
925}).end()
926           
927.children(".cancel").click(function(){
928    UI.dialogs.addEvent.dialog("close");
929}).end()
930           
931.children(".save").click(function(){
932    /* Validação */
933    var msg = false;                   
934    if(msg = validDateEvent()){
935        $(".new-event-win.active").find('.messages-validation').removeClass('hidden').find('.message label').html(msg);
936        return false;
937    }
938                       
939    canDiscardEventDialog = true;
940                       
941    var exit = function(event){
942        if(event)
943            DataLayer.remove('schedulable', event, false);
944
945        UI.dialogs.addEvent.children().find('form.form-addevent').submit();
946        UI.dialogs.addEvent.dialog("close");
947    }
948                       
949    if(repeat){
950        DataLayer.remove('repeat', false);
951        DataLayer.put('repeat', repeat);
952        DataLayer.commit('repeat', false, exit(repeat.schedulable));
953    }else
954        exit();
955}).end()
956               
957.children(".export").click(function(){
958    UI.dialogs.addEvent.children().find(".form-export").submit();
959});
960
961var dates = UI.dialogs.addEvent.find('input.date').datepicker({
962    dateFormat: User.preferences.dateFormat.replace(/M/g, 'm').replace(/yyyy/g, 'yy'),
963    onSelect : function( selectedDate ){
964        updateMap();
965    }
966});
967//if(path == ""){
968UI.dialogs.addEvent.find('input.time').timepicker({
969    closeText: 'Ok',
970    hourGrid: 4,
971    minuteGrid: 10,
972    ampm : ((User.preferences.hourFormat.length > 5) ? true: false),
973    timeFormat: "hh:mm tt",
974    onSelect: function (selectedDateTime){
975        if ((selectedDateTime.value == '__:__') || (selectedDateTime.value == '__:__ __'))
976                          selectedDateTime.value = "";
977                if(!(User.preferences.hourFormat.length == 5))
978                $(this).val(selectedDateTime.replace(/[\.]/gi, ""));                                                           
979                updateMap();
980    },
981    onClose : function (selectedDateTime){
982        if(!(User.preferences.hourFormat.length == 5))
983            $(this).val(selectedDateTime.replace(/[\.]/gi, ""));
984    },
985    beforeShow: function (selectedDateTime) {
986                if ((selectedDateTime.value == '__:__') || (selectedDateTime.value == '__:__ __'))
987                        selectedDateTime.value = "";
988    }
989});
990//}
991
992UI.dialogs.addEvent.find('.button-add-alarms').click(function(){
993    var li_attach = DataLayer.render(path+'templates/alarms_add_itemlist.ejs', {});
994
995    jQuery('.event-alarms-list').append(li_attach).find('.button.remove').button({
996        text:false,
997        icons:{
998            primary:'ui-icon-close'
999        }
1000    }).click(function(el) {
1001    $(this).parent().remove().find('li').is(':empty')
1002});
1003// valicacao de campos numericos
1004$('.number').numeric();
1005});
1006           
1007                 
1008UI.dialogs.addEvent.find('.button.suggestion-hours').button({
1009    icons: {
1010        primary: "ui-icon-clock"
1011    },
1012    text: 'Sugerir horário'
1013}).click(function () {
1014    $(this).siblings('input').removeAttr('disabled')
1015    .end().parents().find('input[name="allDay"]').removeAttr('disabled');               
1016});
1017
1018
1019if(!repeat)
1020    if(objEvent.me.id == User.me.id){
1021        objEvent.me.id = DataLayer.put('participant', {
1022            user: objEvent.me.id,
1023            mail: objEvent.me.mail
1024            });
1025        objEvent.organizer.id = objEvent.me.id;
1026    }
1027
1028var attendeeHtml = DataLayer.render( path+'templates/attendee_add.ejs', {
1029    event:objEvent
1030});
1031       
1032// load template of attendees
1033var blkAddAtendee = UI.dialogs.addEvent.find('#calendar_addevent_details6').append(attendeeHtml);
1034if(objEvent.attendee.length)
1035                callbackAttendee();
1036/**
1037Opções de delegação do participante/organizer
1038*/             
1039blkAddAtendee.find(".button.participant-delegate").button({
1040    icons: {
1041        primary: "ui-icon-transferthick-e-w"
1042    },
1043    text: false
1044}).click(function () {
1045    if($(this).hasClass('attendee-permissions-change-button')){
1046        if(!$(this).hasClass('disable')){
1047            $(this).removeClass('attendee-permissions-change-button')   
1048            .find('.ui-icon-transferthick-e-w').removeClass('attendee-permissions-change').end();               
1049            blkAddAtendee.find('.block-add-attendee.search').addClass('hidden');
1050            blkAddAtendee.find('.block-add-attendee.search dt').html('Adicionar outros contatos');
1051        }
1052    }else{                                                                     
1053        $(this).addClass('attendee-permissions-change-button')   
1054        .find('.ui-icon-transferthick-e-w').addClass('attendee-permissions-change').end();               
1055        blkAddAtendee.find('.block-add-attendee.search dt').html('Delegar participação para');
1056        blkAddAtendee.find('.block-add-attendee.search').removeClass('hidden');
1057        blkAddAtendee.find('.block-add-attendee.search input.search').focus();
1058    }
1059})
1060.addClass('tiny');             
1061                       
1062//show or hidden permissions attendees
1063//blkAddAtendee.find('.block-attendee-list #attendees-users li').click(show_permissions_attendees);
1064
1065UI.dialogs.addEvent.find(".attendee-list-add .add-attendee-input input").Watermark("digite um email para convidar");
1066/*
1067 * Trata a edição de um novo participante adicionado
1068 */
1069var hasNewAttendee = false;
1070                       
1071blkAddAtendee.find('.attendee-list-add .add-attendee-input span').click(function(data){
1072    blkAddAtendee.find('.attendee-list-add .add-attendee-input input').keydown();
1073});
1074                       
1075blkAddAtendee.find('.attendee-list-add .add-attendee-input input').keydown(function(event) {
1076    if (event.keyCode == '13' && $(this).val() != '' || (event.keyCode == undefined && $(this).val() != '')) {
1077        Encoder.EncodeType = "entity";
1078        $(this).val(Encoder.htmlEncode($(this).val()));
1079                                       
1080        newAttendeeEmail = false;
1081        newAttendeeName  = false;
1082        skipAddNewLine   = false;
1083
1084        var info = $(this).val();
1085
1086        /**
1087        * email válido?
1088        */
1089        info.match(/^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/) ?
1090        newAttendeeEmail = info : newAttendeeName = info;
1091
1092        /**
1093        * 1) busca no banco para saber se o usuário já existe
1094        *               1.1) se existe, atualiza as info na lista de participantes e nao abre o tooltip
1095        *               1.2) se não existe
1096        *                       a) salva como novo usuario externo no banco (apenas com email)
1097        *                       b) exibe tooltip pedindo o nome
1098        *                       c) se o usuário preenche tooltip e salva, atualiza com o nome o usuário recém criado
1099        *                       d) se o usuário cancela o tooltip, fica o usuário salvo apenas com email e sem nome
1100        */
1101
1102        var user = DataLayer.get('user', ["=", "mail", $(this).val()]);
1103        if(!!user && user[0].id)
1104            attendees[user[0].id] = {
1105                name: user[0].name
1106                };
1107                                       
1108        /**
1109        * guarda o último tooltip aberto referente à lista de participantes
1110        */
1111        lastEditAttendeeToolTip = [];
1112
1113        /**
1114        * Valida email e salva um participante externo
1115        */
1116        var saveContact = function() {
1117            Encoder.EncodeType = "entity";
1118
1119            var currentTip = $('.qtip-active');
1120            newAttendeeName  = currentTip.find('input[name="name"]').val();
1121            newAttendeeEmail = currentTip.find('input[name="mail"]').val();
1122
1123            if (!(!!newAttendeeEmail.match(/^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/))) {
1124                currentTip.find('.messages').removeClass('hidden').find('.message label').html('Email inválido.');
1125                return false;
1126            }
1127
1128            DataLayer.put('user', {
1129                id:userId,
1130                name:newAttendeeName,
1131                mail:newAttendeeEmail,
1132                isExternal:isExternal
1133            });
1134
1135            lastEditAttendeeToolTip.find('label')
1136            .filter('.name').html(Encoder.htmlEncode(newAttendeeName)).attr('title', Encoder.htmlEncode(newAttendeeName)).end()
1137            .filter('.mail').html(Encoder.htmlEncode(newAttendeeEmail)).attr('title', Encoder.htmlEncode(newAttendeeEmail));
1138
1139            blkAddAtendee.find('.attendee-list-add .add-attendee-input input').val('');
1140            return true;
1141        }
1142                                               
1143        /**
1144                                         * Formata e adequa um tootip abert para edição de um participante na lista
1145                                         */
1146        var onShowToolTip = function(arg0) {
1147            $('.qtip-active .button.close').button({
1148                icons: {
1149                    primary: "ui-icon-close"
1150                },
1151                text: false
1152            });
1153            $('.qtip-active .button').button()
1154            .filter('.save').click(function(event, ui) {
1155                if(saveContact())
1156                    lastEditAttendeeToolTip.qtip("destroy");
1157                else
1158                    return false;
1159            }).end()
1160            .filter('.cancel').click(function(event, ui) {
1161                lastEditAttendeeToolTip.qtip("destroy");
1162            })
1163
1164            /**
1165                                                 * Trata o ENTER no campo da tooltip, equivalente a salvar
1166                                                 * o novo convidado.
1167                                                 */
1168            $('.qtip-active input').keydown(function(event) {
1169                if (event.keyCode == '13') {                                           
1170                    if (saveContact())                                         
1171                        lastEditAttendeeToolTip.qtip("destroy");
1172                       
1173                    lastEditAttendeeToolTip.qtip("destroy");
1174                    event.preventDefault();
1175                }
1176            })
1177            .filter('[name="name"]').Watermark("informe o nome do contato").end()
1178            .filter('[name="mail"]').Watermark("informe o email do contato");
1179        }
1180                                       
1181        /**
1182                                         * Se o email digitado já foi adicionado na lista,
1183                                         * o usuário deve ser avisado e um botão de edição deve ser exibido
1184                                         */
1185        if(blkAddAtendee.find('label.mail[title="' + newAttendeeEmail + '"]').length) {
1186            hasNewAttendee  = false;
1187            newAttendeeName = blkAddAtendee.find('label.mail[title="' + newAttendeeEmail + '"]').parents('li').find('label.name').attr('title');
1188
1189            blkAddAtendee.find('.email-validation').removeClass('hidden')
1190            .find('.message label').html("O usuário acima já foi adicionado! <a class=\"small button\">Editar</a>")
1191            .find(".button").button().click(function () {
1192                /**
1193                                                         * Se o usuário optar por editar o participante anteriormente adicionado,
1194                                                         * uma tooltip deve ser aberta para este participante, viabilizando a edição
1195                                                         */
1196                blkAddAtendee.find("ul.attendee-list").scrollTo('label.mail[title="' + newAttendeeEmail + '"]');
1197                /**
1198                                                         * Remove tooltip possivelmente existente
1199                                                         */
1200                if (lastEditAttendeeToolTip.length && lastEditAttendeeToolTip.data('qtip'))
1201                    lastEditAttendeeToolTip.qtip('destroy');
1202                                       
1203                lastEditAttendeeToolTip = blkAddAtendee.find('label.mail[title="' + newAttendeeEmail + '"]').parents('li');
1204                lastEditAttendeeToolTip.qtip({
1205                    show: {
1206                        ready: true,
1207                        solo: true,
1208                        when: {
1209                            event: 'click'
1210                        }
1211                    },
1212                hide: false,
1213                content: {
1214                    text: $('<div></div>').html( DataLayer.render( path+'templates/attendee_quick_edit.ejs', {
1215                        attendee:{
1216                            name:newAttendeeName,
1217                            mail:newAttendeeEmail
1218                        }
1219                    } ) ),
1220                title: {
1221                    text:'Detalhes do participante',
1222                    button: '<a class="button close" href="#">close</a>'
1223                }
1224                },
1225                style: {
1226                    name: 'blue',
1227                    tip: {
1228                        corner: 'leftMiddle'
1229                    },
1230                    border: {
1231                        width: 4,
1232                        radius: 8
1233                    },
1234                    width: {
1235                        min: 230,
1236                        max:230
1237                    }
1238                },
1239            position: {
1240                corner: {
1241                    target: 'rightMiddle',
1242                    tooltip: 'leftMiddle'
1243                },
1244                adjust: {
1245                    x:0,
1246                    y:0
1247                }
1248            }
1249            });
1250        lastEditAttendeeToolTip.qtip("api").onShow = onShowToolTip;
1251    });
1252skipAddNewLine = true;
1253} else {
1254    hasNewAttendee  = true;
1255    blkAddAtendee.find('.email-validation').addClass('hidden');
1256}
1257                                       
1258                                       
1259var isExternal = (!!user && !(!!user.isExternal)) ? 0 : 1;
1260
1261/**
1262                                         * Remove tooltip possivelmente existente
1263                                         */
1264if (lastEditAttendeeToolTip.length && lastEditAttendeeToolTip.data('qtip'))
1265    lastEditAttendeeToolTip.qtip('destroy');
1266
1267userId = '';
1268var newAttendeeId = '';
1269
1270if (user){
1271    if (!skipAddNewLine) {
1272        user[0].id =  DataLayer.put('participant', {
1273            user: user[0].id,
1274            isExternal: isExternal,
1275            acl: 'r'
1276        });
1277        user[0].acl = objEvent.acl;
1278        user[0].isDirty = !!!objEvent.id;
1279        user[0].isDelegate = (objEvent.id && (objEvent.me.status == '5'));
1280
1281        blkAddAtendee.find('dd.attendee-list ul.attendee-list').append(
1282            DataLayer.render(path+'templates/participants_add_itemlist.ejs', user)
1283            )
1284        .scrollTo('max');
1285        callbackAttendee();
1286    }
1287                                               
1288    $(this).val('');
1289
1290} else if (!skipAddNewLine) {
1291    /**
1292     * a) salva como novo usuario externo no banco (apenas com email) e...
1293     * adiciona novo contato externo à lista de convidados
1294     */
1295
1296    userId = DataLayer.put('user', {
1297        name: newAttendeeName,
1298        mail: newAttendeeEmail,
1299        isExternal: isExternal
1300    });
1301    newAttendeeId = DataLayer.put('participant', {
1302        user: userId,
1303        isExternal: isExternal
1304    });
1305
1306                                                 
1307    blkAddAtendee.find('dd.attendee-list ul.attendee-list').append(
1308        DataLayer.render(path+'templates/participants_add_itemlist.ejs', [{
1309            id:newAttendeeId,
1310            name: newAttendeeName,
1311            mail: newAttendeeEmail,
1312            isExternal: 1,
1313            acl: objEvent.acl,
1314            isDirty: !!!objEvent.id,
1315        isDelegate: (objEvent.id && (objEvent.me.status == '5'))
1316            }])
1317        ).scrollTo('max');
1318    callbackAttendee();
1319
1320    /**
1321                                                 * Adiciona tootip para atualização dos dados do contato externo
1322                                                 * recém adicionado.
1323                                                 */
1324    lastEditAttendeeToolTip = blkAddAtendee.find('dd.attendee-list li:last');
1325    lastEditAttendeeToolTip.qtip({
1326        show: {
1327            ready: true,
1328            solo: true,
1329            when: {
1330                event: 'click'
1331            }
1332        },
1333    hide: false,
1334    content: {
1335        text: $('<div></div>').html( DataLayer.render( path+'templates/attendee_quick_edit.ejs', {
1336            attendee:{
1337                name:newAttendeeName,
1338                mail:newAttendeeEmail
1339            }
1340        } ) ),
1341    title: {
1342        text:'Detalhes do participante',
1343        button: '<a class="button close" href="#">close</a>'
1344    }
1345    },
1346    style: {
1347        name: 'blue',
1348        tip: {
1349            corner: 'leftMiddle'
1350        },
1351        border: {
1352            width: 4,
1353            radius: 8
1354        },
1355        width: {
1356            min: 230,
1357            max:230
1358        }
1359    },
1360position: {
1361    corner: {
1362        target: 'rightMiddle',
1363        tooltip: 'leftMiddle'
1364    },
1365    adjust: {
1366        x:0,
1367        y:0
1368    }
1369}
1370});
1371                       
1372lastEditAttendeeToolTip.qtip("api").onShow = onShowToolTip;
1373
1374$(this).val('');
1375
1376                                               
1377}
1378event.preventDefault();
1379}
1380                               
1381});
1382
1383/**
1384* Trata a busca de usuários para adição de participantes
1385*/
1386blkAddAtendee.find('.add-attendee-search .ui-icon-search').click(function(event) {
1387    blkAddAtendee.find('.add-attendee-search input').keydown();
1388});
1389                       
1390                       
1391blkAddAtendee.find('.add-attendee-search input').keydown(function(event) {
1392
1393    if(event.keyCode == '13' || typeof(event.keyCode) == 'undefined') {                 
1394        var result = DataLayer.get('user', ["*", "name", $(this).val()], true);
1395
1396        /**
1397        * TODO: trocar por template
1398        */
1399        blkAddAtendee.find('ul.search-result-list').empty().css('overflow', 'hidden');
1400        if (!result) {
1401            blkAddAtendee.find('ul.search-result-list').append('<li><label class="empty">Nenhum resultado encontrado.</label></li>');
1402        }
1403
1404        for(i=0; i<result.length; i++)
1405            result[i].enabled = (blkAddAtendee.find('dd.attendee-list ul.attendee-list label.mail[title="' +  result[i].mail + '"]').length) ? false : true;
1406                                                                                       
1407        blkAddAtendee.find('ul.search-result-list').append(DataLayer.render( path+'templates/participants_search_itemlist.ejs', result));
1408
1409        blkAddAtendee.find('ul.search-result-list li').click(function(event, ui){
1410            if ($(event.target).is('input')) {
1411                old_item = $(event.target).parents('li');
1412                newAttendeeId = DataLayer.put('participant', {
1413                    user: old_item.find('.id').html(),
1414                    isExternal: old_item.find('.isExternal').html()
1415                });
1416                                                       
1417                attendees[old_item.find('.id').html()] = old_item.find('.name').html();
1418                                                       
1419                blkAddAtendee.find('dd.attendee-list ul.attendee-list')
1420                .append(DataLayer.render(path+'templates/participants_add_itemlist.ejs', [{
1421                    id: newAttendeeId,
1422                    name: old_item.find('.name').html(),
1423                    mail: old_item.find('.mail').html(),
1424                    isExternal: old_item.find('.isExternal').html(),
1425                    acl: objEvent.acl,
1426                    isDirty: !!!objEvent.id,
1427            isDelegate: (objEvent.id && (objEvent.me.status == '5'))
1428                    }]))
1429                .scrollTo('max');
1430                /**
1431                                                        * Delegação de participação de um participante com permissão apenas de leitura
1432                                                        *
1433                                                        */
1434                if(!objEvent.acl.organization && !objEvent.acl.write && !objEvent.acl.inviteGuests && objEvent.acl.read ){
1435                                                               
1436                    blkAddAtendee.find('.block-add-attendee.search').addClass('hidden');
1437                    blkAddAtendee.find('.block-add-attendee.search dt').html('Adicionar outros contatos');
1438                                                               
1439                    blkAddAtendee.find('.status option').toggleClass('hidden');
1440                    blkAddAtendee.find('option[value=5]').attr('selected','selected').trigger('change');
1441                    blkAddAtendee.find('.request-update').removeClass('hidden');
1442
1443                    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());
1444                                                               
1445                    blkAddAtendee.find('.me .participant-delegate').addClass('disable ui-button-disabled ui-state-disabled');
1446                    blkAddAtendee.find(".button.close").button({
1447                        icons: {
1448                            primary: "ui-icon-close"
1449                        },
1450                        text: false
1451                    }).click(function () {
1452                                                                       
1453                        $(this).parents('li').find('input[name="delegatedFrom[]"]').val('');
1454                        blkAddAtendee.find('.request-update').addClass('hidden');
1455                        blkAddAtendee.find('.status option').toggleClass('hidden');
1456                        blkAddAtendee.find('option[value=1]').attr('selected','selected').trigger('change');                   
1457                        blkAddAtendee.find('.me .participant-delegate').removeClass('disable ui-button-disabled ui-state-disabled attendee-permissions-change-button')
1458                        .find('.ui-icon-person').removeClass('attendee-permissions-change').end();                     
1459                                                                       
1460                        DataLayer.remove('participant', $(this).parents('li').find('[type=checkbox]').val());
1461                        $(this).parents('li').remove();
1462                    })
1463                    .addClass('tiny');
1464                }else{
1465                    callbackAttendee();
1466                    old_item.remove();
1467                }
1468            }
1469        });
1470
1471        event.preventDefault();
1472    }
1473});
1474
1475//$('.block-add-attendee .search-result-list').selectable();
1476
1477UI.dialogs.addEvent.find('.row.fileupload-buttonbar .button').filter('.delete').button({
1478    icons: {
1479        primary: "ui-icon-close"
1480    },
1481    text: 'Excluir'
1482}).click(function () {
1483    $.Zebra_Dialog('Tem certeza que deseja excluir todos anexos?', {
1484        'type':     'question',
1485        'overlay_opacity': '0.5',
1486        'buttons':  ['Sim', 'Não'],
1487        'onClose':  function(clicked) {
1488            if(clicked == 'Sim'){
1489               
1490                var ids = [];
1491                $.each($('.attachment-list input'), function (i, input) {
1492                     DataLayer.remove('schedulableToAttachment', {
1493                        filter: ['=', 'id', ''+input.value]
1494                        });
1495                });
1496                $('div.new-event-win .attachment-list input').remove();
1497                $('div.new-event-win .row.fileupload-buttonbar .attachments-list p').remove();
1498                $('div.new-event-win .btn-danger.delete').addClass('hidden');
1499            }
1500        }});
1501}).end()
1502.filter('.close').button({
1503    icons: {
1504        primary: "ui-icon-close"
1505    },
1506    text: false
1507}).click(function () {
1508    DataLayer.remove('schedulableToAttachment', $(this).parents('p').find('input[name="fileId[]"]').val());
1509    $(this).parents('p').remove();
1510}).end()
1511.filter('.downlaod-archive').button({
1512    icons: {
1513        primary: "ui-icon-arrowthickstop-1-s"
1514    },
1515    text: false
1516});
1517
1518extendsFileupload('event', path);
1519       
1520if(objEvent.isShared){
1521               
1522    var acls = Calendar.signatureOf[objEvent.calendar].permission.acl;
1523               
1524    if(!acls.write){
1525        UI.dialogs.addEvent.find(':input').attr('disabled', 'disabled');
1526        UI.dialogs.addEvent.find('.button').hide();
1527    }
1528               
1529    if(acls.remove)
1530        UI.dialogs.addEvent.find('.button.remove').show();
1531   
1532    UI.dialogs.addEvent.find('.button.cancel').show(); 
1533}
1534
1535disponibily(objEvent, path, attendees, 'event');
1536
1537/*Seleciona a agenda padrão para criação de um evento*/
1538if(!objEvent.id){
1539    var selectedCalendar = (objEvent.calendar != undefined) ? objEvent.calendar : (User.preferences.defaultCalendar ? User.preferences.defaultCalendar : myCalendar());
1540    UI.dialogs.addEvent.find('option[value="'+selectedCalendar+'"]').attr('selected','selected').trigger('change');
1541}
1542UI.dialogs.addEvent.find(':input').change(function(event){
1543    if (event.keyCode != '27' && event.keyCode != '13')
1544        canDiscardEventDialog = false;
1545}).keydown(function(event){
1546    if (event.keyCode != '27' && event.keyCode != '13')
1547        canDiscardEventDialog = false;
1548});     
1549
1550UI.dialogs.addEvent.dialog('open');
1551
1552}
1553
1554
1555
1556function add_tab_preferences()
1557{
1558    if(!(document.getElementById('preference_tab')))
1559    {
1560        var tab_title = "Preferencias";
1561        $tabs.tabs( "add", "#preference_tab", tab_title );
1562               
1563        /*
1564                DataLayer.render( 'templates/timezone_list.ejs', {}, function( timezones_options ){
1565                        tabPrefCalendar.find('select[name="timezone"]').html(timezones_options).find('option[value="'+User.preferences.timezone+'"]').attr('selected','selected').trigger('change');
1566                });
1567                */
1568        DataLayer.render( 'templates/preferences_calendar.ejs', {
1569            preferences:User.preferences,
1570            calendars: Calendar.calendars,
1571        signatureOf : Calendar.signatureOf
1572            }, function( template ){
1573            var tabPrefCalendar = jQuery('#preference_tab').html( template ).find('.preferences-win');
1574               
1575            tabPrefCalendar.find('select[name="defaultCalendar"] option[value="'+User.preferences.defaultCalendar+'"]').attr('selected','selected').trigger('change');
1576        tabPrefCalendar.find('select[name="dafaultImportCalendar"] option[value="'+User.preferences.dafaultImportCalendar+'"]').attr('selected','selected').trigger('change');
1577 
1578        DataLayer.render( 'templates/timezone_list.ejs', {}, function( timezones_options ){
1579
1580                tabPrefCalendar.find('select[name="timezone"]').html(timezones_options).find('option[value="'+User.preferences.timezone+'"]').attr('selected','selected').trigger('change');
1581            });
1582               
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            });
1592                       
1593            tabPrefCalendar.find('.number').numeric();
1594                       
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            });
1612                       
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            });
1622                                                           
1623            tabPrefCalendar.find("select[name=hourFormat]").change( function() { // evento ao selecionar formato de hora
1624               
1625                tabPrefCalendar.find("input.time").timepicker("destroy");
1626
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                });
1644                               
1645                var defaultStartHour = tabPrefCalendar.find("input[name=defaultStartHour]").val().trim();
1646                var defaultEndHour = tabPrefCalendar.find("input[name=defaultEndHour]").val().trim();
1647               
1648                tabPrefCalendar.find("input.time").mask( (($("select[name=hourFormat] option:selected").val().trim().length > 5) ? "99:99 {}" : "99:99") );
1649               
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))
1653                                       
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            });                 
1659                       
1660                       
1661                       
1662        });             
1663    } else {
1664        $tabs.tabs("select", "#preference_tab");
1665               
1666        return true;
1667    }
1668}
1669
1670
1671function add_tab_configure_calendar(calendar, type)
1672{
1673    $('.qtip.qtip-blue').remove();
1674
1675    var calendars = [];
1676    var signatures = [];
1677    var previewActiveCalendarConf = 0;
1678        var calendarAlarms = [];
1679       
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])))
1692    {
1693        $('.positionHelper').css('display', 'none');
1694        $('.cal-list-options-btn').removeClass('fg-menu-open ui-state-active');
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 );
1701               
1702        var dataColorPicker = {
1703            colorsSuggestions: colors_suggestions()
1704        };
1705               
1706               
1707               
1708        var populateAccordionOnActive = function(event, ui) {
1709            var nowActive = (typeof(event) == 'number') ? event : $(event.target).accordion( "option", "active" );
1710            if (nowActive === false)
1711                        return;
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            }
1720
1721            DataLayer.render( 'templates/configure_calendars_itemlist.ejs', {
1722                user:User,
1723                type:0,
1724                calendar:calendars[nowActive],
1725                signature:signatures[nowActive]
1726                }, function( form_template ){
1727                var form_content = jQuery('#'+tab_selector[type]+' .accordion-user-calendars .ui-accordion-content').eq(nowActive).html( form_template ).find('form');
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();
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       
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                });
1744
1745                form_content.find('.button-add-alarms').click(function(){
1746                    DataLayer.render( 'templates/alarms_add_itemlist.ejs', {type: (parseInt(type) == 1 ? '4' : type) }, function( template ){
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                });
1760
1761
1762            /**
1763                                 * Set color picker
1764                                 */
1765            DataLayer.render( 'templates/calendar_colorpicker.ejs', dataColorPicker, function( template ){
1766                form_content.find('.calendar-colorpicker').html( template );
1767
1768                var f = $.farbtastic(form_content.find('.colorpicker'), colorpickerPreviewChange);
1769                var selected;
1770                var colorpicker = form_content.find('.calendar-colorpicker');
1771                                       
1772                var colorpickerPreviewChange = function(color) {
1773                    var pickedup = form_content.find('.colorwell-selected').val(color).css('background-color', color);
1774
1775                    var colorpicker = form_content.find('.calendar-colorpicker');
1776
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                }
1785                                       
1786                form_content.find('.colorwell').each(function () {
1787                    f.linkTo(this);
1788
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                    }
1801
1802                    $(selected = this).addClass('colorwell-selected');
1803                    f.linkTo(this, colorpickerPreviewChange);
1804                    f.linkTo(colorpickerPreviewChange);
1805
1806                });
1807
1808                form_content.find('select.color-suggestions').change(function() {
1809                    var colors;
1810
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()
1816
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                });
1824
1825                /**
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                                         */
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
1838
1839            form_content.find('.phone').mask("+99 (99) 9999-9999");
1840            form_content.find('.number').numeric();
1841
1842        }); //END DataLayer.render( 'templates/configure_calendars_itemlist.ejs' ...
1843
1844// === validations preferences ====
1845
1846                       
1847} //END populateAccordionOnActive(event, ui)
1848               
1849
1850DataLayer.render( 'templates/configure_calendars.ejs', {
1851    user:User,
1852        type: type,
1853    calendars:calendars,
1854    signatures:signatures
1855}, function( template ){
1856    var template_content = jQuery('#'+tab_selector[type]).html( template ).find('.configure-calendars-win');
1857    template_content.find('.button').button().filter('.save').click(function(evt){
1858        if(calendarAlarms.length)
1859                DataLayer.removeFilter('calendarSignatureAlarm', {filter: ['IN','id', calendarAlarms]});       
1860        template_content.find('form').submit();
1861        $tabs.tabs( "remove", "#"+tab_selector[type]);
1862        DataLayer.commit( false, false, function( received ){
1863            delete Calendar.currentViewKey;
1864            Calendar.load();
1865            refresh_calendars();
1866        });
1867        if(calendarAlarms.length)
1868                Calendar.load();
1869    }).end().filter('.cancel').click(function(evt){
1870        $tabs.tabs( "remove", "#"+tab_selector[type]);
1871    });
1872
1873    /**
1874                         * Muda a estrutura do template para a aplicação do plugin accordion
1875                         */
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'));
1878                       
1879    template_content.find('.accordion-user-calendars').children('fieldset').each(function(index) {
1880        $(this).before($('<h3></h3>').html($(this).children('legend')));
1881    });
1882                       
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});
1892
1893} else {
1894        $('.positionHelper').css('display','none');
1895    $('.cal-list-options-btn').removeClass('fg-menu-open ui-state-active');
1896    $tabs.tabs("select", "#"+tab_selector[type]);
1897    $('.accordion-user-calendars').accordion( "activate" , previewActiveCalendarConf );
1898               
1899    return true;
1900}
1901
1902}
1903
1904function getSelectedCalendars( reverse, type ){
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 
1913    });
1914 
1915    if (!returns.length)
1916            return false;
1917 
1918    return returns;
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(){
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    ]           
1961}
1962
1963function remove_event(eventId, idCalendar, type){
1964    $.Zebra_Dialog('Tem certeza que deseja excluir?', {
1965        'type':     'question',
1966        'overlay_opacity': '0.5',
1967        'buttons':  ['Sim', 'Não'],
1968        'onClose':  function(clicked) {
1969            if(clicked == 'Sim'){
1970
1971                var schedulable = getSchedulable( eventId, '');
1972                schedulable.calendar = ''+idCalendar;
1973                var schudableDecode = DataLayer.encode( "schedulable:preview", schedulable);
1974                var me = schudableDecode.me.user ? schudableDecode.me.user.id : schudableDecode.me.id;
1975
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);
1982                Calendar.rerenderView(true);
1983            }
1984        }
1985    });
1986}
1987
1988function mount_exception(eventID, exception){
1989
1990    getSchedulable( eventID.toString() , '');
1991    var schedulable = DataLayer.get('schedulable', eventID.toString() )
1992    var edit = { repeat: (DataLayer.get('repeat', schedulable.repeat)) };
1993
1994    edit.repeat.startTime = new Date(parseInt(edit.repeat.startTime)).toString('yyyy-MM-dd HH:mm:00');
1995    edit.repeat.endTime = parseInt(edit.repeat.count) > 0 ? '0' : new Date(parseInt(edit.repeat.endTime)).toString('yyyy-MM-dd HH:mm:00');
1996   
1997    edit.repeat.exceptions = ( exception );
1998   
1999    return edit.repeat;
2000}
2001
2002function remove_ocurrence(eventId, idRecurrence){
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    });
2018}
2019
2020
2021function remove_calendar(type){
2022    /* Pode ser assim $('.cal-list-options-btn.ui-state-active').attr('class').replace(/[a-zA-Z-]+/g, ''); */
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, {
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);
2034                               
2035                DataLayer.remove('calendarSignature', Calendar.signatureOf[idCalendar[0]].id );
2036                               
2037                if(idCalendar == User.preferences.defaultCalendar)
2038                    DataLayer.remove( 'modulePreference', User.preferenceIds['defaultCalendar']);
2039                       
2040                DataLayer.commit( false, false, function( received ){
2041                    delete Calendar.currentViewKey;
2042                    Calendar.load();
2043                    refresh_calendars(type);
2044                });
2045            }
2046            $('.positionHelper').css('display', 'none');
2047       
2048        }
2049    });
2050}
2051
2052function refresh_calendars(type){
2053
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    }
2059
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 ){
2062       
2063        var meu_container = $(".calendars-list").html( html );
2064       
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        }
2087       
2088        doMenu();
2089        var currentToolTip = null;
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)
2094                            $('.positionHelper').css('top',offset.top);
2095                }
2096
2097                if ($('.button.config-menu.fg-menu-open')){
2098                        var offset = $('.button.config-menu.fg-menu-open').offset();
2099                        if (offset)
2100                            $('.positionHelper').css('top',offset.top);
2101                }               
2102
2103               
2104                if ($(".new-group.qtip-active").length || $(".new-calendar.qtip-active").length)                       
2105                    $('.qtip-active').css('top',currentToolTip.offset().top - 50);
2106               
2107        });
2108 
2109     $('ul.list-calendars .cal-list-options-btn').on('click',function(){doMenu();});         
2110       
2111
2112    /***************************************New Calendar***************************************/
2113        meu_container.find(".button.new-calendar").button({
2114            icons: {
2115                primary: "ui-icon-plus"
2116            },
2117            text: false
2118        }).click(function () {
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'}
2123               
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) {
2171                               
2172                    $('.qtip-active .button.close').button({
2173                          icons: { primary: "ui-icon-close" },
2174                          text: false
2175                    })
2176                    .click(function(){
2177                                $('.qtip.qtip-blue').remove();
2178                    });
2179                   
2180                $('.qtip-active').addClass(typeCalendar.type);
2181
2182                    $('.qtip-active .button.cancel').button().click(function(){
2183                                $('.qtip.qtip-blue').remove();
2184                    });
2185                               
2186
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                    });
2224       
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           }
2243    });
2244
2245    $("img.cal-list-img").click(function(evt) {
2246           $(".cal-list-options_1").toggleClass( "hidden" );
2247    });
2248
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
2255    $(".my-calendars a.title-my-calendars").click(function() {
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");
2259    });
2260               
2261    $(".signed-calendars a.title-signed-calendars").click(function() {
2262           $(".signed-calendars ul.signed-list-calendars").toggleClass( "hidden");
2263    });
2264
2265    $("ul li.list-calendars-item").click(function(evt) {
2266       
2267        });   
2268
2269    $("ul li.list-calendars-item .ui-corner-all").click(function(evt) {
2270        //alert('teste');
2271        });   
2272       
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    });
2281       
2282       
2283    meu_container.find('.title-signed-calendars').click(function(evt){
2284        var status = $(this).parent().find('.status-list-shared');
2285                       
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    });
2291               
2292    $('.calendar-view').click(function(evt){
2293 
2294        var checkBox = $(this);
2295        var calendarId = $(this).val();
2296 
2297        Calendar.signatureOf[ calendarId ].hidden =  (checkBox.is(':checked') ? 0 : 1 );
2298 
2299        DataLayer.put('calendarSignature', {id: Calendar.signatureOf[ calendarId ].id , hidden: Calendar.signatureOf[ calendarId ].hidden }  );
2300        DataLayer.commit();
2301 
2302 
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         }
2317    });
2318});
2319}
2320
2321function add_events_list(keyword, type)
2322{
2323    if ($.trim(keyword) == "") return;
2324    var tab_title = "";
2325    if (keyword){
2326                type = 2;
2327                if(keyword.length < 10)
2328                        tab_title = keyword;
2329                else
2330                        tab_title = keyword.substr(0,10) + '..."';
2331    }else{
2332                if(type){
2333                        if(!!parseInt(type))
2334                                tab_title = "Lista de tarefas";
2335                        else
2336                                tab_title = "Lista de eventos";
2337                }
2338    }
2339        var tab_selector = ['tab_events_list_', 'tab_tasks_list_', 'tab_all_list_'];
2340    keyword = ( keyword || '' ).replace( /\s+/g, "_" );
2341       
2342    if(!(document.getElementById(tab_selector[type] + (Base64.encode(keyword)).replace(/[^\w\s]/gi, "") )))     
2343    {
2344        Encoder.EncodeType = "entity";
2345        $tabs.tabs( "add", "#"+tab_selector[type] + (Base64.encode(keyword)).replace(/[^\w\s]/gi, ""), Encoder.htmlEncode(tab_title) );
2346    }
2347    else /* Tab already opened */
2348    {
2349                //$tabs.tabs("option", "selected", 2);
2350        }
2351       
2352    pageselectCallback(keyword, 0, false, type); // load page 1 and insert data on event_list.ejs
2353       
2354    $('.preferences-win.active .button.save, .preferences-win.active .button.cancel, .preferences-win.active .button.import, .preferences-win.active .button.export').button();
2355}
2356
2357function paginatorSearch(currentView){
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)
2372                pageselectCallback($(currentView+' [name = keyword]').val(), ((parseInt($(currentView+' [name = page_index]').val())) +1), false,  2);
2373        }else{
2374            if(parseInt($(currentView+' [name = page_index]').val()) > 0)
2375                pageselectCallback($(currentView+' [name = keyword]').val(), ((parseInt($(currentView+' [name = page_index]').val())) -1), false, 2);
2376        }
2377    });
2378}
2379
2380function mountTitleList(page_index ,view){
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    }
2411}
2412
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>');
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');
2421               
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)
2434            pageselectCallback($(currentView+' [name = keyword]').val(), 0, 'agendaDay', type);
2435        else if(goView.indexOf('month') > 0)
2436            pageselectCallback($(currentView+' [name = keyword]').val(), 0, 'month', type);
2437        else if(goView.indexOf('year') > 0)
2438            pageselectCallback($(currentView+' [name = keyword]').val(), 0, 'year', type);
2439        else if(goView.indexOf('agendaWeek') > 0)
2440            pageselectCallback($(currentView+' [name = keyword]').val(), 0, 'agendaWeek', type);
2441
2442    });
2443
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)
2456            pageselectCallback($(currentView+' [name = keyword]').val(), ((parseInt($(currentView+' [name = page_index]').val())) +1), view, type);
2457        else
2458            pageselectCallback($(currentView+' [name = keyword]').val(), ((parseInt($(currentView+' [name = page_index]').val())) -1), view, type);
2459    });
2460}
2461
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();
2468                listEvents.find('.list-events-paginator').remove();
2469                listEvents = listEvents.html();
2470                type = $(this).parents('.ui-tabs-panel').attr("id").split("_")[1];
2471
2472                var data = {
2473                        type : type == "tasks" ? "task-list" : ( type == "events" ? "event-list" : "search"),
2474                        html : listEvents,
2475                        InfoPage : $(this).parents('table.header-paginator').find( '.fc-header-title' ).text()
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){
2485    if(!!$(currentView).find('.fc-calendar').length)
2486        return;
2487    $(currentView+' .events-list.events-list-win.active').prepend($('.fc-header:first').clone());
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();                     
2492               
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');           
2496               
2497    //Adicionar class no header padronizar com a tela principal
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       
2504    if(typeView == 'search'){
2505        $(currentView+' .events-list.events-list-win.active .header-paginator .fc-header-right span.fc-button:not(.fc-button-print)').remove();
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
2511        paginatorList(currentView, view, type);
2512}
2513
2514function mountCriteriaList(view, page_index, calerdars_selecteds){
2515    var rangeStart , rangeEnd;
2516    switch (view){
2517        case 'basicDay':
2518        case 'agendaDay':
2519            rangeStart = new Date.today().add({ days: page_index }).getTime();
2520            rangeEnd = rangeStart + 86400000;
2521            break;
2522        case 'agendaWeek':
2523            var dateStart = new Date().moveToDayOfWeek(dateCalendar.dayOfWeek[User.preferences.weekStart]);
2524            var dateEnd = new Date().moveToDayOfWeek(dateCalendar.dayOfWeek[User.preferences.weekStart]);
2525            dateEnd.setHours(0,0,0);
2526            dateStart.setHours(0,0,0); 
2527            rangeStart = dateStart.add({ days: (7 * page_index) }).getTime();
2528            rangeEnd = dateEnd.add({ days: (7 * page_index)+7 }).getTime();
2529            break;
2530        case 'month':
2531            var date = Date.today().add({ months: page_index })
2532            rangeStart = date.moveToFirstDayOfMonth().getTime();
2533            rangeEnd = date.moveToLastDayOfMonth().getTime() + 86400000;
2534            break;
2535        case 'year':
2536            var dateStart = new Date().add({ years: page_index });
2537            var dateEnd = new Date().add({ years: page_index });
2538            dateEnd.setHours(0,0,0);
2539            dateStart.setHours(0,0,0);
2540            if(dateStart.getMonth() != 0)
2541                    dateStart.moveToMonth(0, -1)
2542            if(dateEnd.getMonth() != 11)
2543            dateEnd.moveToMonth(11)
2544
2545        rangeStart = dateStart.moveToFirstDayOfMonth().getTime();
2546        rangeEnd = dateEnd.moveToLastDayOfMonth().getTime() + 86400000;
2547            break; 
2548    }
2549                       
2550    var timezone = {};
2551    for(var i in Calendar.signatureOf)
2552            timezone[i] = Calendar.signatureOf[i].calendar.timezone;
2553       
2554    return  {
2555        rangeStart: rangeStart,
2556        rangeEnd: rangeEnd,
2557            order: 'startTime',
2558            timezones: timezone,
2559        calendar: calerdars_selecteds
2560        };
2561}
2562
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)){   
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        );
2578    }else{
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        }
2603         
2604        var results = DataLayer.encode('schedulable:list', DataLayer.dispatch('modules/calendar/schedules', criteria));
2605        //var results = DataLayer.get('schedulable:detail', criteria);
2606        keyword = ( keyword || '' ).replace( /\s+/g, "_" );
2607        }
2608// não há resultados   
2609
2610var currentView = '#'+tab_selector[type] + ((Base64.encode(keyword)).replace(/[^\w\s]/gi, "") || '');
2611
2612if ((((typeof(results) == 'undefined') || (!results.events_list )) && selecteds) &&(keyword != '' && keyword != null)) {
2613    $(currentView).html(
2614                '<div title="'+title+'" class="events-list events-list-win active empty">' +
2615                '<label>'+label_nofound_search[type]+'</label>' +
2616                '</div>'
2617        );
2618// há resultados e Agendas Selecionadas
2619} else{
2620    if(typeof(results) != 'undefined'){
2621                results['page_index'] = page_index;
2622                results['keyword'] = keyword;
2623                results['tab_title'] = tab_title[type];
2624                DataLayer.render( 'templates/event_list.ejs', results, function( html ){
2625                       
2626                        $(currentView).html( html );
2627                        $('.events-list-win .menu-container .button').button();
2628                                                                                                                       
2629                        $(".event-details-item").parent().click(function(event){
2630                        event.stopImmediatePropagation();
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")
2654                        .find('.button.delete').click(function(event){
2655                                var eventId = $(this).siblings('[name="eventid"]').val();
2656                                var calendarId = $(this).siblings('[name="calendarid"]').val();
2657                                remove_event(eventId, calendarId, 2);
2658                                event.stopImmediatePropagation()
2659                        })
2660                        .end().find('.button.edit').click(function(event){
2661
2662                var schedulable = $(this).siblings('[name="eventid"]').val();
2663                switch($(this).siblings('[name="eventtype"]').val()){
2664
2665                    case '1':
2666                        eventDetails( getSchedulable( schedulable, '' ), true );
2667                    break;
2668                    case '2':
2669                        taskDetails( getSchedulable( schedulable, '' ), true );
2670                    break;
2671                    case '3':
2672                        activityDetails( getSchedulable( schedulable, '' ), true );
2673                    break;
2674                }
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();
2681                                html.find(".fc-header-title").remove();
2682                                var html = html.html();
2683                                var data = {
2684                                        type : $(this).parents('.details-event-list').hasClass("details-event") ? "event-detail" : "task-detail",
2685                                        html : html,
2686                                        InfoPage : 'Detalhes: '+$(this).parents('tr.start-date').find('td span a').text()
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()
2694                        });
2695
2696                        });
2697                        paginatorListEvent(currentView, (keyword == '' || keyword == null) ? 'list' : 'search',  !!view ? view : User.preferences.defaultCalView, type);
2698                });
2699    }else{
2700                $(currentView).html(
2701                        '<div title="'+title+'" class="events-list events-list-win active empty">' +
2702                        '<input type="hidden" name="page_index" value="'+page_index+'"></inpunt>'+
2703                        '<input type="hidden" name="keyword" value="'+keyword+'"></inpunt>'+
2704                        '<label class="empty-result">'+label_nofound[type]+'</label>' +
2705                        '</div>'
2706                        );
2707                paginatorListEvent(currentView, 'list', !!view ? view : User.preferences.defaultCalView, type);
2708    }
2709}
2710        if(currentView != '#'+tab_selector[type])
2711            $tabs.tabs("select", currentView);
2712}
2713
2714function show_modal_import_export(tab, calendarId, typeView){
2715    $('.qtip.qtip-blue').remove();
2716    DataLayer.render( 'templates/import_export.ejs', {
2717        calendars: typeView == 0 ? Calendar.calendars : Calendar.groups,
2718        owner: User.me.id,
2719        typeView: typeView
2720        }, function( html ){
2721
2722        if (!UI.dialogs.importCalendar) {
2723            UI.dialogs.importCalendar = jQuery('#div-import-export-calendar')
2724            .append('<div title="Importar e Exportar "' + (typeView == 0 ? 'Eventos' : 'Tarefas') + '" class="import-export import-export-win active"> <div>')
2725            .find('.import-export-win.active').html(html).dialog({
2726                resizable: false,
2727                modal:true,
2728                width:500,
2729                position: 'center'
2730            });
2731                       
2732        } else {
2733            UI.dialogs.importCalendar.html(html);
2734        }
2735               
2736        var tabsImportExport = UI.dialogs.importCalendar.find(".tabs-import-export").tabs({
2737            selected: tab
2738        });
2739       
2740        UI.dialogs.importCalendar.find('.button').button();
2741
2742        tabsImportExport.find('option[value="'+calendarId+'"]').attr('selected','selected').trigger('change');
2743               
2744        var form = false;
2745        $('.import-event-form').fileupload({
2746            sequentialUploads: true,
2747            add: function (e, data) {
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
2764            },
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        },
2771            done: function(e, data){
2772            var msg = '';
2773            var type = '';
2774
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';
2778
2779                $('div.import-export').find('a.button').button('option', 'disabled', false)
2780                $('.import-event-form').find('span.file-add img ').remove();
2781
2782            }else{
2783
2784                if(data.result.indexOf('schedulable') >= 0){
2785                    msg = 'Importação realizada com sucesso!';
2786                    type = 'confirmation';
2787                    Calendar.rerenderView(true);
2788                }else{
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                    }
2804                }
2805
2806                UI.dialogs.importCalendar.dialog("close");
2807            }
2808
2809            $.Zebra_Dialog(msg, {
2810                'type':     type,
2811                'overlay_opacity': '0.5',
2812                'buttons':  ['Fechar']
2813            });
2814            }
2815        });
2816
2817        UI.dialogs.importCalendar.find(".menu-import-event")       
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();
2825        });
2826           
2827        UI.dialogs.importCalendar.find(".menu-export-event")       
2828        .children(".export").click(function(){
2829             
2830            $('.export-event-form', UI.dialogs.importCalendar).submit();
2831            UI.dialogs.importCalendar.dialog("close");
2832        /**
2833                         * TODO - implementar ação de exportação
2834                         */
2835        });
2836       
2837        UI.dialogs.importCalendar.find(".menu-container")
2838        .children(".cancel").click(function(){
2839            UI.dialogs.importCalendar.dialog("close");
2840        });   
2841               
2842        UI.dialogs.importCalendar.dialog("open");
2843    });
2844}
2845
2846function copyAndMoveTo(calendar, event, idRecurrence, type, evt){
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)
2856        type = $('.calendar-copy-move input[name="typeEvent"]').val();
2857
2858    getSchedulable(event,'');
2859    var schedulable = DataLayer.get('schedulable', event.toString());
2860    schedulable['class'] = '1';
2861       
2862    calendar = !!calendar ? calendar : schedulable.calendar;
2863
2864    owner = decodeOwnerCalendar(calendar);
2865       
2866    if(typeof(schedulable) == "array")
2867        schedulable = schedulable[0];
2868       
2869    //Move eventos entre agendas
2870    if(parseInt(type) == 0){
2871               
2872        schedulable.lastCalendar = schedulable.calendar;
2873    schedulable.calendar = calendar;
2874        DataLayer.put('schedulable', schedulable);
2875       
2876        DataLayer.commit();
2877    //copia eventos entre agendas
2878    }else{
2879       
2880        var newSchedulable = schedulable;
2881       
2882        delete newSchedulable.id;
2883        delete newSchedulable.uid;
2884        delete newSchedulable.sequence;
2885        delete newSchedulable.dtstamp;
2886               
2887        delete schedulable.DayLigth;
2888        delete schedulable.rangeStart
2889        delete schedulable.rangeEnd;
2890        delete schedulable.lastUpdate;
2891               
2892        delete schedulable.calendar;
2893               
2894        if(schedulable.repeat && type == "1" ){
2895            var repeat = DataLayer.get('repeat', schedulable.repeat);
2896            delete repeat.schedulable;
2897            delete repeat.id;
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');
2900                   
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) ? '' : ',');
2908                           
2909            }
2910                   
2911                   
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;
2921               
2922        schedulable.calendar = DataLayer.copy(calendar);
2923               
2924        var participants = DataLayer.copy(schedulable.participants);
2925        delete schedulable.participants;
2926
2927    if(schedulable['type'] == '2')
2928        delete schedulable['historic'];
2929
2930        schedulable.participants =  $.map( participants, function( attendee, i ){
2931                       
2932            var participant = DataLayer.get('participant', attendee, false);
2933                       
2934            if(typeof(participant) == 'array')
2935                    participant = participant[0];
2936
2937        if(owner.id != participant.user)
2938            delete participant.status;
2939       
2940            delete participant.delegatedFrom;
2941            delete participant.id;
2942            delete participant.schedulable;
2943                       
2944            participant.id = DataLayer.put('participant', participant);
2945                       
2946            return participant ;
2947        });
2948        //Edit ocurrence
2949        if(parseInt(type) == 3){
2950            newSchedulable.endTime = !!evt.end  ? evt.end.getTime() :  ((evt.start).getTime() + 86400000);
2951            newSchedulable.startTime = evt.start.getTime();
2952                   
2953            return newSchedulable;
2954        }
2955        newSchedulable.endTime = new Date(parseInt(newSchedulable.endTime) - (parseInt(newSchedulable.allDay) ? 86400000 : 0)).toString('yyyy-MM-dd HH:mm:00');
2956        newSchedulable.startTime = new Date(parseInt(newSchedulable.startTime)).toString('yyyy-MM-dd HH:mm:00');
2957       
2958        DataLayer.put('schedulable', newSchedulable);
2959
2960    }
2961}
2962
2963function messageHelper(msg, isShow){
2964    if(isShow)
2965        new $.Zebra_Dialog('<span style="width: 50px; height: 50px;">'+
2966                            '<img src="'+DataLayer.dispatchPath+'/modules/calendar/img/loading.gif"></img>'+
2967                        '</span><label class="messagesHelpers"> '+ msg +' </label>' , {
2968                        'buttons':  false,
2969                        'modal': true,
2970                        'overlay_opacity': '0.5',
2971                        'keyboard': false,
2972                        'overlay_close': false,
2973                        'type': false,
2974                        'custom_class': 'messagesHelpersExpressoCalendar'
2975                        }
2976                    );
2977    else{
2978        $('.messagesHelpersExpressoCalendar').remove();
2979        $('.ZebraDialogOverlay').remove();
2980    }
2981}
2982
2983function extendsFileupload(view, path){
2984    var viewName = 'div.new-'+view+'-win';
2985   
2986    path = !!path ? path : '';
2987   
2988    var maxSizeFile = 2000000;
2989    $('#fileupload'+view).fileupload({
2990        sequentialUploads: true,
2991        add: function (e, data) {
2992            if(data.files[0].size < maxSizeFile)
2993                data.submit();
2994        },
2995        change: function (e, data) {
2996            $.each(data.files, function (index, file) {
2997                var attach = {};
2998                attach.fileName = file.name;
2999                var ext = file.name.split('.');
3000                if(file.name.length > 10)
3001                    attach.fileName = ext.length == 1 ? file.name.substr(0, 10) :  file.name.substr(0, 6) + '.' + ext[ext.length -1];
3002                attach.fileSize = formatBytes(file.size);
3003                if(file.size > maxSizeFile)
3004                    attach.error = 'Tamanho de arquivo nao permitido!!'
3005                               
3006                $(viewName+' .attachments-list').append(DataLayer.render(path+'templates/attachment_add_itemlist.ejs', {
3007                    file : attach
3008                }));
3009                               
3010                if(file.size < maxSizeFile){
3011                    $(viewName+' .fileinput-button.new').append(data.fileInput[0]).removeClass('new');
3012                    $(viewName+' .attachments-list').find('[type=file]').addClass('hidden');
3013                                       
3014                }else
3015                    $(viewName+' .fileinput-button.new').removeClass('new');
3016                               
3017                               
3018                $(viewName+' .attachments-list').find('.button.close').button({
3019                    icons: {
3020                        primary: "ui-icon-close"
3021                    },
3022                    text: false
3023                }).click(function(){
3024                    var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
3025                    $(viewName+' .attachment-list').find('input[value="'+idAttach+'"]').remove();
3026                    $(this).parent().remove();
3027               
3028                    if(!$(viewName+' .attachment-list input').length)
3029                        $(viewName+' .btn-danger.delete').addClass('hidden');
3030               
3031                });     
3032                               
3033            })
3034        },
3035        done: function(e, data){
3036            var currentUpload = $(viewName+' .progress.after-upload:first').removeClass('after-upload').addClass('on-complete').hide();
3037
3038            if(!!data.result && data.result != "[]"){
3039                $(viewName+' .btn-danger.delete').removeClass('hidden');
3040                var newAttach = (attch = jQuery.parseJSON(data.result)) ? attch : jQuery.parseJSON(data.result[0].activeElement.childNodes[0].data);
3041                $(viewName+' .attachment-list').append('<input tyepe="hidden" name="attachment[]" value="'+newAttach['attachment'][0][0].id+'"/>');
3042                currentUpload.removeClass('on-complete').parents('p')
3043                .append('<input type="hidden" name="fileId[]" value="'+newAttach['attachment'][0][0].id+'"/>')
3044                .find('.status-upload').addClass('ui-icon ui-icon-check');
3045            }else
3046                currentUpload.removeClass('on-complete').parents('p').find('.status-upload').addClass('ui-icon ui-icon-cancel');
3047        }
3048    });
3049    $('.attachments-list .button').button();   
3050
3051    if(!!window.FormData)                       
3052        $('#fileupload'+view).bind('fileuploadstart', function () {
3053            var widget = $(this),
3054            progressElement = $('#fileupload-progress-'+view).fadeIn(),
3055            interval = 500,
3056            total = 0,
3057            loaded = 0,
3058            loadedBefore = 0,
3059            progressTimer,
3060            progressHandler = function (e, data) {
3061                loaded = data.loaded;
3062                total = data.total;
3063            },
3064            stopHandler = function () {
3065                widget
3066                .unbind('fileuploadprogressall', progressHandler)
3067                .unbind('fileuploadstop', stopHandler);
3068                window.clearInterval(progressTimer);
3069                progressElement.fadeOut(function () {
3070                    progressElement.html('');
3071                });
3072            },
3073            formatTime = function (seconds) {
3074                var date = new Date(seconds * 1000);
3075                return ('0' + date.getUTCHours()).slice(-2) + ':' +
3076                ('0' + date.getUTCMinutes()).slice(-2) + ':' +
3077                ('0' + date.getUTCSeconds()).slice(-2);
3078            },
3079            /* formatBytes = function (bytes) {
3080            if (bytes >= 1000000000) {
3081                return (bytes / 1000000000).toFixed(2) + ' GB';
3082            }
3083            if (bytes >= 1000000) {
3084                return (bytes / 1000000).toFixed(2) + ' MB';
3085            }
3086            if (bytes >= 1000) {
3087                return (bytes / 1000).toFixed(2) + ' KB';
3088            }
3089            return bytes + ' B';
3090        },*/
3091            formatPercentage = function (floatValue) {
3092                return (floatValue * 100).toFixed(2) + ' %';
3093            },
3094            updateProgressElement = function (loaded, total, bps) {
3095                progressElement.html(
3096                    formatBytes(bps) + 'ps | ' +
3097                    formatTime((total - loaded) / bps) + ' | ' +
3098                    formatPercentage(loaded / total) + ' | ' +
3099                    formatBytes(loaded) + ' / ' + formatBytes(total)
3100                    );
3101            },
3102            intervalHandler = function () {
3103                var diff = loaded - loadedBefore;
3104                if (!diff) {
3105                    return;
3106                }
3107                loadedBefore = loaded;
3108                updateProgressElement(
3109                    loaded,
3110                    total,
3111                    diff * (1000 / interval)
3112                    );
3113            };
3114            widget
3115            .bind('fileuploadprogressall', progressHandler)
3116            .bind('fileuploadstop', stopHandler);
3117            progressTimer = window.setInterval(intervalHandler, interval);
3118        });
3119   
3120}
Note: See TracBrowser for help on using the repository browser.