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

Revision 8021, 106.6 KB checked in by douglas, 11 years ago (diff)

Ticket #3392 - Preferencia para que a visualizacao diaria fique sem as horas

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