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