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