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