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

Revision 7993, 106.3 KB checked in by cristiano, 11 years ago (diff)

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

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
189            var part = DataLayer.get('participant' , value );
190            var user = DataLayer.get('user' , part.user );
191
192            attendees[part.user] = user.name;
193        });
194    }
195
196    if(path == undefined)
197        path = "";
198               
199    if( !decoded )
200        objEvent = DataLayer.decode( "schedulable:calendar", objEvent );
201
202    if(!isMail)
203        objEvent = DataLayer.encode( "schedulable:preview", objEvent );
204       
205    if(typeof(objEvent.id) == 'undefined'){
206        objEvent.alarms = Calendar.signatureOf[User.preferences.defaultCalendar || Calendar.calendarIds[0]].defaultAlarms || false;
207        objEvent.useAlarmDefault = 1;
208    }
209       
210    /**
211         * canDiscardEventDialog deve ser true se não houver alterações no evento
212         */
213    canDiscardEventDialog = true;
214    /**
215         * zebraDiscardEventDialog é uma flag indicando que uma janela de confirmação (Zebra_Dialog)
216         * já está aberta na tela, uma vez que não é possivel acessar o evento ESC utilizado para fechá-la
217         */
218    zebraDiscardEventDialog = false;
219       
220    /**
221                ACLs do participant
222        */
223    acl_names = {
224        'w': 'acl-white',
225        'i': 'acl-invite-guests',
226        'p': 'acl-participation-required'
227    };
228
229    var dependsDelegate = function(reference, inverse){
230        if(inverse){
231            if(reference.find('input[name="attendee[]"]').val() == blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val())
232                blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val(blkAddAtendee.find('.me input[name="attendee[]"]').val());
233        }else{
234            if(blkAddAtendee.find('.me input[name="attendee[]"]').val() == blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val())
235                blkAddAtendee.find('li.organizer input[name="attendee_organizer"]').val(reference.find('input[name="attendee[]"]').val());
236        }
237       
238    };
239   
240    var removeOthers = function(){
241        var other = blkAddAtendee.find('.delegate.attendee-permissions-change-button');
242        if(other.lenght){
243            dependsDelegate(other.parents('li'), true);
244        }
245        blkAddAtendee.find('.delegate').removeClass('attendee-permissions-change-button');
246        blkAddAtendee.find('.ui-icon-transferthick-e-w').removeClass('attendee-permissions-change');
247       
248    };
249
250    var callbackAttendee = function(){
251        //Cria qtip de permissões pelo click do checkbox
252        var checked = false;
253        blkAddAtendee.find("li.not-attendee").addClass('hidden');
254       
255        blkAddAtendee.find("li .button").filter(".close.new").button({
256            icons: {
257                primary: "ui-icon-close"
258            },
259            text: false
260        }).click(function () {
261        var participant = DataLayer.get('participant' , $(this).parents('li').find('[type=checkbox]').val());
262            DataLayer.remove('participant', participant.id);
263            if($(this).parent().find('.button.delegate').hasClass('attendee-permissions-change-button')){
264                removeOthers();
265                blkAddAtendee.find('.request-update').addClass('hidden');
266                blkAddAtendee.find('.status option').toggleClass('hidden');
267                               
268                blkAddAtendee.find('option[value=1]').attr('selected','selected').trigger('change');
269            }
270            $(this).parents('li').remove();
271                       
272            if(blkAddAtendee.find(".attendee-list li").length == 1)
273                blkAddAtendee.find("li.not-attendee").removeClass('hidden');
274        delete attendees[participant.user];
275        })
276        .addClass('tiny disable ui-button-disabled ui-state-disabled')
277        .removeClass('new').end()
278       
279        .filter(".delegate.new").button({
280            icons: {
281                primary: "ui-icon-transferthick-e-w"
282            },
283            text: false
284        }).click(function () {
285            var me = $(this).parents('li');
286            if($(this).hasClass('attendee-permissions-change-button')){
287                $(this).removeClass('attendee-permissions-change-button')   
288                    .find('.ui-icon-transferthick-e-w').removeClass('attendee-permissions-change').end();               
289               
290                me.find('input[name="delegatedFrom[]"]').val('');
291                dependsDelegate(me, true);
292                               
293                blkAddAtendee.find('.request-update').addClass('hidden');
294                blkAddAtendee.find('.status option').toggleClass('hidden');
295
296                blkAddAtendee.find('option[value=1]').attr('selected','selected').trigger('change');
297                               
298            }else{
299                removeOthers();
300                       
301                $(this).addClass('attendee-permissions-change-button')   
302                .find('.ui-icon-transferthick-e-w').addClass('attendee-permissions-change').end();               
303               
304                me.find('input[name="delegatedFrom[]"]').val(blkAddAtendee.find('.me input[name="attendee[]"]').val());
305               
306                dependsDelegate(me, false);
307                       
308                blkAddAtendee.find('.request-update').removeClass('hidden');
309                if(blkAddAtendee.find('.status option.hidden').length == 1)
310                    blkAddAtendee.find('.status option').toggleClass('hidden');
311                       
312                blkAddAtendee.find('option[value=5]').attr('selected','selected').trigger('change');
313            }
314        })
315        .addClass('tiny disable ui-button-disabled ui-state-disabled')
316        .removeClass('new').end()
317               
318        .filter(".edit.new").button({
319            icons: {
320                primary: "ui-icon-key"
321            },
322            text: false
323        }).click(function() {
324                       
325            if(!!!checked)
326                $(this).parents('li').find('[type=checkbox]').attr('checked', (!$(this).parent().find('[type=checkbox]').is(':checked'))).end();
327                       
328            var aclsParticipant =  $(this).parents('li').find('input[name="attendeeAcl[]"]').val();
329            checked = false;
330                       
331            if( $('.qtip.qtip-blue.qtip-active').val() !== ''){
332                blkAddAtendee.find('dd.attendee-list').qtip({
333                    show: {
334                    ready: true,
335            solo: true,
336            when: {
337                    event: 'click'
338                    }
339                },
340                hide: false,
341                content: {
342                text: $('<div></div>').html( DataLayer.render( path + 'templates/attendee_permissions.ejs', {} ) ),
343                title: {
344                text:'Permissões',
345                button: '<a class="button close" href="#">close</a>'
346                }
347                },
348                style: {
349                name: 'blue',
350            tip: {
351                corner: 'leftMiddle'
352                },
353            border: {
354                width: 4,
355            radius: 8
356                },
357            width: {
358                min: 230,
359            max:230
360                }
361            },
362            position: {
363            corner: {
364            target: 'rightMiddle',
365            tooltip: 'leftMiddle'
366            },
367            adjust: {
368            x:0,
369            y:0
370            }
371            }
372            })
373        .qtip("api").onShow = function(arg0) {
374            $('.qtip-active .button.close').button({
375                icons: {
376                    primary: "ui-icon-close"
377                },
378                text: false
379            })
380            .click(function(){
381                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
382            });
383                                       
384            $('.qtip-active .button.save').button().click(function(){
385                                               
386                var acl = '';
387                $('.qtip-active').find('[type=checkbox]:checked').each(function(i, obj) {
388                    acl+= obj.value;
389                });
390
391                blkAddAtendee.find('dd.attendee-list [type=checkbox]:checked').siblings('input[name="attendeeAcl[]"]').each(function(i, obj) {
392                    obj.value = 'r'+acl;
393                }).parents('li').find('.button.edit').addClass('attendee-permissions-change-button')   
394                .find('.ui-icon-key').addClass('attendee-permissions-change');               
395                                               
396                blkAddAtendee.find('dd.attendee-list [type=checkbox]').attr('checked', false);
397                                               
398                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
399                                       
400            });
401            $('.qtip-active .button.cancel').button().click(function(){
402                blkAddAtendee.find('dd.attendee-list [type=checkbox]').attr('checked', false);
403                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
404            });
405                                       
406            if(aclsParticipant)
407                for(var i = 1; i < aclsParticipant.length; i++){
408                    $('.qtip-active').find('input[name="'+acl_names[aclsParticipant.charAt(i)]+'"]').attr('checked', true);
409                }
410                                                       
411            $('.qtip .button').button();
412                                       
413        };
414        }else{
415            if(!$('.new-event-win dd.attendee-list').find('[type=checkbox]:checked').length){
416                blkAddAtendee.find('dd.attendee-list').qtip('destroy');
417            }else{
418                $('.qtip-active .button.save .ui-button-text').html('Aplicar a todos')
419            }
420                       
421        };                     
422    })
423.addClass('tiny disable ui-button-disabled ui-state-disabled')
424.removeClass('new').end()
425               
426.filter(".open-delegate.new").click(function(){
427    if($(this).hasClass('ui-icon-triangle-1-e')){
428        $(this).removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
429        $(this).parents('li').find('.list-delegates').removeClass('hidden');
430    }else{
431        $(this).removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
432        $(this).parents('li').find('.list-delegates').addClass('hidden');
433    }
434               
435}).removeClass('new');
436       
437       
438blkAddAtendee.find("li input[type=checkbox].new").click(function(){
439    if(!$('.new-event-win dd.attendee-list').find('[type=checkbox]:checked').length){
440        blkAddAtendee.find('dd.attendee-list').qtip('destroy');
441    }else{
442        checked = true;
443        $(this).parents('li').find('.button.edit').click();
444    }
445}).removeClass('new');
446       
447UI.dialogs.addEvent.find('.attendees-list li').hover(
448    function () {
449        $(this).addClass("hover-attendee");
450        $(this).find('.button').removeClass('disable ui-button-disabled ui-state-disabled').end()
451        .find('.attendee-options').addClass('hover-attendee');
452    },
453    function () {
454        $(this).removeClass("hover-attendee");
455        $(this).find('.button').addClass('disable ui-button-disabled ui-state-disabled').end()
456        .find('.attendee-options').removeClass('hover-attendee');;
457    }
458    );
459}
460
461var html = DataLayer.render( path+'templates/event_add.ejs', {
462    event:objEvent
463});     
464               
465if (!UI.dialogs.addEvent) {
466    UI.dialogs.addEvent = jQuery('#sandbox').append('<div title="Criar Evento" class="new-event-win active"> <div>').find('.new-event-win.active').html(html).dialog({
467        resizable: false,
468        modal:true,
469        autoOpen: false,
470        width:"auto",
471        position: 'center',
472        close: function(event, ui) {
473                /**
474                 * Remove tooltip possivelmente existente
475                 */
476                if ($('.qtip.qtip-blue.qtip-active').length)
477                        $('.qtip.qtip-blue.qtip-active').qtip('destroy');                                               
478                attendees  = {};
479        },
480        beforeClose: function(event, ui) {
481
482            if (!canDiscardEventDialog && !zebraDiscardEventDialog) {
483                zebraDiscardEventDialog = true;
484                window.setTimeout(function() {
485                    $.Zebra_Dialog('Suas alterações no evento não foram salvas. Deseja descartar as alterações?', {
486                        'type':     'question',
487                        'overlay_opacity': '0.5',
488                        'buttons':  ['Descartar alterações', 'Continuar editando'],
489                        'onClose':  function(clicked) {
490                            if(clicked == 'Descartar alterações') {
491                                canDiscardEventDialog = true;
492                                /**
493                                *Remoção dos anexos do eventos caso seja cancelado a edição
494                                */
495                                DataLayer.rollback();
496
497                                var ids = false;
498                                $.each($('.attachment-list input'), function (i, input) {
499                                    DataLayer.put('attachment', {id: ''+input.value});
500                                    DataLayer.remove('attachment', ''+input.value);
501                                        ids = true;
502                                });
503                                if(ids)
504                                        DataLayer.commit();
505                       
506                               
507                                                                               
508                                UI.dialogs.addEvent.dialog('close');
509                            }else{
510                                zebraDiscardEventDialog = false;
511                            }
512                                                                       
513                            /**
514                            * Uma vez aberta uma janela de confirmação (Zebra_Dialog), ao fechá-la
515                            * com ESC, para que o evento ESC não seja propagado para fechamento da
516                            * janela de edição de eventos, deve ser setada uma flag indicando que
517                            * já existe uma janela de confirmação aberta.
518                            */
519                            if (!clicked) {
520                                window.setTimeout(function() {
521                                    zebraDiscardEventDialog = false;
522                                }, 200);
523                            }
524                        }
525                    });
526                                                       
527                }, 300);
528
529            }
530            //DataLayer.rollback();
531            return canDiscardEventDialog;
532        },
533        dragStart: function(event, ui) {
534                if ($('.qtip.qtip-blue.qtip-active').length)
535                        $('.qtip.qtip-blue.qtip-active').qtip('destroy');
536        }
537    });
538                       
539} else {
540    UI.dialogs.addEvent.html(html);
541}
542               
543var tabs = UI.dialogs.addEvent.children('.content').tabs({
544        select: function(event, ui) {
545                if ($('.qtip.qtip-blue.qtip-active').length)
546                        $('.qtip.qtip-blue.qtip-active').qtip('destroy');
547        }       
548        });
549var calendar = DataLayer.get('calendar', objEvent.calendar);
550                               
551if ( (calendar.timezone != objEvent.timezone) && objEvent.id){
552    UI.dialogs.addEvent.find('.calendar-addevent-details-txt-timezone').find('option[value="'+objEvent.timezone+'"]').attr('selected','selected').trigger('change');
553    UI.dialogs.addEvent.find('.calendar_addevent_details_lnk_timezone').addClass('hidden');
554    $('.calendar-addevent-details-txt-timezone').removeClass('hidden');
555                       
556}
557
558DataLayer.render( path+'templates/event_repeat.ejs', {
559    event:objEvent
560}, function( repeatHtml ){
561
562    UI.dialogs.addEvent.find('#calendar_addevent_details3').html(repeatHtml);
563    $(".date").datepicker({
564                dateFormat: User.preferences.dateFormat.replace(/M/g, 'm').replace(/yyyy/g, 'yy')
565                });
566                 
567    if(objEvent.repeat)
568    {
569        if( objEvent.repeat['id'] )
570        {
571            $("[name='repeatId']:last").val( objEvent.repeat['id'] );
572        }
573
574        if( objEvent.repeat['frequency'] !== 'none' )
575        {
576            if( objEvent.repeat['startTime'] && objEvent.repeat['startTime'] !== "0" )
577            {
578                $("[name='startOptions'] [value='customDate']:last").attr( 'selected', 'selected' );
579                $("[name='start']:last").val(new Date( parseInt(objEvent.repeat['startTime']) ).toString( User.preferences.dateFormat ) );
580            }
581            else
582            {
583                $("[name='start']:last").val($("[name='startDate']:last").val());     
584                $("[name='start']:last").readOnly=true;
585                $("[name='start']:last").datepicker("disable");
586            }
587                             
588            $(".finish_event").removeClass("hidden");
589
590            if(objEvent.repeat['endTime'] && objEvent.repeat['endTime'] !== "0" )
591            {
592                //$("[name='occurrences']").addClass("hidden");
593                $(".customDateEnd").removeClass("hidden");
594                $(".endRepeat option[value='customDate']").attr('selected', 'selected')                                         
595                $(".customDateEnd").val( new Date( parseInt(objEvent.repeat['endTime']) )/*.setTimezoneOffset( Timezone.timezone( objEvent.timezone ) )*/.toString( User.preferences.dateFormat ) ); 
596            }
597            else if (objEvent.repeat['count'] && objEvent.repeat['count'] !== "0" ) {
598                $(".endRepeat option[value='occurrences']").attr('selected', 'selected');                                               
599                $(".occurrencesEnd").removeClass("hidden");
600                $(".occurrencesEnd").val(objEvent.repeat['count']);                                             
601            }
602                             
603            switch ( objEvent.repeat['frequency'] )
604            {
605                case "daily":
606                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Dia(s)")
607                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
608                    $(".frequency option[value='daily']").attr('selected', 'selected');
609                    break;
610                case "weekly":
611                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Semana(s)")
612                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
613                   
614                    $(".frequency option[value='weekly']").attr('selected', 'selected');
615                                           
616                    $(".event-repeat-weekly").removeClass("hidden");
617                                           
618                    var day = [];
619                                           
620                    if( objEvent.repeat.byday )
621                        day = objEvent.repeat.byday.split(',');
622                                           
623                    for(i=0; i<day.length; i++)
624                        $(".event-repeat-weekly [value='" + day[i] + "']").attr("checked","checked");
625                                           
626                    break;
627                case "monthly":
628                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Mes(s)")
629                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
630                   
631                    $(".frequency option[value='monthly']").attr('selected', 'selected')
632                   
633                    $(".event-repeat-monthly:last").removeClass("hidden").find("input[type=radio][name=repeatmonthyType]").click(function(){
634                                if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
635                                    $(".event-repeat-weekly:last").removeClass("hidden");
636                                else
637                                    $(".event-repeat-weekly:last").addClass("hidden");
638                    });
639                   
640                                           
641                        if( objEvent.repeat && objEvent.repeat.bymonthday != ''){
642
643                                $("input[type=radio][name=repeatmonthyType][value=0]").attr('checked', 'checked');
644
645                        }else if(objEvent.repeat){
646
647                                $("input[type=radio][name=repeatmonthyType][value=1]").attr('checked', 'checked');
648
649                                var days = objEvent.repeat.byday.split(',');
650
651                                $.each(days, function(i, e){
652                                        $(".event-repeat-weekly:last").find('input[name="repeatweekly[]"][value="'+e+'"]').attr('checked', 'checked');
653                                });
654
655                        }
656
657
658                    if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
659                                $(".event-repeat-weekly:last").removeClass("hidden");
660                    else
661                                $(".event-repeat-weekly:last").addClass("hidden");
662                    break;
663                case "yearly":
664                    $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Ano(s)")
665                    .end().find(".eventInterval").val( objEvent.repeat['interval'] || "1" );
666                    $(".frequency option[value='yearly']").attr('selected', 'selected')
667                    break;     
668            }
669        }
670    }
671    else {
672        $(".endRepeat option[value='never']").attr('selected', 'selected');
673    }
674
675
676    $(".event-repeat-container:last").find(".repeat-in").find("[name=startOptions]").change(function(){                                       
677
678        if($(this).find("option:selected").val() == "Today"){
679            $("[name='start']:last").val($("[name='startDate']:last").val());
680            $("[name='start']:last").readOnly=true;
681            $("[name='start']:last").datepicker("disable");
682        }
683        else{
684            $("[name='start']:last").readOnly=false;
685            $("[name='start']:last").datepicker("enable");
686        }
687    });
688    $(".event-repeat-container:last").find(".repeat-in").find("[name=endOptions]").change(function(){                                       
689        if($(this).find("option:selected").val() == "never"){
690            $("[name='occurrences']").addClass("hidden");
691            $("[name='end']:last").addClass("hidden");
692        }
693        else if($(this).find("option:selected").val() == "customDate"){
694            $("[name='occurrences']").addClass("hidden");
695            $("[name='end']:last").removeClass("hidden");   
696        }
697        else{
698            $("[name='end']:last").addClass("hidden");
699            $("[name='occurrences']").removeClass("hidden");                                       
700        }
701    });
702                       
703    $("[name='frequency']:last").change(function () {
704        $(".frequency-option").addClass("hidden");
705        if($(this).val() == "none"){
706            $(".repeat-in").addClass("hidden");
707            return;
708        }else{
709            $(".repeat-in").removeClass("hidden");
710            $("[name='start']:last").val($("[name='startDate']:last").val());
711        }
712                 
713                                 
714        switch($(this).val()){
715            case "daily":
716                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Dia(s)");
717                break;
718            case "weekly":
719                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Semana(s)");
720                $(".event-repeat-weekly:last").removeClass("hidden");
721                break;
722            case "monthly":
723                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Mes(s)");
724                $(".event-repeat-monthly:last").removeClass("hidden").find("input[type=radio][name=repeatmonthyType]").click(function(){
725                    if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
726                        $(".event-repeat-weekly:last").removeClass("hidden");
727                    else
728                        $(".event-repeat-weekly:last").addClass("hidden");
729                });
730                if($("input[type=radio][name=repeatmonthyType]:checked").val() == "1")
731                    $(".event-repeat-weekly:last").removeClass("hidden");
732                else
733                    $(".event-repeat-weekly:last").addClass("hidden");
734                break;
735            default:
736                $(".event-repeat-container:last").find(".repeat-in").find(".interval").html("Ano(s)");
737                break;
738        }
739                               
740    });
741});
742
743UI.dialogs.addEvent.find('.calendar_addevent_details_lnk_timezone').click(function(e){
744    $(this).addClass('hidden');
745    $('.calendar-addevent-details-txt-timezone').removeClass('hidden');
746    e.preventDefault();
747});
748               
749UI.dialogs.addEvent.find('.button.remove').button({
750    text:false,
751    icons:{
752        primary:'ui-icon-close'
753    }
754}).click(function(el){
755    var id;
756    if( id = $(this).parent().find('input[name="alarmId[]"]').val())
757        DataLayer.remove('alarm', id);
758    $(this).parent().remove().find('li').is(':empty');
759});
760
761var myCalendar = function(){
762        for(var i in Calendar.signatures)
763            if(Calendar.signatures[i].isOwner == "1")
764                return Calendar.signatures[i].calendar.id;
765}
766
767/*Seleciona a agenda padrão para visualização/edição de um evento*/
768if(objEvent.id)
769    UI.dialogs.addEvent.find('option[value="'+objEvent.calendar+'"]').attr('selected','selected').trigger('change');
770
771/*Adicionar alarms padrões, quando alterado a agenda do usuário*/               
772UI.dialogs.addEvent.find('select[name="calendar"]').change(function(){
773    if((typeof($('input[name = "idEvent"]').val()) == 'undefined') || (!!!$('input[name = "idEvent"]').val())) {
774        $('input[name = "isDefaultAlarm[]"]').parent().remove();
775        UI.dialogs.addEvent.find('input[name="defaultAlarm"]').parent().removeClass('hidden');
776        var calendarSelected = Calendar.signatureOf[$(this).val()];
777        calendarSelected.useAlarmDefault = 1;
778        if(calendarSelected.defaultAlarms != ""){
779            var li_attach = DataLayer.render(path+'templates/alarms_add_itemlist.ejs', {
780                alarm:calendarSelected
781            });
782            jQuery('.event-alarms-list').append(li_attach).find('.button.remove').button({
783                text:false,
784                icons:{
785                    primary:'ui-icon-close'
786                }
787            }).click(function(el) {
788            $(this).parent().remove().find('li').is(':empty');
789        });
790
791    }else{
792        UI.dialogs.addEvent.find('input[name="defaultAlarm"]').parent().addClass('hidden');
793    }
794}
795
796    var participant =  UI.dialogs.addEvent.find('dd.me input[name="attendee[]"]').val();
797    var calendar = $(this).val();
798   
799    if( !parseInt(Calendar.signatureOf[calendar].isOwner) ){
800        var signature = Calendar.signatureOf[calendar];
801        var organizer = DataLayer.get('calendarSignature', {
802            filter: ['AND', ['=','calendar',signature.calendar.id], ['=','isOwner','1']],
803            criteria: {
804                deepness: 2
805            }
806        });
807                           
808    if($.isArray(organizer))
809        organizer = organizer[0];
810    DataLayer.put('participant', {
811        id: participant,
812        user: organizer.user.id,
813        mail: organizer.user.mail
814        });
815                           
816    UI.dialogs.addEvent.find('dt.me').html(organizer.user.name);
817    UI.dialogs.addEvent.find('li.organizer input[name="attendee_organizer"]').val(participant);
818    UI.dialogs.addEvent.find('li.organizer label').filter('.name').html(organizer.user.name).end()
819    .filter('.mail').html(organizer.user.mail).attr('title',organizer.user.mail);
820
821}else{
822    UI.dialogs.addEvent.find('dt.me').html(User.me.name);
823    DataLayer.put('participant', {
824        id: participant,
825        user: User.me.id,
826        mail: User.me.mail
827        });
828    UI.dialogs.addEvent.find('li.organizer input[name="attendee_organizer"]').val(participant);
829    UI.dialogs.addEvent.find('li.organizer label').filter('.name').html(User.me.name).end()
830    .filter('.mail').html(User.me.mail).attr('title',User.me.mail);
831}
832
833});
834
835/*Checkbox adicionar alarms padrões*/
836UI.dialogs.addEvent.find('input[name="defaultAlarm"]').click(function(){
837    if($(this).attr("checked")){
838        $('input[name="isDefaultAlarm[]"]').parent().remove();
839        var calendarSelected = Calendar.signatureOf[$('select[name="calendar"]').val()];
840        calendarSelected.useAlarmDefault = 1;
841        if(calendarSelected.defaultAlarms != ""){
842            var li_attach = DataLayer.render(path+'templates/alarms_add_itemlist.ejs', {
843                alarm:calendarSelected
844            });
845            jQuery('.event-alarms-list').append(li_attach).find('.button.remove').button({
846                text:false,
847                icons:{
848                    primary:'ui-icon-close'
849                }
850            }).click(function(el) {
851            var id;
852            if( id = $(this).parent().find('input[name="alarmId[]"]').val())
853                DataLayer.remove('alarm', id);
854            $(this).parent().remove().find('li').is(':empty')
855        });
856    }
857} else {
858    $('input[name="isDefaultAlarm[]"]').parent().remove();
859}
860});
861/* Checkbox allday */
862UI.dialogs.addEvent.find('input[name="allDay"]').click(function(){
863    $(this).attr("checked") ?
864    UI.dialogs.addEvent.find('.start-time, .end-time').addClass('hidden') :
865    UI.dialogs.addEvent.find('.start-time, .end-time').removeClass('hidden');
866    updateMap(true);
867});
868
869UI.dialogs.addEvent.find('.button').button();
870UI.dialogs.addEvent.find('.button.add').button({
871    icons: {
872        secondary: "ui-icon-plus"
873    }
874});
875
876// ==== validation events ====
877UI.dialogs.addEvent.find(".input-group .h1").Watermark("Evento sem título");
878if(User.preferences.hourFormat.length == 5) {
879    UI.dialogs.addEvent.find(".end-time, .start-time").mask("99:99", {
880        completed: function(){
881            updateMap();
882        }
883    });
884} else {
885    $.mask.definitions['{']='[ap]';
886    $.mask.definitions['}']='[m]';
887    UI.dialogs.addEvent.find(".end-time, .start-time").mask("99:99 {}", {
888        completed:function(){
889            $(this).val(date.Calendar.defaultToAmPm($(this).val()));
890            $(this).timepicker("refresh");
891            $(this).val($(this).val().replace(/[\.]/gi, ""));
892            updateMap();
893        }
894    });
895}
896UI.dialogs.addEvent.find(".number").numeric();
897User.preferences.dateFormat.indexOf('-') > 0 ?
898UI.dialogs.addEvent.find(".date").mask("99-99-9999", {
899    completed:function(){
900        updateMap();
901    }
902}) :
903UI.dialogs.addEvent.find(".date").mask("99/99/9999", {
904    completed:function(){
905        updateMap();
906    }
907});
908
909UI.dialogs.addEvent.find(".menu-addevent")
910.children(".delete").click(function(){
911    $.Zebra_Dialog('Tem certeza que deseja excluir o evento?', {
912        'type':     'question',
913        'overlay_opacity': '0.5',
914        'buttons':  ['Sim', 'Não'],
915        'onClose':  function(clicked) {
916            if(clicked == 'Sim'){
917                canDiscardEventDialog = true;
918                /* Remove por filtro */
919                DataLayer.removeFilter('schedulable', {filter: ['AND', ['=', 'id', objEvent.id], ['=', 'calendar', objEvent.calendar], ['=','user',(objEvent.me.user ? objEvent.me.user.id : objEvent.me.id)]]});
920                Calendar.rerenderView(true);
921                /********************/
922                UI.dialogs.addEvent.dialog("close");
923            }
924        }
925    });
926}).end()
927           
928.children(".cancel").click(function(){
929    UI.dialogs.addEvent.dialog("close");
930}).end()
931           
932.children(".save").click(function(){
933    /* Validação */
934    var msg = false;                   
935    if(msg = validDateEvent()){
936        $(".new-event-win.active").find('.messages-validation').removeClass('hidden').find('.message label').html(msg);
937        return false;
938    }
939                       
940    canDiscardEventDialog = true;
941                       
942    var exit = function(event){
943        if(event)
944            DataLayer.remove('schedulable', event, false);
945
946        UI.dialogs.addEvent.children().find('form.form-addevent').submit();
947        UI.dialogs.addEvent.dialog("close");
948    }
949                       
950    if(repeat){
951        DataLayer.remove('repeat', false);
952        DataLayer.put('repeat', repeat);
953        DataLayer.commit('repeat', false, exit(repeat.schedulable));
954    }else
955        exit();
956}).end()
957               
958.children(".export").click(function(){
959    UI.dialogs.addEvent.children().find(".form-export").submit();
960});
961
962var dates = UI.dialogs.addEvent.find('input.date').datepicker({
963    dateFormat: User.preferences.dateFormat.replace(/M/g, 'm').replace(/yyyy/g, 'yy'),
964    onSelect : function( selectedDate ){
965        updateMap();
966    }
967});
968//if(path == ""){
969UI.dialogs.addEvent.find('input.time').timepicker({
970    closeText: 'Ok',
971    hourGrid: 4,
972    minuteGrid: 10,
973    ampm : ((User.preferences.hourFormat.length > 5) ? true: false),
974    timeFormat: "hh:mm tt",
975    onSelect: function (selectedDateTime){
976        if ((selectedDateTime.value == '__:__') || (selectedDateTime.value == '__:__ __'))
977                          selectedDateTime.value = "";
978                if(!(User.preferences.hourFormat.length == 5))
979                $(this).val(selectedDateTime.replace(/[\.]/gi, ""));                                                           
980                updateMap();
981    },
982    onClose : function (selectedDateTime){
983        if(!(User.preferences.hourFormat.length == 5))
984            $(this).val(selectedDateTime.replace(/[\.]/gi, ""));
985    },
986    beforeShow: function (selectedDateTime) {
987                if ((selectedDateTime.value == '__:__') || (selectedDateTime.value == '__:__ __'))
988                        selectedDateTime.value = "";
989    }
990});
991//}
992
993UI.dialogs.addEvent.find('.button-add-alarms').click(function(){
994    var li_attach = DataLayer.render(path+'templates/alarms_add_itemlist.ejs', {});
995
996    jQuery('.event-alarms-list').append(li_attach).find('.button.remove').button({
997        text:false,
998        icons:{
999            primary:'ui-icon-close'
1000        }
1001    }).click(function(el) {
1002    $(this).parent().remove().find('li').is(':empty')
1003});
1004// valicacao de campos numericos
1005$('.number').numeric();
1006});
1007           
1008                 
1009UI.dialogs.addEvent.find('.button.suggestion-hours').button({
1010    icons: {
1011        primary: "ui-icon-clock"
1012    },
1013    text: 'Sugerir horário'
1014}).click(function () {
1015    $(this).siblings('input').removeAttr('disabled')
1016    .end().parents().find('input[name="allDay"]').removeAttr('disabled');               
1017});
1018
1019
1020if(!repeat)
1021    if(objEvent.me.id == User.me.id){
1022        objEvent.me.id = DataLayer.put('participant', {
1023            user: objEvent.me.id,
1024            mail: objEvent.me.mail
1025            });
1026        objEvent.organizer.id = objEvent.me.id;
1027    }
1028
1029var attendeeHtml = DataLayer.render( path+'templates/attendee_add.ejs', {
1030    event:objEvent
1031});
1032       
1033// load template of attendees
1034var blkAddAtendee = UI.dialogs.addEvent.find('#calendar_addevent_details6').append(attendeeHtml);
1035if(objEvent.attendee.length)
1036                callbackAttendee();
1037/**
1038Opções de delegação do participante/organizer
1039*/             
1040blkAddAtendee.find(".button.participant-delegate").button({
1041    icons: {
1042        primary: "ui-icon-transferthick-e-w"
1043    },
1044    text: false
1045}).click(function () {
1046    if($(this).hasClass('attendee-permissions-change-button')){
1047        if(!$(this).hasClass('disable')){
1048            $(this).removeClass('attendee-permissions-change-button')   
1049            .find('.ui-icon-transferthick-e-w').removeClass('attendee-permissions-change').end();               
1050            blkAddAtendee.find('.block-add-attendee.search').addClass('hidden');
1051            blkAddAtendee.find('.block-add-attendee.search dt').html('Adicionar outros contatos');
1052        }
1053    }else{                                                                     
1054        $(this).addClass('attendee-permissions-change-button')   
1055        .find('.ui-icon-transferthick-e-w').addClass('attendee-permissions-change').end();               
1056        blkAddAtendee.find('.block-add-attendee.search dt').html('Delegar participação para');
1057        blkAddAtendee.find('.block-add-attendee.search').removeClass('hidden');
1058        blkAddAtendee.find('.block-add-attendee.search input.search').focus();
1059    }
1060})
1061.addClass('tiny');             
1062                       
1063//show or hidden permissions attendees
1064//blkAddAtendee.find('.block-attendee-list #attendees-users li').click(show_permissions_attendees);
1065
1066UI.dialogs.addEvent.find(".attendee-list-add .add-attendee-input input").Watermark("digite um email para convidar");
1067/*
1068 * Trata a edição de um novo participante adicionado
1069 */
1070var hasNewAttendee = false;
1071                       
1072blkAddAtendee.find('.attendee-list-add .add-attendee-input span').click(function(data){
1073    blkAddAtendee.find('.attendee-list-add .add-attendee-input input').keydown();
1074});
1075                       
1076blkAddAtendee.find('.attendee-list-add .add-attendee-input input').keydown(function(event) {
1077    if (event.keyCode == '13' && $(this).val() != '' || (event.keyCode == undefined && $(this).val() != '')) {
1078        Encoder.EncodeType = "entity";
1079        $(this).val(Encoder.htmlEncode($(this).val()));
1080                                       
1081        newAttendeeEmail = false;
1082        newAttendeeName  = false;
1083        skipAddNewLine   = false;
1084
1085        var info = $(this).val();
1086
1087        /**
1088        * email válido?
1089        */
1090        info.match(/^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/) ?
1091        newAttendeeEmail = info : newAttendeeName = info;
1092
1093        /**
1094        * 1) busca no banco para saber se o usuário já existe
1095        *               1.1) se existe, atualiza as info na lista de participantes e nao abre o tooltip
1096        *               1.2) se não existe
1097        *                       a) salva como novo usuario externo no banco (apenas com email)
1098        *                       b) exibe tooltip pedindo o nome
1099        *                       c) se o usuário preenche tooltip e salva, atualiza com o nome o usuário recém criado
1100        *                       d) se o usuário cancela o tooltip, fica o usuário salvo apenas com email e sem nome
1101        */
1102
1103        var user = DataLayer.get('user', ["=", "mail", $(this).val()]);
1104        if(!!user && user[0].id)
1105            attendees[user[0].id] = {
1106                name: user[0].name
1107                };
1108                                       
1109        /**
1110        * guarda o último tooltip aberto referente à lista de participantes
1111        */
1112        lastEditAttendeeToolTip = [];
1113
1114        /**
1115        * Valida email e salva um participante externo
1116        */
1117        var saveContact = function() {
1118            Encoder.EncodeType = "entity";
1119
1120            var currentTip = $('.qtip-active');
1121            newAttendeeName  = currentTip.find('input[name="name"]').val();
1122            newAttendeeEmail = currentTip.find('input[name="mail"]').val();
1123
1124            if (!(!!newAttendeeEmail.match(/^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/))) {
1125                currentTip.find('.messages').removeClass('hidden').find('.message label').html('Email inválido.');
1126                return false;
1127            }
1128
1129            DataLayer.put('user', {
1130                id:userId,
1131                name:newAttendeeName,
1132                mail:newAttendeeEmail,
1133                isExternal:isExternal
1134            });
1135
1136            lastEditAttendeeToolTip.find('label')
1137            .filter('.name').html(Encoder.htmlEncode(newAttendeeName)).attr('title', Encoder.htmlEncode(newAttendeeName)).end()
1138            .filter('.mail').html(Encoder.htmlEncode(newAttendeeEmail)).attr('title', Encoder.htmlEncode(newAttendeeEmail));
1139
1140            blkAddAtendee.find('.attendee-list-add .add-attendee-input input').val('');
1141            return true;
1142        }
1143                                               
1144        /**
1145                                         * Formata e adequa um tootip abert para edição de um participante na lista
1146                                         */
1147        var onShowToolTip = function(arg0) {
1148            $('.qtip-active .button.close').button({
1149                icons: {
1150                    primary: "ui-icon-close"
1151                },
1152                text: false
1153            });
1154            $('.qtip-active .button').button()
1155            .filter('.save').click(function(event, ui) {
1156                if(saveContact())
1157                    lastEditAttendeeToolTip.qtip("destroy");
1158                else
1159                    return false;
1160            }).end()
1161            .filter('.cancel').click(function(event, ui) {
1162                lastEditAttendeeToolTip.qtip("destroy");
1163            })
1164
1165            /**
1166                                                 * Trata o ENTER no campo da tooltip, equivalente a salvar
1167                                                 * o novo convidado.
1168                                                 */
1169            $('.qtip-active input').keydown(function(event) {
1170                if (event.keyCode == '13') {                                           
1171                    if (saveContact())                                         
1172                        lastEditAttendeeToolTip.qtip("destroy");
1173                       
1174                    lastEditAttendeeToolTip.qtip("destroy");
1175                    event.preventDefault();
1176                }
1177            })
1178            .filter('[name="name"]').Watermark("informe o nome do contato").end()
1179            .filter('[name="mail"]').Watermark("informe o email do contato");
1180        }
1181                                       
1182        /**
1183                                         * Se o email digitado já foi adicionado na lista,
1184                                         * o usuário deve ser avisado e um botão de edição deve ser exibido
1185                                         */
1186        if(blkAddAtendee.find('label.mail[title="' + newAttendeeEmail + '"]').length) {
1187            hasNewAttendee  = false;
1188            newAttendeeName = blkAddAtendee.find('label.mail[title="' + newAttendeeEmail + '"]').parents('li').find('label.name').attr('title');
1189
1190            blkAddAtendee.find('.email-validation').removeClass('hidden')
1191            .find('.message label').html("O usuário acima já foi adicionado! <a class=\"small button\">Editar</a>")
1192            .find(".button").button().click(function () {
1193                /**
1194                                                         * Se o usuário optar por editar o participante anteriormente adicionado,
1195                                                         * uma tooltip deve ser aberta para este participante, viabilizando a edição
1196                                                         */
1197                blkAddAtendee.find("ul.attendee-list").scrollTo('label.mail[title="' + newAttendeeEmail + '"]');
1198                /**
1199                                                         * Remove tooltip possivelmente existente
1200                                                         */
1201                if (lastEditAttendeeToolTip.length && lastEditAttendeeToolTip.data('qtip'))
1202                    lastEditAttendeeToolTip.qtip('destroy');
1203                                       
1204                lastEditAttendeeToolTip = blkAddAtendee.find('label.mail[title="' + newAttendeeEmail + '"]').parents('li');
1205                lastEditAttendeeToolTip.qtip({
1206                    show: {
1207                        ready: true,
1208                        solo: true,
1209                        when: {
1210                            event: 'click'
1211                        }
1212                    },
1213                hide: false,
1214                content: {
1215                    text: $('<div></div>').html( DataLayer.render( path+'templates/attendee_quick_edit.ejs', {
1216                        attendee:{
1217                            name:newAttendeeName,
1218                            mail:newAttendeeEmail
1219                        }
1220                    } ) ),
1221                title: {
1222                    text:'Detalhes do participante',
1223                    button: '<a class="button close" href="#">close</a>'
1224                }
1225                },
1226                style: {
1227                    name: 'blue',
1228                    tip: {
1229                        corner: 'leftMiddle'
1230                    },
1231                    border: {
1232                        width: 4,
1233                        radius: 8
1234                    },
1235                    width: {
1236                        min: 230,
1237                        max:230
1238                    }
1239                },
1240            position: {
1241                corner: {
1242                    target: 'rightMiddle',
1243                    tooltip: 'leftMiddle'
1244                },
1245                adjust: {
1246                    x:0,
1247                    y:0
1248                }
1249            }
1250            });
1251        lastEditAttendeeToolTip.qtip("api").onShow = onShowToolTip;
1252    });
1253skipAddNewLine = true;
1254} else {
1255    hasNewAttendee  = true;
1256    blkAddAtendee.find('.email-validation').addClass('hidden');
1257}
1258                                       
1259                                       
1260var isExternal = (!!user && !(!!user.isExternal)) ? 0 : 1;
1261
1262/**
1263                                         * Remove tooltip possivelmente existente
1264                                         */
1265if (lastEditAttendeeToolTip.length && lastEditAttendeeToolTip.data('qtip'))
1266    lastEditAttendeeToolTip.qtip('destroy');
1267
1268userId = '';
1269var newAttendeeId = '';
1270
1271if (user){
1272    if (!skipAddNewLine) {
1273        user[0].id =  DataLayer.put('participant', {
1274            user: user[0].id,
1275            isExternal: isExternal,
1276            acl: 'r'
1277        });
1278        user[0].acl = objEvent.acl;
1279        user[0].isDirty = !!!objEvent.id;
1280        user[0].isDelegate = (objEvent.id && (objEvent.me.status == '5'));
1281
1282        blkAddAtendee.find('dd.attendee-list ul.attendee-list').append(
1283            DataLayer.render(path+'templates/participants_add_itemlist.ejs', user)
1284            )
1285        .scrollTo('max');
1286        callbackAttendee();
1287    }
1288                                               
1289    $(this).val('');
1290
1291} else if (!skipAddNewLine) {
1292    /**
1293     * a) salva como novo usuario externo no banco (apenas com email) e...
1294     * adiciona novo contato externo à lista de convidados
1295     */
1296
1297    userId = DataLayer.put('user', {
1298        name: newAttendeeName,
1299        mail: newAttendeeEmail,
1300        isExternal: isExternal
1301    });
1302    newAttendeeId = DataLayer.put('participant', {
1303        user: userId,
1304        isExternal: isExternal
1305    });
1306
1307                                                 
1308    blkAddAtendee.find('dd.attendee-list ul.attendee-list').append(
1309        DataLayer.render(path+'templates/participants_add_itemlist.ejs', [{
1310            id:newAttendeeId,
1311            name: newAttendeeName,
1312            mail: newAttendeeEmail,
1313            isExternal: 1,
1314            acl: objEvent.acl,
1315            isDirty: !!!objEvent.id,
1316        isDelegate: (objEvent.id && (objEvent.me.status == '5'))
1317            }])
1318        ).scrollTo('max');
1319    callbackAttendee();
1320
1321    /**
1322                                                 * Adiciona tootip para atualização dos dados do contato externo
1323                                                 * recém adicionado.
1324                                                 */
1325    lastEditAttendeeToolTip = blkAddAtendee.find('dd.attendee-list li:last');
1326    lastEditAttendeeToolTip.qtip({
1327        show: {
1328            ready: true,
1329            solo: true,
1330            when: {
1331                event: 'click'
1332            }
1333        },
1334    hide: false,
1335    content: {
1336        text: $('<div></div>').html( DataLayer.render( path+'templates/attendee_quick_edit.ejs', {
1337            attendee:{
1338                name:newAttendeeName,
1339                mail:newAttendeeEmail
1340            }
1341        } ) ),
1342    title: {
1343        text:'Detalhes do participante',
1344        button: '<a class="button close" href="#">close</a>'
1345    }
1346    },
1347    style: {
1348        name: 'blue',
1349        tip: {
1350            corner: 'leftMiddle'
1351        },
1352        border: {
1353            width: 4,
1354            radius: 8
1355        },
1356        width: {
1357            min: 230,
1358            max:230
1359        }
1360    },
1361position: {
1362    corner: {
1363        target: 'rightMiddle',
1364        tooltip: 'leftMiddle'
1365    },
1366    adjust: {
1367        x:0,
1368        y:0
1369    }
1370}
1371});
1372                       
1373lastEditAttendeeToolTip.qtip("api").onShow = onShowToolTip;
1374
1375$(this).val('');
1376
1377                                               
1378}
1379event.preventDefault();
1380}
1381                               
1382});
1383
1384/**
1385* Trata a busca de usuários para adição de participantes
1386*/
1387blkAddAtendee.find('.add-attendee-search .ui-icon-search').click(function(event) {
1388    blkAddAtendee.find('.add-attendee-search input').keydown();
1389});
1390                       
1391                       
1392blkAddAtendee.find('.add-attendee-search input').keydown(function(event) {
1393
1394    if(event.keyCode == '13' || typeof(event.keyCode) == 'undefined') {                 
1395        var result = DataLayer.get('user', ["*", "name", $(this).val()], true);
1396
1397        /**
1398        * TODO: trocar por template
1399        */
1400        blkAddAtendee.find('ul.search-result-list').empty().css('overflow', 'hidden');
1401        if (!result) {
1402            blkAddAtendee.find('ul.search-result-list').append('<li><label class="empty">Nenhum resultado encontrado.</label></li>');
1403        }
1404
1405        for(i=0; i<result.length; i++)
1406            result[i].enabled = (blkAddAtendee.find('dd.attendee-list ul.attendee-list label.mail[title="' +  result[i].mail + '"]').length) ? false : true;
1407                                                                                       
1408        blkAddAtendee.find('ul.search-result-list').append(DataLayer.render( path+'templates/participants_search_itemlist.ejs', result));
1409
1410        blkAddAtendee.find('ul.search-result-list li').click(function(event, ui){
1411            if ($(event.target).is('input')) {
1412                old_item = $(event.target).parents('li');
1413                newAttendeeId = DataLayer.put('participant', {
1414                    user: old_item.find('.id').html(),
1415                    isExternal: old_item.find('.isExternal').html()
1416                });
1417                                                       
1418                attendees[old_item.find('.id').html()] = old_item.find('.name').html();
1419                                                       
1420                blkAddAtendee.find('dd.attendee-list ul.attendee-list')
1421                .append(DataLayer.render(path+'templates/participants_add_itemlist.ejs', [{
1422                    id: newAttendeeId,
1423                    name: old_item.find('.name').html(),
1424                    mail: old_item.find('.mail').html(),
1425                    isExternal: old_item.find('.isExternal').html(),
1426                    acl: objEvent.acl,
1427                    isDirty: !!!objEvent.id,
1428            isDelegate: (objEvent.id && (objEvent.me.status == '5'))
1429                    }]))
1430                .scrollTo('max');
1431                /**
1432                                                        * Delegação de participação de um participante com permissão apenas de leitura
1433                                                        *
1434                                                        */
1435                if(!objEvent.acl.organization && !objEvent.acl.write && !objEvent.acl.inviteGuests && objEvent.acl.read ){
1436                                                               
1437                    blkAddAtendee.find('.block-add-attendee.search').addClass('hidden');
1438                    blkAddAtendee.find('.block-add-attendee.search dt').html('Adicionar outros contatos');
1439                                                               
1440                    blkAddAtendee.find('.status option').toggleClass('hidden');
1441                    blkAddAtendee.find('option[value=5]').attr('selected','selected').trigger('change');
1442                    blkAddAtendee.find('.request-update').removeClass('hidden');
1443
1444                    blkAddAtendee.find('dd.attendee-list ul.attendee-list li .button.close').parents('li').find('input[name="delegatedFrom[]"]').val(blkAddAtendee.find('.me input[name="attendee[]"]').val());
1445                                                               
1446                    blkAddAtendee.find('.me .participant-delegate').addClass('disable ui-button-disabled ui-state-disabled');
1447                    blkAddAtendee.find(".button.close").button({
1448                        icons: {
1449                            primary: "ui-icon-close"
1450                        },
1451                        text: false
1452                    }).click(function () {
1453                                                                       
1454                        $(this).parents('li').find('input[name="delegatedFrom[]"]').val('');
1455                        blkAddAtendee.find('.request-update').addClass('hidden');
1456                        blkAddAtendee.find('.status option').toggleClass('hidden');
1457                        blkAddAtendee.find('option[value=1]').attr('selected','selected').trigger('change');                   
1458                        blkAddAtendee.find('.me .participant-delegate').removeClass('disable ui-button-disabled ui-state-disabled attendee-permissions-change-button')
1459                        .find('.ui-icon-person').removeClass('attendee-permissions-change').end();                     
1460                                                                       
1461                        DataLayer.remove('participant', $(this).parents('li').find('[type=checkbox]').val());
1462                        $(this).parents('li').remove();
1463                    })
1464                    .addClass('tiny');
1465                }else{
1466                    callbackAttendee();
1467                    old_item.remove();
1468                }
1469            }
1470        });
1471
1472        event.preventDefault();
1473    }
1474});
1475
1476//$('.block-add-attendee .search-result-list').selectable();
1477
1478UI.dialogs.addEvent.find('.row.fileupload-buttonbar .button').filter('.delete').button({
1479    icons: {
1480        primary: "ui-icon-close"
1481    },
1482    text: 'Excluir'
1483}).click(function () {
1484    $.Zebra_Dialog('Tem certeza que deseja excluir todos anexos?', {
1485        'type':     'question',
1486        'overlay_opacity': '0.5',
1487        'buttons':  ['Sim', 'Não'],
1488        'onClose':  function(clicked) {
1489            if(clicked == 'Sim'){
1490               
1491                var ids = [];
1492                $.each($('.attachment-list input'), function (i, input) {
1493                     DataLayer.remove('schedulableToAttachment', {
1494                        filter: ['=', 'id', ''+input.value]
1495                        });
1496                });
1497                $('div.new-event-win .attachment-list input').remove();
1498                $('div.new-event-win .row.fileupload-buttonbar .attachments-list p').remove();
1499                $('div.new-event-win .btn-danger.delete').addClass('hidden');
1500            }
1501        }});
1502}).end()
1503.filter('.close').button({
1504    icons: {
1505        primary: "ui-icon-close"
1506    },
1507    text: false
1508}).click(function () {
1509    DataLayer.remove('schedulableToAttachment', $(this).parents('p').find('input[name="fileId[]"]').val());
1510    $(this).parents('p').remove();
1511}).end()
1512.filter('.downlaod-archive').button({
1513    icons: {
1514        primary: "ui-icon-arrowthickstop-1-s"
1515    },
1516    text: false
1517});
1518
1519extendsFileupload('event', path);
1520       
1521if(objEvent.isShared){
1522               
1523    var acls = Calendar.signatureOf[objEvent.calendar].permission.acl;
1524               
1525    if(!acls.write){
1526        UI.dialogs.addEvent.find(':input').attr('disabled', 'disabled');
1527        UI.dialogs.addEvent.find('.button').hide();
1528    }
1529               
1530    if(acls.remove)
1531        UI.dialogs.addEvent.find('.button.remove').show();
1532   
1533    UI.dialogs.addEvent.find('.button.cancel').show(); 
1534}
1535
1536disponibily(objEvent, path, attendees, 'event');
1537
1538/*Seleciona a agenda padrão para criação de um evento*/
1539if(!objEvent.id){
1540    var selectedCalendar = (objEvent.calendar != undefined) ? objEvent.calendar : (User.preferences.defaultCalendar ? User.preferences.defaultCalendar : myCalendar());
1541    UI.dialogs.addEvent.find('option[value="'+selectedCalendar+'"]').attr('selected','selected').trigger('change');
1542}
1543UI.dialogs.addEvent.find(':input').change(function(event){
1544    if (event.keyCode != '27' && event.keyCode != '13')
1545        canDiscardEventDialog = false;
1546}).keydown(function(event){
1547    if (event.keyCode != '27' && event.keyCode != '13')
1548        canDiscardEventDialog = false;
1549});     
1550
1551UI.dialogs.addEvent.dialog('open');
1552
1553}
1554
1555
1556
1557function add_tab_preferences()
1558{
1559    if(!(document.getElementById('preference_tab')))
1560    {
1561        var tab_title = "Preferencias";
1562        $tabs.tabs( "add", "#preference_tab", tab_title );
1563               
1564        /*
1565                DataLayer.render( 'templates/timezone_list.ejs', {}, function( timezones_options ){
1566                        tabPrefCalendar.find('select[name="timezone"]').html(timezones_options).find('option[value="'+User.preferences.timezone+'"]').attr('selected','selected').trigger('change');
1567                });
1568                */
1569        DataLayer.render( 'templates/preferences_calendar.ejs', {
1570            preferences:User.preferences,
1571            calendars: Calendar.calendars,
1572        signatureOf : Calendar.signatureOf
1573            }, function( template ){
1574            var tabPrefCalendar = jQuery('#preference_tab').html( template ).find('.preferences-win');
1575               
1576            tabPrefCalendar.find('select[name="defaultCalendar"] option[value="'+User.preferences.defaultCalendar+'"]').attr('selected','selected').trigger('change');
1577        tabPrefCalendar.find('select[name="dafaultImportCalendar"] option[value="'+User.preferences.dafaultImportCalendar+'"]').attr('selected','selected').trigger('change');
1578
1579        DataLayer.render( 'templates/timezone_list.ejs', {}, function( timezones_options ){
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  (parseInt(type) == 3) ? participant.id : participant ;
2947        });
2948
2949        //Edit ocurrence
2950        if(parseInt(type) == 3){
2951            newSchedulable.endTime = !!evt.end  ? evt.end.getTime() :  ((evt.start).getTime() + 86400000);
2952            newSchedulable.startTime = evt.start.getTime();
2953                   
2954            return newSchedulable;
2955        }
2956        newSchedulable.endTime = new Date(parseInt(newSchedulable.endTime) - (parseInt(newSchedulable.allDay) ? 86400000 : 0)).toString('yyyy-MM-dd HH:mm:00');
2957        newSchedulable.startTime = new Date(parseInt(newSchedulable.startTime)).toString('yyyy-MM-dd HH:mm:00');
2958       
2959        DataLayer.put('schedulable', newSchedulable);
2960
2961    }
2962}
2963
2964function messageHelper(msg, isShow){
2965    if(isShow)
2966        new $.Zebra_Dialog('<span style="width: 50px; height: 50px;">'+
2967                            '<img src="'+DataLayer.dispatchPath+'/modules/calendar/img/loading.gif"></img>'+
2968                        '</span><label class="messagesHelpers"> '+ msg +' </label>' , {
2969                        'buttons':  false,
2970                        'modal': true,
2971                        'overlay_opacity': '0.5',
2972                        'keyboard': false,
2973                        'overlay_close': false,
2974                        'type': false,
2975                        'custom_class': 'messagesHelpersExpressoCalendar'
2976                        }
2977                    );
2978    else{
2979        $('.messagesHelpersExpressoCalendar').remove();
2980        $('.ZebraDialogOverlay').remove();
2981    }
2982}
2983
2984function extendsFileupload(view, path){
2985    var viewName = 'div.new-'+view+'-win';
2986   
2987    path = !!path ? path : '';
2988   
2989    var maxSizeFile = 2000000;
2990    $('#fileupload'+view).fileupload({
2991        sequentialUploads: true,
2992        add: function (e, data) {
2993            if(data.files[0].size < maxSizeFile)
2994                data.submit();
2995        },
2996        change: function (e, data) {
2997            $.each(data.files, function (index, file) {
2998                var attach = {};
2999                attach.fileName = file.name;
3000                var ext = file.name.split('.');
3001                if(file.name.length > 10)
3002                    attach.fileName = ext.length == 1 ? file.name.substr(0, 10) :  file.name.substr(0, 6) + '.' + ext[ext.length -1];
3003                attach.fileSize = formatBytes(file.size);
3004                if(file.size > maxSizeFile)
3005                    attach.error = 'Tamanho de arquivo nao permitido!!'
3006                               
3007                $(viewName+' .attachments-list').append(DataLayer.render(path+'templates/attachment_add_itemlist.ejs', {
3008                    file : attach
3009                }));
3010                               
3011                if(file.size < maxSizeFile){
3012                    $(viewName+' .fileinput-button.new').append(data.fileInput[0]).removeClass('new');
3013                    $(viewName+' .attachments-list').find('[type=file]').addClass('hidden');
3014                                       
3015                }else
3016                    $(viewName+' .fileinput-button.new').removeClass('new');
3017                               
3018                               
3019                $(viewName+' .attachments-list').find('.button.close').button({
3020                    icons: {
3021                        primary: "ui-icon-close"
3022                    },
3023                    text: false
3024                }).click(function(){
3025                    var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
3026                    $(viewName+' .attachment-list').find('input[value="'+idAttach+'"]').remove();
3027                    $(this).parent().remove();
3028               
3029                    if(!$(viewName+' .attachment-list input').length)
3030                        $(viewName+' .btn-danger.delete').addClass('hidden');
3031               
3032                });     
3033                               
3034            })
3035        },
3036        done: function(e, data){
3037            var currentUpload = $(viewName+' .progress.after-upload:first').removeClass('after-upload').addClass('on-complete').hide();
3038
3039            if(!!data.result && data.result != "[]"){
3040                $(viewName+' .btn-danger.delete').removeClass('hidden');
3041                var newAttach = (attch = jQuery.parseJSON(data.result)) ? attch : jQuery.parseJSON(data.result[0].activeElement.childNodes[0].data);
3042                $(viewName+' .attachment-list').append('<input tyepe="hidden" name="attachment[]" value="'+newAttach['attachment'][0][0].id+'"/>');
3043                currentUpload.removeClass('on-complete').parents('p')
3044                .append('<input type="hidden" name="fileId[]" value="'+newAttach['attachment'][0][0].id+'"/>')
3045                .find('.status-upload').addClass('ui-icon ui-icon-check');
3046            }else
3047                currentUpload.removeClass('on-complete').parents('p').find('.status-upload').addClass('ui-icon ui-icon-cancel');
3048        }
3049    });
3050    $('.attachments-list .button').button();   
3051
3052    if(!!window.FormData)                       
3053        $('#fileupload'+view).bind('fileuploadstart', function () {
3054            var widget = $(this),
3055            progressElement = $('#fileupload-progress-'+view).fadeIn(),
3056            interval = 500,
3057            total = 0,
3058            loaded = 0,
3059            loadedBefore = 0,
3060            progressTimer,
3061            progressHandler = function (e, data) {
3062                loaded = data.loaded;
3063                total = data.total;
3064            },
3065            stopHandler = function () {
3066                widget
3067                .unbind('fileuploadprogressall', progressHandler)
3068                .unbind('fileuploadstop', stopHandler);
3069                window.clearInterval(progressTimer);
3070                progressElement.fadeOut(function () {
3071                    progressElement.html('');
3072                });
3073            },
3074            formatTime = function (seconds) {
3075                var date = new Date(seconds * 1000);
3076                return ('0' + date.getUTCHours()).slice(-2) + ':' +
3077                ('0' + date.getUTCMinutes()).slice(-2) + ':' +
3078                ('0' + date.getUTCSeconds()).slice(-2);
3079            },
3080            /* formatBytes = function (bytes) {
3081            if (bytes >= 1000000000) {
3082                return (bytes / 1000000000).toFixed(2) + ' GB';
3083            }
3084            if (bytes >= 1000000) {
3085                return (bytes / 1000000).toFixed(2) + ' MB';
3086            }
3087            if (bytes >= 1000) {
3088                return (bytes / 1000).toFixed(2) + ' KB';
3089            }
3090            return bytes + ' B';
3091        },*/
3092            formatPercentage = function (floatValue) {
3093                return (floatValue * 100).toFixed(2) + ' %';
3094            },
3095            updateProgressElement = function (loaded, total, bps) {
3096                progressElement.html(
3097                    formatBytes(bps) + 'ps | ' +
3098                    formatTime((total - loaded) / bps) + ' | ' +
3099                    formatPercentage(loaded / total) + ' | ' +
3100                    formatBytes(loaded) + ' / ' + formatBytes(total)
3101                    );
3102            },
3103            intervalHandler = function () {
3104                var diff = loaded - loadedBefore;
3105                if (!diff) {
3106                    return;
3107                }
3108                loadedBefore = loaded;
3109                updateProgressElement(
3110                    loaded,
3111                    total,
3112                    diff * (1000 / interval)
3113                    );
3114            };
3115            widget
3116            .bind('fileuploadprogressall', progressHandler)
3117            .bind('fileuploadstop', stopHandler);
3118            progressTimer = window.setInterval(intervalHandler, interval);
3119        });
3120   
3121}
Note: See TracBrowser for help on using the repository browser.