46e1cea8e6170ca265105a69a17b92f4f87b2d19
[odoo/odoo.git] / addons / mail / static / src / js / mail.js
1 openerp.mail = function (session) {
2     var _t = session.web._t,
3        _lt = session.web._lt;
4
5     var mail = session.mail;
6
7     openerp_mail_followers(session, mail);          // import mail_followers.js
8     openerp_FieldMany2ManyTagsEmail(session);       // import manyy2many_tags_email.js
9     openerp_announcement(session);
10
11     /**
12      * ------------------------------------------------------------
13      * ChatterUtils
14      * ------------------------------------------------------------
15      * 
16      * This class holds a few tools method for Chatter.
17      * Some regular expressions not used anymore, kept because I want to
18      * - (^|\s)@((\w|@|\.)*): @login@log.log
19      * - (^|\s)\[(\w+).(\w+),(\d)\|*((\w|[@ .,])*)\]: [ir.attachment,3|My Label],
20      *   for internal links
21      */
22
23     mail.ChatterUtils = {
24
25         /** parse text to find email: Tagada <address@mail.fr> -> [Tagada, address@mail.fr] or False */
26         parse_email: function (text) {
27             var result = text.match(/(.*)<(.*@.*)>/);
28             if (result) {
29                 return [_.str.trim(result[1]), _.str.trim(result[2])];
30             }
31             result = text.match(/(.*@.*)/);
32             if (result) {
33                 return [_.str.trim(result[1]), _.str.trim(result[1])];
34             }
35             return [text, false];
36         },
37
38         /* Get an image in /web/binary/image?... */
39         get_image: function (session, model, field, id, resize) {
40             var r = resize ? encodeURIComponent(resize) : '';
41             id = id || '';
42             return session.url('/web/binary/image', {model: model, field: field, id: id, resize: r});
43         },
44
45         /* Get the url of an attachment {'id': id} */
46         get_attachment_url: function (session, message_id, attachment_id) {
47             return session.url('/mail/download_attachment', {
48                 'model': 'mail.message',
49                 'id': message_id,
50                 'method': 'download_attachment',
51                 'attachment_id': attachment_id
52             });
53         },
54
55         /**
56          * Replaces some expressions
57          * - :name - shortcut to an image
58          */
59         do_replace_expressions: function (string) {
60             var icon_list = ['al', 'pinky']
61             /* special shortcut: :name, try to find an icon if in list */
62             var regex_login = new RegExp(/(^|\s):((\w)*)/g);
63             var regex_res = regex_login.exec(string);
64             while (regex_res != null) {
65                 var icon_name = regex_res[2];
66                 if (_.include(icon_list, icon_name))
67                     string = string.replace(regex_res[0], regex_res[1] + '<img src="/mail/static/src/img/_' + icon_name + '.png" width="22px" height="22px" alt="' + icon_name + '"/>');
68                 regex_res = regex_login.exec(string);
69             }
70             return string;
71         },
72
73         /**
74          * Replaces textarea text into html text (add <p>, <a>)
75          * TDE note : should be done server-side, in Python -> use mail.compose.message ?
76          */
77         get_text2html: function (text) {
78             return text
79                 .replace(/((?:https?|ftp):\/\/[\S]+)/g,'<a href="$1">$1</a> ')
80                 .replace(/[\n\r]/g,'<br/>')                
81         },
82
83         /* Returns the complete domain with "&" 
84          * TDE note: please add some comments to explain how/why
85          */
86         expand_domain: function (domain) {
87             var new_domain = [];
88             var nb_and = -1;
89             // TDE note: smarted code maybe ?
90             for ( var k = domain.length-1; k >= 0 ; k-- ) {
91                 if ( typeof domain[k] != 'array' && typeof domain[k] != 'object' ) {
92                     nb_and -= 2;
93                     continue;
94                 }
95                 nb_and += 1;
96             }
97
98             for (var k = 0; k < nb_and ; k++) {
99                 domain.unshift('&');
100             }
101
102             return domain;
103         },
104
105         // inserts zero width space between each letter of a string so that
106         // the word will correctly wrap in html boxes smaller than the text
107         breakword: function(str){
108             var out = '';
109             if (!str) {
110                 return str;
111             }
112             for(var i = 0, len = str.length; i < len; i++){
113                 out += _.str.escapeHTML(str[i]) + '&#8203;';
114             }
115             return out;
116         },
117     };
118
119
120     /**
121      * ------------------------------------------------------------
122      * MessageCommon
123      * ------------------------------------------------------------
124      * 
125      * Common base for expandables, chatter messages and composer. It manages
126      * the various variables common to those models.
127      */
128
129     mail.MessageCommon = session.web.Widget.extend({
130
131     /**
132      * ------------------------------------------------------------
133      * FIXME: this comment was moved as is from the ThreadMessage Init as
134      * part of a refactoring. Check that it is still correct
135      * ------------------------------------------------------------
136      * This widget handles the display of a messages in a thread. 
137      * Displays a record and performs some formatting on the record :
138      * - record.date: formatting according to the user timezone
139      * - record.timerelative: relative time givein by timeago lib
140      * - record.avatar: image url
141      * - record.attachment_ids[].url: url of each attachmentThe
142      * thread view :
143      * - root thread
144      * - - sub message (parent_id = root message)
145      * - - - sub thread
146      * - - - - sub sub message (parent id = sub thread)
147      * - - sub message (parent_id = root message)
148      * - - - sub thread
149      */
150         
151         init: function (parent, datasets, options) {
152             this._super(parent, options);
153
154             // record options
155             this.options = datasets.options || options || {};
156             // record domain and context
157             this.domain = datasets.domain || options.domain || [];
158             this.context = _.extend({
159                 default_model: false,
160                 default_res_id: 0,
161                 default_parent_id: false }, options.context || {});
162
163             // data of this message
164             this.id = datasets.id ||  false,
165             this.last_id = this.id,
166             this.model = datasets.model || this.context.default_model || false,
167             this.res_id = datasets.res_id || this.context.default_res_id ||  false,
168             this.parent_id = datasets.parent_id ||  false,
169             this.type = datasets.type ||  false,
170             this.subtype = datasets.subtype ||  false,
171             this.is_author = datasets.is_author ||  false,
172             this.author_avatar = datasets.author_avatar || false,
173             this.is_private = datasets.is_private ||  false,
174             this.subject = datasets.subject ||  false,
175             this.name = datasets.name ||  false,
176             this.record_name = datasets.record_name ||  false,
177             this.body = datasets.body || '',
178             this.body_short = datasets.body_short || '',
179             this.vote_nb = datasets.vote_nb || 0,
180             this.has_voted = datasets.has_voted ||  false,
181             this.is_favorite = datasets.is_favorite ||  false,
182             this.thread_level = datasets.thread_level ||  0,
183             this.to_read = datasets.to_read || false,
184             this.author_id = datasets.author_id || false,
185             this.attachment_ids = datasets.attachment_ids ||  [],
186             this.partner_ids = datasets.partner_ids || [];
187             this.date = datasets.date;
188             this.user_pid = datasets.user_pid || false;
189             this.format_data();
190
191             // update record_name: Partner profile
192             if (this.model == 'res.partner') {
193                 this.record_name = 'Partner Profile of ' + this.record_name;
194             }
195             else if (this.model == 'hr.employee') {
196                 this.record_name = 'News from ' + this.record_name;
197             }
198             // record options and data
199             this.show_record_name = this.options.show_record_name && this.record_name && !this.thread_level;
200             this.options.show_read = false;
201             this.options.show_unread = false;
202             if (this.options.show_read_unread_button) {
203                 if (this.options.read_action == 'read') this.options.show_read = true;
204                 else if (this.options.read_action == 'unread') this.options.show_unread = true;
205                 else {
206                     this.options.show_read = this.to_read;
207                     this.options.show_unread = !this.to_read;
208                 }
209                 this.options.rerender = true;
210                 this.options.toggle_read = true;
211             }
212             this.parent_thread = typeof parent.on_message_detroy == 'function' ? parent : this.options.root_thread;
213             this.thread = false;
214         },
215
216         /* Convert date, timerelative and avatar in displayable data. */
217         format_data: function () {
218
219             //formating and add some fields for render
220             this.date = this.date ? session.web.str_to_datetime(this.date) : false;
221             this.display_date = moment(this.date).format('ddd MMM DD YYYY LT');
222             if (this.date && new Date().getTime()-this.date.getTime() < 7*24*60*60*1000) {
223                 this.timerelative = $.timeago(this.date);
224             }
225             if (this.author_avatar) {
226                 this.avatar = "data:image/png;base64," + this.author_avatar;
227             } else if (this.type == 'email' && (!this.author_id || !this.author_id[0])) {
228                 this.avatar = ('/mail/static/src/img/email_icon.png');
229             } else if (this.author_id && this.template != 'mail.compose_message') {
230                 this.avatar = mail.ChatterUtils.get_image(this.session, 'res.partner', 'image_small', this.author_id[0]);
231             } else {
232                 this.avatar = mail.ChatterUtils.get_image(this.session, 'res.users', 'image_small', this.session.uid);
233             }
234             if (this.author_id && this.author_id[1]) {
235                 var parsed_email = mail.ChatterUtils.parse_email(this.author_id[1]);
236                 this.author_id.push(parsed_email[0], parsed_email[1]);
237             }
238             if (this.partner_ids && this.partner_ids.length > 3) {
239                 this.extra_partners_nbr = this.partner_ids.length - 3;
240                 this.extra_partners_str = ''
241                 var extra_partners = this.partner_ids.slice(3);
242                 for (var key in extra_partners) {
243                     this.extra_partners_str += extra_partners[key][1];
244                 }
245             }
246         },
247
248
249         /* upload the file on the server, add in the attachments list and reload display
250          */
251         display_attachments: function () {
252             for (var l in this.attachment_ids) {
253                 var attach = this.attachment_ids[l];
254                 if (!attach.formating) {
255                     attach.url = mail.ChatterUtils.get_attachment_url(this.session, this.id, attach.id);
256                     attach.name = mail.ChatterUtils.breakword(attach.name || attach.filename);
257                     attach.formating = true;
258                 }
259             }
260             this.$(".oe_msg_attachment_list").html( session.web.qweb.render('mail.thread.message.attachments', {'widget': this}) );
261         },
262
263         /* return the link to resized image
264          */
265         attachments_resize_image: function (id, resize) {
266             return mail.ChatterUtils.get_image(this.session, 'ir.attachment', 'datas', id, resize);
267         },
268
269         /* get all child message id linked.
270          * @return array of id
271         */
272         get_child_ids: function () {
273             return _.map(this.get_childs(), function (val) { return val.id; });
274         },
275
276         /* get all child message linked.
277          * @return array of message object
278         */
279         get_childs: function (nb_thread_level) {
280             var res=[];
281             if (arguments[1] && this.id) res.push(this);
282             if ((isNaN(nb_thread_level) || nb_thread_level>0) && this.thread) {
283                 _(this.thread.messages).each(function (val, key) {
284                     res = res.concat( val.get_childs((isNaN(nb_thread_level) ? undefined : nb_thread_level-1), true) );
285                 });
286             }
287             return res;
288         },
289
290         /**
291          * search a message in all thread and child thread.
292          * This method return an object message.
293          * @param {object}{int} option.id
294          * @param {object}{string} option.model
295          * @param {object}{boolean} option._go_thread_wall
296          *      private for check the top thread
297          * @return thread object
298          */
299         browse_message: function (options) {
300             // goto the wall thread for launch browse
301             if (!options._go_thread_wall) {
302                 options._go_thread_wall = true;
303                 for (var i in this.options.root_thread.messages) {
304                     var res=this.options.root_thread.messages[i].browse_message(options);
305                     if (res) return res;
306                 }
307             }
308
309             if (this.id==options.id)
310                 return this;
311
312             for (var i in this.thread.messages) {
313                 if (this.thread.messages[i].thread) {
314                     var res=this.thread.messages[i].browse_message(options);
315                     if (res) return res;
316                 }
317             }
318
319             return false;
320         },
321
322         /**
323          * call on_message_delete on his parent thread
324         */
325         destroy: function () {
326
327             this._super();
328             this.parent_thread.on_message_detroy(this);
329
330         }
331
332     });
333
334     /**
335      * ------------------------------------------------------------
336      * ComposeMessage widget
337      * ------------------------------------------------------------
338      * 
339      * This widget handles the display of a form to compose a new message.
340      * This form is a mail.compose.message form_view.
341      * On first time : display a compact textarea that is not the compose form.
342      * When the user focuses the textarea, the compose message is instantiated.
343      */
344     
345     mail.ThreadComposeMessage = mail.MessageCommon.extend({
346         template: 'mail.compose_message',
347
348         /**
349          * @param {Object} parent parent
350          * @param {Object} [options]
351          *      @param {Object} [context] context passed to the
352          *          mail.compose.message DataSetSearch. Please refer to this model
353          *          for more details about fields and default values.
354          * @param {Object} recipients = [
355                         {
356                             'email_address': [str],
357                             'partner_id': False/[int],
358                             'name': [str],
359                             'full_name': name<email_address>,
360                         },
361                         { ... },
362                     ]
363          */
364
365         init: function (parent, datasets, options) {
366             this._super(parent, datasets, options);
367             this.show_compact_message = false;
368             this.show_delete_attachment = true;
369             this.is_log = false;
370             this.recipients = [];
371             this.recipient_ids = [];
372         },
373
374         start: function () {
375             this._super.apply(this, arguments);
376
377             this.ds_attachment = new session.web.DataSetSearch(this, 'ir.attachment');
378             this.fileupload_id = _.uniqueId('oe_fileupload_temp');
379             $(window).on(this.fileupload_id, this.on_attachment_loaded);
380
381             this.display_attachments();
382             this.bind_events();
383         },
384
385         /* when a user click on the upload button, send file read on_attachment_loaded
386         */
387         on_attachment_change: function (event) {
388             event.stopPropagation();
389             var self = this;
390             var $target = $(event.target);
391             if ($target.val() !== '') {
392
393                 var filename = $target.val().replace(/.*[\\\/]/,'');
394
395                 // if the files exits for this answer, delete the file before upload
396                 var attachments=[];
397                 for (var i in this.attachment_ids) {
398                     if ((this.attachment_ids[i].filename || this.attachment_ids[i].name) == filename) {
399                         if (this.attachment_ids[i].upload) {
400                             return false;
401                         }
402                         this.ds_attachment.unlink([this.attachment_ids[i].id]);
403                     } else {
404                         attachments.push(this.attachment_ids[i]);
405                     }
406                 }
407                 this.attachment_ids = attachments;
408
409                 // submit file
410                 this.$('form.oe_form_binary_form').submit();
411
412                 this.$(".oe_attachment_file").hide();
413
414                 this.attachment_ids.push({
415                     'id': 0,
416                     'name': filename,
417                     'filename': filename,
418                     'url': '',
419                     'upload': true
420                 });
421                 this.display_attachments();
422             }
423         },
424         
425         /* when the file is uploaded 
426         */
427         on_attachment_loaded: function (event, result) {
428
429             if (result.erorr || !result.id ) {
430                 this.do_warn( session.web.qweb.render('mail.error_upload'), result.error);
431                 this.attachment_ids = _.filter(this.attachment_ids, function (val) { return !val.upload; });
432             } else {
433                 for (var i in this.attachment_ids) {
434                     if (this.attachment_ids[i].filename == result.filename && this.attachment_ids[i].upload) {
435                         this.attachment_ids[i]={
436                             'id': result.id,
437                             'name': result.name,
438                             'filename': result.filename,
439                             'url': mail.ChatterUtils.get_attachment_url(this.session, this.id, result.id)
440                         };
441                     }
442                 }
443             }
444             this.display_attachments();
445             var $input = this.$('input.oe_form_binary_file');
446             $input.after($input.clone(true)).remove();
447             this.$(".oe_attachment_file").show();
448         },
449
450         /* unlink the file on the server and reload display
451          */
452         on_attachment_delete: function (event) {
453             event.stopPropagation();
454             var attachment_id=$(event.target).data("id");
455             if (attachment_id) {
456                 var attachments=[];
457                 for (var i in this.attachment_ids) {
458                     if (attachment_id!=this.attachment_ids[i].id) {
459                         attachments.push(this.attachment_ids[i]);
460                     }
461                     else {
462                         this.ds_attachment.unlink([attachment_id]);
463                     }
464                 }
465                 this.attachment_ids = attachments;
466                 this.display_attachments();
467             }
468         },
469
470         bind_events: function () {
471             var self = this;
472             this.$('.oe_compact_inbox').on('click', self.on_toggle_quick_composer);
473             this.$('.oe_compose_post').on('click', self.on_toggle_quick_composer);
474             this.$('.oe_compose_log').on('click', self.on_toggle_quick_composer);
475             this.$('input.oe_form_binary_file').on('change', _.bind( this.on_attachment_change, this));
476             this.$('.oe_cancel').on('click', _.bind( this.on_cancel, this));
477             this.$('.oe_post').on('click', self.on_message_post);
478             this.$('.oe_full').on('click', _.bind( this.on_compose_fullmail, this, this.id ? 'reply' : 'comment'));
479             /* stack for don't close the compose form if the user click on a button */
480             this.$('.oe_msg_left, .oe_msg_center').on('mousedown', _.bind( function () { this.stay_open = true; }, this));
481             this.$('.oe_msg_left, .oe_msg_content').on('mouseup', _.bind( function () { this.$('textarea').focus(); }, this));
482             var ev_stay = {};
483             ev_stay.mouseup = ev_stay.keydown = ev_stay.focus = function () { self.stay_open = false; };
484             this.$('textarea').on(ev_stay);
485             this.$('textarea').autosize();
486
487             // auto close
488             this.$('textarea').on('blur', self.on_toggle_quick_composer);
489
490             // event: delete child attachments off the oe_msg_attachment_list box
491             this.$(".oe_msg_attachment_list").on('click', '.oe_delete', this.on_attachment_delete);
492
493             this.$(".oe_recipients").on('change', 'input', this.on_checked_recipient);
494         },
495
496         on_compose_fullmail: function (default_composition_mode) {
497             var self = this;
498             if(!this.do_check_attachment_upload()) {
499                 return false;
500             }
501             var recipient_done = $.Deferred();
502             if (this.is_log) {
503                 recipient_done.resolve([]);
504             }
505             else {
506                 recipient_done = this.check_recipient_partners();
507             }
508             $.when(recipient_done).done(function (partner_ids) {
509                 var context = {
510                     'default_parent_id': self.id,
511                     'default_body': mail.ChatterUtils.get_text2html(self.$el ? (self.$el.find('textarea:not(.oe_compact)').val() || '') : ''),
512                     'default_attachment_ids': _.map(self.attachment_ids, function (file) {return file.id;}),
513                     'default_partner_ids': partner_ids,
514                     'default_is_log': self.is_log,
515                     'mail_post_autofollow': true,
516                     'mail_post_autofollow_partner_ids': partner_ids,
517                     'is_private': self.is_private
518                 };
519                 if (default_composition_mode != 'reply' && self.context.default_model && self.context.default_res_id) {
520                     context.default_model = self.context.default_model;
521                     context.default_res_id = self.context.default_res_id;
522                 }
523
524                 var action = {
525                     type: 'ir.actions.act_window',
526                     res_model: 'mail.compose.message',
527                     view_mode: 'form',
528                     view_type: 'form',
529                     views: [[false, 'form']],
530                     target: 'new',
531                     context: context,
532                 };
533
534                 self.do_action(action);
535                 self.on_cancel();
536             });
537
538         },
539
540         reinit: function() {
541             var $render = $( session.web.qweb.render('mail.compose_message', {'widget': this}) );
542
543             $render.insertAfter(this.$el.last());
544             this.$el.remove();
545             this.$el = $render;
546
547             this.display_attachments();
548             this.bind_events();
549         },
550
551         on_cancel: function (event) {
552             if (event) event.stopPropagation();
553             this.attachment_ids=[];
554             this.stay_open = false;
555             this.show_composer = false;
556             this.reinit();
557         },
558
559         /* return true if all file are complete else return false and make an alert */
560         do_check_attachment_upload: function () {
561             if (_.find(this.attachment_ids, function (file) {return file.upload;})) {
562                 this.do_warn(session.web.qweb.render('mail.error_upload'), session.web.qweb.render('mail.error_upload_please_wait'));
563                 return false;
564             } else {
565                 return true;
566             }
567         },
568
569         check_recipient_partners: function () {
570             var self = this;
571             var check_done = $.Deferred();
572             var recipients = _.filter(this.recipients, function (recipient) { return recipient.checked });
573             var recipients_to_find = _.filter(recipients, function (recipient) { return (! recipient.partner_id) });
574             var names_to_find = _.pluck(recipients_to_find, 'full_name');
575             var recipients_to_check = _.filter(recipients, function (recipient) { return (recipient.partner_id && ! recipient.email_address) });
576             var recipient_ids = _.pluck(_.filter(recipients, function (recipient) { return recipient.partner_id && recipient.email_address }), 'partner_id');
577             var names_to_remove = [];
578             var recipient_ids_to_remove = [];
579
580             // have unknown names -> call message_get_partner_info_from_emails to try to find partner_id
581             var find_done = $.Deferred();
582             if (names_to_find.length > 0) {
583                 find_done = self.parent_thread.ds_thread._model.call('message_partner_info_from_emails', [this.context.default_res_id, names_to_find]);
584             }
585             else {
586                 find_done.resolve([]);
587             }
588
589             // for unknown names + incomplete partners -> open popup - cancel = remove from recipients
590             $.when(find_done).pipe(function (result) {
591                 var emails_deferred = [];
592                 var recipient_popups = result.concat(recipients_to_check);
593
594                 _.each(recipient_popups, function (partner_info) {
595                     var deferred = $.Deferred()
596                     emails_deferred.push(deferred);
597
598                     var partner_name = partner_info.full_name;
599                     var partner_id = partner_info.partner_id;
600                     var parsed_email = mail.ChatterUtils.parse_email(partner_name);
601
602                     var pop = new session.web.form.FormOpenPopup(this);                    
603                     pop.show_element(
604                         'res.partner',
605                         partner_id,
606                         {   'force_email': true,
607                             'ref': "compound_context",
608                             'default_name': parsed_email[0],
609                             'default_email': parsed_email[1],
610                         }, {
611                             title: _t("Please complete partner's informations"),
612                         }
613                     );
614                     pop.on('closed', self, function () {
615                         deferred.resolve();
616                     });
617                     pop.view_form.on('on_button_cancel', self, function () {
618                         names_to_remove.push(partner_name);
619                         if (partner_id) {
620                             recipient_ids_to_remove.push(partner_id);
621                         }
622                     });
623                 });
624
625                 $.when.apply($, emails_deferred).then(function () {
626                     var new_names_to_find = _.difference(names_to_find, names_to_remove);
627                     find_done = $.Deferred();
628                     if (new_names_to_find.length > 0) {
629                         find_done = self.parent_thread.ds_thread._model.call('message_partner_info_from_emails', [self.context.default_res_id, new_names_to_find, true]);
630                     }
631                     else {
632                         find_done.resolve([]);
633                     }
634                     $.when(find_done).pipe(function (result) {
635                         var recipient_popups = result.concat(recipients_to_check);
636                         _.each(recipient_popups, function (partner_info) {
637                             if (partner_info.partner_id && _.indexOf(partner_info.partner_id, recipient_ids_to_remove) == -1) {
638                                 recipient_ids.push(partner_info.partner_id);
639                             }
640                         });
641                     }).pipe(function () {
642                         check_done.resolve(recipient_ids);
643                     });
644                 });
645             });
646             
647             return check_done;
648         },
649
650         on_message_post: function (event) {
651             var self = this;
652             if (self.flag_post) {
653                 return;
654             }
655             self.flag_post = true;
656             if (this.do_check_attachment_upload() && (this.attachment_ids.length || this.$('textarea').val().match(/\S+/))) {
657                 if (this.is_log) {
658                     this.do_send_message_post([], this.is_log);
659                 }
660                 else {
661                     this.check_recipient_partners().done(function (partner_ids) {
662                         self.do_send_message_post(partner_ids, self.is_log);
663                     });
664                 }
665             }
666         },
667
668         /* do post a message and fetch the message */
669         do_send_message_post: function (partner_ids, log) {
670             var self = this;
671             var values = {
672                 'body': this.$('textarea').val(),
673                 'subject': false,
674                 'parent_id': this.context.default_parent_id,
675                 'attachment_ids': _.map(this.attachment_ids, function (file) {return file.id;}),
676                 'partner_ids': partner_ids,
677                 'context': _.extend(this.parent_thread.context, {
678                     'mail_post_autofollow': true,
679                     'mail_post_autofollow_partner_ids': partner_ids,
680                 }),
681                 'type': 'comment',
682                 'content_subtype': 'plaintext',
683             };
684             if (log) {
685                 values['subtype'] = false;
686             }
687             else {
688                 values['subtype'] = 'mail.mt_comment';   
689             }
690             this.parent_thread.ds_thread._model.call('message_post', [this.context.default_res_id], values).done(function (message_id) {
691                 var thread = self.parent_thread;
692                 var root = thread == self.options.root_thread;
693                 if (self.options.display_indented_thread < self.thread_level && thread.parent_message) {
694                     var thread = thread.parent_message.parent_thread;
695                 }
696                 // create object and attach to the thread object
697                 thread.message_fetch([["id", "=", message_id]], false, [message_id], function (arg, data) {
698                     var message = thread.create_message_object( data.slice(-1)[0] );
699                     // insert the message on dom
700                     thread.insert_message( message, root ? undefined : self.$el, root );
701                 });
702                 self.on_cancel();
703                 self.flag_post = false;
704             });
705         },
706
707         /* Quick composer: toggle minimal / expanded mode
708          * - toggle minimal (one-liner) / expanded (textarea, buttons) mode
709          * - when going into expanded mode:
710          *  - call `message_get_suggested_recipients` to have a list of partners to add
711          *  - compute email_from list (list of unknown email_from to propose to create partners)
712          */
713         on_toggle_quick_composer: function (event) {
714             var self = this;
715             var $input = $(event.target);
716             this.compute_emails_from();
717             var email_addresses = _.pluck(this.recipients, 'email_address');
718             var suggested_partners = $.Deferred();
719
720             // if clicked: call for suggested recipients
721             if (event.type == 'click') {
722                 this.is_log = $input.hasClass('oe_compose_log');
723                 suggested_partners = this.parent_thread.ds_thread.call('message_get_suggested_recipients', [[this.context.default_res_id], this.context]).done(function (additional_recipients) {
724                     var thread_recipients = additional_recipients[self.context.default_res_id];
725                     _.each(thread_recipients, function (recipient) {
726                         var parsed_email = mail.ChatterUtils.parse_email(recipient[1]);
727                         if (_.indexOf(email_addresses, parsed_email[1]) == -1) {
728                             self.recipients.push({
729                                 'checked': true,
730                                 'partner_id': recipient[0],
731                                 'full_name': recipient[1],
732                                 'name': parsed_email[0],
733                                 'email_address': parsed_email[1],
734                                 'reason': recipient[2],
735                             })
736                         }
737                     });
738                 });
739             }
740             else {
741                 suggested_partners.resolve({});
742             }
743
744             // when call for suggested partners finished: re-render the widget
745             $.when(suggested_partners).pipe(function (additional_recipients) {
746                 if ((!self.stay_open || (event && event.type == 'click')) && (!self.show_composer || !self.$('textarea:not(.oe_compact)').val().match(/\S+/) && !self.attachment_ids.length)) {
747                     self.show_composer = !self.show_composer || self.stay_open;
748                     self.reinit();
749                 }
750                 if (!self.stay_open && self.show_composer && (!event || event.type != 'blur')) {
751                     self.$('textarea:not(.oe_compact):first').focus();
752                 }
753             });
754
755             return suggested_partners;
756         },
757
758         do_hide_compact: function () {
759             this.show_compact_message = false;
760             if (!this.show_composer) {
761                 this.reinit();
762             }
763         },
764
765         do_show_compact: function () {
766             this.show_compact_message = true;
767             if (!this.show_composer) {
768                 this.reinit();
769             }
770         },
771
772         /** Compute the list of unknown email_from the the given thread
773          * TDE FIXME: seems odd to delegate to the composer
774          * TDE TODO: please de-obfuscate and comment your code */
775         compute_emails_from: function () {
776             var self = this;
777             var messages = [];
778
779             if (this.parent_thread.parent_message) {
780                 // go to the parented message
781                 var message = this.parent_thread.parent_message;
782                 var parent_message = message.parent_id ? message.parent_thread.parent_message : message;
783                 if(parent_message){
784                     var messages = [parent_message].concat(parent_message.get_childs());
785                 }
786             } else if (this.options.emails_from_on_composer) {
787                 // get all wall messages if is not a mail.Wall
788                 _.each(this.options.root_thread.messages, function (msg) {messages.push(msg); messages.concat(msg.get_childs());});
789             }
790
791             _.each(messages, function (thread) {
792                 if (thread.author_id && !thread.author_id[0] &&
793                     !_.find(self.recipients, function (recipient) {return recipient.email_address == thread.author_id[3];})) {
794                     self.recipients.push({  'full_name': thread.author_id[1],
795                                             'name': thread.author_id[2],
796                                             'email_address': thread.author_id[3],
797                                             'partner_id': false,
798                                             'checked': true,
799                                             'reason': 'Incoming email author'
800                                         });
801                 }
802             });
803             return self.recipients;
804         },
805
806         on_checked_recipient: function (event) {
807             var $input = $(event.target);
808             var full_name = $input.attr("data");
809             _.each(this.recipients, function (recipient) {
810                 if (recipient.full_name == full_name) {
811                     recipient.checked = $input.is(":checked");
812                 }
813             });
814         },
815     });
816
817     /**
818      * ------------------------------------------------------------
819      * Thread Message Expandable Widget
820      * ------------------------------------------------------------
821      *
822      * This widget handles the display the expandable message in a thread.
823      * - thread
824      * - - visible message
825      * - - expandable
826      * - - visible message
827      * - - visible message
828      * - - expandable
829      */
830     mail.ThreadExpandable = mail.MessageCommon.extend({
831         template: 'mail.thread.expandable',
832
833         init: function (parent, datasets, options) {
834             this._super(parent, datasets, options);
835             this.type = 'expandable';
836             this.max_limit = datasets.max_limit;
837             this.nb_messages = datasets.nb_messages;
838             this.flag_used = false;
839         },
840         
841         start: function () {
842             this._super.apply(this, arguments);
843             this.bind_events();
844         },
845
846         reinit: function () {
847             var $render = $(session.web.qweb.render('mail.thread.expandable', {'widget': this}));
848             this.$el.replaceWith( $render );
849             this.$el = $render;
850             this.bind_events();
851         },
852
853         /**
854          * Bind events in the widget. Each event is slightly described
855          * in the function. */
856         bind_events: function () {
857             this.$('.oe_msg_more_message').on('click', this.on_expandable);
858         },
859
860         animated_destroy: function (fadeTime) {
861             var self=this;
862             this.$el.fadeOut(fadeTime, function () {
863                 self.destroy();
864             });
865         },
866
867         /*The selected thread and all childs (messages/thread) became read
868         * @param {object} mouse envent
869         */
870         on_expandable: function (event) {
871             if (event)event.stopPropagation();
872             if (this.flag_used) {
873                 return false
874             }
875             this.flag_used = true;
876
877             var self = this;
878
879             // read messages
880             self.parent_thread.message_fetch(this.domain, this.context, false, function (arg, data) {
881                 self.id = false;
882                 // insert the message on dom after this message
883                 self.parent_thread.switch_new_message(data, self.$el);
884                 self.animated_destroy(200);
885             });
886
887             return false;
888         },
889
890     });
891
892     mail.ThreadMessage = mail.MessageCommon.extend({
893         template: 'mail.thread.message',
894         
895         start: function () {
896             this._super.apply(this, arguments);
897             this.bind_events();
898             if(this.thread_level < this.options.display_indented_thread) {
899                 this.create_thread();
900             }
901             this.display_attachments();
902
903             this.ds_notification = new session.web.DataSetSearch(this, 'mail.notification');
904             this.ds_message = new session.web.DataSetSearch(this, 'mail.message');
905         },
906
907         /**
908          * Bind events in the widget. Each event is slightly described
909          * in the function. */
910         bind_events: function () {
911             var self = this;
912             // header icons bindings
913             this.$('.oe_read').on('click', this.on_message_read);
914             this.$('.oe_unread').on('click', this.on_message_unread);
915             this.$('.oe_msg_delete').on('click', this.on_message_delete);
916             this.$('.oe_reply').on('click', this.on_message_reply);
917             this.$('.oe_star').on('click', this.on_star);
918             this.$('.oe_msg_vote').on('click', this.on_vote);
919             this.$('.oe_mail_vote_count').on('mouseenter', this.on_hover);
920             this.$('.oe_mail_expand').on('click', this.on_expand);
921             this.$('.oe_mail_reduce').on('click', this.on_expand);
922             this.$('.oe_mail_action_model').on('click', this.on_record_clicked);
923             this.$('.oe_mail_action_author').on('click', this.on_record_author_clicked);
924         },
925         on_hover : function(event){
926             var self = this;
927             var voter = "";
928             var limit = 10;
929             event.stopPropagation();
930             var $target = $(event.target).hasClass("fa-thumbs-o-up") ? $(event.target).parent() : $(event.target);
931             //Note: We can set data-content attr on target element once we fetch data so that next time when one moves mouse on element it saves call
932             //But if there is new like comes then we'll not have new likes in popover in that case
933             if ($target.data('liker-list'))
934             {
935                 voter = $target.data('liker-list');
936                 self.bindTooltipTo($target, voter);
937                 $target.tooltip('hide').tooltip('show');
938                 $(".tooltip").on("mouseleave", function () {
939                     $(this).remove();
940                 });
941             }else{
942                 this.ds_message.call('get_likers_list', [this.id, limit])
943                 .done(function (data) {
944                     _.each(data, function(people, index) {
945                         voter = voter + people.substring(0,1).toUpperCase() + people.substring(1);
946                         if(index != data.length-1) {
947                             voter = voter + "<br/>";
948                         }
949                     });
950                     $target.data('liker-list', voter);
951                     self.bindTooltipTo($target, voter);
952                     $target.tooltip('hide').tooltip('show');
953                     $(".tooltip").on("mouseleave", function () {
954                         $(this).remove();
955                     });
956                 });
957             }
958             return true;
959         },
960         bindTooltipTo: function($el, value) {
961             $el.tooltip({
962                 'title': value,
963                 'placement': 'top',
964                 'container': this.el,
965                 'html': true,
966                 'trigger': 'manual',
967                 'animation': false
968              }).on("mouseleave", function () {
969                 setTimeout(function () {
970                     if (!$(".tooltip:hover").length) {
971                         $el.tooltip("hide");
972                     }
973                 },100);
974             });
975         },
976         on_record_clicked: function  (event) {
977             event.preventDefault();
978             var self = this;
979             var state = {
980                 'model': this.model,
981                 'id': this.res_id,
982                 'title': this.record_name
983             };
984             session.webclient.action_manager.do_push_state(state);
985             this.context.params = {
986                 model: this.model,
987                 res_id: this.res_id,
988             };
989             this.thread.ds_thread.call("message_redirect_action", {context: this.context}).then(function(action){
990                 self.do_action(action); 
991             });
992         },
993
994         on_record_author_clicked: function  (event) {
995             event.preventDefault();
996             var partner_id = $(event.target).data('partner');
997             var state = {
998                 'model': 'res.partner',
999                 'id': partner_id,
1000                 'title': this.record_name
1001             };
1002             session.webclient.action_manager.do_push_state(state);
1003             var action = {
1004                 type:'ir.actions.act_window',
1005                 view_type: 'form',
1006                 view_mode: 'form',
1007                 res_model: 'res.partner',
1008                 views: [[false, 'form']],
1009                 res_id: partner_id,
1010             }
1011             this.do_action(action);
1012         },
1013
1014         /* Call the on_compose_message on the thread of this message. */
1015         on_message_reply:function (event) {
1016             event.stopPropagation();
1017             this.create_thread();
1018             this.thread.on_compose_message(event);
1019             return false;
1020         },
1021
1022         on_expand: function (event) {
1023             event.stopPropagation();
1024             this.$('.oe_msg_body:first > .oe_msg_body_short:first').toggle();
1025             this.$('.oe_msg_body:first > .oe_msg_body_long:first').toggle();
1026             return false;
1027         },
1028
1029         /**
1030          * Instantiate the thread object of this message.
1031          * Each message have only one thread.
1032          */
1033         create_thread: function () {
1034             if (this.thread) {
1035                 return false;
1036             }
1037             /*create thread*/
1038             this.thread = new mail.Thread(this, this, {
1039                     'domain': this.domain,
1040                     'context':{
1041                         'default_model': this.model,
1042                         'default_res_id': this.res_id,
1043                         'default_parent_id': this.id
1044                     },
1045                     'options': this.options
1046                 }
1047             );
1048             /*insert thread in parent message*/
1049             this.thread.insertAfter(this.$el);
1050         },
1051         
1052         /**
1053          * Fade out the message and his child thread.
1054          * Then this object is destroyed.
1055          */
1056         animated_destroy: function (fadeTime) {
1057             var self=this;
1058             this.$el.fadeOut(fadeTime, function () {
1059                 self.parent_thread.message_to_expandable(self);
1060             });
1061             if (this.thread) {
1062                 this.thread.$el.fadeOut(fadeTime);
1063             }
1064         },
1065
1066         /**
1067          * Wait a confirmation for delete the message on the DB.
1068          * Make an animate destroy
1069          */
1070         on_message_delete: function (event) {
1071             event.stopPropagation();
1072             if (! confirm(_t("Do you really want to delete this message?"))) { return false; }
1073             
1074             this.animated_destroy(150);
1075             // delete this message and his childs
1076             var ids = [this.id].concat( this.get_child_ids() );
1077             this.ds_message.unlink(ids);
1078             return false;
1079         },
1080
1081         /* Check if the message must be destroy and detroy it or check for re render widget
1082         * @param {callback} apply function
1083         */
1084         check_for_rerender: function () {
1085             var self = this;
1086
1087             var messages = [this].concat(this.get_childs());
1088             var message_ids = _.map(messages, function (msg) { return msg.id;});
1089             var domain = mail.ChatterUtils.expand_domain( this.options.root_thread.domain )
1090                 .concat([["id", "in", message_ids ]]);
1091
1092             return this.parent_thread.ds_message.call('message_read', [undefined, domain, [], !!this.parent_thread.options.display_indented_thread, this.context, this.parent_thread.id])
1093                 .then( function (records) {
1094                     // remove message not loaded
1095                     _.map(messages, function (msg) {
1096                         if(!_.find(records, function (record) { return record.id == msg.id; })) {
1097                             msg.animated_destroy(150);
1098                         } else {
1099                             msg.renderElement();
1100                             msg.start();
1101                         }
1102                         self.options.root_thread.MailWidget.do_reload_menu_emails();
1103                     });
1104
1105                 });
1106         },
1107
1108         on_message_read: function (event) {
1109             event.stopPropagation();
1110             this.on_message_read_unread(true);
1111             return false;
1112         },
1113
1114         on_message_unread: function (event) {
1115             event.stopPropagation();
1116             this.on_message_read_unread(false);
1117             return false;
1118         },
1119
1120         /* Set the selected thread and all childs as read or unread, based on
1121          * read parameter.
1122          * @param {boolean} read_value
1123          */
1124         on_message_read_unread: function (read_value) {
1125             var self = this;
1126             var messages = [this].concat(this.get_childs());
1127
1128             // inside the inbox, when the user mark a message as read/done, don't apply this value
1129             // for the stared/favorite message
1130             if (this.options.view_inbox && read_value) {
1131                 var messages = _.filter(messages, function (val) { return !val.is_favorite && val.id; });
1132                 if (!messages.length) {
1133                     this.check_for_rerender();
1134                     return false;
1135                 }
1136             }
1137             var message_ids = _.map(messages, function (val) { return val.id; });
1138
1139             this.ds_message.call('set_message_read', [message_ids, read_value, true, this.context])
1140                 .then(function () {
1141                     // apply modification
1142                     _.each(messages, function (msg) {
1143                         msg.to_read = !read_value;
1144                         if (msg.options.toggle_read) {
1145                             msg.options.show_read = msg.to_read;
1146                             msg.options.show_unread = !msg.to_read;
1147                         }
1148                     });
1149                     // check if the message must be display, destroy or rerender
1150                     self.check_for_rerender();
1151                 });
1152             return false;
1153         },
1154
1155         /**
1156          * add or remove a vote for a message and display the result
1157         */
1158         on_vote: function (event) {
1159             event.stopPropagation();
1160             this.ds_message.call('vote_toggle', [[this.id]])
1161                 .then(
1162                     _.bind(function (vote) {
1163                         this.has_voted = vote;
1164                         this.vote_nb += this.has_voted ? 1 : -1;
1165                         this.display_vote();
1166                     }, this));
1167             return false;
1168         },
1169
1170         /**
1171          * Display the render of this message's vote
1172         */
1173         display_vote: function () {
1174             var vote_element = session.web.qweb.render('mail.thread.message.vote', {'widget': this});
1175             this.$(".oe_msg_footer:first .oe_mail_vote_count").remove();
1176             this.$(".oe_msg_footer:first .oe_msg_vote").replaceWith(vote_element);
1177             this.$('.oe_msg_vote').on('click', this.on_vote);
1178             this.$('.oe_mail_vote_count').on('mouseenter', this.on_hover);
1179         },
1180
1181         /**
1182          * add or remove a favorite (or starred) for a message and change class on the DOM
1183         */
1184         on_star: function (event) {
1185             event.stopPropagation();
1186             var self=this;
1187             var button = self.$('.oe_star:first');
1188
1189             this.ds_message.call('set_message_starred', [[self.id], !self.is_favorite, true])
1190                 .then(function (star) {
1191                     self.is_favorite=star;
1192                     if (self.is_favorite) {
1193                         button.addClass('oe_starred');
1194                     } else {
1195                         button.removeClass('oe_starred');
1196                     }
1197
1198                     if (self.options.view_inbox && self.is_favorite) {
1199                         self.on_message_read_unread(true);
1200                     } else {
1201                         self.check_for_rerender();
1202                     }
1203                 });
1204             return false;
1205         },
1206
1207     });
1208
1209     /**
1210      * ------------------------------------------------------------
1211      * Thread Widget
1212      * ------------------------------------------------------------
1213      *
1214      * This widget handles the display of a thread of messages. The
1215      * thread view:
1216      * - root thread
1217      * - - sub message (parent_id = root message)
1218      * - - - sub thread
1219      * - - - - sub sub message (parent id = sub thread)
1220      * - - sub message (parent_id = root message)
1221      * - - - sub thread
1222      */
1223     mail.Thread = session.web.Widget.extend({
1224         template: 'mail.thread',
1225
1226         /**
1227          * @param {Object} parent parent
1228          * @param {Array} [domain]
1229          * @param {Object} [context] context of the thread. It should
1230             contain at least default_model, default_res_id. Please refer to
1231             the ComposeMessage widget for more information about it.
1232          * @param {Object} [options]
1233          *      @param {Object} [message] read about mail.ThreadMessage object
1234          *      @param {Object} [thread]
1235          *          @param {int} [display_indented_thread] number thread level to indented threads.
1236          *              other are on flat mode
1237          *          @param {Array} [parents] liked with the parents thread
1238          *              use with browse, fetch... [O]= top parent
1239          */
1240         init: function (parent, datasets, options) {
1241             var self = this;
1242             this._super(parent, options);
1243             this.MailWidget = parent instanceof mail.Widget ? parent : false;
1244             this.domain = options.domain || [];
1245             this.context = _.extend(options.context || {});
1246
1247             this.options = options.options;
1248             this.options.root_thread = (options.options.root_thread != undefined ? options.options.root_thread : this);
1249             this.options.show_compose_message = this.options.show_compose_message && !this.thread_level;
1250             
1251             // record options and data
1252             this.parent_message= parent.thread!= undefined ? parent : false ;
1253
1254             // data of this thread
1255             this.id = datasets.id || false;
1256             this.last_id = datasets.last_id || false;
1257             this.parent_id = datasets.parent_id || false;
1258             this.is_private = datasets.is_private || false;
1259             this.author_id = datasets.author_id || false;
1260             this.thread_level = (datasets.thread_level+1) || 0;
1261             datasets.partner_ids = datasets.partner_ids || [];
1262             if (datasets.author_id && !_.contains(_.flatten(datasets.partner_ids),datasets.author_id[0]) && datasets.author_id[0]) {
1263                 datasets.partner_ids.push(datasets.author_id);
1264             }
1265             this.user_pid = datasets.user_pid || false;
1266             this.partner_ids = datasets.partner_ids;
1267             this.messages = [];
1268             this.options.flat_mode = (this.options.display_indented_thread - this.thread_level > 0);
1269
1270             // object compose message
1271             this.compose_message = false;
1272
1273             this.ds_thread = new session.web.DataSetSearch(this, this.context.default_model || 'mail.thread');
1274             this.ds_message = new session.web.DataSetSearch(this, 'mail.message');
1275             this.render_mutex = new $.Mutex();
1276         },
1277         
1278         start: function () {
1279             this._super.apply(this, arguments);
1280             this.bind_events();
1281             return $.when();
1282         },
1283
1284         /* instantiate the compose message object and insert this on the DOM.
1285         * The compose message is display in compact form.
1286         */
1287         instantiate_compose_message: function () {
1288             // add message composition form view
1289             if (!this.compose_message) {
1290                 this.compose_message = new mail.ThreadComposeMessage(this, this, {
1291                     'context': this.options.compose_as_todo && !this.thread_level ? _.extend(this.context, { 'default_starred': true }) : this.context,
1292                     'options': this.options,
1293                 });
1294                 if (!this.thread_level || this.thread_level > this.options.display_indented_thread) {
1295                     this.compose_message.insertBefore(this.$el);
1296                 } else {
1297                     this.compose_message.prependTo(this.$el);
1298                 }
1299             }
1300         },
1301
1302         /* When the expandable object is visible on screen (with scrolling)
1303          * then the on_expandable function is launch
1304         */
1305         on_scroll: function () {
1306             var expandables = 
1307             _.each( _.filter(this.messages, function (val) {return val.max_limit && !val.parent_id;}), function (val) {
1308                 var pos = val.$el.position();
1309                 if (pos.top) {
1310                     /* bottom of the screen */
1311                     var bottom = $(window).scrollTop()+$(window).height()+200;
1312                     if (bottom > pos.top) {
1313                         val.on_expandable();
1314                     }
1315                 }
1316             });
1317         },
1318
1319         /**
1320          * Bind events in the widget. Each event is slightly described
1321          * in the function. */
1322         bind_events: function () {
1323             var self = this;
1324             self.$('.oe_mail_list_recipients .oe_more').on('click', self.on_show_recipients);
1325             self.$('.oe_mail_compose_textarea .oe_more_hidden').on('click', self.on_hide_recipients);
1326         },
1327
1328         /**
1329          *show all the partner list of this parent message
1330         */
1331         on_show_recipients: function () {
1332             var p=$(this).parent(); 
1333             p.find('.oe_more_hidden, .oe_hidden').show(); 
1334             p.find('.oe_more').hide(); 
1335             return false;
1336         },
1337
1338         /**
1339          *hide a part of the partner list of this parent message
1340         */
1341         on_hide_recipients: function () {
1342             var p=$(this).parent(); 
1343             p.find('.oe_more_hidden, .oe_hidden').hide(); 
1344             p.find('.oe_more').show(); 
1345             return false;
1346         },
1347
1348         /* get all child message/thread id linked.
1349          * @return array of id
1350         */
1351         get_child_ids: function () {
1352             return _.map(this.get_childs(), function (val) { return val.id; });
1353         },
1354
1355         /* get all child message/thread linked.
1356          * @param {int} nb_thread_level, number of traversed thread level for this search
1357          * @return array of thread object
1358         */
1359         get_childs: function (nb_thread_level) {
1360             var res=[];
1361             if (arguments[1]) res.push(this);
1362             if (isNaN(nb_thread_level) || nb_thread_level>0) {
1363                 _(this.messages).each(function (val, key) {
1364                     if (val.thread) {
1365                         res = res.concat( val.thread.get_childs((isNaN(nb_thread_level) ? undefined : nb_thread_level-1), true) );
1366                     }
1367                 });
1368             }
1369             return res;
1370         },
1371
1372         /**
1373          *search a thread in all thread and child thread.
1374          * This method return an object thread.
1375          * @param {object}{int} option.id
1376          * @param {object}{string} option.model
1377          * @param {object}{boolean} option._go_thread_wall
1378          *      private for check the top thread
1379          * @param {object}{boolean} option.default_return_top_thread
1380          *      return the top thread (wall) if no thread found
1381          * @return thread object
1382          */
1383         browse_thread: function (options) {
1384             // goto the wall thread for launch browse
1385             if (!options._go_thread_wall) {
1386                 options._go_thread_wall = true;
1387                 return this.options.root_thread.browse_thread(options);
1388             }
1389
1390             if (this.id == options.id) {
1391                 return this;
1392             }
1393
1394             if (options.id) {
1395                 for (var i in this.messages) {
1396                     if (this.messages[i].thread) {
1397                         var res = this.messages[i].thread.browse_thread({'id':options.id, '_go_thread_wall':true});
1398                         if (res) return res;
1399                     }
1400                 }
1401             }
1402
1403             //if option default_return_top_thread, return the top if no found thread
1404             if (options.default_return_top_thread) {
1405                 return this;
1406             }
1407
1408             return false;
1409         },
1410
1411         /**
1412          *search a message in all thread and child thread.
1413          * This method return an object message.
1414          * @param {object}{int} option.id
1415          * @param {object}{string} option.model
1416          * @param {object}{boolean} option._go_thread_wall
1417          *      private for check the top thread
1418          * @return message object
1419          */
1420         browse_message: function (options) {
1421             if (this.options.root_thread.messages[0])
1422                 return this.options.root_thread.messages[0].browse_message(options);
1423         },
1424
1425         /**
1426          *If compose_message doesn't exist, instantiate the compose message.
1427         * Call the on_toggle_quick_composer method to allow the user to write his message.
1428         * (Is call when a user click on "Reply" button)
1429         */
1430         on_compose_message: function (event) {
1431             this.instantiate_compose_message();
1432             this.compose_message.on_toggle_quick_composer(event);
1433             return false;
1434         },
1435
1436         /**
1437          *display the message "there are no message" on the thread
1438         */
1439         no_message: function () {
1440             var no_message = $(session.web.qweb.render('mail.wall_no_message', {}));
1441             if (this.options.help) {
1442                 no_message.html(this.options.help);
1443             }
1444             if (!this.$el.find(".oe_view_nocontent").length)
1445             {
1446                 no_message.appendTo(this.$el);
1447             }
1448         },
1449
1450         /**
1451          *make a request to read the message (calling RPC to "message_read").
1452          * The result of this method is send to the switch message for sending ach message to
1453          * his parented object thread.
1454          * @param {Array} replace_domain: added to this.domain
1455          * @param {Object} replace_context: added to this.context
1456          * @param {Array} ids read (if the are some ids, the method don't use the domain)
1457          */
1458         message_fetch: function (replace_domain, replace_context, ids, callback) {
1459             return this.ds_message.call('message_read', [
1460                     // ids force to read
1461                     ids === false ? undefined : ids && ids.slice(0, this.options.fetch_limit),
1462                     // domain + additional
1463                     (replace_domain ? replace_domain : this.domain), 
1464                     // ids allready loaded
1465                     (this.id ? [this.id].concat( this.get_child_ids() ) : this.get_child_ids()), 
1466                     // option for sending in flat mode by server
1467                     this.options.flat_mode, 
1468                     // context + additional
1469                     (replace_context ? replace_context : this.context), 
1470                     // parent_id
1471                     this.context.default_parent_id || undefined,
1472                     this.options.fetch_limit,
1473                 ]).done(callback ? _.bind(callback, this, arguments) : this.proxy('switch_new_message')
1474                 ).done(this.proxy('message_fetch_set_read'));
1475         },
1476
1477         message_fetch_set_read: function (message_list) {
1478             if (! this.context.mail_read_set_read) return;
1479             var self = this;
1480             this.render_mutex.exec(function() {
1481                 msg_ids = _.pluck(message_list, 'id');
1482                 return self.ds_message.call('set_message_read', [msg_ids, true, false, self.context])
1483                     .then(function (nb_read) {
1484                         if (nb_read) {
1485                             self.options.root_thread.MailWidget.do_reload_menu_emails();
1486                         }
1487                     });
1488              });
1489         },
1490
1491         /**
1492          *create the message object and attached on this thread.
1493          * When the message object is create, this method call insert_message for,
1494          * displaying this message on the DOM.
1495          * @param : {object} data from calling RPC to "message_read"
1496          */
1497         create_message_object: function (data) {
1498             var self = this;
1499
1500             data.thread_level = self.thread_level || 0;
1501             data.options = _.extend(data.options || {}, self.options);
1502
1503             if (data.type=='expandable') {
1504                 var message = new mail.ThreadExpandable(self, data, {'context':{
1505                     'default_model': data.model || self.context.default_model,
1506                     'default_res_id': data.res_id || self.context.default_res_id,
1507                     'default_parent_id': self.id,
1508                 }});
1509             } else {
1510                 data.record_name= (data.record_name != '' && data.record_name) || (self.parent_message && self.parent_message.record_name);
1511                 var message = new mail.ThreadMessage(self, data, {'context':{
1512                     'default_model': data.model,
1513                     'default_res_id': data.res_id,
1514                     'default_parent_id': data.id,
1515                 }});
1516             }
1517
1518             // check if the message is already create
1519             for (var i in self.messages) {
1520                 if (message.id && self.messages[i] && self.messages[i].id == message.id) {
1521                     self.messages[i].destroy();
1522                 }
1523             }
1524             self.messages.push( message );
1525
1526             return message;
1527         },
1528
1529         /**
1530          *insert the message on the DOM.
1531          * All message (and expandable message) are sorted. The method get the
1532          * older and newer message to insert the message (before, after).
1533          * If there are no older or newer, the message is prepend or append to
1534          * the thread (parent object or on root thread for flat view).
1535          * The sort is define by the thread_level (O for newer on top).
1536          * @param : {object} ThreadMessage object
1537          */
1538         insert_message: function (message, dom_insert_after, prepend) {
1539             var self=this;
1540             if (this.options.show_compact_message > this.thread_level) {
1541                 this.instantiate_compose_message();
1542                 this.compose_message.do_show_compact();
1543             }
1544
1545             this.$('.oe_view_nocontent').remove();
1546             if (dom_insert_after && dom_insert_after.parent()[0] == self.$el[0]) {
1547                 message.insertAfter(dom_insert_after);
1548             } else if (prepend) {
1549                 message.prependTo(self.$el);
1550             } else {
1551                 message.appendTo(self.$el);
1552             }
1553             message.$el.hide().fadeIn(500);
1554
1555             return message
1556         },
1557         
1558         /**
1559          *get the parent thread of the messages.
1560          * Each message is send to his parent object (or parent thread flat mode) for creating the object message.
1561          * @param : {Array} datas from calling RPC to "message_read"
1562          */
1563         switch_new_message: function (records, dom_insert_after) {
1564             var self=this;
1565             var dom_insert_after = typeof dom_insert_after == 'object' ? dom_insert_after : false;
1566             _(records).each(function (record) {
1567                 var thread = self.browse_thread({
1568                     'id': record.parent_id, 
1569                     'default_return_top_thread':true
1570                 });
1571                 // create object and attach to the thread object
1572                 var message = thread.create_message_object( record );
1573                 // insert the message on dom
1574                 thread.insert_message( message, dom_insert_after);
1575             });
1576             if (!records.length && this.options.root_thread == this) {
1577                 this.no_message();
1578             }
1579         },
1580
1581         /**
1582          * this method is call when the widget of a message or an expandable message is destroy
1583          * in this thread. The this.messages array is filter to remove this message
1584          */
1585         on_message_detroy: function (message) {
1586
1587             this.messages = _.filter(this.messages, function (val) { return !val.isDestroyed(); });
1588             if (this.options.root_thread == this && !this.messages.length) {
1589                 this.no_message();
1590             }
1591             return false;
1592
1593         },
1594
1595         /**
1596          * Convert a destroyed message into a expandable message
1597          */
1598         message_to_expandable: function (message) {
1599
1600             if (!this.thread_level || message.isDestroyed()) {
1601                 message.destroy();
1602                 return false;
1603             }
1604
1605             var messages = _.sortBy( this.messages, function (val) { return val.id; });
1606             var it = _.indexOf( messages, message );
1607
1608             var msg_up = message.$el.prev('.oe_msg');
1609             var msg_down = message.$el.next('.oe_msg');
1610             var msg_up = msg_up.hasClass('oe_msg_expandable') ? _.find( this.messages, function (val) { return val.$el[0] == msg_up[0]; }) : false;
1611             var msg_down = msg_down.hasClass('oe_msg_expandable') ? _.find( this.messages, function (val) { return val.$el[0] == msg_down[0]; }) : false;
1612
1613             var message_dom = [ ["id", "=", message.id] ];
1614
1615             if ( msg_up && msg_up.type == "expandable" && msg_down && msg_down.type == "expandable") {
1616                 // concat two expandable message and add this message to this dom
1617                 msg_up.domain = mail.ChatterUtils.expand_domain( msg_up.domain );
1618                 msg_down.domain = mail.ChatterUtils.expand_domain( msg_down.domain );
1619
1620                 msg_down.domain = ['|','|'].concat( msg_up.domain ).concat( message_dom ).concat( msg_down.domain );
1621
1622                 if ( !msg_down.max_limit ) {
1623                     msg_down.nb_messages += 1 + msg_up.nb_messages;
1624                 }
1625
1626                 msg_up.$el.remove();
1627                 msg_up.destroy();
1628
1629                 msg_down.reinit();
1630
1631             } else if ( msg_up && msg_up.type == "expandable") {
1632                 // concat preview expandable message and this message to this dom
1633                 msg_up.domain = mail.ChatterUtils.expand_domain( msg_up.domain );
1634                 msg_up.domain = ['|'].concat( msg_up.domain ).concat( message_dom );
1635                 
1636                 msg_up.nb_messages++;
1637
1638                 msg_up.reinit();
1639
1640             } else if ( msg_down && msg_down.type == "expandable") {
1641                 // concat next expandable message and this message to this dom
1642                 msg_down.domain = mail.ChatterUtils.expand_domain( msg_down.domain );
1643                 msg_down.domain = ['|'].concat( msg_down.domain ).concat( message_dom );
1644                 
1645                 // it's maybe a message expandable for the max limit read message
1646                 if ( !msg_down.max_limit ) {
1647                     msg_down.nb_messages++;
1648                 }
1649                 
1650                 msg_down.reinit();
1651
1652             } else {
1653                 // create a expandable message
1654                 var expandable = new mail.ThreadExpandable(this, {
1655                     'model': message.model,
1656                     'parent_id': message.parent_id,
1657                     'nb_messages': 1,
1658                     'thread_level': message.thread_level,
1659                     'parent_id': message.parent_id,
1660                     'domain': message_dom,
1661                     'options': message.options,
1662                     }, {
1663                     'context':{
1664                         'default_model': message.model || this.context.default_model,
1665                         'default_res_id': message.res_id || this.context.default_res_id,
1666                         'default_parent_id': this.id,
1667                     }
1668                 });
1669
1670                 // add object on array and DOM
1671                 this.messages.push(expandable);
1672                 expandable.insertAfter(message.$el);
1673             }
1674
1675             // destroy message
1676             message.destroy();
1677
1678             return true;
1679         },
1680     });
1681
1682     /**
1683      * ------------------------------------------------------------
1684      * mail : root Widget
1685      * ------------------------------------------------------------
1686      *
1687      * This widget handles the display of messages with thread options. Its main
1688      * use is to receive a context and a domain, and to delegate the message
1689      * fetching and displaying to the Thread widget.
1690      */
1691     session.web.client_actions.add('mail.Widget', 'session.mail.Widget');
1692     mail.Widget = session.web.Widget.extend({
1693         template: 'mail.Root',
1694
1695         /**
1696          * @param {Object} parent parent
1697          * @param {Array} [domain]
1698          * @param {Object} [context] context of the thread. It should
1699          *   contain at least default_model, default_res_id. Please refer to
1700          *   the compose_message widget for more information about it.
1701          * @param {Object} [options]
1702          *...  @param {Number} [truncate_limit=250] number of character to
1703          *      display before having a "show more" link; note that the text
1704          *      will not be truncated if it does not have 110% of the parameter
1705          *...  @param {Boolean} [show_record_name] display the name and link for do action
1706          *...  @param {boolean} [show_reply_button] display the reply button
1707          *...  @param {boolean} [show_read_unread_button] display the read/unread button
1708          *...  @param {int} [display_indented_thread] number thread level to indented threads.
1709          *      other are on flat mode
1710          *...  @param {Boolean} [show_compose_message] allow to display the composer
1711          *...  @param {Boolean} [show_compact_message] display the compact message on the thread
1712          *      when the user clic on this compact mode, the composer is open
1713          *...  @param {Array} [message_ids] List of ids to fetch by the root thread.
1714          *      When you use this option, the domain is not used for the fetch root.
1715          *     @param {String} [no_message] Message to display when there are no message
1716          *     @param {Boolean} [show_link] Display partner (authors, followers...) on link or not
1717          *     @param {Boolean} [compose_as_todo] The root composer mark automatically the message as todo
1718          *     @param {Boolean} [readonly] Read only mode, hide all action buttons and composer
1719          */
1720         init: function (parent, action) {
1721             this._super(parent, action);
1722             var self = this;
1723             this.action = _.clone(action);
1724             this.domain = this.action.domain || this.action.params.domain || [];
1725             this.context = this.action.context || this.action.params.context || {};
1726
1727             this.action.params = _.extend({
1728                 'display_indented_thread' : -1,
1729                 'show_reply_button' : false,
1730                 'show_read_unread_button' : false,
1731                 'truncate_limit' : 250,
1732                 'show_record_name' : false,
1733                 'show_compose_message' : false,
1734                 'show_compact_message' : false,
1735                 'compose_placeholder': false,
1736                 'show_link': true,
1737                 'view_inbox': false,
1738                 'message_ids': undefined,
1739                 'compose_as_todo' : false,
1740                 'readonly' : false,
1741                 'emails_from_on_composer': true,
1742                 'fetch_limit': 30   // limit of chatter messages
1743             }, this.action.params);
1744
1745             this.action.params.help = this.action.help || false;
1746         },
1747
1748         start: function (options) {
1749             this._super.apply(this, arguments);
1750             this.message_render();
1751         },
1752         
1753         /**
1754         * create an object "related_menu"
1755         * contains the menu widget and the sub menu related of this wall
1756         */
1757         do_reload_menu_emails: function () {
1758             var menu = session.webclient.menu;
1759             if (!menu || !menu.current_menu) {
1760                 return $.when();
1761             }
1762             return menu.rpc("/web/menu/load_needaction", {'menu_ids': [menu.current_menu]}).done(function(r) {
1763                 menu.on_needaction_loaded(r);
1764             }).then(function () {
1765                 menu.trigger("need_action_reloaded");
1766             });
1767         },
1768
1769         /**
1770          *Create the root thread and display this object in the DOM.
1771          * Call the no_message method then c all the message_fetch method 
1772          * of this root thread to display the messages.
1773          */
1774         message_render: function (search) {
1775
1776             this.thread = new mail.Thread(this, {}, {
1777                 'domain' : this.domain,
1778                 'context' : this.context,
1779                 'options': this.action.params,
1780             });
1781
1782             this.thread.appendTo( this.$el );
1783
1784             if (this.action.params.show_compose_message) {
1785                 this.thread.instantiate_compose_message();
1786                 this.thread.compose_message.do_show_compact();
1787             }
1788
1789             this.thread.message_fetch(null, null, this.action.params.message_ids);
1790
1791         },
1792
1793     });
1794
1795
1796     /**
1797      * ------------------------------------------------------------
1798      * mail_thread Widget
1799      * ------------------------------------------------------------
1800      *
1801      * This widget handles the display of messages on a document. Its main
1802      * use is to receive a context and a domain, and to delegate the message
1803      * fetching and displaying to the Thread widget.
1804      * Use Help on the field to display a custom "no message loaded"
1805      */
1806     session.web.form.widgets.add('mail_thread', 'openerp.mail.RecordThread');
1807     mail.RecordThread = session.web.form.AbstractField.extend({
1808         template: 'mail.record_thread',
1809
1810         init: function (parent, node) {
1811             this._super.apply(this, arguments);
1812             this.ParentViewManager = parent;
1813             this.node = _.clone(node);
1814             this.node.params = _.extend({
1815                 'display_indented_thread': -1,
1816                 'show_reply_button': false,
1817                 'show_read_unread_button': true,
1818                 'read_action': 'unread',
1819                 'show_record_name': false,
1820                 'show_compact_message': 1,
1821                 'display_log_button' : true,
1822             }, this.node.params);
1823             if (this.node.attrs.placeholder) {
1824                 this.node.params.compose_placeholder = this.node.attrs.placeholder;
1825             }
1826             if (this.node.attrs.readonly) {
1827                 this.node.params.readonly = this.node.attrs.readonly;
1828             }
1829             if ('display_log_button' in this.options) {
1830                 this.node.params.display_log_button = this.options.display_log_button;
1831             }
1832             this.domain = (this.node.params && this.node.params.domain) || (this.field && this.field.domain) || [];
1833
1834             if (!this.ParentViewManager.is_action_enabled('edit')) {
1835                 this.node.params.show_link = false;
1836             }
1837         },
1838
1839         start: function () {
1840             this._super.apply(this, arguments);
1841             // NB: check the actual_mode property on view to know if the view is in create mode anymore
1842             this.view.on("change:actual_mode", this, this._check_visibility);
1843             this._check_visibility();
1844         },
1845
1846         _check_visibility: function () {
1847             this.$el.toggle(this.view.get("actual_mode") !== "create");
1848         },
1849
1850         render_value: function () {
1851             var self = this;
1852
1853             if (! this.view.datarecord.id || session.web.BufferedDataSet.virtual_id_regex.test(this.view.datarecord.id)) {
1854                 this.$('oe_mail_thread').hide();
1855                 return;
1856             }
1857
1858             this.node.params = _.extend(this.node.params, {
1859                 'message_ids': this.get_value(),
1860                 'show_compose_message': this.view.is_action_enabled('edit'),
1861             });
1862             this.node.context = {
1863                 'mail_read_set_read': true,  // set messages as read in Chatter
1864                 'default_res_id': this.view.datarecord.id || false,
1865                 'default_model': this.view.model || false,
1866             };
1867
1868             if (this.root) {
1869                 $('<span class="oe_mail-placeholder"/>').insertAfter(this.root.$el);
1870                 this.root.destroy();
1871             }
1872             // create and render Thread widget
1873             this.root = new mail.Widget(this, _.extend(this.node, {
1874                 'domain' : (this.domain || []).concat([['model', '=', this.view.model], ['res_id', '=', this.view.datarecord.id]]),
1875             }));
1876
1877             return this.root.replace(this.$('.oe_mail-placeholder'));
1878         },
1879     });
1880
1881
1882     /**
1883      * ------------------------------------------------------------
1884      * Aside Widget
1885      * ------------------------------------------------------------
1886      * 
1887      * This widget handles the display of a sidebar on the Wall. Its main use
1888      * is to display group and employees suggestion (if hr is installed).
1889      */
1890     mail.WallSidebar = session.web.Widget.extend({
1891         template: 'mail.wall.sidebar',
1892     });
1893
1894
1895     /**
1896      * ------------------------------------------------------------
1897      * Wall Widget
1898      * ------------------------------------------------------------
1899      *
1900      * This widget handles the display of messages on a Wall. Its main
1901      * use is to receive a context and a domain, and to delegate the message
1902      * fetching and displaying to the Thread widget.
1903      */
1904
1905     session.web.client_actions.add('mail.wall', 'session.mail.Wall');
1906     mail.Wall = session.web.Widget.extend({
1907         template: 'mail.wall',
1908
1909         /**
1910          * @param {Object} parent parent
1911          * @param {Object} [options]
1912          * @param {Array} [options.domain] domain on the Wall
1913          * @param {Object} [options.context] context, is an object. It should
1914          *      contain default_model, default_res_id, to give it to the threads.
1915          */
1916         init: function (parent, action) {
1917             this._super(parent, action);
1918             this.ActionManager = parent;
1919
1920             this.action = _.clone(action);
1921             this.domain = this.action.params.domain || this.action.domain || [];
1922             this.context = _.extend(this.action.params.context || {}, this.action.context || {});
1923
1924             // filter some parameters that we will propagate as search_default
1925             this.defaults = {};
1926             for (var key in this.action.context.params) {
1927                 if (_.indexOf(['model', 'res_id'], key) == -1) {
1928                     continue;
1929                 }
1930                 this.context['search_default_' + key] = this.action.context.params[key];
1931             }
1932             for (var key in this.context) {
1933                 if (key.match(/^search_default_/)) {
1934                     this.defaults[key.replace(/^search_default_/, '')] = this.context[key];
1935                 }
1936             }
1937             this.action.params = _.extend({
1938                 'display_indented_thread': 1,
1939                 'show_reply_button': true,
1940                 'show_read_unread_button': true,
1941                 'show_compose_message': true,
1942                 'show_record_name': true,
1943                 'show_compact_message': this.action.params.view_mailbox ? false : 1,
1944                 'view_inbox': false,
1945                 'emails_from_on_composer': false,
1946                 'fetch_limit': 1000   // allow inbox to load all children messages
1947             }, this.action.params);
1948         },
1949
1950         start: function () {
1951             this._super.apply(this);
1952             this.bind_events();
1953             var searchview_loaded = this.load_searchview(this.defaults);
1954             if (! this.searchview.has_defaults) {
1955                 this.message_render();
1956             }
1957             // render sidebar
1958             var wall_sidebar = new mail.WallSidebar(this);
1959             wall_sidebar.appendTo(this.$el.find('.oe_mail_wall_aside'));
1960         },
1961
1962         /**
1963          * Load the mail.message search view
1964          * @param {Object} defaults ??
1965          */
1966         load_searchview: function (defaults) {
1967             var self = this,
1968                 ds_msg = new session.web.DataSetSearch(this, 'mail.message'),
1969                 options = { $buttons: this.$('.oe-search-options') };
1970             this.searchview = new session.web.SearchView(this, ds_msg, false, defaults || {}, options);
1971             this.searchview.on('search_data', this, this.do_searchview_search);
1972             this.searchview.appendTo(this.$('.oe-view-manager-search-view')).then(function () {
1973                 self.searchview.toggle_visibility(true);
1974             });
1975             if (this.searchview.has_defaults) {
1976                 this.searchview.ready.then(this.searchview.do_search);
1977             }
1978             return this.searchview
1979         },
1980
1981         /**
1982          * Get the domains, contexts and groupbys in parameter from search
1983          * view, then render the filtered threads.
1984          * @param {Array} domains
1985          * @param {Array} contexts
1986          * @param {Array} groupbys
1987          */
1988         do_searchview_search: function (domains, contexts, groupbys) {
1989             var self = this;
1990             session.web.pyeval.eval_domains_and_contexts({
1991                 domains: domains || [],
1992                 contexts: contexts || [],
1993                 group_by_seq: groupbys || []
1994             }).then(function (results) {
1995                 if(self.root) {
1996                     $('<span class="oe_mail-placeholder"/>').insertAfter(self.root.$el);
1997                     self.root.destroy();
1998                 }
1999                 return self.message_render(results);
2000             });
2001         },
2002
2003         /**
2004          * Create the root thread widget and display this object in the DOM
2005          */
2006         message_render: function (search) {
2007             var domain = this.domain.concat(search && search['domain'] ? search['domain'] : []);
2008             var context = _.extend(this.context, search && search['context'] ? search['context'] : {});
2009
2010             this.root = new mail.Widget(this, _.extend(this.action, {
2011                 'domain' : domain,
2012                 'context' : context,
2013             }));
2014             return this.root.replace(this.$('.oe_mail-placeholder'));
2015         },
2016
2017         bind_events: function () {
2018             var self=this;
2019             this.$(".oe_write_full").click(function (event) {
2020                 event.stopPropagation();
2021                 var action = {
2022                     name: _t('Compose Email'),
2023                     type: 'ir.actions.act_window',
2024                     res_model: 'mail.compose.message',
2025                     view_mode: 'form',
2026                     view_type: 'form',
2027                     action_from: 'mail.ThreadComposeMessage',
2028                     views: [[false, 'form']],
2029                     target: 'new',
2030                     context: {
2031                     },
2032                 };
2033                 session.client.action_manager.do_action(action);
2034             });
2035             this.$(".oe_write_onwall").click(function (event) { self.root.thread.on_compose_message(event); });
2036         }
2037     });
2038
2039     /**
2040      * ------------------------------------------------------------
2041      * Sub-widgets loading
2042      * ------------------------------------------------------------
2043      * 
2044      * Load here widgets that could depend on widgets defined in mail.js
2045      */
2046
2047     openerp.mail.suggestions(session, mail);        // import suggestion.js (suggestion widget)
2048
2049 };