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

Revision 7992, 106.5 KB checked in by douglas, 11 years ago (diff)

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

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