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

Revision 7980, 105.8 KB checked in by cristiano, 11 years ago (diff)

Ticket #3378 - Importação automatica de eventos nos participantes

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