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