[MERGE] forward port of branch 8.0 up to 591e329
[odoo/odoo.git] / addons / web_calendar / static / src / js / web_calendar.js
1 /*---------------------------------------------------------
2  * OpenERP web_calendar
3  *---------------------------------------------------------*/
4
5 _.str.toBoolElse = function (str, elseValues, trueValues, falseValues) {
6     var ret = _.str.toBool(str, trueValues, falseValues);
7     if (_.isUndefined(ret)) {
8         return elseValues;
9     }
10     return ret;
11 };
12
13 openerp.web_calendar = function(instance) {
14     var _t = instance.web._t,
15         _lt = instance.web._lt,
16         QWeb = instance.web.qweb;
17
18     function get_class(name) {
19         return new instance.web.Registry({'tmp' : name}).get_object("tmp");
20     }
21
22     function get_fc_defaultOptions() {
23         shortTimeformat = moment._locale._longDateFormat.LT;
24         var dateFormat = instance.web.normalize_format(_t.database.parameters.date_format);
25         return {
26             weekNumberTitle: _t("W"),
27             allDayText: _t("All day"),
28             buttonText : {
29                 today:    _t("Today"),
30                 month:    _t("Month"),
31                 week:     _t("Week"),
32                 day:      _t("Day")
33             },
34             monthNames: moment.months(),
35             monthNamesShort: moment.monthsShort(),
36             dayNames: moment.weekdays(),
37             dayNamesShort: moment.weekdaysShort(),
38             firstDay: moment._locale._week.dow,
39             weekNumbers: true,
40             axisFormat : shortTimeformat.replace(/:mm/,'(:mm)'),
41             timeFormat : {
42                // for agendaWeek and agendaDay               
43                agenda: shortTimeformat + '{ - ' + shortTimeformat + '}', // 5:00 - 6:30
44                 // for all other views
45                 '': shortTimeformat.replace(/:mm/,'(:mm)')  // 7pm
46             },
47             titleFormat: {
48                 month: 'MMMM yyyy',
49                 week: dateFormat + "{ '—'"+ dateFormat,
50                 day: dateFormat,
51             },
52             columnFormat: {
53                 month: 'ddd',
54                 week: 'ddd ' + dateFormat,
55                 day: 'dddd ' + dateFormat,
56             },
57             weekMode : 'liquid',
58             aspectRatio: 1.8,
59             snapMinutes: 15,
60         };
61     }
62
63     function is_virtual_id(id) {
64         return typeof id === "string" && id.indexOf('-') >= 0;
65     }
66
67     function isNullOrUndef(value) {
68         return _.isUndefined(value) || _.isNull(value);
69     }
70
71     instance.web.views.add('calendar', 'instance.web_calendar.CalendarView');
72
73     instance.web_calendar.CalendarView = instance.web.View.extend({
74         template: "CalendarView",
75         display_name: _lt('Calendar'),
76         quick_create_instance: 'instance.web_calendar.QuickCreate',
77
78         init: function (parent, dataset, view_id, options) {
79             this._super(parent);
80             this.ready = $.Deferred();
81             this.set_default_options(options);
82             this.dataset = dataset;
83             this.model = dataset.model;
84             this.fields_view = {};
85             this.view_id = view_id;
86             this.view_type = 'calendar';
87             this.color_map = {};
88             this.range_start = null;
89             this.range_stop = null;
90             this.selected_filters = [];
91
92             this.shown = $.Deferred();
93         },
94
95         set_default_options: function(options) {
96             this._super(options);
97             _.defaults(this.options, {
98                 confirm_on_delete: true
99             });
100         },
101
102         destroy: function() {
103             this.$calendar.fullCalendar('destroy');
104             if (this.$small_calendar) {
105                 this.$small_calendar.datepicker('destroy');
106             }
107             this._super.apply(this, arguments);
108         },
109
110         view_loading: function (fv) {
111             /* xml view calendar options */
112             var attrs = fv.arch.attrs,
113                 self = this;
114             this.fields_view = fv;
115             this.$calendar = this.$el.find(".oe_calendar_widget");
116
117             this.info_fields = [];
118
119             /* buttons */
120             this.$buttons = $(QWeb.render("CalendarView.buttons", {'widget': this}));
121             if (this.options.$buttons) {
122                 this.$buttons.appendTo(this.options.$buttons);
123             } else {
124                 this.$el.find('.oe_calendar_buttons').replaceWith(this.$buttons);
125             }
126
127             this.$buttons.on('click', 'button.oe_calendar_button_new', function () {
128                 self.dataset.index = null;
129                 self.do_switch_view('form');
130             });
131
132             if (!attrs.date_start) {
133                 throw new Error(_t("Calendar view has not defined 'date_start' attribute."));
134             }
135
136             this.$el.addClass(attrs['class']);
137
138             this.name = fv.name || attrs.string;
139             this.view_id = fv.view_id;
140
141             this.mode = attrs.mode;                 // one of month, week or day
142             this.date_start = attrs.date_start;     // Field name of starting date field
143             this.date_delay = attrs.date_delay;     // duration
144             this.date_stop = attrs.date_stop;
145             this.all_day = attrs.all_day;
146             this.how_display_event = '';
147             this.attendee_people = attrs.attendee;
148
149             if (!isNullOrUndef(attrs.quick_create_instance)) {
150                 self.quick_create_instance = 'instance.' + attrs.quick_create_instance;
151             }
152
153             //if quick_add = False, we don't allow quick_add
154             //if quick_add = not specified in view, we use the default quick_create_instance
155             //if quick_add = is NOT False and IS specified in view, we this one for quick_create_instance'   
156
157             this.quick_add_pop = (isNullOrUndef(attrs.quick_add) || _.str.toBoolElse(attrs.quick_add, true));
158             if (this.quick_add_pop && !isNullOrUndef(attrs.quick_add)) {
159                 self.quick_create_instance = 'instance.' + attrs.quick_add;
160             }
161             // The display format which will be used to display the event where fields are between "[" and "]"
162             if (!isNullOrUndef(attrs.display)) {
163                 this.how_display_event = attrs.display; // String with [FIELD]
164             }
165
166             // If this field is set ot true, we don't open the event in form view, but in a popup with the view_id passed by this parameter
167             if (isNullOrUndef(attrs.event_open_popup) || !_.str.toBoolElse(attrs.event_open_popup, true)) {
168                 this.open_popup_action = false;
169             } else {
170                 this.open_popup_action = attrs.event_open_popup;
171             }
172             // If this field is set to true, we will use the calendar_friends model as filter and not the color field.
173             this.useContacts = (!isNullOrUndef(attrs.use_contacts) && _.str.toBool(attrs.use_contacts)) && (!isNullOrUndef(self.options.$sidebar));
174
175             // If this field is set ot true, we don't add itself as an attendee when we use attendee_people to add each attendee icon on an event
176             // The color is the color of the attendee, so don't need to show again that it will be present
177             this.colorIsAttendee = (!(isNullOrUndef(attrs.color_is_attendee) || !_.str.toBoolElse(attrs.color_is_attendee, true))) && (!isNullOrUndef(self.options.$sidebar));
178
179             // if we have not sidebar, (eg: Dashboard), we don't use the filter "coworkers"
180             if (isNullOrUndef(self.options.$sidebar)) {
181                 this.useContacts = false;
182                 this.colorIsAttendee = false;
183                 this.attendee_people = undefined;
184             }
185
186 /*
187             Will be more logic to do it in futur, but see below to stay Retro-compatible
188             
189             if (isNull(attrs.avatar_model)) {
190                 this.avatar_model = 'res.partner'; 
191             }
192             else {
193                 if (attrs.avatar_model == 'False') {
194                     this.avatar_model = null;
195                 }
196                 else {  
197                     this.avatar_model = attrs.avatar_model;
198                 }
199             }            
200 */
201             if (isNullOrUndef(attrs.avatar_model)) {
202                 this.avatar_model = null;
203             } else {
204                 this.avatar_model = attrs.avatar_model;
205             }
206
207             if (isNullOrUndef(attrs.avatar_title)) {
208                 this.avatar_title = this.avatar_model;
209             } else {
210                 this.avatar_title = attrs.avatar_title;
211             }
212
213             if (isNullOrUndef(attrs.avatar_filter)) {
214                 this.avatar_filter = this.avatar_model;
215             } else {
216                 this.avatar_filter = attrs.avatar_filter;
217             }
218
219             this.color_field = attrs.color;
220
221             if (this.color_field && this.selected_filters.length === 0) {
222                 var default_filter;
223                 if ((default_filter = this.dataset.context['calendar_default_' + this.color_field])) {
224                     this.selected_filters.push(default_filter + '');
225                 }
226             }
227
228             this.fields = fv.fields;
229
230             for (var fld = 0; fld < fv.arch.children.length; fld++) {
231                 this.info_fields.push(fv.arch.children[fld].attrs.name);
232             }
233
234             self.shown.done(this._do_show_init.bind(this));
235             var edit_check = new instance.web.Model(this.dataset.model)
236                 .call("check_access_rights", ["write", false])
237                 .then(function (write_right) {
238                     self.write_right = write_right;
239                 });
240             var init = new instance.web.Model(this.dataset.model)
241                 .call("check_access_rights", ["create", false])
242                 .then(function (create_right) {
243                     self.create_right = create_right;
244                     self.ready.resolve();
245                     self.trigger('calendar_view_loaded', fv);
246                 });
247             return $.when(edit_check, init);
248         },
249         _do_show_init: function () {
250             var self = this;
251             this.init_calendar().then(function() {
252                 $(window).trigger('resize');
253                 self.trigger('calendar_view_loaded', self.fields_view);
254             });
255         },
256         get_fc_init_options: function () {
257             //Documentation here : http://arshaw.com/fullcalendar/docs/
258             var self = this;
259             return  $.extend({}, get_fc_defaultOptions(), {
260                 
261                 defaultView: (this.mode == "month")?"month":
262                     (this.mode == "week"?"agendaWeek":
263                      (this.mode == "day"?"agendaDay":"month")),
264                 header: {
265                     left: 'prev,next today',
266                     center: 'title',
267                     right: 'month,agendaWeek,agendaDay'
268                 },
269                 selectable: !this.options.read_only_mode && this.create_right,
270                 selectHelper: true,
271                 editable: !this.options.read_only_mode,
272                 droppable: true,
273
274                 // callbacks
275
276                 eventDrop: function (event, _day_delta, _minute_delta, _all_day, _revertFunc) {
277                     var data = self.get_event_data(event);
278                     self.proxy('update_record')(event._id, data); // we don't revert the event, but update it.
279                 },
280                 eventResize: function (event, _day_delta, _minute_delta, _revertFunc) {
281                     var data = self.get_event_data(event);
282                     self.proxy('update_record')(event._id, data);
283                 },
284                 eventRender: function (event, element, view) {
285                     element.find('.fc-event-title').html(event.title);
286                 },
287                 eventAfterRender: function (event, element, view) {
288                     if ((view.name !== 'month') && (((event.end-event.start)/60000)<=30)) {
289                         //if duration is too small, we see the html code of img
290                         var current_title = $(element.find('.fc-event-time')).text();
291                         var new_title = current_title.substr(0,current_title.indexOf("<img")>0?current_title.indexOf("<img"):current_title.length);
292                         element.find('.fc-event-time').html(new_title);
293                     }
294                 },
295                 eventClick: function (event) { self.open_event(event._id,event.title); },
296                 select: function (start_date, end_date, all_day, _js_event, _view) {
297                     var data_template = self.get_event_data({
298                         start: start_date,
299                         end: end_date,
300                         allDay: all_day,
301                     });
302                     self.open_quick_create(data_template);
303
304                 },
305
306                 unselectAuto: false,
307
308
309             });
310         },
311
312         calendarMiniChanged: function (context) {
313             return function(datum,obj) {
314                 var curView = context.$calendar.fullCalendar( 'getView');
315                 var curDate = new Date(obj.currentYear , obj.currentMonth, obj.currentDay);
316
317                 if (curView.name == "agendaWeek") {
318                     if (curDate <= curView.end && curDate >= curView.start) {
319                         context.$calendar.fullCalendar('changeView','agendaDay');
320                     }
321                 }
322                 else if (curView.name != "agendaDay" || (curView.name == "agendaDay" && moment(curDate).diff(moment(curView.start))===0)) {
323                         context.$calendar.fullCalendar('changeView','agendaWeek');
324                 }
325                 context.$calendar.fullCalendar('gotoDate', obj.currentYear , obj.currentMonth, obj.currentDay);
326             };
327         },
328
329         init_calendar: function() {
330             var self = this;
331              
332             if (!this.sidebar && this.options.$sidebar) {
333                 translate = get_fc_defaultOptions();
334                 this.sidebar = new instance.web_calendar.Sidebar(this);
335                 this.sidebar.appendTo(this.$el.find('.oe_calendar_sidebar_container'));
336
337                 this.$small_calendar = self.$el.find(".oe_calendar_mini");
338                 this.$small_calendar.datepicker({ 
339                     onSelect: self.calendarMiniChanged(self),
340                     dayNamesMin : translate.dayNamesShort,
341                     monthNames: translate.monthNamesShort,
342                     firstDay: translate.firstDay,
343                 });
344
345                 this.extraSideBar();                
346             }
347             self.$calendar.fullCalendar(self.get_fc_init_options());
348             
349             return $.when();
350         },
351         extraSideBar: function() {
352         },
353
354         open_quick_create: function(data_template) {
355             if (!isNullOrUndef(this.quick)) {
356                 return this.quick.trigger('close');
357             }
358             var QuickCreate = get_class(this.quick_create_instance);
359             
360             this.options.disable_quick_create =  this.options.disable_quick_create || !this.quick_add_pop;
361             
362             this.quick = new QuickCreate(this, this.dataset, true, this.options, data_template);
363             this.quick.on('added', this, this.quick_created)
364                     .on('slowadded', this, this.slow_created)
365                     .on('close', this, function() {
366                         this.quick.destroy();
367                         delete this.quick;
368                         this.$calendar.fullCalendar('unselect');
369                     });
370             this.quick.replace(this.$el.find('.oe_calendar_qc_placeholder'));
371             this.quick.focus();
372             
373         },
374
375         /**
376          * Refresh one fullcalendar event identified by it's 'id' by reading OpenERP record state.
377          * If event was not existent in fullcalendar, it'll be created.
378          */
379         refresh_event: function(id) {
380             var self = this;
381             if (is_virtual_id(id)) {
382                 // Should avoid "refreshing" a virtual ID because it can't
383                 // really be modified so it should never be refreshed. As upon
384                 // edition, a NEW event with a non-virtual id will be created.
385                 console.warn("Unwise use of refresh_event on a virtual ID.");
386             }
387             this.dataset.read_ids([id], _.keys(this.fields)).done(function (incomplete_records) {
388                 self.perform_necessary_name_gets(incomplete_records).then(function(records) {
389                     // Event boundaries were already changed by fullcalendar, but we need to reload them:
390                     var new_event = self.event_data_transform(records[0]);
391                     // fetch event_obj
392                     var event_objs = self.$calendar.fullCalendar('clientEvents', id);
393                     if (event_objs.length == 1) { // Already existing obj to update
394                         var event_obj = event_objs[0];
395                         // update event_obj
396                         _(new_event).each(function (value, key) {
397                             event_obj[key] = value;
398                         });
399                         self.$calendar.fullCalendar('updateEvent', event_obj);
400                     } else { // New event object to create
401                         self.$calendar.fullCalendar('renderEvent', new_event);
402                         // By forcing attribution of this event to this source, we
403                         // make sure that the event will be removed when the source
404                         // will be removed (which occurs at each do_search)
405                         self.$calendar.fullCalendar('clientEvents', id)[0].source = self.event_source;
406                     }
407                 });
408             });
409         },
410
411         get_color: function(key) {
412             if (this.color_map[key]) {
413                 return this.color_map[key];
414             }
415             var index = (((_.keys(this.color_map).length + 1) * 5) % 24) + 1;
416             this.color_map[key] = index;
417             return index;
418         },
419         
420
421         /**
422          * In o2m case, records from dataset won't have names attached to their *2o values.
423          * We should make sure this is the case.
424          */
425         perform_necessary_name_gets: function(evts) {
426             var def = $.Deferred();
427             var self = this;
428             var to_get = {};
429             _(this.info_fields).each(function (fieldname) {
430                 if (!_(["many2one", "one2one"]).contains(
431                     self.fields[fieldname].type))
432                     return;
433                 to_get[fieldname] = [];
434                 _(evts).each(function (evt) {
435                     var value = evt[fieldname];
436                     if (value === false || (value instanceof Array)) {
437                         return;
438                     }
439                     to_get[fieldname].push(value);
440                 });
441                 if (to_get[fieldname].length === 0) {
442                     delete to_get[fieldname];
443                 }
444             });
445             var defs = _(to_get).map(function (ids, fieldname) {
446                 return (new instance.web.Model(self.fields[fieldname].relation))
447                     .call('name_get', ids).then(function (vals) {
448                         return [fieldname, vals];
449                     });
450             });
451
452             $.when.apply(this, defs).then(function() {
453                 var values = arguments;
454                 _(values).each(function(value) {
455                     var fieldname = value[0];
456                     var name_gets = value[1];
457                     _(name_gets).each(function(name_get) {
458                         _(evts).chain()
459                             .filter(function (e) {return e[fieldname] == name_get[0];})
460                             .each(function(evt) {
461                                 evt[fieldname] = name_get;
462                             });
463                     });
464                 });
465                 def.resolve(evts);
466             });
467             return def;
468         },
469         
470         /**
471          * Transform OpenERP event object to fullcalendar event object
472          */
473         event_data_transform: function(evt) {
474             var self = this;
475
476             var date_delay = evt[this.date_delay] || 1.0,
477                 all_day = this.all_day ? evt[this.all_day] : false,
478                 res_computed_text = '',
479                 the_title = '',
480                 attendees = [];
481
482             if (!all_day) {
483                 date_start = instance.web.auto_str_to_date(evt[this.date_start]);
484                 date_stop = this.date_stop ? instance.web.auto_str_to_date(evt[this.date_stop]) : null;
485             }
486             else {
487                 date_start = instance.web.auto_str_to_date(evt[this.date_start].split(' ')[0],'start');
488                 date_stop = this.date_stop ? instance.web.auto_str_to_date(evt[this.date_stop].split(' ')[0],'start') : null;
489             }
490
491             if (this.info_fields) {
492                 var temp_ret = {};
493                 res_computed_text = this.how_display_event;
494                 
495                 _.each(this.info_fields, function (fieldname) {
496                     var value = evt[fieldname];
497                     if (_.contains(["many2one", "one2one"], self.fields[fieldname].type)) {
498                         if (value === false) {
499                             temp_ret[fieldname] = null;
500                         }
501                         else if (value instanceof Array) {
502                             temp_ret[fieldname] = value[1]; // no name_get to make
503                         }
504                         else {
505                             throw new Error("Incomplete data received from dataset for record " + evt.id);
506                         }
507                     }
508                     else if (_.contains(["one2many","many2many"], self.fields[fieldname].type)) {
509                         if (value === false) {
510                             temp_ret[fieldname] = null;
511                         }
512                         else if (value instanceof Array)  {
513                             temp_ret[fieldname] = value; // if x2many, keep all id !
514                         }
515                         else {
516                             throw new Error("Incomplete data received from dataset for record " + evt.id);
517                         }
518                     }
519                     else {
520                         temp_ret[fieldname] = value;
521                     }
522                     res_computed_text = res_computed_text.replace("["+fieldname+"]",temp_ret[fieldname]);
523                 });
524
525                 
526                 if (res_computed_text.length) {
527                     the_title = res_computed_text;
528                 }
529                 else {
530                     var res_text= [];
531                     _.each(temp_ret, function(val,key) { res_text.push(val); });
532                     the_title = res_text.join(', ');
533                 }
534                 the_title = _.escape(the_title);
535                 
536                 
537                 the_title_avatar = '';
538                 
539                 if (! _.isUndefined(this.attendee_people)) {
540                     var MAX_ATTENDEES = 3;
541                     var attendee_showed = 0;
542                     var attendee_other = '';
543
544                     _.each(temp_ret[this.attendee_people],
545                         function (the_attendee_people) {
546                             attendees.push(the_attendee_people);
547                             attendee_showed += 1;
548                             if (attendee_showed<= MAX_ATTENDEES) {
549                                 if (self.avatar_model !== null) {
550                                        the_title_avatar += '<img title="' + self.all_attendees[the_attendee_people] + '" class="attendee_head"  \
551                                                             src="/web/binary/image?model=' + self.avatar_model + '&field=image_small&id=' + the_attendee_people + '"></img>';
552                                 }
553                                 else {
554                                     if (!self.colorIsAttendee || the_attendee_people != temp_ret[self.color_field]) {
555                                             tempColor = (self.all_filters[the_attendee_people] !== undefined) 
556                                                         ? self.all_filters[the_attendee_people].color
557                                                         : (self.all_filters[-1] ? self.all_filters[-1].color : 1);
558                                         the_title_avatar += '<i class="fa fa-user attendee_head color_'+tempColor+'" title="' + self.all_attendees[the_attendee_people] + '" ></i>';
559                                     }//else don't add myself
560                                 }
561                             }
562                             else {
563                                 attendee_other += self.all_attendees[the_attendee_people] +", ";
564                             }
565                         }
566                     );
567                     if (attendee_other.length>2) {
568                         the_title_avatar += '<span class="attendee_head" title="' + attendee_other.slice(0, -2) + '">+</span>';
569                     }
570                     the_title = the_title_avatar + the_title;
571                 }
572             }
573             
574             if (!date_stop && date_delay) {
575                 var m_start = moment(date_start).add(date_delay,'hours');
576                 date_stop = m_start.toDate();
577             }
578             var r = {
579                 'start': moment(date_start).format('YYYY-MM-DD HH:mm:ss'),
580                 'end': moment(date_stop).format('YYYY-MM-DD HH:mm:ss'),
581                 'title': the_title,
582                 'allDay': (this.fields[this.date_start].type == 'date' || (this.all_day && evt[this.all_day]) || false),
583                 'id': evt.id,
584                 'attendees':attendees
585             };
586             if (!self.useContacts || self.all_filters[evt[this.color_field]] !== undefined) {
587                 if (this.color_field && evt[this.color_field]) {
588                     var color_key = evt[this.color_field];
589                     if (typeof color_key === "object") {
590                         color_key = color_key[0];
591                     }
592                     r.className = 'cal_opacity calendar_color_'+ this.get_color(color_key);
593                 }
594             }
595             else  { // if form all, get color -1
596                   r.className = 'cal_opacity calendar_color_'+ self.all_filters[-1].color;
597             }
598             return r;
599         },
600         
601         /**
602          * Transform fullcalendar event object to OpenERP Data object
603          */
604         get_event_data: function(event) {
605
606             // Normalize event_end without changing fullcalendars event.
607             var data = {
608                 name: event.title
609             };            
610             
611             var event_end = event.end;
612             //Bug when we move an all_day event from week or day view, we don't have a dateend or duration...            
613             if (event_end == null) {
614                 var m_date = moment(event.start).add(2, 'hours');
615                 event_end = m_date.toDate();
616             }
617
618             if (event.allDay) {
619                 // Sometimes fullcalendar doesn't give any event.end.
620                 if (event_end == null || _.isUndefined(event_end)) {
621                     event_end = new Date(event.start);
622                 }
623                 if (this.all_day) {
624                     date_start_day = new Date(Date.UTC(event.start.getFullYear(),event.start.getMonth(),event.start.getDate()));
625                     date_stop_day = new Date(Date.UTC(event_end.getFullYear(),event_end.getMonth(),event_end.getDate()));                    
626                 }
627                 else {
628                     date_start_day = new Date(event.start.getFullYear(),event.start.getMonth(),event.start.getDate(),7);
629                     date_stop_day = new Date(event_end.getFullYear(),event_end.getMonth(),event_end.getDate(),19);
630                 }
631                 data[this.date_start] = instance.web.datetime_to_str(date_start_day);
632                 if (this.date_stop) {
633                     data[this.date_stop] = instance.web.datetime_to_str(date_stop_day);
634                 }
635                 diff_seconds = Math.round((date_stop_day.getTime() - date_start_day.getTime()) / 1000);
636                                 
637             }
638             else {
639                 data[this.date_start] = instance.web.datetime_to_str(event.start);
640                 if (this.date_stop) {
641                     data[this.date_stop] = instance.web.datetime_to_str(event_end);
642                 }
643                 diff_seconds = Math.round((event_end.getTime() - event.start.getTime()) / 1000);
644             }
645
646             if (this.all_day) {
647                 data[this.all_day] = event.allDay;
648             }
649
650             if (this.date_delay) {
651                 
652                 data[this.date_delay] = diff_seconds / 3600;
653             }
654             return data;
655         },
656
657         do_search: function (domain, context, _group_by) {
658             var self = this;
659             this.shown.done(function () {
660                 self._do_search(domain, context, _group_by);
661             });
662         },
663         _do_search: function(domain, context, _group_by) {
664             var self = this;
665            if (! self.all_filters) {            
666                 self.all_filters = {}                
667            }
668
669             if (! _.isUndefined(this.event_source)) {
670                 this.$calendar.fullCalendar('removeEventSource', this.event_source);
671             }
672             this.event_source = {
673                 events: function(start, end, callback) {
674                     var current_event_source = self.event_source;
675                     self.dataset.read_slice(_.keys(self.fields), {
676                         offset: 0,
677                         domain: self.get_range_domain(domain, start, end),
678                         context: context,
679                     }).done(function(events) {
680                         if (self.dataset.index === null) {
681                             if (events.length) {
682                                 self.dataset.index = 0;
683                             }
684                         } else if (self.dataset.index >= events.length) {
685                             self.dataset.index = events.length ? 0 : null;
686                         }
687
688                         if (self.event_source !== current_event_source) {
689                             console.log("Consecutive ``do_search`` called. Cancelling.");
690                             return;
691                         }
692                         
693                         if (!self.useContacts) {  // If we use all peoples displayed in the current month as filter in sidebars
694                             var filter_value;
695                             var filter_item;
696                             
697                             self.now_filter_ids = [];
698
699                             _.each(events, function (e) {
700                                 filter_value = e[self.color_field][0];
701                                 if (!self.all_filters[e[self.color_field][0]]) {
702                                     filter_item = {
703                                         value: filter_value,
704                                         label: e[self.color_field][1],
705                                         color: self.get_color(filter_value),
706                                         avatar_model: (_.str.toBoolElse(self.avatar_filter, true) ? self.avatar_filter : false ),
707                                         is_checked: true
708                                     };
709                                     self.all_filters[e[self.color_field][0]] = filter_item;
710                                 }
711                                 if (! _.contains(self.now_filter_ids, filter_value)) {
712                                     self.now_filter_ids.push(filter_value);
713                                 }
714                             });
715
716                             if (self.sidebar) {
717                                 self.sidebar.filter.events_loaded();
718                                 self.sidebar.filter.set_filters();
719                                 
720                                 events = $.map(events, function (e) {
721                                     if (_.contains(self.now_filter_ids,e[self.color_field][0]) &&  self.all_filters[e[self.color_field][0]].is_checked) {
722                                         return e;
723                                     }
724                                     return null;
725                                 });
726                             }
727                             
728                         }
729                         else { //WE USE CONTACT
730                             if (self.attendee_people !== undefined) {
731                                 //if we don't filter on 'Everybody's Calendar
732                                 if (!self.all_filters[-1] || !self.all_filters[-1].is_checked) {
733                                     var checked_filter = $.map(self.all_filters, function(o) { if (o.is_checked) { return o.value; }});
734                                     // If we filter on contacts... we keep only events from coworkers
735                                     events = $.map(events, function (e) {
736                                         if (_.intersection(checked_filter,e[self.attendee_people]).length) {
737                                             return e;
738                                         }
739                                         return null;
740                                     });
741                                 }
742                             }
743
744                             
745                         }
746
747                         var all_attendees = $.map(events, function (e) { return e[self.attendee_people]; });
748                         all_attendees = _.chain(all_attendees).flatten().uniq().value();
749
750                         self.all_attendees = {};
751                         if (self.avatar_title !== null) {
752                             new instance.web.Model(self.avatar_title).query(["name"]).filter([["id", "in", all_attendees]]).all().then(function(result) {
753                                 _.each(result, function(item) {
754                                     self.all_attendees[item.id] = item.name;
755                                 });
756                             }).done(function() {
757                                 return self.perform_necessary_name_gets(events).then(callback);
758                             });
759                         }
760                         else {
761                             _.each(all_attendees,function(item){
762                                     self.all_attendees[item] = '';
763                             });
764                             return self.perform_necessary_name_gets(events).then(callback);
765                         }
766                     });
767                 },
768                 eventDataTransform: function (event) {
769                     return self.event_data_transform(event);
770                 },
771             };
772             this.$calendar.fullCalendar('addEventSource', this.event_source);
773         },
774         /**
775          * Build OpenERP Domain to filter object by this.date_start field
776          * between given start, end dates.
777          */
778         get_range_domain: function(domain, start, end) {
779             var format = instance.web.date_to_str;
780             
781             extend_domain = [[this.date_start, '>=', format(start)],
782                      [this.date_start, '<=', format(end)]];
783
784             if (this.date_stop) {
785                 //add at start 
786                 extend_domain.splice(0,0,'|','|','&');
787                 //add at end 
788                 extend_domain.push(
789                                 '&',
790                                 [this.date_start, '<=', format(start)],
791                                 [this.date_stop, '>=', format(start)],
792                                 '&',
793                                 [this.date_start, '<=', format(end)],
794                                 [this.date_stop, '>=', format(start)]
795                 );
796                 //final -> (A & B) | (C & D) | (E & F) ->  | | & A B & C D & E F
797             }
798             return new instance.web.CompoundDomain(domain, extend_domain);
799         },
800
801         /**
802          * Updates record identified by ``id`` with values in object ``data``
803          */
804         update_record: function(id, data) {
805             var self = this;
806             delete(data.name); // Cannot modify actual name yet
807             var index = this.dataset.get_id_index(id);
808             if (index !== null) {
809                 event_id = this.dataset.ids[index];
810                 this.dataset.write(event_id, data, {}).done(function() {
811                     if (is_virtual_id(event_id)) {
812                         // this is a virtual ID and so this will create a new event
813                         // with an unknown id for us.
814                         self.$calendar.fullCalendar('refetchEvents');
815                     } else {
816                         // classical event that we can refresh
817                         self.refresh_event(event_id);
818                     }
819                 });
820             }
821             return false;
822         },
823         open_event: function(id, title) {
824             var self = this;
825             if (! this.open_popup_action) {
826                 var index = this.dataset.get_id_index(id);
827                 this.dataset.index = index;
828                 if (this.write_right) {
829                     this.do_switch_view('form', null, { mode: "edit" });
830                 } else {
831                     this.do_switch_view('form', null, { mode: "view" });
832                 }
833             }
834             else {
835                 var pop = new instance.web.form.FormOpenPopup(this);
836                 var id_cast = parseInt(id).toString() == id ? parseInt(id) : id;
837                 pop.show_element(this.dataset.model, id_cast, this.dataset.get_context(), {
838                     title: _.str.sprintf(_t("View: %s"),title),
839                     view_id: +this.open_popup_action,
840                     res_id: id_cast,
841                     target: 'new',
842                     readonly:true
843                 });
844
845                var form_controller = pop.view_form;
846                form_controller.on("load_record", self, function(){
847                     button_delete = _.str.sprintf("<button class='oe_button oe_bold delme'><span> %s </span></button>",_t("Delete"));
848                     button_edit = _.str.sprintf("<button class='oe_button oe_bold editme oe_highlight'><span> %s </span></button>",_t("Edit Event"));
849                     
850                     pop.$el.closest(".modal").find(".modal-footer").prepend(button_delete);
851                     pop.$el.closest(".modal").find(".modal-footer").prepend(button_edit);
852                     
853                     $('.delme').click(
854                         function() {
855                             $('.oe_form_button_cancel').trigger('click');
856                             self.remove_event(id);
857                         }
858                     );
859                     $('.editme').click(
860                         function() {
861                             $('.oe_form_button_cancel').trigger('click');
862                             self.dataset.index = self.dataset.get_id_index(id);
863                             self.do_switch_view('form', null, { mode: "edit" });
864                         }
865                     );
866                });
867             }
868             return false;
869         },
870
871         do_show: function() {            
872             if (this.$buttons) {
873                 this.$buttons.show();
874             }
875             this.do_push_state({});
876             this.shown.resolve();
877             return this._super();
878         },
879         do_hide: function () {
880             if (this.$buttons) {
881                 this.$buttons.hide();
882             }
883             return this._super();
884         },
885         is_action_enabled: function(action) {
886             if (action === 'create' && !this.options.creatable) {
887                 return false;
888             }
889             return this._super(action);
890         },
891
892         /**
893          * Handles a newly created record
894          *
895          * @param {id} id of the newly created record
896          */
897         quick_created: function (id) {
898
899             /** Note:
900              * it's of the most utter importance NOT to use inplace
901              * modification on this.dataset.ids as reference to this
902              * data is spread out everywhere in the various widget.
903              * Some of these reference includes values that should
904              * trigger action upon modification.
905              */
906             this.dataset.ids = this.dataset.ids.concat([id]);
907             this.dataset.trigger("dataset_changed", id);
908             this.refresh_event(id);
909         },
910         slow_created: function () {
911             // refresh all view, because maybe some recurrents item
912             var self = this;
913             if (self.sidebar) {
914                 // force filter refresh
915                 self.sidebar.filter.is_loaded = false;
916             }
917             self.$calendar.fullCalendar('refetchEvents');
918         },
919
920         remove_event: function(id) {
921             var self = this;
922             function do_it() {
923                 return $.when(self.dataset.unlink([id])).then(function() {
924                     self.$calendar.fullCalendar('removeEvents', id);
925                 });
926             }
927             if (this.options.confirm_on_delete) {
928                 if (confirm(_t("Are you sure you want to delete this record ?"))) {
929                     return do_it();
930                 }
931             } else
932                 return do_it();
933         },
934     });
935
936
937     /**
938      * Quick creation view.
939      *
940      * Triggers a single event "added" with a single parameter "name", which is the
941      * name entered by the user
942      *
943      * @class
944      * @type {*}
945      */
946     instance.web_calendar.QuickCreate = instance.web.Widget.extend({
947         template: 'CalendarView.quick_create',
948         
949         init: function(parent, dataset, buttons, options, data_template) {
950             this._super(parent);
951             this.dataset = dataset;
952             this._buttons = buttons || false;
953             this.options = options;
954
955             // Can hold data pre-set from where you clicked on agenda
956             this.data_template = data_template || {};
957         },
958         get_title: function () {
959             var parent = this.getParent();
960             if (_.isUndefined(parent)) {
961                 return _t("Create");
962             }
963             var title = (_.isUndefined(parent.field_widget)) ?
964                     (parent.string || parent.name) :
965                     parent.field_widget.string || parent.field_widget.name || '';
966             return _t("Create: ") + title;
967         },
968         start: function () {
969             var self = this;
970
971             if (this.options.disable_quick_create) {
972                 this.$el.hide();
973                 this.slow_create();
974                 return;
975             }
976
977             self.$input = this.$el.find('input');
978             self.$input.keyup(function enterHandler (event) {
979                 if(event.keyCode == 13){
980                     self.$input.off('keyup', enterHandler);
981                     if (!self.quick_add()){
982                         self.$input.on('keyup', enterHandler);
983                     }
984                 }
985             });
986             
987             var submit = this.$el.find(".oe_calendar_quick_create_add");
988             submit.click(function clickHandler() {
989                 submit.off('click', clickHandler);
990                 if (!self.quick_add()){
991                    submit.on('click', clickHandler);                }
992                 self.focus();
993             });
994             this.$el.find(".oe_calendar_quick_create_edit").click(function () {
995                 self.slow_add();
996                 self.focus();
997             });
998             this.$el.find(".oe_calendar_quick_create_close").click(function (ev) {
999                 ev.preventDefault();
1000                 self.trigger('close');
1001             });
1002             self.$input.keyup(function enterHandler (e) {
1003                 if (e.keyCode == 27 && self._buttons) {
1004                     self.trigger('close');
1005                 }
1006             });
1007             self.$el.dialog({ title: this.get_title()});
1008             self.on('added', self, function() {
1009                 self.trigger('close');
1010             });
1011             
1012             self.$el.on('dialogclose', self, function() {
1013                 self.trigger('close');
1014             });
1015
1016         },
1017         focus: function() {
1018             this.$el.find('input').focus();
1019         },
1020
1021         /**
1022          * Gathers data from the quick create dialog a launch quick_create(data) method
1023          */
1024         quick_add: function() {
1025             var val = this.$input.val();
1026             if (/^\s*$/.test(val)) {
1027                 return false;
1028             }
1029             return this.quick_create({'name': val}).always(function() { return true; });
1030         },
1031         
1032         slow_add: function() {
1033             var val = this.$input.val();
1034             this.slow_create({'name': val});
1035         },
1036
1037         /**
1038          * Handles saving data coming from quick create box
1039          */
1040         quick_create: function(data, options) {
1041             var self = this;
1042             return this.dataset.create($.extend({}, this.data_template, data), options)
1043                 .then(function(id) {
1044                     self.trigger('added', id);
1045                     self.$input.val("");
1046                 }).fail(function(r, event) {
1047                     event.preventDefault();
1048                     // This will occurs if there are some more fields required
1049                     self.slow_create(data);
1050                 });
1051         },
1052
1053         /**
1054          * Show full form popup
1055          */
1056          get_form_popup_infos: function() {
1057             var parent = this.getParent();
1058             var infos = {
1059                 view_id: false,
1060                 title: this.name,
1061             };
1062             if (!_.isUndefined(parent) && !(_.isUndefined(parent.ViewManager))) {
1063                 infos.view_id = parent.ViewManager.get_view_id('form');
1064             }
1065             return infos;
1066         },
1067         slow_create: function(data) {
1068             //if all day, we could reset time to display 00:00:00
1069             
1070             var self = this;
1071             var def = $.Deferred();
1072             var defaults = {};
1073             var created = false;
1074
1075             _.each($.extend({}, this.data_template, data), function(val, field_name) {
1076                 defaults['default_' + field_name] = val;
1077             });
1078                         
1079             var pop_infos = self.get_form_popup_infos();
1080             var pop = new instance.web.form.FormOpenPopup(this);
1081             var context = new instance.web.CompoundContext(this.dataset.context, defaults);
1082             pop.show_element(this.dataset.model, null, this.dataset.get_context(defaults), {
1083                 title: this.get_title(),
1084                 disable_multiple_selection: true,
1085                 view_id: pop_infos.view_id,
1086                 // Ensuring we use ``self.dataset`` and DO NOT create a new one.
1087                 create_function: function(data, options) {
1088                     return self.dataset.create(data, options).done(function(r) {
1089                     }).fail(function (r, event) {
1090                        if (!r.data.message) { //else manage by openerp
1091                             throw new Error(r);
1092                        }
1093                     });
1094                 },
1095                 read_function: function(id, fields, options) {
1096                     return self.dataset.read_ids.apply(self.dataset, arguments).done(function() {
1097                     }).fail(function (r, event) {
1098                         if (!r.data.message) { //else manage by openerp
1099                             throw new Error(r);
1100                         }
1101                     });
1102                 },
1103             });
1104             pop.on('closed', self, function() {
1105                 // ``self.trigger('close')`` would itself destroy all child element including
1106                 // the slow create popup, which would then re-trigger recursively the 'closed' signal.  
1107                 // Thus, here, we use a deferred and its state to cut the endless recurrence.
1108                 if (def.state() === "pending") {
1109                     def.resolve();
1110                 }
1111             });
1112             pop.on('create_completed', self, function(id) {
1113                 created = true;
1114                 self.trigger('slowadded');
1115             });
1116             def.then(function() {
1117                 if (created) {
1118                     var parent = self.getParent();
1119                     parent.$calendar.fullCalendar('refetchEvents');
1120                 }
1121                 self.trigger('close');
1122             });
1123             return def;
1124         },
1125     });
1126
1127
1128     /**
1129      * Form widgets
1130      */
1131
1132     function widget_calendar_lazy_init() {
1133         if (instance.web.form.Many2ManyCalendarView) {
1134             return;
1135         }
1136
1137         instance.web_calendar.FieldCalendarView = instance.web_calendar.CalendarView.extend({
1138
1139             init: function (parent) {
1140                 this._super.apply(this, arguments);
1141                 // Warning: this means only a field_widget should instanciate this Class
1142                 this.field_widget = parent;
1143             },
1144
1145             view_loading: function (fv) {
1146                 var self = this;
1147                 return $.when(this._super.apply(this, arguments)).then(function() {
1148                     self.on('event_rendered', this, function (event, element, view) {
1149
1150                     });
1151                 });
1152             },
1153
1154             // In forms, we could be hidden in a notebook. Thus we couldn't
1155             // render correctly fullcalendar so we try to detect when we are
1156             // not visible to wait for when we will be visible.
1157             init_calendar: function() {
1158                 if (this.$calendar.width() !== 0) { // visible
1159                     return this._super();
1160                 }
1161                 // find all parents tabs.
1162                 var def = $.Deferred();
1163                 var self = this;
1164                 this.$calendar.parents(".ui-tabs").on('tabsactivate', this, function() {
1165                     if (self.$calendar.width() !== 0) { // visible
1166                         self.$calendar.fullCalendar(self.get_fc_init_options());
1167                         def.resolve();
1168                     }
1169                 });
1170                 return def;
1171             },
1172         });
1173     }
1174
1175     instance.web_calendar.BufferedDataSet = instance.web.BufferedDataSet.extend({
1176
1177         /**
1178          * Adds verification on possible missing fields for the sole purpose of
1179          * O2M dataset being compatible with the ``slow_create`` detection of
1180          * missing fields... which is as simple to try to write and upon failure
1181          * go to ``slow_create``. Current BufferedDataSet would'nt fail because
1182          * they do not send data to the server at create time.
1183          */
1184         create: function (data, options) {
1185             var def = $.Deferred();
1186             var self = this;
1187             var create = this._super;
1188             if (_.isUndefined(this.required_fields)) {
1189                 this.required_fields = (new instance.web.Model(this.model))
1190                     .call('fields_get').then(function (fields_def) {
1191                         return _(fields_def).chain()
1192                          // equiv to .pairs()
1193                             .map(function (value, key) { return [key, value]; })
1194                          // equiv to .omit(self.field_widget.field.relation_field)
1195                             .filter(function (pair) { return pair[0] !== self.field_widget.field.relation_field; })
1196                             .filter(function (pair) { return pair[1].required; })
1197                             .map(function (pair) { return pair[0]; })
1198                             .value();
1199                     });
1200             }
1201             $.when(this.required_fields).then(function (required_fields) {
1202                 var missing_fields = _(required_fields).filter(function (v) {
1203                     return _.isUndefined(data[v]);
1204                 });
1205                 var default_get = (missing_fields.length !== 0) ?
1206                     self.default_get(missing_fields) : [];
1207                 $.when(default_get).then(function (defaults) {
1208
1209                     // Remove all fields that have a default from the missing fields.
1210                     missing_fields = _(missing_fields).filter(function (f) {
1211                         return _.isUndefined(defaults[f]);
1212                     });
1213                     if (missing_fields.length !== 0) {
1214                         def.reject(
1215                             _.str.sprintf(
1216                                 _t("Missing required fields %s"), missing_fields.join(", ")),
1217                             $.Event());
1218                         return;
1219                     }
1220                     create.apply(self, [data, options]).then(function (result) {
1221                         def.resolve(result);
1222                     });
1223                 });
1224             });
1225             return def;
1226         },
1227     });
1228
1229     instance.web_calendar.fields_dataset = new instance.web.Registry({
1230         'many2many': 'instance.web.DataSetStatic',
1231         'one2many': 'instance.web_calendar.BufferedDataSet',
1232     });
1233
1234
1235     function get_field_dataset_class(type) {
1236         var obj = instance.web_calendar.fields_dataset.get_any([type]);
1237         if (!obj) {
1238             throw new Error(_.str.sprintf(_t("Dataset for type '%s' is not defined."), type));
1239         }
1240
1241         // Override definition of legacy datasets to add field_widget context
1242         return obj.extend({
1243             init: function (parent) {
1244                 this._super.apply(this, arguments);
1245                 this.field_widget = parent;
1246             },
1247             get_context: function() {
1248                 this.context = this.field_widget.build_context();
1249                 return this.context;
1250             }
1251         });
1252     }
1253
1254     /**
1255      * Common part to manage any field using calendar view
1256      */
1257     instance.web_calendar.FieldCalendar = instance.web.form.AbstractField.extend({
1258
1259         disable_utility_classes: true,
1260         calendar_view_class: 'instance.web_calendar.FieldCalendarView',
1261
1262         init: function(field_manager, node) {
1263             this._super(field_manager, node);
1264             widget_calendar_lazy_init();
1265             this.is_loaded = $.Deferred();
1266             this.initial_is_loaded = this.is_loaded;
1267
1268             var self = this;
1269
1270             // This dataset will use current widget to '.build_context()'.
1271             var field_type = field_manager.fields_view.fields[node.attrs.name].type;
1272             this.dataset = new (get_field_dataset_class(field_type))(
1273                 this, this.field.relation);
1274
1275             this.dataset.on('unlink', this, function(_ids) {
1276                 this.dataset.trigger('dataset_changed');
1277             });
1278
1279             // quick_create widget instance will be attached when spawned
1280             this.quick_create = null;
1281
1282             this.no_rerender = true;
1283
1284         },
1285
1286         start: function() {
1287             this._super.apply(this, arguments);
1288
1289             var self = this;
1290
1291             self.load_view();
1292             self.on("change:effective_readonly", self, function() {
1293                 self.is_loaded = self.is_loaded.then(function() {
1294                     self.calendar_view.destroy();
1295                     return $.when(self.load_view()).done(function() {
1296                         self.render_value();
1297                     });
1298                 });
1299             });
1300         },
1301
1302         load_view: function() {
1303             var self = this;
1304             var calendar_view_class = get_class(this.calendar_view_class);
1305             this.calendar_view = new calendar_view_class(this, this.dataset, false, $.extend({
1306                 'create_text': _t("Add"),
1307                 'creatable': self.get("effective_readonly") ? false : true,
1308                 'quick_creatable': self.get("effective_readonly") ? false : true,
1309                 'read_only_mode': self.get("effective_readonly") ? true : false,
1310                 'confirm_on_delete': false,
1311             }, this.options));
1312             var embedded = (this.field.views || {}).calendar;
1313             if (embedded) {
1314                 this.calendar_view.set_embedded_view(embedded);
1315             }
1316             var loaded = $.Deferred();
1317             this.calendar_view.on("calendar_view_loaded", self, function() {
1318                 self.initial_is_loaded.resolve();
1319                 loaded.resolve();
1320             });
1321             this.calendar_view.on('switch_mode', this, this.open_popup);
1322             $.async_when().done(function () {
1323                 self.calendar_view.appendTo(self.$el);
1324             });
1325             return loaded;
1326         },
1327
1328         render_value: function() {
1329             var self = this;
1330             this.dataset.set_ids(this.get("value"));
1331             this.is_loaded = this.is_loaded.then(function() {
1332                 return self.calendar_view.do_search(self.build_domain(), self.dataset.get_context(), []);
1333             });
1334         },
1335
1336         open_popup: function(type, unused) {
1337             if (type !== "form") { return; }
1338             if (this.dataset.index == null) {
1339                 if (typeof this.open_popup_add === "function") {
1340                     this.open_popup_add();
1341                 }
1342             } else {
1343                 if (typeof this.open_popup_edit === "function") {
1344                     this.open_popup_edit();
1345                 }
1346             }
1347         },
1348
1349         open_popup_add: function() {
1350             throw new Error("Not Implemented");
1351         },
1352
1353         open_popup_edit: function() {
1354             var id = this.dataset.ids[this.dataset.index];
1355             var self = this;
1356             var pop = (new instance.web.form.FormOpenPopup(this));
1357             pop.show_element(this.field.relation, id, this.build_context(), {
1358                 title: _t("Open: ") + this.string,
1359                 write_function: function(id, data, _options) {
1360                     return self.dataset.write(id, data, {}).done(function() {
1361                         // Note that dataset will trigger itself the
1362                         // ``dataset_changed`` signal
1363                         self.calendar_view.refresh_event(id);
1364                     });
1365                 },
1366                 read_function: function(id, fields, options) {
1367                     return self.dataset.read_ids.apply(self.dataset, arguments).done(function() {
1368                     }).fail(function (r, event) {
1369                         throw new Error(r);
1370                     });
1371                 },
1372
1373                 alternative_form_view: this.field.views ? this.field.views.form : undefined,
1374                 parent_view: this.view,
1375                 child_name: this.name,
1376                 readonly: this.get("effective_readonly")
1377             });
1378         }
1379     });
1380
1381     instance.web_calendar.Sidebar = instance.web.Widget.extend({
1382         template: 'CalendarView.sidebar',
1383         
1384         start: function() {
1385             this._super();
1386             this.filter = new instance.web_calendar.SidebarFilter(this, this.getParent());
1387             this.filter.appendTo(this.$el.find('.oe_calendar_filter'));
1388         }
1389     });
1390     instance.web_calendar.SidebarFilter = instance.web.Widget.extend({
1391         events: {
1392             'change input:checkbox': 'filter_click'
1393         },
1394         init: function(parent, view) {
1395             this._super(parent);
1396             this.view = view;
1397         },
1398         set_filters: function() {
1399             var self = this;
1400             _.forEach(self.view.all_filters, function(o) {
1401                 if (_.contains(self.view.now_filter_ids, o.value)) {
1402                     self.$('div.oe_calendar_responsible input[value=' + o.value + ']').prop('checked',o.is_checked);
1403                 }
1404             });
1405         },
1406         events_loaded: function(filters) {
1407             var self = this;
1408             if (filters == null) {
1409                 filters = [];
1410                 _.forEach(self.view.all_filters, function(o) {
1411                     if (_.contains(self.view.now_filter_ids, o.value)) {
1412                         filters.push(o);
1413                     }
1414                 });
1415             }            
1416             this.$el.html(QWeb.render('CalendarView.sidebar.responsible', { filters: filters }));
1417         },
1418         filter_click: function(e) {
1419             var self = this;
1420             if (self.view.all_filters[0] && e.target.value == self.view.all_filters[0].value) {
1421                 self.view.all_filters[0].is_checked = e.target.checked;
1422             } else {
1423                 self.view.all_filters[parseInt(e.target.value)].is_checked = e.target.checked;
1424             }
1425             self.view.$calendar.fullCalendar('refetchEvents');
1426         },
1427     });
1428
1429 };