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

Revision 7983, 106.2 KB checked in by cristiano, 11 years ago (diff)

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

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