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