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

Revision 7996, 106.9 KB checked in by thiago, 11 years ago (diff)

Ticket #3383 - Implementado a melhoria de time e date no calendar.

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