c068074b4573e9e61c7bcf5805f71bf3709caba6
[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     /**
8      * ------------------------------------------------------------
9      * FormView
10      * ------------------------------------------------------------
11      * 
12      * Override of formview do_action method, to catch all return action about
13      * mail.compose.message. The purpose is to bind 'Send by e-mail' buttons
14      * and redirect them to the Chatter.
15      */
16
17     session.web.FormView = session.web.FormView.extend({
18         do_action: function(action, on_close) {
19             if (action.res_model == 'mail.compose.message' && this.fields && this.fields.message_ids && this.fields.message_ids.view.get("actual_mode") != 'create') {
20                 var record_thread = this.fields.message_ids;
21                 var thread = record_thread.thread;
22                 thread.instantiate_composition_form('comment', true, false, 0, action.context);
23                 return false;
24             }
25             else {
26                 return this._super(action, on_close);
27             }
28         },
29     });
30
31
32     /**
33      * ------------------------------------------------------------
34      * ChatterUtils
35      * ------------------------------------------------------------
36      * 
37      * This class holds a few tools method that will be used by
38      * the various Chatter widgets.
39      */
40
41     mail.ChatterUtils = {
42
43         /**
44         * mail_int_mapping: structure to keep a trace of internal links mapping
45         *      mail_int_mapping['model'] = {
46         *          'name_get': [[id,label], [id,label], ...]
47         *          'fetch_ids': [id, id, ...] } */
48         //var mail_int_mapping = {};
49         
50         /**
51         * mail_msg_struct: structure to orrganize chatter messages
52         */
53         //var mail_msg_struct = {}; // TODO: USE IT OR NOT :)
54
55         /* generic chatter events binding */
56         bind_events: function(widget) {
57             // event: click on an internal link to a document: model, login
58             widget.$element.delegate('a.oe_mail_internal_link', 'click', function (event) {
59                 event.preventDefault();
60                 // lazy implementation: fetch data and try to redirect
61                 if (! event.srcElement.dataset.resModel) return false;
62                 else var res_model = event.srcElement.dataset.resModel;
63                 var res_login = event.srcElement.dataset.resLogin;
64                 if (! res_login) return false;
65                 var ds = new session.web.DataSet(widget, res_model);
66                 var defer = ds.call('search', [[['login', '=', res_login]]]).pipe(function (records) {
67                     if (records[0]) {
68                         widget.do_action({ type: 'ir.actions.act_window', res_model: res_model, res_id: parseInt(records[0]), views: [[false, 'form']]});
69                     }
70                     else return false;
71                 });
72             });
73         },
74
75         /** get an image in /web/binary/image?... */
76         get_image: function(session_prefix, session_id, model, field, id) {
77             return session_prefix + '/web/binary/image?session_id=' + session_id + '&model=' + model + '&field=' + field + '&id=' + (id || '');
78         },
79
80         /** checks if tue current user is the message author */
81         is_author: function (widget, message_user_id) {
82             return (widget.session && widget.session.uid != 0 && widget.session.uid == message_user_id);
83         },
84
85         /**
86         * Add records to comments_structure array
87         * @param {Array} records records from mail.message sorted by date desc
88         * @returns {Object} cs comments_structure: dict
89         *       cs.model_to_root_ids = {model: [root_ids], }
90         *       cs.new_root_ids = [new_root_ids]
91         *       cs.root_ids = [root_ids]
92         *       cs.msgs = {record.id: record,}
93         *       cs.tree_struct = {record.id: {
94         *           'level': record_level in hierarchy, 0 is root,
95         *           'msg_nbr': number of childs,
96         *           'direct_childs': [msg_ids],
97         *           'all_childs': [msg_ids],
98         *           'for_thread_msgs': [records],
99         *           'ancestors': [msg_ids], } }
100         */
101         records_struct_add_records: function(cs, records, parent_id) {
102             var cur_iter = 0; var max_iter = 10; var modif = true;
103             while ( modif && (cur_iter++) < max_iter) {
104                 modif = false;
105                 _(records).each(function (record) {
106                     // root and not yet recorded
107                     if ( (record.parent_id == false || record.parent_id[0] == parent_id) && ! cs['msgs'][record.id]) {
108                         // add to model -> root_list ids
109                         if (! cs['model_to_root_ids'][record.model]) cs['model_to_root_ids'][record.model] = [record.id];
110                         else cs['model_to_root_ids'][record.model].push(record.id);
111                         // add root data
112                         cs['new_root_ids'].push(record.id);
113                         // add record
114                         cs['tree_struct'][record.id] = {'level': 0, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [record], 'msg_nbr': -1, 'ancestors': []};
115                         cs['msgs'][record.id] = record;
116                         modif = true;
117                     }
118                     // not yet recorded, but parent is recorded
119                     else if (! cs['msgs'][record.id] && cs['msgs'][record.parent_id[0]]) {
120                         var parent_level = cs['tree_struct'][record.parent_id[0]]['level'];
121                         // update parent structure
122                         cs['tree_struct'][record.parent_id[0]]['direct_childs'].push(record.id);
123                         cs['tree_struct'][record.parent_id[0]]['for_thread_msgs'].push(record);
124                         // update ancestors structure
125                         for (ancestor_id in cs['tree_struct'][record.parent_id[0]]['ancestors']) {
126                             cs['tree_struct'][ancestor_id]['all_childs'].push(record.id);
127                         }
128                         // add record
129                         cs['tree_struct'][record.id] = {'level': parent_level+1, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [], 'msg_nbr': -1, 'ancestors': []};
130                         cs['msgs'][record.id] = record;
131                         modif = true;
132                     }
133                 });
134             }
135             return cs;
136         },
137
138         /* copy cs.new_root_ids into cs.root_ids */
139         records_struct_update_after_display: function(cs) {
140             // update TODO
141             cs['root_ids'] = _.union(cs['root_ids'], cs['new_root_ids']);
142             cs['new_root_ids'] = [];
143             return cs;
144         },
145
146         /**
147          *    CONTENT MANIPULATION
148          * 
149          * Regular expressions
150          * - (^|\s)@((\w|@|\.)*): @login@log.log, supports inner '@' for
151          *   logins that are emails
152          *      1. '(void)'
153          *      2. login@log.log
154          * - (^|\s)\[(\w+).(\w+),(\d)\|*((\w|[@ .,])*)\]: [ir.attachment,3|My Label],
155          *   for internal links to model ir.attachment, id=3, and with
156          *   optional label 'My Label'. Note that having a '|Label' is not
157          *   mandatory, because the regex should still be correct.
158          *      1. '(void)'
159          *      2. 'ir'
160          *      3. 'attachment'
161          *      4. '3'
162          *      5. 'My Label'
163          */
164
165         /** Removes html tags, except b, em, br, ul, li */
166         do_text_remove_html_tags: function (string) {
167             var html = $('<div/>').text(string.replace(/\s+/g, ' ')).html().replace(new RegExp('&lt;(/)?(b|em|br|br /|ul|li|div)\\s*&gt;', 'gi'), '<$1$2>');
168             return html;
169         },
170         
171         /** Replaces line breaks by html line breaks (br) */
172         do_text_nl2br: function (str, is_xhtml) {   
173             var break_tag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';    
174             return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ break_tag +'$2');
175         },
176
177         /* Add a prefix before each new line of the original string */
178         do_text_quote: function (str, prefix) {
179             return str.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ break_tag +'$2' + prefix || '> ');
180         },
181
182         /**
183          * Replaces some expressions
184          * - @login - shorcut to link to a res.user, given its login
185          * - [ir.attachment,3|My Label] - shortcut to an internal
186          *   document
187          * - :name - shortcut to an image
188          */
189         do_replace_expressions: function (string) {
190             var self = this;
191             var icon_list = ['al', 'pinky']
192             /* shortcut to user: @login */
193             var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
194             var regex_res = regex_login.exec(string);
195             while (regex_res != null) {
196                 var login = regex_res[2];
197                 string = string.replace(regex_res[0], regex_res[1] + '<a href="#" class="oe_mail_internal_link" data-res-model="res.users" data-res-login = ' + login + '>@' + login + '</a>');
198                 regex_res = regex_login.exec(string);
199             }
200             /* shortcut for internal document */
201             var regex_login = new RegExp(/(^|\s)\[(\w+).(\w+),(\d)\|*((\w|[@ .,])*)\]/g);
202             var regex_res = regex_login.exec(string);
203             while (regex_res != null) {
204                 var res_model = regex_res[2] + '.' + regex_res[3];
205                 var res_id = regex_res[4];
206                 if (! regex_res[5]) {
207                     var label = res_model + ':' + res_id }
208                 else {
209                     var label = regex_res[5];
210                 }
211                 string = string.replace(regex_res[0], regex_res[1] + '<a href="#model=' + res_model + '&id=' + res_id + '>' + label + '</a>');
212                 regex_res = regex_login.exec(string);
213             }
214             /* special shortcut: :name, try to find an icon if in list */
215             var regex_login = new RegExp(/(^|\s):((\w)*)/g);
216             var regex_res = regex_login.exec(string);
217             while (regex_res != null) {
218                 var icon_name = regex_res[2];
219                 if (_.include(icon_list, icon_name))
220                     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 + '"/>');
221                 regex_res = regex_login.exec(string);
222             }
223             return string;
224         },
225
226         /**
227          * Checks a string to find an expression that will be replaced
228          * by an internal link and requiring a name_get to replace
229          * the expression.
230          * :param mapping: structure to keep a trace of internal links mapping
231          *                  mapping['model'] = {
232          *                      name_get': [[id,label], [id,label], ...]
233          *                      'to_fetch_ids': [id, id, ...]
234          *                  }
235          * CURRENTLY NOT IMPLEMENTED */
236         do_check_for_name_get_mapping: function(string, mapping) {
237             /* shortcut to user: @login */
238             //var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
239             //var regex_res = regex_login.exec(string);
240             //while (regex_res != null) {
241                 //var login = regex_res[2];
242                 //if (! ('res.users' in this.map_hash)) { this.map_hash['res.users']['name'] = []; }
243                 //this.map_hash['res.users']['login'].push(login);
244                 //regex_res = regex_login.exec(string);
245             //}
246             /* document link with name_get: [res.model,name] */
247             /* internal link with id: [res.model,id], or [res.model,id|display_name] */
248             //var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
249             //regex_res = regex_intlink.exec(string);
250             //while (regex_res != null) {
251                 //var res_model = regex_res[2] + '.' + regex_res[3];
252                 //var res_name = regex_res[4];
253                 //if (! (res_model in this.map_hash)) { this.map_hash[res_model]['name'] = []; }
254                 //this.map_hash[res_model]['name'].push(res_name);
255                 //regex_res = regex_intlink.exec(string);
256             //}
257         },
258         
259         /**
260          * Updates the mapping; check for to_fetch_ids for each recorded
261          * model, and perform a name_get to update the mapping.
262          * CURRENTLY NOT IMPLEMENTED */
263         do_update_name_get_mapping: function(mapping) {
264         },
265     };
266
267
268     /**
269      * ------------------------------------------------------------
270      * ComposeMessage widget
271      * ------------------------------------------------------------
272      * 
273      * This widget handles the display of a form to compose a new message.
274      * This form is an OpenERP form_view, build on a mail.compose.message
275      * wizard.
276      */
277
278     mail.ComposeMessage = session.web.Widget.extend({
279         template: 'mail.compose_message',
280         
281         /**
282          * @param {Object} parent parent
283          * @param {Object} [params]
284          * @param {String} [params.res_model] res_model of document [REQUIRED]
285          * @param {Number} [params.res_id] res_id of record [REQUIRED]
286          * @param {Number} [params.email_mode] true/false, tells whether
287          *      we are in email sending mode
288          * @param {Number} [params.formatting] true/false, tells whether
289          *      we are in advance formatting mode
290          * @param {String} [params.model] mail.compose.message.mode (see
291          *      composition wizard)
292          * @param {Number} [params.msg_id] id of a message in case we are in
293          *      reply mode
294          */
295         init: function(parent, params) {
296             var self = this;
297             this._super(parent);
298             // options
299             this.params = params || {};
300             this.params.context = params.context || {};
301             this.params.email_mode = params.email_mode || false;
302             this.params.formatting = params.formatting || false;
303             this.params.mode = params.mode || 'comment';
304             this.params.form_xml_id = params.form_xml_id || 'email_compose_message_wizard_form_chatter';
305             this.params.form_view_id = false;
306             if (this.params.mode == 'reply') {
307                 this.params.active_id = this.params.msg_id;
308             } else {
309                 this.params.active_id = this.params.res_id;
310             }
311             this.email_mode = false;
312             this.formatting = false;
313         },
314
315         /**
316          * Reinitialize the widget field values to the default values. The
317          * purpose is to avoid to destroy and re-build a form view. Default
318          * values are therefore given as for an onchange. */
319         reinit: function() {
320             var self = this;
321             if (! this.form_view) return;
322             var call_defer = this.ds_compose.call('default_get', [['subject', 'body_text', 'body_html', 'dest_partner_ids'], this.ds_compose.get_context()]).then(
323                 function (result) {
324                     self.form_view.on_processed_onchange({'value': result}, []);
325                 });
326             return call_defer;
327         },
328
329         /**
330          * Override-hack of do_action: clean the form */
331         do_action: function(action, on_close) {
332             // this.init_comments();
333             return this._super(action, on_close);
334         },
335
336         /**
337          * Widget start function
338          * - builds and initializes the form view */
339         start: function() {
340             var self = this;
341             this._super.apply(this, arguments);
342             // customize display: add avatar, clean previous content
343             var user_avatar = mail.ChatterUtils.get_image(this.session.prefix,
344                 this.session.session_id, 'res.users', 'image_small', this.session.uid);
345             this.$element.find('img.oe_mail_icon').attr('src', user_avatar);
346             this.$element.find('div.oe_mail_msg_content').empty();
347             // create a context for the default_get of the compose form
348             var widget_context = {
349                 'active_model': this.params.res_model,
350                 'active_id': this.params.active_id,
351                 'mail.compose.message.mode': this.params.mode,
352             };
353             var context = _.extend({}, this.params.context, widget_context);
354             this.ds_compose = new session.web.DataSetSearch(this, 'mail.compose.message', context);
355             // find the id of the view to display in the chatter form
356             var data_ds = new session.web.DataSetSearch(this, 'ir.model.data');
357             var deferred_form_id =data_ds.call('get_object_reference', ['mail', this.params.form_xml_id]).then( function (result) {
358                 if (result) {
359                     self.params.form_view_id = result[1];
360                 }
361             }).pipe(this.proxy('create_form_view'));
362             return deferred_form_id;
363         },
364
365         /**
366          * Create a FormView, then append it to the to widget DOM. */
367         create_form_view: function () {
368             var self = this;
369             // destroy previous form_view if any
370             if (this.form_view) { this.form_view.destroy(); }
371             // create the FormView
372             this.form_view = new session.web.FormView(this, this.ds_compose, this.params.form_view_id, {
373                 action_buttons: false,
374                 pager: false,
375                 initial_mode: 'edit',
376                 disable_autofocus: true,
377             });
378             // add the form, bind events, activate the form
379             var msg_node = this.$element.find('div.oe_mail_msg_content');
380             return $.when(this.form_view.appendTo(msg_node)).pipe(function() {
381                 self.bind_events();
382                 self.form_view.do_show();
383                 if (self.params.email_mode) { self.toggle_email_mode(); }
384                 if (self.params.formatting) { self.toggle_formatting_mode(); }
385             });
386         },
387
388         destroy: function() {
389             this._super.apply(this, arguments);
390         },
391
392         /**
393          * Bind events in the widget. Each event is slightly described
394          * in the function. */
395         bind_events: function() {
396             var self = this;
397             this.$element.find('button.oe_form_button').click(function (event) {
398                 event.preventDefault();
399             });
400             // event: click on 'Send an Email' link that toggles the form for
401             // sending an email (partner_ids)
402             this.$element.find('a.oe_mail_compose_message_email').click(function (event) {
403                 event.preventDefault();
404                 self.toggle_email_mode();
405             });
406             // event: click on 'Formatting' icon-link that toggles the advanced
407             // formatting options for writing a message (subject, body_html)
408             this.$element.find('a.oe_mail_compose_message_formatting').click(function (event) {
409                 event.preventDefault();
410                 self.toggle_formatting_mode();
411             });
412             // event: click on 'Attachment' icon-link that opens the dialog to
413             // add an attachment.
414             this.$element.find('a.oe_mail_compose_message_attachment').click(function (event) {
415                 event.preventDefault();
416                 // not yet implemented
417                 self.set_body_value('attachment', 'attachment');
418             });
419             // event: click on 'Checklist' icon-link that toggles the options
420             // for adding checklist.
421             this.$element.find('a.oe_mail_compose_message_checklist').click(function (event) {
422                 event.preventDefault();
423                 // not yet implemented
424                 self.set_body_value('checklist', 'checklist');
425             });
426         },
427
428         /**
429          * Toggle the formatting mode. */
430         toggle_formatting_mode: function() {
431             var self = this;
432             this.formatting = ! this.formatting;
433             // calls onchange
434             var call_defer = this.ds_compose.call('onchange_formatting', [[], this.formatting, this.params.res_model, this.params.res_id]).then(
435                 function (result) {
436                     self.form_view.on_processed_onchange(result, []);
437                 });
438             // update context of datasetsearch
439             this.ds_compose.context.formatting = this.formatting;
440             // toggle display
441             this.$element.find('span.oe_mail_compose_message_subject').toggleClass('oe_mail_compose_message_invisible');
442             this.$element.find('div.oe_mail_compose_message_body_text').toggleClass('oe_mail_compose_message_invisible');
443             this.$element.find('div.oe_mail_compose_message_body_html').toggleClass('oe_mail_compose_message_invisible');
444         },
445
446         /**
447          * Toggle the email mode. */
448         toggle_email_mode: function() {
449             var self = this;
450             this.email_mode = ! this.email_mode;
451             // calls onchange
452             var call_defer = this.ds_compose.call('onchange_email_mode', [[], this.email_mode, this.params.res_model, this.params.res_id]).then(
453                 function (result) {
454                     self.form_view.on_processed_onchange(result, []);
455                 });
456             // update context of datasetsearch
457             this.ds_compose.context.email_mode = this.email_mode;
458             // update 'Post' button -> 'Send'
459             // update 'Send an Email' link -> 'Post a comment'
460             if (this.email_mode) {
461                 this.$element.find('button.oe_mail_compose_message_button_send').html('<span>Send</span>');
462                 this.$element.find('a.oe_mail_compose_message_email').html('Comment');
463             } else {
464                 this.$element.find('button.oe_mail_compose_message_button_send').html('<span>Post</span>');
465                 this.$element.find('a.oe_mail_compose_message_email').html('Send an Email');
466             }
467             // toggle display
468             this.$element.find('div.oe_mail_compose_message_partner_ids').toggleClass('oe_mail_compose_message_invisible');
469         },
470
471         /**
472          * Update the values of the composition form; with possible different
473          * values for body_text and body_html. */
474         set_body_value: function(body_text, body_html) {
475             this.form_view.fields.body_text.set_value(body_text);
476             this.form_view.fields.body_html.set_value(body_html);
477         },
478     }),
479
480     /** 
481      * ------------------------------------------------------------
482      * Thread Widget
483      * ------------------------------------------------------------
484      *
485      * This widget handles the display of a thread of messages. The
486      * [thread_level] parameter sets the thread level number:
487      * - root message
488      * - - sub message (parent_id = root message)
489      * - - - sub sub message (parent id = sub message)
490      * - - sub message (parent_id = root message)
491      * This widget has 2 ways of initialization, either you give records
492      * to be rendered, either it will fetch [limit] messages related to
493      * [res_model]:[res_id].
494      */
495
496     mail.Thread = session.web.Widget.extend({
497         template: 'mail.thread',
498
499         /**
500          * @param {Object} parent parent
501          * @param {Object} [params]
502          * @param {String} [params.res_model] res_model of document [REQUIRED]
503          * @param {Number} [params.res_id] res_id of record [REQUIRED]
504          * @param {Number} [params.uid] user id [REQUIRED]
505          * @param {Bool}   [params.parent_id=false] parent_id of message
506          * @param {Number} [params.thread_level=0] number of levels in the thread
507          *      (only 0 or 1 currently)
508          * @param {Bool}   [params.is_wall=false] thread is displayed in the wall
509          * @param {Number} [params.msg_more_limit=150] number of character to
510          *      display before having a "show more" link; note that the text
511          *      will not be truncated if it does not have 110% of the parameter
512          *      (ex: 110 characters needed to be truncated and be displayed as
513          *      a 100-characters message)
514          * @param {Number} [params.limit=100] maximum number of messages to fetch
515          * @param {Number} [params.offset=0] offset for fetching messages
516          * @param {Number} [params.records=null] records to show instead of fetching messages
517          */
518         init: function(parent, params) {
519             this._super(parent);
520             // options
521             this.params = params;
522             this.params.parent_id = this.params.parent_id || false;
523             this.params.thread_level = this.params.thread_level || 0;
524             this.params.is_wall = this.params.is_wall || (this.params.records != undefined) || false;
525             this.params.msg_more_limit = this.params.msg_more_limit || 250;
526             this.params.limit = this.params.limit || 100;
527             // this.params.limit = 3; // tmp for testing
528             this.params.offset = this.params.offset || 0;
529             this.params.records = this.params.records || null;
530             // datasets and internal vars
531             this.ds = new session.web.DataSetSearch(this, this.params.res_model);
532             this.ds_users = new session.web.DataSetSearch(this, 'res.users');
533             this.ds_msg = new session.web.DataSetSearch(this, 'mail.message');
534             this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
535             // display customization vars
536             this.display = {};
537             this.display.show_post_comment = this.params.show_post_comment || false;
538             this.display.show_reply = (this.params.thread_level > 0 && this.params.is_wall);
539             this.display.show_delete = ! this.params.is_wall;
540             this.display.show_hide = this.params.is_wall;
541             this.display.show_reply_by_email = ! this.params.is_wall;
542             this.display.show_more = (this.params.thread_level == 0);
543         },
544         
545         start: function() {
546             this._super.apply(this, arguments);
547             // add events
548             this.bind_events();
549             // display user, fetch comments
550             this.display_current_user();
551             if (this.params.records) var display_done = this.display_comments_from_parameters(this.params.records);
552             else var display_done = this.init_comments();
553             // customize display
554             $.when(display_done).then(this.proxy('do_customize_display'));            
555             // add message composition form view
556             if (this.display.show_post_comment) {
557                 var compose_done = this.instantiate_composition_form();
558             }
559             return display_done && compose_done;
560         },
561
562         /**
563          * Override-hack of do_action: automatically reload the chatter.
564          * Normally it should be called only when clicking on 'Post/Send'
565          * in the composition form. */
566         do_action: function(action, on_close) {
567             this.init_comments();
568             if (this.compose_message_widget) {
569                 this.compose_message_widget.reinit(); }
570             return this._super(action, on_close);
571         },
572
573         instantiate_composition_form: function(mode, email_mode, formatting, msg_id, context) {
574             if (this.compose_message_widget) {
575                 this.compose_message_widget.destroy();
576             }
577             this.compose_message_widget = new mail.ComposeMessage(this, {
578                 'extended_mode': false, 'uid': this.params.uid, 'res_model': this.params.res_model,
579                 'res_id': this.params.res_id, 'mode': mode || 'comment', 'msg_id': msg_id,
580                 'email_mode': email_mode || false, 'formatting': formatting || false,
581                 'context': context || false } );
582             var composition_node = this.$element.find('div.oe_mail_thread_action');
583             composition_node.empty();
584             var compose_done = this.compose_message_widget.appendTo(composition_node);
585             return compose_done;
586         },
587
588         do_customize_display: function() {
589             if (this.display.show_post_comment) { this.$element.find('div.oe_mail_thread_action').eq(0).show(); }
590         },
591
592         /**
593          * Bind events in the widget. Each event is slightly described
594          * in the function. */
595         bind_events: function() {
596             var self = this;
597             // generic events from Chatter Mixin
598             mail.ChatterUtils.bind_events(this);
599             // event: click on 'more' at bottom of thread
600             this.$element.find('button.oe_mail_button_more').click(function () {
601                 self.do_more();
602             });
603             // event: writing in basic textarea of composition form (quick reply)
604             this.$element.find('textarea.oe_mail_compose_textarea').keyup(function (event) {
605                 var charCode = (event.which) ? event.which : window.event.keyCode;
606                 if (event.shiftKey && charCode == 13) { this.value = this.value+"\n"; }
607                 else if (charCode == 13) { return self.do_comment(); }
608             });
609             // event: click on 'Reply' in msg
610             this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_reply', 'click', function (event) {
611                 var act_dom = $(this).parents('div.oe_mail_thread_display').find('div.oe_mail_thread_action:first');
612                 act_dom.toggle();
613                 event.preventDefault();
614             });
615             // event: click on 'attachment(s)' in msg
616             this.$element.delegate('a.oe_mail_msg_view_attachments', 'click', function (event) {
617                 var act_dom = $(this).parent().parent().parent().find('.oe_mail_msg_attachments');
618                 act_dom.toggle();
619                 event.preventDefault();
620             });
621             // event: click on 'Delete' in msg side menu
622             this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_delete', 'click', function (event) {
623                 if (! confirm(_t("Do you really want to delete this message?"))) { return false; }
624                 var msg_id = event.srcElement.dataset.id;
625                 if (! msg_id) return false;
626                 var call_defer = self.ds_msg.unlink([parseInt(msg_id)]);
627                 $(event.srcElement).parents('li.oe_mail_thread_msg').eq(0).hide();
628                 if (self.params.thread_level > 0) {
629                     $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
630                 }
631                 event.preventDefault();
632                 return call_defer;
633             });
634             // event: click on 'Hide' in msg side menu
635             this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_hide', 'click', function (event) {
636                 if (! confirm(_t("Do you really want to hide this thread ?"))) { return false; }
637                 var msg_id = event.srcElement.dataset.id;
638                 if (! msg_id) return false;
639                 var call_defer = self.ds.call('message_remove_pushed_notifications', [[self.params.res_id], [parseInt(msg_id)], true]);
640                 $(event.srcElement).parents('li.oe_mail_thread_msg').eq(0).hide();
641                 if (self.params.thread_level > 0) {
642                     $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
643                 }
644                 event.preventDefault();
645                 return call_defer;
646             });
647             // event: click on "Reply" in msg side menu (email style)
648             this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_reply_by_email', 'click', function (event) {
649                 var msg_id = event.srcElement.dataset.msg_id;
650                 var email_mode = (event.srcElement.dataset.type == 'email');
651                 var formatting = (event.srcElement.dataset.formatting == 'html');
652                 if (! msg_id) return false;
653                 self.instantiate_composition_form('reply', email_mode, formatting, msg_id);
654                 event.preventDefault();
655             });
656         },
657         
658         destroy: function () {
659             this._super.apply(this, arguments);
660         },
661         
662         init_comments: function() {
663             var self = this;
664             this.params.offset = 0;
665             this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
666             this.$element.find('div.oe_mail_thread_display').empty();
667             var domain = this.get_fetch_domain(this.comments_structure);
668             return this.fetch_comments(this.params.limit, this.params.offset, domain).then();
669         },
670         
671         fetch_comments: function (limit, offset, domain) {
672             var self = this;
673             var defer = this.ds.call('message_read', [[this.params.res_id], (this.params.thread_level > 0), (this.comments_structure['root_ids']),
674                                     (limit+1) || (this.params.limit+1), offset||this.params.offset, domain||undefined ]).then(function (records) {
675                 if (records.length <= self.params.limit) self.display.show_more = false;
676                 // else { self.display.show_more = true; records.pop(); }
677                 // else { self.display.show_more = true; records.splice(0, 1); }
678                 else { self.display.show_more = true; }
679                 self.display_comments(records);
680                 // TODO: move to customize display
681                 if (self.display.show_more == true) self.$element.find('div.oe_mail_thread_more:last').show();
682                 else  self.$element.find('div.oe_mail_thread_more:last').hide();
683             });
684             
685             return defer;
686         },
687
688         display_comments_from_parameters: function (records) {
689             if (records.length > 0 && records.length < (records[0].child_ids.length+1) ) this.display.show_more = true;
690             else this.display.show_more = false;
691             var defer = this.display_comments(records);
692             // TODO: move to customize display
693             if (this.display.show_more == true) $('div.oe_mail_thread_more').eq(-2).show();
694             else $('div.oe_mail_thread_more').eq(-2).hide();
695             return defer;
696         },
697         
698         display_comments: function (records) {
699             var self = this;
700             // sort the records
701             mail.ChatterUtils.records_struct_add_records(this.comments_structure, records, this.params.parent_id);
702             //build attachments download urls and compute time-relative from dates
703             for (var k in records) {
704                 records[k].timerelative = $.timeago(records[k].date);
705                 if (records[k].attachments) {
706                     for (var l in records[k].attachments) {
707                         var url = self.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=datas_fname&id='+records[k].attachments[l].id;
708                         records[k].attachments[l].url = url;
709                     }
710                 }
711             }
712             _(records).each(function (record) {
713                 var sub_msgs = [];
714                 if ((record.parent_id == false || record.parent_id[0] == self.params.parent_id) && self.params.thread_level > 0 ) {
715                     var sub_list = self.comments_structure['tree_struct'][record.id]['direct_childs'];
716                     _(records).each(function (record) {
717                         //if (record.parent_id == false || record.parent_id[0] == self.params.parent_id) return;
718                         if (_.indexOf(sub_list, record.id) != -1) {
719                             sub_msgs.push(record);
720                         }
721                     });
722                     self.display_comment(record);
723                     self.thread = new mail.Thread(self, {'res_model': self.params.res_model, 'res_id': self.params.res_id, 'uid': self.params.uid,
724                                                             'records': sub_msgs, 'thread_level': (self.params.thread_level-1), 'parent_id': record.id,
725                                                             'is_wall': self.params.is_wall});
726                     self.$element.find('li.oe_mail_thread_msg:last').append('<div class="oe_mail_thread_subthread"/>');
727                     self.thread.appendTo(self.$element.find('div.oe_mail_thread_subthread:last'));
728                 }
729                 else if (self.params.thread_level == 0) {
730                     self.display_comment(record);
731                 }
732             });
733             mail.ChatterUtils.records_struct_update_after_display(this.comments_structure);
734             // update offset for "More" buttons
735             if (this.params.thread_level == 0) this.params.offset += records.length;
736         },
737
738         /** Displays a record, performs text/link formatting */
739         display_comment: function (record) {
740             record.body = mail.ChatterUtils.do_text_nl2br($.trim(record.body), true);
741             // if (record.type == 'email' && record.state == 'received') {
742             if (record.type == 'email') {
743                 record.mini_url = ('/mail/static/src/img/email_icon.png');
744             } else {
745                 record.mini_url = mail.ChatterUtils.get_image(this.session.prefix, this.session.session_id, 'res.users', 'image_small', record.user_id[0]);
746             }
747             // body text manipulation
748             if (record.subtype == 'plain') {
749                 record.body = mail.ChatterUtils.do_text_remove_html_tags(record.body);
750             }
751             record.body = mail.ChatterUtils.do_replace_expressions(record.body);
752             // format date according to the user timezone
753             record.date = session.web.format_value(record.date, {type:"datetime"});
754             // is the user the author ?
755             record.is_author = mail.ChatterUtils.is_author(this, record.user_id[0]);
756             // render
757             var rendered = session.web.qweb.render('mail.thread.message', {'record': record, 'thread': this, 'params': this.params, 'display': this.display});
758             // expand feature
759             $(rendered).appendTo(this.$element.children('div.oe_mail_thread_display:first'));
760             this.$element.find('div.oe_mail_msg_record_body').expander({
761                 slicePoint: this.params.msg_more_limit,
762                 expandText: 'read more',
763                 userCollapseText: '[^]',
764                 detailClass: 'oe_mail_msg_tail',
765                 moreClass: 'oe_mail_expand',
766                 lessClass: 'oe_mail_reduce',
767                 });
768         },
769
770         display_current_user: function () {
771             var avatar = mail.ChatterUtils.get_image(this.session.prefix, this.session.session_id, 'res.users', 'image_small', this.params.uid);
772             return this.$element.find('img.oe_mail_icon').attr('src', avatar);
773         },
774         
775         do_comment: function () {
776             var comment_node = this.$element.find('textarea');
777             var body_text = comment_node.val();
778             comment_node.val('');
779             return this.ds.call('message_append_note', [[this.params.res_id], '', body_text, this.params.parent_id, 'comment', 'plain']).then(
780                 this.proxy('init_comments'));
781         },
782         
783         /**
784          * Create a domain to fetch new comments according to
785          * comment already present in comments_structure
786          * @param {Object} comments_structure (see chatter utils)
787          * @returns {Array} fetch_domain (OpenERP domain style)
788          */
789         get_fetch_domain: function (comments_structure) {
790             var domain = [];
791             var ids = comments_structure.root_ids.slice();
792             var ids2 = [];
793             // must be child of current parent
794             if (this.params.parent_id) { domain.push(['id', 'child_of', this.params.parent_id]); }
795             _(comments_structure.root_ids).each(function (id) { // each record
796                 ids.push(id);
797                 ids2.push(id);
798             });
799             if (this.params.parent_id != false) {
800                 ids2.push(this.params.parent_id);
801             }
802             // must not be children of already fetched messages
803             if (ids.length > 0) {
804                 domain.push('&');
805                 domain.push('!');
806                 domain.push(['id', 'child_of', ids]);
807             }
808             if (ids2.length > 0) {
809                 domain.push(['id', 'not in', ids2]);
810             }
811             return domain;
812         },
813         
814         do_more: function () {
815             domain = this.get_fetch_domain(this.comments_structure);
816             return this.fetch_comments(this.params.limit, this.params.offset, domain);
817         },
818     });
819
820
821     /** 
822      * ------------------------------------------------------------
823      * mail_thread Widget
824      * ------------------------------------------------------------
825      *
826      * This widget handles the display of the Chatter on documents.
827      */
828
829     /* Add mail_thread widget to registry */
830     session.web.form.widgets.add('mail_thread', 'openerp.mail.RecordThread');
831
832     /** mail_thread widget: thread of comments */
833     mail.RecordThread = session.web.form.AbstractField.extend({
834         // QWeb template to use when rendering the object
835         template: 'mail.record_thread',
836
837        init: function() {
838             this._super.apply(this, arguments);
839             this.params = this.get_definition_options();
840             this.params.thread_level = this.params.thread_level || 0;
841             this.params.see_subscribers = true;
842             this.params.see_subscribers_options = this.params.see_subscribers_options || false;
843             this.thread = null;
844             this.ds = new session.web.DataSet(this, this.view.model);
845             this.ds_users = new session.web.DataSet(this, 'res.users');
846         },
847         
848         start: function() {
849             var self = this;
850             
851             // NB: all the widget should be modified to check the actual_mode property on view, not use
852             // any other method to know if the view is in create mode anymore
853             this.view.on("change:actual_mode", this, this._check_visibility);
854             this._check_visibility();
855             
856             mail.ChatterUtils.bind_events(this);
857             this.$element.find('button.oe_mail_button_followers').click(function () { self.do_toggle_followers(); });
858             if (! this.params.see_subscribers_options) {
859                 this.$element.find('button.oe_mail_button_followers').hide(); }
860             this.$element.find('button.oe_mail_button_follow').click(function () { self.do_follow(); })
861                 .mouseover(function () { $(this).html('Follow').removeClass('oe_mail_button_mouseout').addClass('oe_mail_button_mouseover'); })
862                 .mouseleave(function () { $(this).html('Not following').removeClass('oe_mail_button_mouseover').addClass('oe_mail_button_mouseout'); });
863             this.$element.find('button.oe_mail_button_unfollow').click(function () { self.do_unfollow(); })
864                 .mouseover(function () { $(this).html('Unfollow').removeClass('oe_mail_button_mouseout').addClass('oe_mail_button_mouseover'); })
865                 .mouseleave(function () { $(this).html('Following').removeClass('oe_mail_button_mouseover').addClass('oe_mail_button_mouseout'); });
866             this.reinit();
867         },
868         
869         _check_visibility: function() {
870             this.$element.toggle(this.view.get("actual_mode") !== "create");
871         },
872         
873         destroy: function () {
874             this._super.apply(this, arguments);
875         },
876         
877         reinit: function() {
878             this.params.see_subscribers = true;
879             this.params.see_subscribers_options = this.params.see_subscribers_options || false;
880             this.$element.find('button.oe_mail_button_followers').html('Hide followers')
881             this.$element.find('button.oe_mail_button_follow').hide();
882             this.$element.find('button.oe_mail_button_unfollow').hide();
883         },
884         
885         set_value: function() {
886             this._super.apply(this, arguments);
887             var self = this;
888             this.reinit();
889             if (! this.view.datarecord.id ||
890                 session.web.BufferedDataSet.virtual_id_regex.test(this.view.datarecord.id)) {
891                 this.$element.find('.oe_mail_thread').hide();
892                 return;
893             }
894             // fetch followers
895             var fetch_sub_done = this.fetch_subscribers();
896             // create and render Thread widget
897             this.$element.find('div.oe_mail_recthread_main').empty();
898             if (this.thread) this.thread.destroy();
899             this.thread = new mail.Thread(this, {'res_model': this.view.model, 'res_id': this.view.datarecord.id, 'uid': this.session.uid,
900                                                 'thread_level': this.params.thread_level, 'show_post_comment': true, 'limit': 15});
901             var thread_done = this.thread.appendTo(this.$element.find('div.oe_mail_recthread_main'));
902             return fetch_sub_done && thread_done;
903         },
904         
905         fetch_subscribers: function () {
906             return this.ds.call('message_read_subscribers', [[this.view.datarecord.id]]).then(this.proxy('display_subscribers'));
907         },
908         
909         display_subscribers: function (records) {
910             var self = this;
911             this.is_subscriber = false;
912             var user_list = this.$element.find('ul.oe_mail_followers_display').empty();
913             this.$element.find('div.oe_mail_recthread_followers h4').html('Followers (' + records.length + ')');
914             _(records).each(function (record) {
915                 if (record.id == self.session.uid) { self.is_subscriber = true; }
916                 record.avatar_url = mail.ChatterUtils.get_image(self.session.prefix, self.session.session_id, 'res.users', 'image_small', record.id);
917                 $(session.web.qweb.render('mail.record_thread.subscriber', {'record': record})).appendTo(user_list);
918             });
919             if (self.is_subscriber) {
920                 self.$element.find('button.oe_mail_button_follow').hide();
921                 self.$element.find('button.oe_mail_button_unfollow').show(); }
922             else {
923                 self.$element.find('button.oe_mail_button_follow').show();
924                 self.$element.find('button.oe_mail_button_unfollow').hide(); }
925         },
926         
927         do_follow: function () {
928             return this.ds.call('message_subscribe', [[this.view.datarecord.id]]).pipe(this.proxy('fetch_subscribers'));
929         },
930         
931         do_unfollow: function () {
932             var self = this;
933             return this.ds.call('message_unsubscribe', [[this.view.datarecord.id]]).then(function (record) {
934                 if (record == false) self.do_notify("Impossible to unsubscribe", "You are automatically subscribed to this record. You cannot unsubscribe.");
935                 }).pipe(this.proxy('fetch_subscribers'));
936         },
937         
938         do_toggle_followers: function () {
939             this.params.see_subscribers = ! this.params.see_subscribers;
940             if (this.params.see_subscribers) { this.$element.find('button.oe_mail_button_followers').html('Hide followers'); }
941             else { this.$element.find('button.oe_mail_button_followers').html('Show followers'); }
942             this.$element.find('div.oe_mail_recthread_followers').toggle();
943         },
944     });
945
946
947     /** 
948      * ------------------------------------------------------------
949      * WallView Widget
950      * ------------------------------------------------------------
951      *
952      * This widget handles the display of the Chatter on the Wall.
953      */
954
955     /* Add WallView widget to registry */
956     session.web.client_actions.add('mail.wall', 'session.mail.Wall');
957
958     /* WallView widget: a wall of messages */
959     mail.Wall = session.web.Widget.extend({
960         template: 'mail.wall',
961
962         /**
963          * @param {Object} parent parent
964          * @param {Object} [params]
965          * @param {Number} [params.limit=20] number of messages to show and fetch
966          * @param {Number} [params.search_view_id=false] search view id for messages
967          * @var {Array} comments_structure (see chatter utils)
968          */
969         init: function (parent, params) {
970             this._super(parent);
971             this.params = {};
972             this.params.limit = params.limit || 25;
973             this.params.domain = params.domain || [];
974             this.params.context = params.context || {};
975             this.params.res_model = params.res_model || false;
976             this.params.res_id = params.res_id || false;
977             this.params.search_view_id = params.search_view_id || false;
978             this.params.thread_level = params.thread_level || 1;
979             this.params.title = params.title || false;
980             this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
981             this.display_show_more = true;
982             this.thread_list = [];
983             this.search = {'domain': [], 'context': {}, 'groupby': {}}
984             this.search_results = {'domain': [], 'context': {}, 'groupby': {}}
985             // datasets
986             this.ds_msg = new session.web.DataSet(this, 'mail.message');
987             this.ds_thread = new session.web.DataSet(this, 'mail.thread');
988             this.ds_users = new session.web.DataSet(this, 'res.users');
989         },
990
991         start: function () {
992             this._super.apply(this, arguments);
993             this.display_current_user();
994             // add events
995             this.add_event_handlers();
996             // load mail.message search view
997             var search_view_ready = this.load_search_view(this.params.search_view_id, {}, false);
998             // load composition form
999             var compose_done = this.instantiate_composition_form();
1000             // fetch first threads
1001             var comments_ready = this.init_and_fetch_comments(this.params.limit, 0);
1002             return (search_view_ready && comments_ready && compose_done);
1003         },
1004
1005         /**
1006          * Override-hack of do_action: automatically reload the chatter.
1007          * Normally it should be called only when clicking on 'Post/Send'
1008          * in the composition form. */
1009         do_action: function(action, on_close) {
1010             this.init_and_fetch_comments();
1011             if (this.compose_message_widget) {
1012                 this.compose_message_widget.reinit(); }
1013             return this._super(action, on_close);
1014         },
1015
1016         destroy: function () {
1017             this._super.apply(this, arguments);
1018         },
1019
1020         instantiate_composition_form: function(mode, msg_id) {
1021             if (this.compose_message_widget) {
1022                 this.compose_message_widget.destroy();
1023             }
1024             debugger;
1025             this.compose_message_widget = new mail.ComposeMessage(this, {
1026                 'extended_mode': false, 'uid': this.session.uid, 'res_model': this.params.res_model,
1027                 'res_id': this.params.res_id, 'mode': mode || 'comment', 'msg_id': msg_id });
1028             var composition_node = this.$element.find('div.oe_mail_wall_action');
1029             composition_node.empty();
1030             var compose_done = this.compose_message_widget.appendTo(composition_node);
1031             return compose_done;
1032         },
1033
1034         /** Add events */
1035         add_event_handlers: function () {
1036             var self = this;
1037             // display more threads
1038             this.$element.find('button.oe_mail_wall_button_more').click(function () { return self.do_more(); });
1039         },
1040
1041         /**
1042          * Loads the mail.message search view
1043          * @param {Number} view_id id of the search view to load
1044          * @param {Object} defaults ??
1045          * @param {Boolean} hidden some kind of trick we do not care here
1046          */
1047         load_search_view: function (view_id, defaults, hidden) {
1048             var self = this;
1049             this.searchview = new session.web.SearchView(this, this.ds_msg, view_id || false, defaults || {}, hidden || false);
1050             var search_view_loaded = this.searchview.appendTo(this.$element.find('.oe_view_manager_view_search'));
1051             return $.when(search_view_loaded).then(function () {
1052                 self.searchview.on_search.add(self.do_searchview_search);
1053             });
1054         },
1055
1056         /**
1057          * Aggregate the domains, contexts and groupbys in parameter
1058          * with those from search form, and then calls fetch_comments
1059          * to actually fetch comments
1060          * @param {Array} domains
1061          * @param {Array} contexts
1062          * @param {Array} groupbys
1063          */
1064         do_searchview_search: function(domains, contexts, groupbys) {
1065             var self = this;
1066             this.rpc('/web/session/eval_domain_and_context', {
1067                 domains: domains || [],
1068                 contexts: contexts || [],
1069                 group_by_seq: groupbys || []
1070             }, function (results) {
1071                 self.search_results['context'] = results.context;
1072                 self.search_results['domain'] = results.domain;
1073                 self.search_results['groupby'] = results.group_by;
1074                 return self.init_and_fetch_comments();
1075             });
1076         },
1077
1078         display_current_user: function () {
1079             //return this.$element.find('img.oe_mail_msg_image').attr('src', this.thread_get_avatar('res.users', 'avatar', this.session.uid));
1080         }, 
1081
1082         /**
1083          * Initializes the wall and calls fetch_comments
1084          * @param {Number} limit: number of notifications to fetch
1085          * @param {Number} offset: offset in notifications search
1086          * @param {Array} domain
1087          * @param {Array} context
1088          */
1089         init_and_fetch_comments: function() {
1090             this.search['domain'] = _.union(this.params.domain, this.search_results.domain);
1091             this.search['context'] = _.extend(this.params.context, this.search_results.context);
1092             this.display_show_more = true;
1093             this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
1094             this.$element.find('ul.oe_mail_wall_threads').empty();
1095             return this.fetch_comments(this.params.limit, 0);
1096         },
1097
1098         /**
1099          * Fetches wall messages
1100          * @param {Number} limit: number of notifications to fetch
1101          * @param {Number} offset: offset in notifications search
1102          * @param {Array} domain
1103          * @param {Array} context
1104          */
1105         fetch_comments: function (limit, offset, additional_domain, additional_context) {
1106             var self = this;
1107             if (additional_domain) var fetch_domain = this.search['domain'].concat(additional_domain);
1108             else var fetch_domain = this.search['domain'];
1109             if (additional_context) var fetch_context = _.extend(this.search['context'], additional_context);
1110             else var fetch_context = this.search['context'];
1111             return this.ds_thread.call('message_get_pushed_messages', 
1112                 [[this.session.uid], true, [], (limit || 0), (offset || 0), fetch_domain, fetch_context]).then(this.proxy('display_comments'));
1113         },
1114
1115         /**
1116          * @param {Array} records records to show in threads
1117          */
1118         display_comments: function (records) {
1119             var self = this;
1120             this.do_update_show_more(records.length >= self.params.limit);
1121             mail.ChatterUtils.records_struct_add_records(this.comments_structure, records, false);
1122             _(this.comments_structure['new_root_ids']).each(function (root_id) {
1123                 var records = self.comments_structure.tree_struct[root_id]['for_thread_msgs'];
1124                 var model_name = self.comments_structure.msgs[root_id]['model'];
1125                 var res_id = self.comments_structure.msgs[root_id]['res_id'];
1126                 var render_res = session.web.qweb.render('mail.wall_thread_container', {});
1127                 $('<li class="oe_mail_wall_thread">').html(render_res).appendTo(self.$element.find('ul.oe_mail_wall_threads'));
1128                 var thread = new mail.Thread(self, {
1129                     'res_model': model_name, 'res_id': res_id, 'uid': self.session.uid, 'records': records,
1130                     'parent_id': false, 'thread_level': self.params.thread_level, 'show_hide': true, 'is_wall': true}
1131                     );
1132                 self.thread_list.push(thread);
1133                 return thread.appendTo(self.$element.find('li.oe_mail_wall_thread:last'));
1134             });
1135             // update TODO
1136             this.comments_structure['root_ids'] = _.union(this.comments_structure['root_ids'], this.comments_structure['new_root_ids']);
1137             this.comments_structure['new_root_ids'] = [];
1138         },
1139
1140         /**
1141          * Create a domain to fetch new comments according to
1142          * comments already present in comments_structure
1143          * - for each model:
1144          * -- should not be child of already displayed ids
1145          * @returns {Array} fetch_domain (OpenERP domain style)
1146          */
1147         get_fetch_domain: function () {
1148             var self = this;
1149             var model_to_root = {};
1150             var fetch_domain = [];
1151             _(this.comments_structure['model_to_root_ids']).each(function (sc_model, model_name) {
1152                 fetch_domain.push('|', ['model', '!=', model_name], '!', ['id', 'child_of', sc_model]);
1153             });
1154             return fetch_domain;
1155         },
1156         
1157         /** Display update: show more button */
1158         do_update_show_more: function (new_value) {
1159             if (new_value != undefined) this.display_show_more = new_value;
1160             if (this.display_show_more) this.$element.find('div.oe_mail_wall_more:last').show();
1161             else this.$element.find('div.oe_mail_wall_more:last').hide();
1162         },
1163         
1164         /** Action: Shows more discussions */
1165         do_more: function () {
1166             var domain = this.get_fetch_domain();
1167             return this.fetch_comments(this.params.limit, 0, domain);
1168         },
1169     });
1170 };