56e06006e8d479f4f02740c12b26faab79372628
[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('new_email_partner', [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             console.log(partner_ids);
627             this.parent_thread.ds_thread._model.call('message_post_user_api', [this.context.default_res_id], {
628                 'body': this.$('textarea').val(),
629                 'subject': false,
630                 'parent_id': this.context.default_parent_id,
631                 'attachment_ids': _.map(this.attachment_ids, function (file) {return file.id;}),
632                 'partner_ids': partner_ids,
633                 'context': this.parent_thread.context,
634             }).done(function (message_id) {
635                 var thread = self.parent_thread;
636                 var root = thread == self.options.root_thread;
637                 if (self.options.display_indented_thread < self.thread_level && thread.parent_message) {
638                     var thread = thread.parent_message.parent_thread;
639                 }
640                 // create object and attach to the thread object
641                 thread.message_fetch([["id", "=", message_id]], false, [message_id], function (arg, data) {
642                     var message = thread.create_message_object( data[0] );
643                     // insert the message on dom
644                     thread.insert_message( message, root ? undefined : self.$el, root );
645                 });
646                 self.on_cancel();
647             });
648         },
649
650         /* convert the compact mode into the compose message
651         */
652         on_compose_expandable: function (event) {
653             this.get_emails_from();
654             if ((!this.stay_open || (event && event.type == 'click')) && (!this.show_composer || !this.$('textarea:not(.oe_compact)').val().match(/\S+/) && !this.attachment_ids.length)) {
655                 this.show_composer = !this.show_composer || this.stay_open;
656                 this.reinit();
657             }
658             if (!this.stay_open && this.show_composer && (!event || event.type != 'blur')) {
659                 this.$('textarea:not(.oe_compact):first').focus();
660             }
661             return true;
662         },
663
664         do_hide_compact: function () {
665             this.show_compact_message = false;
666             if (!this.show_composer) {
667                 this.reinit();
668             }
669         },
670
671         do_show_compact: function () {
672             this.show_compact_message = true;
673             if (!this.show_composer) {
674                 this.reinit();
675             }
676         },
677
678         get_emails_from: function () {
679             var self = this;
680             var messages = [];
681
682             if (this.parent_thread.parent_message) {
683                 // go to the parented message
684                 var message = this.parent_thread.parent_message;
685                 var parent_message = message.parent_id ? message.parent_thread.parent_message : message;
686                 var messages = [parent_message].concat(parent_message.get_childs());
687             } else if (this.options.emails_from_on_composer) {
688                 // get all wall messages if is not a mail.Wall
689                 _.each(this.options.root_thread.messages, function (msg) {messages.push(msg); messages.concat(msg.get_childs());});
690             }
691             
692             _.each(messages, function (thread) {
693                 if (thread.author_id && !thread.author_id[0] &&
694                     !_.find(self.emails_from, function (from) {return from[0][4] == thread.author_id[4];})) {
695                     self.emails_from.push([thread.author_id, true]);
696                 }
697             });
698             return self.emails_from;
699         },
700
701         on_checked_email_from: function (event) {
702             var $input = $(event.target);
703             var email = $input.attr("data");
704             _.each(this.emails_from, function (email_from) {
705                 if (email_from[0][4] == email) {
706                     email_from[1] = $input.is(":checked");
707                 }
708             });
709         },
710     });
711
712     /**
713      * ------------------------------------------------------------
714      * Thread Message Expandable Widget
715      * ------------------------------------------------------------
716      *
717      * This widget handles the display the expandable message in a thread.
718      * - thread
719      * - - visible message
720      * - - expandable
721      * - - visible message
722      * - - visible message
723      * - - expandable
724      */
725     mail.ThreadExpandable = mail.MessageCommon.extend({
726         template: 'mail.thread.expandable',
727
728         init: function (parent, datasets, options) {
729             this._super(parent, datasets, options);
730             this.type = 'expandable';
731             this.max_limit = datasets.max_limit;
732             this.nb_messages = datasets.nb_messages;
733             this.flag_used = false;
734         },
735         
736         start: function () {
737             this._super.apply(this, arguments);
738             this.bind_events();
739         },
740
741         reinit: function () {
742             var $render = $(session.web.qweb.render('mail.thread.expandable', {'widget': this}));
743             this.$el.replaceWith( $render );
744             this.$el = $render;
745             this.bind_events();
746         },
747
748         /**
749          * Bind events in the widget. Each event is slightly described
750          * in the function. */
751         bind_events: function () {
752             this.$('.oe_msg_more_message').on('click', this.on_expandable);
753         },
754
755         animated_destroy: function (fadeTime) {
756             var self=this;
757             this.$el.fadeOut(fadeTime, function () {
758                 self.destroy();
759             });
760         },
761
762         /*The selected thread and all childs (messages/thread) became read
763         * @param {object} mouse envent
764         */
765         on_expandable: function (event) {
766             if (event)event.stopPropagation();
767             if (this.flag_used) {
768                 return false
769             }
770             this.flag_used = true;
771
772             var self = this;
773
774             // read messages
775             self.parent_thread.message_fetch(this.domain, this.context, false, function (arg, data) {
776                 if (self.options.root_thread == self.parent_thread) {
777                     data.reverse();
778                 }
779                 self.id = false;
780                 // insert the message on dom after this message
781                 self.parent_thread.switch_new_message( data, self.$el );
782                 self.animated_destroy(200);
783             });
784
785             return false;
786         },
787
788     });
789
790     mail.ThreadMessage = mail.MessageCommon.extend({
791         template: 'mail.thread.message',
792         
793         start: function () {
794             this._super.apply(this, arguments);
795             this.expender();
796             this.bind_events();
797             if(this.thread_level < this.options.display_indented_thread) {
798                 this.create_thread();
799             }
800             this.display_attachments();
801
802             this.ds_notification = new session.web.DataSetSearch(this, 'mail.notification');
803             this.ds_message = new session.web.DataSetSearch(this, 'mail.message');
804         },
805
806         /**
807          * Bind events in the widget. Each event is slightly described
808          * in the function. */
809         bind_events: function () {
810             var self = this;
811             // header icons bindings
812             this.$('.oe_read').on('click', this.on_message_read);
813             this.$('.oe_unread').on('click', this.on_message_unread);
814             this.$('.oe_msg_delete').on('click', this.on_message_delete);
815             this.$('.oe_reply').on('click', this.on_message_reply);
816             this.$('.oe_star').on('click', this.on_star);
817             this.$('.oe_msg_vote').on('click', this.on_vote);
818         },
819
820         /* Call the on_compose_message on the thread of this message. */
821         on_message_reply:function (event) {
822             event.stopPropagation();
823             this.create_thread();
824             this.thread.on_compose_message(event);
825             return false;
826         },
827
828         expender: function () {
829             this.$('.oe_msg_body:first').expander({
830                 slicePoint: this.options.truncate_limit,
831                 expandText: 'read more',
832                 userCollapseText: 'read less',
833                 detailClass: 'oe_msg_tail',
834                 moreClass: 'oe_mail_expand',
835                 lessClass: 'oe_mail_reduce',
836                 });
837         },
838
839         /**
840          * Instantiate the thread object of this message.
841          * Each message have only one thread.
842          */
843         create_thread: function () {
844             if (this.thread) {
845                 return false;
846             }
847             /*create thread*/
848             this.thread = new mail.Thread(this, this, {
849                     'domain': this.domain,
850                     'context':{
851                         'default_model': this.model,
852                         'default_res_id': this.res_id,
853                         'default_parent_id': this.id
854                     },
855                     'options': this.options
856                 }
857             );
858             /*insert thread in parent message*/
859             this.thread.insertAfter(this.$el);
860         },
861         
862         /**
863          * Fade out the message and his child thread.
864          * Then this object is destroyed.
865          */
866         animated_destroy: function (fadeTime) {
867             var self=this;
868             this.$el.fadeOut(fadeTime, function () {
869                 self.parent_thread.message_to_expandable(self);
870             });
871             if (this.thread) {
872                 this.thread.$el.fadeOut(fadeTime);
873             }
874         },
875
876         /**
877          * Wait a confirmation for delete the message on the DB.
878          * Make an animate destroy
879          */
880         on_message_delete: function (event) {
881             event.stopPropagation();
882             if (! confirm(_t("Do you really want to delete this message?"))) { return false; }
883             
884             this.animated_destroy(150);
885             // delete this message and his childs
886             var ids = [this.id].concat( this.get_child_ids() );
887             this.ds_message.unlink(ids);
888             return false;
889         },
890
891         /* Check if the message must be destroy and detroy it or check for re render widget
892         * @param {callback} apply function
893         */
894         check_for_rerender: function () {
895             var self = this;
896
897             var messages = [this].concat(this.get_childs());
898             var message_ids = _.map(messages, function (msg) { return msg.id;});
899             var domain = mail.ChatterUtils.expand_domain( this.options.root_thread.domain )
900                 .concat([["id", "in", message_ids ]]);
901
902             return this.parent_thread.ds_message.call('message_read', [undefined, domain, [], !!this.parent_thread.options.display_indented_thread, this.context, this.parent_thread.id])
903                 .then( function (records) {
904                     // remove message not loaded
905                     _.map(messages, function (msg) {
906                         if(!_.find(records, function (record) { return record.id == msg.id; })) {
907                             msg.animated_destroy(150);
908                         } else {
909                             msg.renderElement();
910                             msg.start();
911                         }
912                         if( self.options.root_thread.__parentedParent.__parentedParent.do_reload_menu_emails ) {
913                             self.options.root_thread.__parentedParent.__parentedParent.do_reload_menu_emails();
914                         }
915                     });
916
917                 });
918         },
919
920         on_message_read: function (event) {
921             event.stopPropagation();
922             this.on_message_read_unread(true);
923             return false;
924         },
925
926         on_message_unread: function (event) {
927             event.stopPropagation();
928             this.on_message_read_unread(false);
929             return false;
930         },
931
932         /* Set the selected thread and all childs as read or unread, based on
933          * read parameter.
934          * @param {boolean} read_value
935          */
936         on_message_read_unread: function (read_value) {
937             var self = this;
938             var messages = [this].concat(this.get_childs());
939
940             // inside the inbox, when the user mark a message as read/done, don't apply this value
941             // for the stared/favorite message
942             if (this.options.view_inbox && read_value) {
943                 var messages = _.filter(messages, function (val) { return !val.is_favorite && val.id; });
944                 if (!messages.length) {
945                     this.check_for_rerender();
946                     return false;
947                 }
948             }
949             var message_ids = _.map(messages, function (val) { return val.id; });
950
951             this.ds_message.call('set_message_read', [message_ids, read_value, true, this.context])
952                 .then(function () {
953                     // apply modification
954                     _.each(messages, function (msg) {
955                         msg.to_read = !read_value;
956                         if (msg.options.toggle_read) {
957                             msg.options.show_read = msg.to_read;
958                             msg.options.show_unread = !msg.to_read;
959                         }
960                     });
961                     // check if the message must be display, destroy or rerender
962                     self.check_for_rerender();
963                 });
964             return false;
965         },
966
967         /**
968          * add or remove a vote for a message and display the result
969         */
970         on_vote: function (event) {
971             event.stopPropagation();
972             this.ds_message.call('vote_toggle', [[this.id]])
973                 .then(
974                     _.bind(function (vote) {
975                         this.has_voted = vote;
976                         this.vote_nb += this.has_voted ? 1 : -1;
977                         this.display_vote();
978                     }, this));
979             return false;
980         },
981
982         /**
983          * Display the render of this message's vote
984         */
985         display_vote: function () {
986             var vote_element = session.web.qweb.render('mail.thread.message.vote', {'widget': this});
987             this.$(".oe_msg_footer:first .oe_mail_vote_count").remove();
988             this.$(".oe_msg_footer:first .oe_msg_vote").replaceWith(vote_element);
989             this.$('.oe_msg_vote').on('click', this.on_vote);
990         },
991
992         /**
993          * add or remove a favorite (or starred) for a message and change class on the DOM
994         */
995         on_star: function (event) {
996             event.stopPropagation();
997             var self=this;
998             var button = self.$('.oe_star:first');
999
1000             this.ds_message.call('set_message_starred', [[self.id], !self.is_favorite, true])
1001                 .then(function (star) {
1002                     self.is_favorite=star;
1003                     if (self.is_favorite) {
1004                         button.addClass('oe_starred');
1005                     } else {
1006                         button.removeClass('oe_starred');
1007                     }
1008
1009                     if (self.options.view_inbox && self.is_favorite) {
1010                         self.on_message_read_unread(true);
1011                     } else {
1012                         self.check_for_rerender();
1013                     }
1014                 });
1015             return false;
1016         },
1017
1018     });
1019
1020     /**
1021      * ------------------------------------------------------------
1022      * Thread Widget
1023      * ------------------------------------------------------------
1024      *
1025      * This widget handles the display of a thread of messages. The
1026      * thread view:
1027      * - root thread
1028      * - - sub message (parent_id = root message)
1029      * - - - sub thread
1030      * - - - - sub sub message (parent id = sub thread)
1031      * - - sub message (parent_id = root message)
1032      * - - - sub thread
1033      */
1034     mail.Thread = session.web.Widget.extend({
1035         template: 'mail.thread',
1036
1037         /**
1038          * @param {Object} parent parent
1039          * @param {Array} [domain]
1040          * @param {Object} [context] context of the thread. It should
1041             contain at least default_model, default_res_id. Please refer to
1042             the ComposeMessage widget for more information about it.
1043          * @param {Object} [options]
1044          *      @param {Object} [message] read about mail.ThreadMessage object
1045          *      @param {Object} [thread]
1046          *          @param {int} [display_indented_thread] number thread level to indented threads.
1047          *              other are on flat mode
1048          *          @param {Array} [parents] liked with the parents thread
1049          *              use with browse, fetch... [O]= top parent
1050          */
1051         init: function (parent, datasets, options) {
1052             var self = this;
1053             this._super(parent, options);
1054             this.domain = options.domain || [];
1055             this.context = _.extend(options.context || {});
1056
1057             this.options = options.options;
1058             this.options.root_thread = (options.options.root_thread != undefined ? options.options.root_thread : this);
1059             this.options.show_compose_message = this.options.show_compose_message && !this.thread_level;
1060             
1061             // record options and data
1062             this.parent_message= parent.thread!= undefined ? parent : false ;
1063
1064             // data of this thread
1065             this.id = datasets.id || false;
1066             this.last_id = datasets.last_id || false;
1067             this.parent_id = datasets.parent_id || false;
1068             this.is_private = datasets.is_private || false;
1069             this.author_id = datasets.author_id || false;
1070             this.thread_level = (datasets.thread_level+1) || 0;
1071             datasets.partner_ids = datasets.partner_ids || [];
1072             if (datasets.author_id && ! _.contains(datasets.partner_ids, datasets.author_id) && datasets.author_id[0]) {
1073                 datasets.partner_ids.push(datasets.author_id);
1074             }
1075             this.partner_ids = datasets.partner_ids;
1076             this.messages = [];
1077
1078             this.options.flat_mode = !!(this.options.display_indented_thread > this.thread_level ? this.options.display_indented_thread - this.thread_level : 0);
1079
1080             // object compose message
1081             this.compose_message = false;
1082
1083             this.ds_thread = new session.web.DataSetSearch(this, this.context.default_model || 'mail.thread');
1084             this.ds_message = new session.web.DataSetSearch(this, 'mail.message');
1085             this.render_mutex = new $.Mutex();
1086         },
1087         
1088         start: function () {
1089             this._super.apply(this, arguments);
1090             this.bind_events();
1091         },
1092
1093         /* instantiate the compose message object and insert this on the DOM.
1094         * The compose message is display in compact form.
1095         */
1096         instantiate_compose_message: function () {
1097             // add message composition form view
1098             if (!this.compose_message) {
1099                 this.compose_message = new mail.ThreadComposeMessage(this, this, {
1100                     'context': this.options.compose_as_todo && !this.thread_level ? _.extend(this.context, { 'default_starred': true }) : this.context,
1101                     'options': this.options,
1102                 });
1103                 if (!this.thread_level || this.thread_level > this.options.display_indented_thread) {
1104                     this.compose_message.insertBefore(this.$el);
1105                 } else {
1106                     this.compose_message.prependTo(this.$el);
1107                 }
1108             }
1109         },
1110
1111         /* When the expandable object is visible on screen (with scrolling)
1112          * then the on_expandable function is launch
1113         */
1114         on_scroll: function () {
1115             var expandables = 
1116             _.each( _.filter(this.messages, function (val) {return val.max_limit && !val.parent_id;}), function (val) {
1117                 var pos = val.$el.position();
1118                 if (pos.top) {
1119                     /* bottom of the screen */
1120                     var bottom = $(window).scrollTop()+$(window).height()+200;
1121                     if (bottom > pos.top) {
1122                         val.on_expandable();
1123                     }
1124                 }
1125             });
1126         },
1127
1128         /**
1129          * Bind events in the widget. Each event is slightly described
1130          * in the function. */
1131         bind_events: function () {
1132             var self = this;
1133             self.$('.oe_mail_list_recipients .oe_more').on('click', self.on_show_recipients);
1134             self.$('.oe_mail_compose_textarea .oe_more_hidden').on('click', self.on_hide_recipients);
1135         },
1136
1137         /**
1138          *show all the partner list of this parent message
1139         */
1140         on_show_recipients: function () {
1141             var p=$(this).parent(); 
1142             p.find('.oe_more_hidden, .oe_hidden').show(); 
1143             p.find('.oe_more').hide(); 
1144             return false;
1145         },
1146
1147         /**
1148          *hide a part of the partner list of this parent message
1149         */
1150         on_hide_recipients: function () {
1151             var p=$(this).parent(); 
1152             p.find('.oe_more_hidden, .oe_hidden').hide(); 
1153             p.find('.oe_more').show(); 
1154             return false;
1155         },
1156
1157         /* get all child message/thread id linked.
1158          * @return array of id
1159         */
1160         get_child_ids: function () {
1161             return _.map(this.get_childs(), function (val) { return val.id; });
1162         },
1163
1164         /* get all child message/thread linked.
1165          * @param {int} nb_thread_level, number of traversed thread level for this search
1166          * @return array of thread object
1167         */
1168         get_childs: function (nb_thread_level) {
1169             var res=[];
1170             if (arguments[1]) res.push(this);
1171             if (isNaN(nb_thread_level) || nb_thread_level>0) {
1172                 _(this.messages).each(function (val, key) {
1173                     if (val.thread) {
1174                         res = res.concat( val.thread.get_childs((isNaN(nb_thread_level) ? undefined : nb_thread_level-1), true) );
1175                     }
1176                 });
1177             }
1178             return res;
1179         },
1180
1181         /**
1182          *search a thread in all thread and child thread.
1183          * This method return an object thread.
1184          * @param {object}{int} option.id
1185          * @param {object}{string} option.model
1186          * @param {object}{boolean} option._go_thread_wall
1187          *      private for check the top thread
1188          * @param {object}{boolean} option.default_return_top_thread
1189          *      return the top thread (wall) if no thread found
1190          * @return thread object
1191          */
1192         browse_thread: function (options) {
1193             // goto the wall thread for launch browse
1194             if (!options._go_thread_wall) {
1195                 options._go_thread_wall = true;
1196                 return this.options.root_thread.browse_thread(options);
1197             }
1198
1199             if (this.id == options.id) {
1200                 return this;
1201             }
1202
1203             if (options.id) {
1204                 for (var i in this.messages) {
1205                     if (this.messages[i].thread) {
1206                         var res = this.messages[i].thread.browse_thread({'id':options.id, '_go_thread_wall':true});
1207                         if (res) return res;
1208                     }
1209                 }
1210             }
1211
1212             //if option default_return_top_thread, return the top if no found thread
1213             if (options.default_return_top_thread) {
1214                 return this;
1215             }
1216
1217             return false;
1218         },
1219
1220         /**
1221          *search a message in all thread and child thread.
1222          * This method return an object message.
1223          * @param {object}{int} option.id
1224          * @param {object}{string} option.model
1225          * @param {object}{boolean} option._go_thread_wall
1226          *      private for check the top thread
1227          * @return message object
1228          */
1229         browse_message: function (options) {
1230             if (this.options.root_thread.messages[0])
1231                 return this.options.root_thread.messages[0].browse_message(options);
1232         },
1233
1234         /**
1235          *If compose_message doesn't exist, instantiate the compose message.
1236         * Call the on_compose_expandable method to allow the user to write his message.
1237         * (Is call when a user click on "Reply" button)
1238         */
1239         on_compose_message: function (event) {
1240             this.instantiate_compose_message();
1241             this.compose_message.on_compose_expandable(event);
1242             return false;
1243         },
1244
1245         /**
1246          *display the message "there are no message" on the thread
1247         */
1248         no_message: function () {
1249             var no_message = $(session.web.qweb.render('mail.wall_no_message', {}));
1250             if (this.options.help) {
1251                 no_message.html(this.options.help);
1252             }
1253             no_message.appendTo(this.$el);
1254         },
1255
1256         /**
1257          *make a request to read the message (calling RPC to "message_read").
1258          * The result of this method is send to the switch message for sending ach message to
1259          * his parented object thread.
1260          * @param {Array} replace_domain: added to this.domain
1261          * @param {Object} replace_context: added to this.context
1262          * @param {Array} ids read (if the are some ids, the method don't use the domain)
1263          */
1264         message_fetch: function (replace_domain, replace_context, ids, callback) {
1265             return this.ds_message.call('message_read', [
1266                     // ids force to read
1267                     ids == false ? undefined : ids, 
1268                     // domain + additional
1269                     (replace_domain ? replace_domain : this.domain), 
1270                     // ids allready loaded
1271                     (this.id ? [this.id].concat( this.get_child_ids() ) : this.get_child_ids()), 
1272                     // option for sending in flat mode by server
1273                     this.options.flat_mode, 
1274                     // context + additional
1275                     (replace_context ? replace_context : this.context), 
1276                     // parent_id
1277                     this.context.default_parent_id || undefined
1278                 ]).done(callback ? _.bind(callback, this, arguments) : this.proxy('switch_new_message')
1279                 ).done(this.proxy('message_fetch_set_read'));
1280         },
1281
1282         message_fetch_set_read: function (message_list) {
1283             if (! this.context.mail_read_set_read) return;
1284             this.render_mutex.exec(_.bind(function() {
1285                 msg_ids = _.pluck(message_list, 'id');
1286                 return this.ds_message.call('set_message_read', [
1287                         msg_ids, true, false, this.context]);
1288              }, this));
1289         },
1290
1291         /**
1292          *create the message object and attached on this thread.
1293          * When the message object is create, this method call insert_message for,
1294          * displaying this message on the DOM.
1295          * @param : {object} data from calling RPC to "message_read"
1296          */
1297         create_message_object: function (data) {
1298             var self = this;
1299
1300             var data = _.extend(data, {'thread_level': data.thread_level ? data.thread_level : self.thread_level});
1301             data.options = _.extend(self.options, data.options);
1302
1303             if (data.type=='expandable') {
1304                 var message = new mail.ThreadExpandable(self, data, {'context':{
1305                     'default_model': data.model || self.context.default_model,
1306                     'default_res_id': data.res_id || self.context.default_res_id,
1307                     'default_parent_id': self.id,
1308                 }});
1309             } else {
1310                 data.record_name= (data.record_name != '' && data.record_name) || (self.parent_message && self.parent_message.record_name);
1311                 var message = new mail.ThreadMessage(self, data, {'context':{
1312                     'default_model': data.model,
1313                     'default_res_id': data.res_id,
1314                     'default_parent_id': data.id,
1315                 }});
1316             }
1317
1318             // check if the message is already create
1319             for (var i in self.messages) {
1320                 if (message.id && self.messages[i] && self.messages[i].id == message.id) {
1321                     self.messages[i].destroy();
1322                 }
1323             }
1324             self.messages.push( message );
1325
1326             return message;
1327         },
1328
1329         /**
1330          *insert the message on the DOM.
1331          * All message (and expandable message) are sorted. The method get the
1332          * older and newer message to insert the message (before, after).
1333          * If there are no older or newer, the message is prepend or append to
1334          * the thread (parent object or on root thread for flat view).
1335          * The sort is define by the thread_level (O for newer on top).
1336          * @param : {object} ThreadMessage object
1337          */
1338         insert_message: function (message, dom_insert_after, prepend) {
1339             var self=this;
1340             if (this.options.show_compact_message > this.thread_level) {
1341                 this.instantiate_compose_message();
1342                 this.compose_message.do_show_compact();
1343             }
1344
1345             this.$('.oe_view_nocontent').remove();
1346
1347             if (dom_insert_after) {
1348                 message.insertAfter(dom_insert_after);
1349             } else if (prepend) {
1350                 message.prependTo(self.$el);
1351             } else {
1352                 message.appendTo(self.$el);
1353             }
1354             message.$el.hide().fadeIn(500);
1355
1356             return message
1357         },
1358         
1359         /**
1360          *get the parent thread of the messages.
1361          * Each message is send to his parent object (or parent thread flat mode) for creating the object message.
1362          * @param : {Array} datas from calling RPC to "message_read"
1363          */
1364         switch_new_message: function (records, dom_insert_after) {
1365             var self=this;
1366             _(records).each(function (record) {
1367                 var thread = self.browse_thread({
1368                     'id': record.parent_id, 
1369                     'default_return_top_thread':true
1370                 });
1371                 // create object and attach to the thread object
1372                 var message = thread.create_message_object( record );
1373                 // insert the message on dom
1374                 thread.insert_message( message, typeof dom_insert_after == 'object' ? dom_insert_after : false);
1375             });
1376             if (!records.length && this.options.root_thread == this) {
1377                 this.no_message();
1378             }
1379         },
1380
1381         /**
1382          * this method is call when the widget of a message or an expandable message is destroy
1383          * in this thread. The this.messages array is filter to remove this message
1384          */
1385         on_message_detroy: function (message) {
1386
1387             this.messages = _.filter(this.messages, function (val) { return !val.isDestroyed(); });
1388             if (this.options.root_thread == this && !this.messages.length) {
1389                 this.no_message();
1390             }
1391             return false;
1392
1393         },
1394
1395         /**
1396          * Convert a destroyed message into a expandable message
1397          */
1398         message_to_expandable: function (message) {
1399
1400             if (!this.thread_level || message.isDestroyed()) {
1401                 message.destroy();
1402                 return false;
1403             }
1404
1405             var messages = _.sortBy( this.messages, function (val) { return val.id; });
1406             var it = _.indexOf( messages, message );
1407
1408             var msg_up = message.$el.prev('.oe_msg');
1409             var msg_down = message.$el.next('.oe_msg');
1410             var msg_up = msg_up.hasClass('oe_msg_expandable') ? _.find( this.messages, function (val) { return val.$el[0] == msg_up[0]; }) : false;
1411             var msg_down = msg_down.hasClass('oe_msg_expandable') ? _.find( this.messages, function (val) { return val.$el[0] == msg_down[0]; }) : false;
1412
1413             var message_dom = [ ["id", "=", message.id] ];
1414
1415             if ( msg_up && msg_up.type == "expandable" && msg_down && msg_down.type == "expandable") {
1416                 // concat two expandable message and add this message to this dom
1417                 msg_up.domain = mail.ChatterUtils.expand_domain( msg_up.domain );
1418                 msg_down.domain = mail.ChatterUtils.expand_domain( msg_down.domain );
1419
1420                 msg_down.domain = ['|','|'].concat( msg_up.domain ).concat( message_dom ).concat( msg_down.domain );
1421
1422                 if ( !msg_down.max_limit ) {
1423                     msg_down.nb_messages += 1 + msg_up.nb_messages;
1424                 }
1425
1426                 msg_up.$el.remove();
1427                 msg_up.destroy();
1428
1429                 msg_down.reinit();
1430
1431             } else if ( msg_up && msg_up.type == "expandable") {
1432                 // concat preview expandable message and this message to this dom
1433                 msg_up.domain = mail.ChatterUtils.expand_domain( msg_up.domain );
1434                 msg_up.domain = ['|'].concat( msg_up.domain ).concat( message_dom );
1435                 
1436                 msg_up.nb_messages++;
1437
1438                 msg_up.reinit();
1439
1440             } else if ( msg_down && msg_down.type == "expandable") {
1441                 // concat next expandable message and this message to this dom
1442                 msg_down.domain = mail.ChatterUtils.expand_domain( msg_down.domain );
1443                 msg_down.domain = ['|'].concat( msg_down.domain ).concat( message_dom );
1444                 
1445                 // it's maybe a message expandable for the max limit read message
1446                 if ( !msg_down.max_limit ) {
1447                     msg_down.nb_messages++;
1448                 }
1449                 
1450                 msg_down.reinit();
1451
1452             } else {
1453                 // create a expandable message
1454                 var expandable = new mail.ThreadExpandable(this, {
1455                     'model': message.model,
1456                     'parent_id': message.parent_id,
1457                     'nb_messages': 1,
1458                     'thread_level': message.thread_level,
1459                     'parent_id': message.parent_id,
1460                     'domain': message_dom,
1461                     'options': message.options,
1462                     }, {
1463                     'context':{
1464                         'default_model': message.model || this.context.default_model,
1465                         'default_res_id': message.res_id || this.context.default_res_id,
1466                         'default_parent_id': this.id,
1467                     }
1468                 });
1469
1470                 // add object on array and DOM
1471                 this.messages.push(expandable);
1472                 expandable.insertAfter(message.$el);
1473             }
1474
1475             // destroy message
1476             message.destroy();
1477
1478             return true;
1479         },
1480     });
1481
1482     /**
1483      * ------------------------------------------------------------
1484      * mail : root Widget
1485      * ------------------------------------------------------------
1486      *
1487      * This widget handles the display of messages with thread options. Its main
1488      * use is to receive a context and a domain, and to delegate the message
1489      * fetching and displaying to the Thread widget.
1490      */
1491     session.web.client_actions.add('mail.Widget', 'session.mail.Widget');
1492     mail.Widget = session.web.Widget.extend({
1493         template: 'mail.Root',
1494
1495         /**
1496          * @param {Object} parent parent
1497          * @param {Array} [domain]
1498          * @param {Object} [context] context of the thread. It should
1499          *   contain at least default_model, default_res_id. Please refer to
1500          *   the compose_message widget for more information about it.
1501          * @param {Object} [options]
1502          *...  @param {Number} [truncate_limit=250] number of character to
1503          *      display before having a "show more" link; note that the text
1504          *      will not be truncated if it does not have 110% of the parameter
1505          *...  @param {Boolean} [show_record_name] display the name and link for do action
1506          *...  @param {boolean} [show_reply_button] display the reply button
1507          *...  @param {boolean} [show_read_unread_button] display the read/unread button
1508          *...  @param {int} [display_indented_thread] number thread level to indented threads.
1509          *      other are on flat mode
1510          *...  @param {Boolean} [show_compose_message] allow to display the composer
1511          *...  @param {Boolean} [show_compact_message] display the compact message on the thread
1512          *      when the user clic on this compact mode, the composer is open
1513          *...  @param {Array} [message_ids] List of ids to fetch by the root thread.
1514          *      When you use this option, the domain is not used for the fetch root.
1515          *     @param {String} [no_message] Message to display when there are no message
1516          *     @param {Boolean} [show_link] Display partner (authors, followers...) on link or not
1517          *     @param {Boolean} [compose_as_todo] The root composer mark automatically the message as todo
1518          *     @param {Boolean} [readonly] Read only mode, hide all action buttons and composer
1519          */
1520         init: function (parent, action) {
1521             this._super(parent, action);
1522             var self = this;
1523             this.action = _.clone(action);
1524             this.domain = this.action.domain || this.action.params.domain || [];
1525             this.context = this.action.context || this.action.params.context || {};
1526
1527             this.action.params = _.extend({
1528                 'display_indented_thread' : -1,
1529                 'show_reply_button' : false,
1530                 'show_read_unread_button' : false,
1531                 'truncate_limit' : 250,
1532                 'show_record_name' : false,
1533                 'show_compose_message' : false,
1534                 'show_compact_message' : false,
1535                 'compose_placeholder': false,
1536                 'show_link': true,
1537                 'view_inbox': false,
1538                 'message_ids': undefined,
1539                 'compose_as_todo' : false,
1540                 'readonly' : false,
1541                 'emails_from_on_composer': true,
1542             }, this.action.params);
1543
1544             this.action.params.help = this.action.help || false;
1545         },
1546
1547         start: function (options) {
1548             this._super.apply(this, arguments);
1549             this.message_render();
1550             this.bind_events();
1551         },
1552         
1553         /**
1554          *Create the root thread and display this object in the DOM.
1555          * Call the no_message method then c all the message_fetch method 
1556          * of this root thread to display the messages.
1557          */
1558         message_render: function (search) {
1559
1560             this.thread = new mail.Thread(this, {}, {
1561                 'domain' : this.domain,
1562                 'context' : this.context,
1563                 'options': this.action.params,
1564             });
1565
1566             this.thread.appendTo( this.$el );
1567
1568             if (this.action.params.show_compose_message) {
1569                 this.thread.instantiate_compose_message();
1570                 this.thread.compose_message.do_show_compact();
1571             }
1572
1573             this.thread.message_fetch(null, null, this.action.params.message_ids);
1574
1575         },
1576
1577         bind_events: function () {
1578             $(document).scroll( _.bind(this.thread.on_scroll, this.thread) );
1579             $(window).resize( _.bind(this.thread.on_scroll, this.thread) );
1580             this.$el.resize( _.bind(this.thread.on_scroll, this.thread) );
1581             window.setTimeout( _.bind(this.thread.on_scroll, this.thread), 500 );
1582         },
1583     });
1584
1585
1586     /**
1587      * ------------------------------------------------------------
1588      * mail_thread Widget
1589      * ------------------------------------------------------------
1590      *
1591      * This widget handles the display of messages on a document. Its main
1592      * use is to receive a context and a domain, and to delegate the message
1593      * fetching and displaying to the Thread widget.
1594      * Use Help on the field to display a custom "no message loaded"
1595      */
1596     session.web.form.widgets.add('mail_thread', 'openerp.mail.RecordThread');
1597     mail.RecordThread = session.web.form.AbstractField.extend({
1598         template: 'mail.record_thread',
1599
1600         init: function (parent, node) {
1601             this._super.apply(this, arguments);
1602             this.node = _.clone(node);
1603             this.node.params = _.extend({
1604                 'display_indented_thread': -1,
1605                 'show_reply_button': false,
1606                 'show_read_unread_button': false,
1607                 'show_record_name': false,
1608                 'show_compact_message': 1,
1609             }, this.node.params);
1610
1611             if (this.node.attrs.placeholder) {
1612                 this.node.params.compose_placeholder = this.node.attrs.placeholder;
1613             }
1614             if (this.node.attrs.readonly) {
1615                 this.node.params.readonly = this.node.attrs.readonly;
1616             }
1617
1618             this.domain = this.node.params && this.node.params.domain || [];
1619
1620             if (!this.__parentedParent.is_action_enabled('edit')) {
1621                 this.node.params.show_link = false;
1622             }
1623         },
1624
1625         start: function () {
1626             this._super.apply(this, arguments);
1627             // NB: check the actual_mode property on view to know if the view is in create mode anymore
1628             this.view.on("change:actual_mode", this, this._check_visibility);
1629             this._check_visibility();
1630         },
1631
1632         _check_visibility: function () {
1633             this.$el.toggle(this.view.get("actual_mode") !== "create");
1634         },
1635
1636         render_value: function () {
1637             var self = this;
1638
1639             if (! this.view.datarecord.id || session.web.BufferedDataSet.virtual_id_regex.test(this.view.datarecord.id)) {
1640                 this.$('oe_mail_thread').hide();
1641                 return;
1642             }
1643
1644             this.node.params = _.extend(this.node.params, {
1645                 'message_ids': this.get_value(),
1646                 'show_compose_message': this.view.is_action_enabled('edit'),
1647             });
1648             this.node.context = {
1649                 'mail_read_set_read': true,  // set messages as read in Chatter
1650                 'default_res_id': this.view.datarecord.id || false,
1651                 'default_model': this.view.model || false,
1652             };
1653
1654             if (this.root) {
1655                 $('<span class="oe_mail-placeholder"/>').insertAfter(this.root.$el);
1656                 this.root.destroy();
1657             }
1658             // create and render Thread widget
1659             this.root = new mail.Widget(this, _.extend(this.node, {
1660                 'domain' : (this.domain || []).concat([['model', '=', this.view.model], ['res_id', '=', this.view.datarecord.id]]),
1661             }));
1662
1663             return this.root.replace(this.$('.oe_mail-placeholder'));
1664         },
1665     });
1666
1667
1668     /**
1669      * ------------------------------------------------------------
1670      * Wall Widget
1671      * ------------------------------------------------------------
1672      *
1673      * This widget handles the display of messages on a Wall. Its main
1674      * use is to receive a context and a domain, and to delegate the message
1675      * fetching and displaying to the Thread widget.
1676      */
1677
1678     session.web.client_actions.add('mail.wall', 'session.mail.Wall');
1679     mail.Wall = session.web.Widget.extend({
1680         template: 'mail.wall',
1681
1682         /**
1683          * @param {Object} parent parent
1684          * @param {Object} [options]
1685          * @param {Array} [options.domain] domain on the Wall
1686          * @param {Object} [options.context] context, is an object. It should
1687          *      contain default_model, default_res_id, to give it to the threads.
1688          */
1689         init: function (parent, action) {
1690             this._super(parent, action);
1691
1692             this.action = _.clone(action);
1693             this.domain = this.action.params.domain || this.action.domain || [];
1694             this.context = _.extend(this.action.params.context || {}, this.action.context || {});
1695
1696             this.defaults = {};
1697             for (var key in this.context) {
1698                 if (key.match(/^search_default_/)) {
1699                     this.defaults[key.replace(/^search_default_/, '')] = this.context[key];
1700                 }
1701             }
1702             this.action.params = _.extend({
1703                 'display_indented_thread': 1,
1704                 'show_reply_button': true,
1705                 'show_read_unread_button': true,
1706                 'show_compose_message': true,
1707                 'show_record_name': true,
1708                 'show_compact_message': this.action.params.view_mailbox ? false : 1,
1709                 'view_inbox': false,
1710                 'emails_from_on_composer': false,
1711             }, this.action.params);
1712         },
1713
1714         start: function () {
1715             this._super.apply(this);
1716             this.bind_events();
1717             var searchview_loaded = this.load_searchview(this.defaults);
1718             if (! this.searchview.has_defaults) {
1719                 this.message_render();
1720             }
1721         },
1722
1723         /**
1724         * crete an object "related_menu"
1725         * contain the menu widget and the the sub menu related of this wall
1726         */
1727         do_reload_menu_emails: function () {
1728             var menu = this.__parentedParent.__parentedParent.menu;
1729             // return this.rpc("/web/menu/load", {'menu_id': 100}).done(function(r) {
1730             //     _.each(menu.data.data.children, function (val) {
1731             //         if (val.id == 100) {
1732             //             val.children = _.find(r.data.children, function (r_val) {return r_val.id == 100;}).children;
1733             //         }
1734             //     });
1735             //     var r = menu.data;
1736             // window.setTimeout(function(){menu.do_reload();}, 0);
1737             // });
1738         },
1739
1740         /**
1741          * Load the mail.message search view
1742          * @param {Object} defaults ??
1743          */
1744         load_searchview: function (defaults) {
1745             
1746             var self = this;
1747             var ds_msg = new session.web.DataSetSearch(this, 'mail.message');
1748             this.searchview = new session.web.SearchView(this, ds_msg, false, defaults || {}, false);
1749             this.searchview.appendTo(this.$('.oe_view_manager_view_search'))
1750                 .then(function () { self.searchview.on('search_data', self, self.do_searchview_search); });
1751             console.log(this.searchview);
1752             if (this.searchview.has_defaults) {
1753                 this.searchview.ready.then(this.searchview.do_search);
1754             }
1755             return this.searchview
1756         },
1757
1758         /**
1759          * Get the domains, contexts and groupbys in parameter from search
1760          * view, then render the filtered threads.
1761          * @param {Array} domains
1762          * @param {Array} contexts
1763          * @param {Array} groupbys
1764          */
1765         do_searchview_search: function (domains, contexts, groupbys) {
1766             var self = this;
1767             session.web.pyeval.eval_domains_and_contexts({
1768                 domains: domains || [],
1769                 contexts: contexts || [],
1770                 group_by_seq: groupbys || []
1771             }).then(function (results) {
1772                 if(self.root) {
1773                     $('<span class="oe_mail-placeholder"/>').insertAfter(self.root.$el);
1774                     self.root.destroy();
1775                 }
1776                 return self.message_render(results);
1777             });
1778         },
1779
1780         /**
1781          * Create the root thread widget and display this object in the DOM
1782          */
1783         message_render: function (search) {
1784             var domain = this.domain.concat(search && search['domain'] ? search['domain'] : []);
1785             var context = _.extend(this.context, search && search['context'] ? search['context'] : {});
1786
1787             this.root = new mail.Widget(this, _.extend(this.action, {
1788                 'domain' : domain,
1789                 'context' : context,
1790             }));
1791             return this.root.replace(this.$('.oe_mail-placeholder'));
1792         },
1793
1794         bind_events: function () {
1795             var self=this;
1796             this.$(".oe_write_full").click(function (event) {
1797                 event.stopPropagation();
1798                 var action = {
1799                     type: 'ir.actions.act_window',
1800                     res_model: 'mail.compose.message',
1801                     view_mode: 'form',
1802                     view_type: 'form',
1803                     action_from: 'mail.ThreadComposeMessage',
1804                     views: [[false, 'form']],
1805                     target: 'new',
1806                     context: {
1807                     },
1808                 };
1809                 session.client.action_manager.do_action(action);
1810             });
1811             this.$(".oe_write_onwall").click(function(){ self.root.thread.on_compose_message(); });
1812         }
1813     });
1814
1815
1816     /**
1817      * ------------------------------------------------------------
1818      * UserMenu
1819      * ------------------------------------------------------------
1820      * 
1821      * Add a link on the top user bar for write a full mail
1822      */
1823     session.web.ComposeMessageTopButton = session.web.Widget.extend({
1824         template:'mail.ComposeMessageTopButton',
1825
1826         start: function () {
1827             this.$('button').on('click', this.on_compose_message );
1828             this._super();
1829         },
1830
1831         on_compose_message: function (event) {
1832             event.stopPropagation();
1833             var action = {
1834                 type: 'ir.actions.act_window',
1835                 res_model: 'mail.compose.message',
1836                 view_mode: 'form',
1837                 view_type: 'form',
1838                 views: [[false, 'form']],
1839                 target: 'new',
1840                 context: {},
1841             };
1842             session.client.action_manager.do_action(action);
1843         },
1844     });
1845
1846     session.web.UserMenu.include({
1847         do_update: function(){
1848             var self = this;
1849             this._super.apply(this, arguments);
1850             this.update_promise.then(function() {
1851                 var mail_button = new session.web.ComposeMessageTopButton();
1852                 mail_button.appendTo(session.webclient.$el.find('.oe_systray'));
1853             });
1854         },
1855     });
1856 };