[IMP] clean design, bugfix on reference fields
[odoo/odoo.git] / addons / web / static / src / js / view_form.js
1 openerp.web.form = function (instance) {
2 var _t = instance.web._t,
3    _lt = instance.web._lt;
4 var QWeb = instance.web.qweb;
5
6 /** @namespace */
7 instance.web.form = {};
8
9 /**
10  * Interface implemented by the form view or any other object
11  * able to provide the features necessary for the fields to work.
12  * 
13  * Properties:
14  *     - display_invalid_fields : if true, all fields where is_valid() return true should
15  *     be displayed as invalid.
16  * Events:
17  *     - view_content_has_changed : when the values of the fields have changed. When
18  *     this event is triggered all fields should reprocess their modifiers.
19  */
20 instance.web.form.FieldManagerMixin = {
21     /**
22      * Must return the asked field as in fields_get.
23      */
24     get_field: function(field_name) {},
25     /**
26      * Called by the field when the translate button is clicked.
27      */
28     open_translate_dialog: function(field) {},
29     /**
30      * Returns true when the view is in create mode.
31      */
32     is_create_mode: function() {},
33 };
34
35 instance.web.views.add('form', 'instance.web.FormView');
36 instance.web.FormView = instance.web.View.extend(_.extend({}, instance.web.form.FieldManagerMixin, {
37     /**
38      * Indicates that this view is not searchable, and thus that no search
39      * view should be displayed (if there is one active).
40      */
41     searchable: false,
42     template: "FormView",
43     display_name: _lt('Form'),
44     view_type: "form",
45     /**
46      * @constructs instance.web.FormView
47      * @extends instance.web.View
48      *
49      * @param {instance.web.Session} session the current openerp session
50      * @param {instance.web.DataSet} dataset the dataset this view will work with
51      * @param {String} view_id the identifier of the OpenERP view object
52      * @param {Object} options
53      *                  - resize_textareas : [true|false|max_height]
54      *
55      * @property {instance.web.Registry} registry=instance.web.form.widgets widgets registry for this form view instance
56      */
57     init: function(parent, dataset, view_id, options) {
58         this._super(parent);
59         this.set_default_options(options);
60         this.dataset = dataset;
61         this.model = dataset.model;
62         this.view_id = view_id || false;
63         this.fields_view = {};
64         this.fields = {};
65         this.fields_order = [];
66         this.datarecord = {};
67         this.default_focus_field = null;
68         this.default_focus_button = null;
69         this.fields_registry = instance.web.form.widgets;
70         this.tags_registry = instance.web.form.tags;
71         this.has_been_loaded = $.Deferred();
72         this.translatable_fields = [];
73         _.defaults(this.options, {
74             "not_interactible_on_create": false,
75             "initial_mode": "view",
76         });
77         this.is_initialized = $.Deferred();
78         this.mutating_mutex = new $.Mutex();
79         this.on_change_mutex = new $.Mutex();
80         this.reload_mutex = new $.Mutex();
81         this.rendering_engine = new instance.web.form.FormRenderingEngineReadonly(this);
82         this.qweb = null; // A QWeb instance will be created if the view is a QWeb template
83     },
84     destroy: function() {
85         _.each(this.get_widgets(), function(w) {
86             w.destroy();
87         });
88         this._super();
89     },
90     on_loaded: function(data) {
91         var self = this;
92         if (!data) {
93             throw new Error("No data provided.");
94         }
95         if (this.arch) {
96             throw "Form view does not support multiple calls to on_loaded";
97         }
98         this.fields_order = [];
99         this.fields_view = data;
100
101         this.rendering_engine.set_fields_registry(this.fields_registry);
102         this.rendering_engine.set_tags_registry(this.tags_registry);
103         if (!this.extract_qweb_template(data)) {
104             this.rendering_engine.set_fields_view(data);
105             var $dest = this.$element.hasClass("oe_form_container") ? this.$element : this.$element.find('.oe_form_container');
106             this.rendering_engine.render_to($dest);
107         }
108
109
110         this.$buttons = $(QWeb.render("FormView.buttons", {'widget':self}));
111         if (this.options.$buttons) {
112             this.$buttons.appendTo(this.options.$buttons);
113         } else {
114             this.$element.find('.oe_form_buttons').replaceWith(this.$buttons);
115         }
116         this.$buttons.on('click','.oe_form_button_create',this.on_button_create);
117         this.$buttons.on('click','.oe_form_button_edit',this.on_button_edit);
118         this.$buttons.on('click','.oe_form_button_save',this.on_button_save);
119         this.$buttons.on('click','.oe_form_button_cancel',this.on_button_cancel);
120
121         this.$pager = $(QWeb.render("FormView.pager", {'widget':self}));
122         if (this.options.$pager) {
123             this.$pager.appendTo(this.options.$pager);
124         } else {
125             this.$element.find('.oe_form_pager').replaceWith(this.$pager);
126         }
127         this.$pager.on('click','a[data-pager-action]',function() {
128             var action = $(this).data('pager-action');
129             self.on_pager_action(action);
130         });
131
132         this.$sidebar = this.options.$sidebar || this.$element.find('.oe_form_sidebar');
133         if (!this.sidebar && this.options.$sidebar) {
134             this.sidebar = new instance.web.Sidebar(this);
135             this.sidebar.appendTo(this.$sidebar);
136             if(this.fields_view.toolbar) {
137                 this.sidebar.add_toolbar(this.fields_view.toolbar);
138             }
139             this.sidebar.add_items('other', [
140                 { label: _t('Delete'), callback: self.on_button_delete },
141                 { label: _t('Duplicate'), callback: self.on_button_duplicate },
142                 { label: _t('Set Default'), callback: function (item) { self.open_defaults_dialog(); } },
143             ]);
144         }
145         this.on("change:mode", this, this.switch_mode);
146         this.set({mode: this.options.initial_mode});
147         this.has_been_loaded.resolve();
148         return $.when();
149     },
150     extract_qweb_template: function(fvg) {
151         for (var i=0, ii=fvg.arch.children.length; i < ii; i++) {
152             var child = fvg.arch.children[i];
153             if (child.tag === "templates") {
154                 this.qweb = new QWeb2.Engine();
155                 this.qweb.add_template(instance.web.json_node_to_xml(child));
156                 if (!this.qweb.has_template('form')) {
157                     throw new Error("No QWeb template found for form view");
158                 }
159                 return true;
160             }
161         }
162         this.qweb = null;
163         return false;
164     },
165     get_fvg_from_qweb: function(record) {
166         var view = this.qweb.render('form', this.get_qweb_context(record));
167         var fvg = _.clone(this.fields_view);
168         fvg.arch = instance.web.xml_to_json(instance.web.str_to_xml(view).firstChild);
169         return fvg;
170     },
171     get_qweb_context: function(record) {
172         var self = this,
173             new_record = {};
174         _.each(record, function(value_, name) {
175             var r = _.clone(self.fields_view.fields[name] || {});
176             if ((r.type === 'date' || r.type === 'datetime') && value_) {
177                 r.raw_value = instance.web.auto_str_to_date(value_);
178             } else {
179                 r.raw_value = value_;
180             }
181             r.value = instance.web.format_value(value_, r);
182             new_record[name] = r;
183         });
184         return {
185             record : new_record,
186             new_record : !record.id
187         };
188     },
189     kill_current_form: function() {
190         _.each(this.getChildren(), function(el) {
191             el.destroy();
192         });
193         this.fields = {};
194         this.fields_order = [];
195         this.default_focus_field = null;
196         this.default_focus_button = null;
197         this.translatable_fields = [];
198         this.$element.find('.oe_form_container').empty();
199     },
200     do_load_state: function(state, warm) {
201         if (state.id && this.datarecord.id != state.id) {
202             if (!this.dataset.get_id_index(state.id)) {
203                 this.dataset.ids.push(state.id);
204             }
205             this.dataset.select_id(state.id);
206             if (warm) {
207                 this.do_show();
208             }
209         }
210     },
211     do_show: function () {
212         var self = this;
213         if (this.sidebar) {
214             this.sidebar.$element.show();
215         }
216         if (this.$buttons) {
217             this.$buttons.show();
218             this.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
219         }
220         if (this.$pager) {
221             this.$pager.show();
222         }
223         this.$element.show().css('visibility', 'hidden');
224         this.$element.removeClass('oe_form_dirty');
225         return this.has_been_loaded.pipe(function() {
226             var result;
227             if (self.dataset.index === null) {
228                 // null index means we should start a new record
229                 result = self.on_button_new();
230             } else {
231                 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
232                     context : { 'bin_size' : true }
233                 }).pipe(self.on_record_loaded);
234             }
235             result.pipe(function() {
236                 self.$element.css('visibility', 'visible');
237             });
238             return result;
239         });
240     },
241     do_hide: function () {
242         if (this.sidebar) {
243             this.sidebar.$element.hide();
244         }
245         if (this.$buttons) {
246             this.$buttons.hide();
247         }
248         if (this.$pager) {
249             this.$pager.hide();
250         }
251         this._super();
252     },
253     on_record_loaded: function(record) {
254         var self = this, set_values = [];
255         if (!record) {
256             this.do_warn("Form", "The record could not be found in the database.", true);
257             return $.Deferred().reject();
258         }
259         this.datarecord = record;
260
261         if (this.qweb) {
262             this.kill_current_form();
263             this.rendering_engine.set_fields_view(this.get_fvg_from_qweb(record));
264             var $dest = this.$element.hasClass("oe_form_container") ? this.$element : this.$element.find('.oe_form_container');
265             this.rendering_engine.render_to($dest);
266         }
267
268         _(this.fields).each(function (field, f) {
269             field._dirty_flag = false;
270             var result = field.set_value(self.datarecord[f] || false);
271             set_values.push(result);
272         });
273         return $.when.apply(null, set_values).pipe(function() {
274             if (!record.id) {
275                 // New record: Second pass in order to trigger the onchanges
276                 // respecting the fields order defined in the view
277                 _.each(self.fields_order, function(field_name) {
278                     if (record[field_name] !== undefined) {
279                         var field = self.fields[field_name];
280                         field._dirty_flag = true;
281                         self.do_onchange(field);
282                     }
283                 });
284             }
285             self.on_form_changed();
286             self.is_initialized.resolve();
287             self.do_update_pager(record.id == null);
288             if (self.sidebar) {
289                self.sidebar.do_attachement_update(self.dataset, self.datarecord.id);
290             }
291             if (self.default_focus_field) {
292                 self.default_focus_field.focus();
293             }
294             if (record.id) {
295                 self.do_push_state({id:record.id});
296             }
297             self.$element.removeClass('oe_form_dirty');
298             self.$buttons.find('.oe_form_button_save').removeClass('oe_form_button_save_dirty');
299         });
300     },
301     on_form_changed: function() {
302         this.trigger("view_content_has_changed");
303     },
304     do_notify_change: function() {
305         this.$element.addClass('oe_form_dirty');
306         this.$buttons.find('.oe_form_button_save').addClass('oe_form_button_save_dirty');
307     },
308     on_pager_action: function(action) {
309         if (this.can_be_discarded()) {
310             switch (action) {
311                 case 'first':
312                     this.dataset.index = 0;
313                     break;
314                 case 'previous':
315                     this.dataset.previous();
316                     break;
317                 case 'next':
318                     this.dataset.next();
319                     break;
320                 case 'last':
321                     this.dataset.index = this.dataset.ids.length - 1;
322                     break;
323             }
324             this.reload();
325         }
326     },
327     do_update_pager: function(hide_index) {
328         var index = hide_index ? '-' : this.dataset.index + 1;
329         this.$pager.find('button').prop('disabled', this.dataset.ids.length < 2).end()
330                    .find('span.oe_pager_index').html(index).end()
331                    .find('span.oe_pager_count').html(this.dataset.ids.length);
332     },
333     parse_on_change: function (on_change, widget) {
334         var self = this;
335         var onchange = _.str.trim(on_change);
336         var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
337         if (!call) {
338             return null;
339         }
340
341         var method = call[1];
342         if (!_.str.trim(call[2])) {
343             return {method: method, args: [], context_index: null}
344         }
345
346         var argument_replacement = {
347             'False': function () {return false;},
348             'True': function () {return true;},
349             'None': function () {return null;},
350             'context': function (i) {
351                 context_index = i;
352                 var ctx = new instance.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
353                 return ctx;
354             }
355         };
356         var parent_fields = null, context_index = null;
357         var args = _.map(call[2].split(','), function (a, i) {
358             var field = _.str.trim(a);
359
360             // literal constant or context
361             if (field in argument_replacement) {
362                 return argument_replacement[field](i);
363             }
364             // literal number
365             if (/^-?\d+(\.\d+)?$/.test(field)) {
366                 return Number(field);
367             }
368             // form field
369             if (self.fields[field]) {
370                 var value_ = self.fields[field].get_value();
371                 return value_ == null ? false : value_;
372             }
373             // parent field
374             var splitted = field.split('.');
375             if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
376                 if (parent_fields === null) {
377                     parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
378                 }
379                 var p_val = parent_fields[_.str.trim(splitted[1])];
380                 if (p_val !== undefined) {
381                     return p_val == null ? false : p_val;
382                 }
383             }
384             // string literal
385             var first_char = field[0], last_char = field[field.length-1];
386             if ((first_char === '"' && last_char === '"')
387                 || (first_char === "'" && last_char === "'")) {
388                 return field.slice(1, -1);
389             }
390
391             throw new Error("Could not get field with name '" + field +
392                             "' for onchange '" + onchange + "'");
393         });
394
395         return {
396             method: method,
397             args: args,
398             context_index: context_index
399         };
400     },
401     do_onchange: function(widget, processed) {
402         var self = this;
403         return this.on_change_mutex.exec(function() {
404             try {
405                 var response = {}, can_process_onchange = $.Deferred();
406                 processed = processed || [];
407                 processed.push(widget.name);
408                 var on_change = widget.node.attrs.on_change;
409                 if (on_change) {
410                     var change_spec = self.parse_on_change(on_change, widget);
411                     if (change_spec) {
412                         var ajax = {
413                             url: '/web/dataset/onchange',
414                             async: false
415                         };
416                         can_process_onchange = self.rpc(ajax, {
417                             model: self.dataset.model,
418                             method: change_spec.method,
419                             args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
420                             context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
421                         }).then(function(r) {
422                             _.extend(response, r);
423                         });
424                     } else {
425                         console.warn("Wrong on_change format", on_change);
426                     }
427                 }
428                 // fail if onchange failed
429                 if (can_process_onchange.isRejected()) {
430                     return can_process_onchange;
431                 }
432
433                 if (widget.field['change_default']) {
434                     var fieldname = widget.name, value_;
435                     if (response.value && (fieldname in response.value)) {
436                         // Use value from onchange if onchange executed
437                         value_ = response.value[fieldname];
438                     } else {
439                         // otherwise get form value for field
440                         value_ = self.fields[fieldname].get_value();
441                     }
442                     var condition = fieldname + '=' + value_;
443
444                     if (value_) {
445                         can_process_onchange = self.rpc({
446                             url: '/web/dataset/call',
447                             async: false
448                         }, {
449                             model: 'ir.values',
450                             method: 'get_defaults',
451                             args: [self.model, condition]
452                         }).then(function (results) {
453                             if (!results.length) { return; }
454                             if (!response.value) {
455                                 response.value = {};
456                             }
457                             for(var i=0; i<results.length; ++i) {
458                                 // [whatever, key, value]
459                                 var triplet = results[i];
460                                 response.value[triplet[1]] = triplet[2];
461                             }
462                         });
463                     }
464                 }
465                 if (can_process_onchange.isRejected()) {
466                     return can_process_onchange;
467                 }
468
469                 return self.on_processed_onchange(response, processed);
470             } catch(e) {
471                 console.error(e);
472                 return $.Deferred().reject();
473             }
474         });
475     },
476     on_processed_onchange: function(response, processed) {
477         try {
478         var result = response;
479         if (result.value) {
480             for (var f in result.value) {
481                 if (!result.value.hasOwnProperty(f)) { continue; }
482                 var field = this.fields[f];
483                 // If field is not defined in the view, just ignore it
484                 if (field) {
485                     var value_ = result.value[f];
486                     if (field.get_value() != value_) {
487                         field.set_value(value_);
488                         field._dirty_flag = true;
489                         if (!_.contains(processed, field.name)) {
490                             this.do_onchange(field, processed);
491                         }
492                     }
493                 }
494             }
495             this.on_form_changed();
496         }
497         if (!_.isEmpty(result.warning)) {
498                 instance.web.dialog($(QWeb.render("CrashManagerWarning", result.warning)), {
499                 modal: true,
500                 buttons: [
501                     {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
502                 ]
503             });
504         }
505         if (result.domain) {
506             function edit_domain(node) {
507                 var new_domain = result.domain[node.attrs.name];
508                 if (new_domain) {
509                     node.attrs.domain = new_domain;
510                 }
511                 _(node.children).each(edit_domain);
512             }
513             edit_domain(this.fields_view.arch);
514         }
515         return $.Deferred().resolve();
516         } catch(e) {
517             console.error(e);
518             return $.Deferred().reject();
519         }
520     },
521     switch_mode: function() {
522         var self = this;
523         if(this.get("mode") == "view") {
524             self.$element.removeClass('oe_form_editable').addClass('oe_form_readonly');
525             self.$buttons.find('.oe_form_buttons_edit').hide();
526             self.$buttons.find('.oe_form_buttons_view').show();
527             self.$sidebar.show();
528             _.each(this.fields,function(field){
529                 field.set({"force_readonly": true});
530             });
531         } else {
532             self.$element.removeClass('oe_form_readonly').addClass('oe_form_editable');
533             self.$buttons.find('.oe_form_buttons_edit').show();
534             self.$buttons.find('.oe_form_buttons_view').hide();
535             self.$sidebar.hide();
536             _.each(this.fields,function(field){
537                 field.set({"force_readonly": false});
538             });
539         }
540     },
541     on_button_save: function() {
542         var self = this;
543         return this.do_save().then(function(result) {
544             self.set({mode: "view"});
545         });
546     },
547     on_button_cancel: function(event) {
548         if (this.can_be_discarded()) {
549             this.set({mode: "view"});
550         }
551         return false;
552     },
553     on_button_new: function() {
554         var self = this;
555         this.set({mode: "edit"});
556         var def = $.Deferred();
557         $.when(this.has_been_loaded).then(function() {
558             if (self.can_be_discarded()) {
559                 var keys = _.keys(self.fields_view.fields);
560                 if (keys.length) {
561                     self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
562                         def.resolve();
563                     });
564                 } else {
565                     self.on_record_loaded({}).then(function() {
566                         def.resolve();
567                     });
568                 }
569             }
570         });
571         return def.promise();
572     },
573     on_button_edit: function() {
574         return this.set({mode: "edit"});
575     },
576     on_button_create: function() {
577         this.dataset.index = null;
578         this.do_show();
579     },
580     on_button_duplicate: function() {
581         var self = this;
582         var def = $.Deferred();
583         $.when(this.has_been_loaded).then(function() {
584             self.dataset.call('copy', [self.datarecord.id, {}, self.dataset.context]).then(function(new_id) {
585                 return self.on_created({ result : new_id });
586             }).then(function() {
587                 return self.set({mode: "edit"});
588             }).then(function() {
589                 def.resolve();
590             });
591         });
592         return def.promise();
593     },
594     on_button_delete: function() {
595         var self = this;
596         var def = $.Deferred();
597         $.when(this.has_been_loaded).then(function() {
598             if (self.datarecord.id && confirm(_t("Do you really want to delete this record?"))) {
599                 self.dataset.unlink([self.datarecord.id]).then(function() {
600                     self.on_pager_action('next');
601                     def.resolve();
602                 });
603             } else {
604                 $.async_when().then(function () {
605                     def.reject();
606                 })
607             }
608         });
609         return def.promise();
610     },
611     can_be_discarded: function() {
612         return !this.$element.is('.oe_form_dirty') || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
613     },
614     /**
615      * Triggers saving the form's record. Chooses between creating a new
616      * record or saving an existing one depending on whether the record
617      * already has an id property.
618      *
619      * @param {Function} success callback on save success
620      * @param {Boolean} [prepend_on_create=false] if ``do_save`` creates a new record, should that record be inserted at the start of the dataset (by default, records are added at the end)
621      */
622     do_save: function(success, prepend_on_create) {
623         var self = this;
624         return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
625             try {
626             var form_invalid = false,
627                 values = {},
628                 first_invalid_field = null;
629             for (var f in self.fields) {
630                 f = self.fields[f];
631                 if (!f.is_valid()) {
632                     form_invalid = true;
633                     if (!first_invalid_field) {
634                         first_invalid_field = f;
635                     }
636                 } else if (f.name !== 'id' && !f.get("readonly") && (!self.datarecord.id || f._dirty_flag)) {
637                     // Special case 'id' field, do not save this field
638                     // on 'create' : save all non readonly fields
639                     // on 'edit' : save non readonly modified fields
640                     values[f.name] = f.get_value();
641                 }
642             }
643             if (form_invalid) {
644                 self.set({'display_invalid_fields': true});
645                 first_invalid_field.focus();
646                 self.on_invalid();
647                 return $.Deferred().reject();
648             } else {
649                 self.set({'display_invalid_fields': false});
650                 var save_deferral;
651                 if (!self.datarecord.id) {
652                     //console.log("FormView(", self, ") : About to create", values);
653                     save_deferral = self.dataset.create(values).pipe(function(r) {
654                         return self.on_created(r, undefined, prepend_on_create);
655                     }, null);
656                 } else if (_.isEmpty(values) && ! self.force_dirty) {
657                     //console.log("FormView(", self, ") : Nothing to save");
658                     save_deferral = $.Deferred().resolve({}).promise();
659                 } else {
660                     self.force_dirty = false;
661                     //console.log("FormView(", self, ") : About to save", values);
662                     save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
663                         return self.on_saved(r);
664                     }, null);
665                 }
666                 return save_deferral.then(success);
667             }
668             } catch (e) {
669                 console.error(e);
670                 return $.Deferred().reject();
671             }
672         });});
673     },
674     on_invalid: function() {
675         var msg = "<ul>";
676         _.each(this.fields, function(f) {
677             if (!f.is_valid()) {
678                 msg += "<li>" + (f.node.attrs.string || f.field.string) + "</li>";
679             }
680         });
681         msg += "</ul>";
682         this.do_warn("The following fields are invalid :", msg);
683     },
684     on_saved: function(r, success) {
685         if (!r.result) {
686             // should not happen in the server, but may happen for internal purpose
687             return $.Deferred().reject();
688         } else {
689             return $.when(this.reload()).pipe(function () {
690                 return $.when(r).then(success); }, null);
691         }
692     },
693     /**
694      * Updates the form' dataset to contain the new record:
695      *
696      * * Adds the newly created record to the current dataset (at the end by
697      *   default)
698      * * Selects that record (sets the dataset's index to point to the new
699      *   record's id).
700      * * Updates the pager and sidebar displays
701      *
702      * @param {Object} r
703      * @param {Function} success callback to execute after having updated the dataset
704      * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
705      */
706     on_created: function(r, success, prepend_on_create) {
707         if (!r.result) {
708             // should not happen in the server, but may happen for internal purpose
709             return $.Deferred().reject();
710         } else {
711             this.datarecord.id = r.result;
712             if (!prepend_on_create) {
713                 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
714                 this.dataset.index = this.dataset.ids.length - 1;
715             } else {
716                 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
717                 this.dataset.index = 0;
718             }
719             this.do_update_pager();
720             if (this.sidebar) {
721                 this.sidebar.do_attachement_update(this.dataset, this.datarecord.id);
722             }
723             //instance.log("The record has been created with id #" + this.datarecord.id);
724             this.reload();
725             return $.when(_.extend(r, {created: true})).then(success);
726         }
727     },
728     on_action: function (action) {
729         console.debug('Executing action', action);
730     },
731     reload: function() {
732         var self = this;
733         return this.reload_mutex.exec(function() {
734             if (self.dataset.index == null) {
735                 self.do_prev_view();
736                 return $.Deferred().reject().promise();
737             }
738             if (self.dataset.index == null || self.dataset.index < 0) {
739                 return $.when(self.on_button_new());
740             } else {
741                 return self.dataset.read_index(_.keys(self.fields_view.fields), {
742                     context : { 'bin_size' : true }
743                 }).pipe(self.on_record_loaded);
744             }
745         });
746     },
747     get_widgets: function() {
748         return _.filter(this.getChildren(), function(obj) {
749             return obj instanceof instance.web.form.FormWidget;
750         });
751     },
752     get_fields_values: function(blacklist) {
753         blacklist = blacklist || [];
754         var values = {};
755         var ids = this.get_selected_ids();
756         values["id"] = ids.length > 0 ? ids[0] : false;
757         _.each(this.fields, function(value_, key) {
758                 if (_.include(blacklist, key))
759                         return;
760             var val = value_.get_value();
761             values[key] = val;
762         });
763         return values;
764     },
765     get_selected_ids: function() {
766         var id = this.dataset.ids[this.dataset.index];
767         return id ? [id] : [];
768     },
769     recursive_save: function() {
770         var self = this;
771         return $.when(this.do_save()).pipe(function(res) {
772             if (self.dataset.parent_view)
773                 return self.dataset.parent_view.recursive_save();
774         });
775     },
776     is_dirty: function() {
777         return _.any(this.fields, function (value_) {
778             return value_._dirty_flag;
779         });
780     },
781     is_interactible_record: function() {
782         var id = this.datarecord.id;
783         if (!id) {
784             if (this.options.not_interactible_on_create)
785                 return false;
786         } else if (typeof(id) === "string") {
787             if(instance.web.BufferedDataSet.virtual_id_regex.test(id))
788                 return false;
789         }
790         return true;
791     },
792     sidebar_context: function () {
793         return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
794     },
795     open_defaults_dialog: function () {
796         var self = this;
797         var fields = _.chain(this.fields)
798             .map(function (field, name) {
799                 var value = field.get_value();
800                 // ignore fields which are empty, invisible, readonly, o2m
801                 // or m2m
802                 if (!value
803                         || field.get('invisible')
804                         || field.get("readonly")
805                         || field.field.type === 'one2many'
806                         || field.field.type === 'many2many') {
807                     return false;
808                 }
809                 var displayed = value;
810                 switch (field.field.type) {
811                 case 'selection':
812                     displayed = _(field.values).find(function (option) {
813                             return option[0] === value;
814                         })[1];
815                     break;
816                 }
817
818                 return {
819                     name: name,
820                     string: field.node.attrs.string || field.field.string,
821                     value: value,
822                     displayed: displayed,
823                     // convert undefined to false
824                     change_default: !!field.field.change_default
825                 }
826             })
827             .compact()
828             .sortBy(function (field) { return field.string; })
829             .value();
830         var conditions = _.chain(fields)
831             .filter(function (field) { return field.change_default; })
832             .value();
833
834         var d = new instance.web.Dialog(this, {
835             title: _t("Set Default"),
836             args: {
837                 fields: fields,
838                 conditions: conditions
839             },
840             buttons: [
841                 {text: _t("Close"), click: function () { d.close(); }},
842                 {text: _t("Save default"), click: function () {
843                     var $defaults = d.$element.find('#formview_default_fields');
844                     var field_to_set = $defaults.val();
845                     if (!field_to_set) {
846                         $defaults.parent().addClass('oe_form_invalid');
847                         return;
848                     }
849                     var condition = d.$element.find('#formview_default_conditions').val(),
850                         all_users = d.$element.find('#formview_default_all').is(':checked');
851                     new instance.web.DataSet(self, 'ir.values').call(
852                         'set_default', [
853                             self.dataset.model,
854                             field_to_set,
855                             self.fields[field_to_set].get_value(),
856                             all_users,
857                             false,
858                             condition || false
859                     ]).then(function () { d.close(); });
860                 }}
861             ]
862         });
863         d.template = 'FormView.set_default';
864         d.open();
865     },
866     register_field: function(field, name) {
867         this.fields[name] = field;
868         this.fields_order.push(name);
869         if (this.get_field(name).translate) {
870             this.translatable_fields.push(field);
871         }
872         field.on('changed_value', this, function() {
873             field._dirty_flag = true;
874             if (field.is_syntax_valid()) {
875                 this.do_onchange(field);
876                 this.on_form_changed(true);
877                 this.do_notify_change();
878             }
879         });
880     },
881     get_field: function(field_name) {
882         return this.fields_view.fields[field_name];
883     },
884     is_create_mode: function() {
885         return !this.datarecord.id;
886     },
887 }));
888
889 /**
890  * Interface to be implemented by rendering engines for the form view.
891  */
892 instance.web.form.FormRenderingEngineInterface = instance.web.Class.extend({
893     set_fields_view: function(fields_view) {},
894     set_fields_registry: function(fields_registry) {},
895     render_to: function($element) {},
896 });
897
898 /**
899  * Default rendering engine for the form view.
900  * 
901  * It is necessary to set the view using set_view() before usage.
902  */
903 instance.web.form.FormRenderingEngine = instance.web.form.FormRenderingEngineInterface.extend({
904     init: function(view) {
905         this.view = view;
906     },
907     set_fields_view: function(fvg) {
908         this.fvg = fvg;
909     },
910     set_tags_registry: function(tags_registry) {
911         this.tags_registry = tags_registry;
912     },
913     set_fields_registry: function(fields_registry) {
914         this.fields_registry = fields_registry;
915     },
916     render_to: function($target) {
917         var self = this;
918         this.$target = $target;
919
920         // TODO: I know this will save the world and all the kitten for a moment,
921         //       but one day, we will have to get rid of xml2json
922         var xml = instance.web.json_node_to_xml(this.fvg.arch);
923         this.$form = $('<div class="oe_form">' + xml + '</div>');
924
925         this.fields_to_init = [];
926         this.tags_to_init = [];
927         this.labels = {};
928         this.process(this.$form);
929
930         this.$form.appendTo(this.$target);
931
932         _.each(this.fields_to_init, function($elem) {
933             var name = $elem.attr("name");
934             if (!self.fvg.fields[name]) {
935                 throw new Error("Field '" + name + "' specified in view could not be found.");
936             }
937             var obj = self.fields_registry.get_any([$elem.attr('widget'), self.fvg.fields[name].type]);
938             if (!obj) {
939                 throw new Error("Widget type '"+ $elem.attr('widget') + "' is not implemented");
940             }
941             var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
942             var $label = self.labels[$elem.attr("name")];
943             if ($label) {
944                 w.set_input_id($label.attr("for"));
945             }
946             self.alter_field(w);
947             self.view.register_field(w, $elem.attr("name"));
948             w.replace($elem);
949         });
950         _.each(this.tags_to_init, function($elem) {
951             var tag_name = $elem[0].tagName.toLowerCase();
952             var obj = self.tags_registry.get_object(tag_name);
953             var w = new (obj)(self.view, instance.web.xml_to_json($elem[0]));
954             w.replace($elem);
955         });
956         // TODO: return a deferred
957     },
958     render_element: function(template /* dictionaries */) {
959         var dicts = [].slice.call(arguments).slice(1);
960         var dict = _.extend.apply(_, dicts);
961         dict['classnames'] = dict['class'] || ''; // class is a reserved word and might caused problem to Safari when used from QWeb
962         return $(QWeb.render(template, dict));
963     },
964     alter_field: function(field) {
965     },
966     toggle_layout_debugging: function() {
967         if (!this.$target.has('.oe_layout_debug_cell:first').length) {
968             this.$target.find('[title]').removeAttr('title');
969             this.$target.find('.oe_form_group_cell').each(function() {
970                 var text = 'W:' + ($(this).attr('width') || '') + ' - C:' + $(this).attr('colspan');
971                 $(this).attr('title', text);
972             });
973         }
974         this.$target.toggleClass('oe_layout_debugging');
975     },
976     process: function($tag) {
977         var self = this;
978         var tagname = $tag[0].nodeName.toLowerCase();
979         if (this.tags_registry.contains(tagname)) {
980             this.tags_to_init.push($tag);
981             return $tag;
982         }
983         var fn = self['process_' + tagname];
984         if (fn) {
985             var args = [].slice.call(arguments);
986             args[0] = $tag;
987             return fn.apply(self, args);
988         } else {
989             // generic tag handling, just process children
990             $tag.children().each(function() {
991                 self.process($(this));
992             });
993             self.handle_common_properties($tag, $tag);
994             $tag.removeAttr("modifiers");
995             return $tag;
996         }
997     },
998     process_sheet: function($sheet) {
999         var $new_sheet = this.render_element('FormRenderingSheet', $sheet.getAttributes());
1000         this.handle_common_properties($new_sheet, $sheet);
1001         var $dst = $new_sheet.find('.oe_form_sheet');
1002         $sheet.contents().appendTo($dst);
1003         $sheet.before($new_sheet).remove();
1004         this.process($new_sheet);
1005     },
1006     process_form: function($form) {
1007         var $new_form = this.render_element('FormRenderingForm', $form.getAttributes());
1008         this.handle_common_properties($new_form, $form);
1009         $form.contents().appendTo($new_form);
1010         if ($form[0] === this.$form[0]) {
1011             // If root element, replace it
1012             this.$form = $new_form;
1013         } else {
1014             $form.before($new_form).remove();
1015         }
1016         this.process($new_form);
1017     },
1018     /*
1019      * Used by direct <field> children of a <group> tag only
1020      * This method will add the implicit <label...> for every field
1021      * in the <group>
1022     */
1023     preprocess_field: function($field) {
1024         var self = this;
1025         var name = $field.attr('name'),
1026             field_colspan = parseInt($field.attr('colspan'), 10),
1027             field_modifiers = JSON.parse($field.attr('modifiers') || '{}');
1028
1029         if ($field.attr('nolabel') === '1')
1030             return;
1031         $field.attr('nolabel', '1');
1032         var found = false;
1033         this.$form.find('label[for="' + name + '"]').each(function(i ,el) {
1034             $(el).parents().each(function(unused, tag) {
1035                 var name = tag.tagName.toLowerCase();
1036                 if (name === "field" || name in self.tags_registry.map)
1037                     found = true;
1038             });
1039         });
1040         if (found)
1041             return;
1042
1043         $label = $('<label/>').attr({
1044             'for' : name,
1045             "modifiers": JSON.stringify({invisible: field_modifiers.invisible}),
1046             "string": $field.attr('string'),
1047             "help": $field.attr('help'),
1048         });
1049         $label.insertBefore($field);
1050         if (field_colspan > 1) {
1051             $field.attr('colspan', field_colspan - 1);
1052         }
1053         return $label;
1054     },
1055     process_field: function($field) {
1056         if ($field.parent().is('group')) {
1057             // No implicit labels for normal fields, only for <group> direct children
1058             var $label = this.preprocess_field($field);
1059             if ($label) {
1060                 this.process($label);
1061             }
1062         }
1063         this.fields_to_init.push($field);
1064         return $field;
1065     },
1066     process_group: function($group) {
1067         var self = this;
1068         $group.children('field').each(function() {
1069             self.preprocess_field($(this));
1070         });
1071         var $new_group = this.render_element('FormRenderingGroup', $group.getAttributes());
1072         var $table;
1073         if ($new_group.first().is('table.oe_form_group')) {
1074             $table = $new_group;
1075         } else if ($new_group.filter('table.oe_form_group').length) {
1076             $table = $new_group.filter('table.oe_form_group').first();
1077         } else {
1078             $table = $new_group.find('table.oe_form_group').first();
1079         }
1080
1081         var $tr, $td,
1082             cols = parseInt($group.attr('col') || 2, 10),
1083             row_cols = cols;
1084
1085         var children = [];
1086         $group.children().each(function(a,b,c) {
1087             var $child = $(this);
1088             var colspan = parseInt($child.attr('colspan') || 1, 10);
1089             var tagName = $child[0].tagName.toLowerCase();
1090             var $td = $('<td/>').addClass('oe_form_group_cell').attr('colspan', colspan);
1091             var newline = tagName === 'newline';
1092
1093             // Note FME: those classes are used in layout debug mode
1094             if ($tr && row_cols > 0 && (newline || row_cols < colspan)) {
1095                 $tr.addClass('oe_form_group_row_incomplete');
1096                 if (newline) {
1097                     $tr.addClass('oe_form_group_row_newline');
1098                 }
1099             }
1100             if (newline) {
1101                 $tr = null;
1102                 return;
1103             }
1104             if (!$tr || row_cols < colspan) {
1105                 $tr = $('<tr/>').addClass('oe_form_group_row').appendTo($table);
1106                 row_cols = cols;
1107             }
1108             row_cols -= colspan;
1109
1110             // invisibility transfer
1111             var field_modifiers = JSON.parse($child.attr('modifiers') || '{}');
1112             var invisible = field_modifiers.invisible;
1113             self.handle_common_properties($td, $("<dummy>").attr("modifiers", JSON.stringify({invisible: invisible})));
1114
1115             $tr.append($td.append($child));
1116             children.push($child[0]);
1117         });
1118         if (row_cols && $td) {
1119             $td.attr('colspan', parseInt($td.attr('colspan'), 10) + row_cols);
1120         }
1121         $group.before($new_group).remove();
1122
1123         $table.find('> tbody > tr').each(function() {
1124             var to_compute = [],
1125                 row_cols = cols,
1126                 total = 100;
1127             $(this).children().each(function() {
1128                 var $td = $(this),
1129                     $child = $td.children(':first');
1130                 switch ($child[0].tagName.toLowerCase()) {
1131                     case 'separator':
1132                         if ($child.attr('orientation') === 'vertical') {
1133                             $td.addClass('oe_vertical_separator').attr('width', '1');
1134                             $td.empty();
1135                             row_cols--;
1136                         }
1137                         break;
1138                     case 'label':
1139                         if ($child.attr('for')) {
1140                             $td.attr('width', '1%').addClass('oe_form_group_cell_label');
1141                             row_cols--;
1142                             total--;
1143                         }
1144                         break;
1145                     default:
1146                         var width = _.str.trim($child.attr('width') || ''),
1147                             iwidth = parseInt(width, 10);
1148                         if (iwidth) {
1149                             if (width.substr(-1) === '%') {
1150                                 total -= iwidth;
1151                                 width = iwidth + '%';
1152                             } else {
1153                                 // Absolute width
1154                                 $td.css('min-width', width + 'px');
1155                             }
1156                             $td.attr('width', width);
1157                             $child.removeAttr('width');
1158                             row_cols--;
1159                         } else {
1160                             to_compute.push($td);
1161                         }
1162
1163                 }
1164             });
1165             var unit = Math.floor(total / row_cols);
1166             if (!$(this).is('.oe_form_group_row_incomplete')) {
1167                 _.each(to_compute, function($td, i) {
1168                     var width = parseInt($td.attr('colspan'), 10) * unit;
1169                     $td.attr('width', ((i == to_compute.length - 1) ? total : width) + '%');
1170                     total -= width;
1171                 });
1172             }
1173         });
1174         _.each(children, function(el) {
1175             self.process($(el));
1176         });
1177         this.handle_common_properties($new_group, $group);
1178         return $new_group;
1179     },
1180     process_notebook: function($notebook) {
1181         var self = this;
1182         var pages = [];
1183         $notebook.find('> page').each(function() {
1184             var $page = $(this);
1185             var page_attrs = $page.getAttributes();
1186             page_attrs.id = _.uniqueId('notebook_page_');
1187             pages.push(page_attrs);
1188             var $new_page = self.render_element('FormRenderingNotebookPage', page_attrs);
1189             $page.contents().appendTo($new_page);
1190             $page.before($new_page).remove();
1191             self.handle_common_properties($new_page, $page);
1192         });
1193         var $new_notebook = this.render_element('FormRenderingNotebook', { pages : pages });
1194         $notebook.contents().appendTo($new_notebook);
1195         $notebook.before($new_notebook).remove();
1196         $new_notebook.children().each(function() {
1197             self.process($(this));
1198         });
1199         $new_notebook.tabs();
1200         this.handle_common_properties($new_notebook, $notebook);
1201         return $new_notebook;
1202     },
1203     process_separator: function($separator) {
1204         var $new_separator = this.render_element('FormRenderingSeparator', $separator.getAttributes());
1205         $separator.before($new_separator).remove();
1206         this.handle_common_properties($new_separator, $separator);
1207         return $new_separator;
1208     },
1209     process_label: function($label) {
1210         var name = $label.attr("for"),
1211             field_orm = this.fvg.fields[name];
1212         var dict = {
1213             string: $label.attr('string') || (field_orm || {}).string || '',
1214             help: $label.attr('help') || (field_orm || {}).help || '',
1215             _for: name ? _.uniqueId('oe-field-input-') : undefined,
1216         };
1217         var align = parseFloat(dict.align);
1218         if (isNaN(align) || align === 1) {
1219             align = 'right';
1220         } else if (align === 0) {
1221             align = 'left';
1222         } else {
1223             align = 'center';
1224         }
1225         dict.align = align;
1226         var $new_label = this.render_element('FormRenderingLabel', dict);
1227         $label.before($new_label).remove();
1228         this.handle_common_properties($new_label, $label);
1229         if (name) {
1230             this.labels[name] = $new_label;
1231         }
1232         return $new_label;
1233     },
1234     handle_common_properties: function($new_element, $node) {
1235         var str_modifiers = $node.attr("modifiers") || "{}"
1236         var modifiers = JSON.parse(str_modifiers);
1237         if (modifiers.invisible !== undefined)
1238             new instance.web.form.InvisibilityChanger(this.view, this.view, modifiers.invisible, $new_element);
1239         $new_element.addClass($node.attr("class") || "");
1240         $new_element.attr('style', $node.attr('style'));
1241     },
1242 });
1243
1244 instance.web.form.FormRenderingEngineReadonly = instance.web.form.FormRenderingEngine.extend({
1245     alter_field: function(field) {
1246         field.set({"force_readonly": true});
1247     },
1248 });
1249
1250 instance.web.form.FormDialog = instance.web.Dialog.extend({
1251     init: function(parent, options, view_id, dataset) {
1252         this._super(parent, options);
1253         this.dataset = dataset;
1254         this.view_id = view_id;
1255         return this;
1256     },
1257     start: function() {
1258         this._super();
1259         this.form = new instance.web.FormView(this, this.dataset, this.view_id, {
1260             pager: false
1261         });
1262         this.form.appendTo(this.$element);
1263         this.form.on_created.add_last(this.on_form_dialog_saved);
1264         this.form.on_saved.add_last(this.on_form_dialog_saved);
1265         return this;
1266     },
1267     select_id: function(id) {
1268         if (this.form.dataset.select_id(id)) {
1269             return this.form.do_show();
1270         } else {
1271             this.do_warn("Could not find id in dataset");
1272             return $.Deferred().reject();
1273         }
1274     },
1275     on_form_dialog_saved: function(r) {
1276         this.close();
1277     }
1278 });
1279
1280 instance.web.form.compute_domain = function(expr, fields) {
1281     var stack = [];
1282     for (var i = expr.length - 1; i >= 0; i--) {
1283         var ex = expr[i];
1284         if (ex.length == 1) {
1285             var top = stack.pop();
1286             switch (ex) {
1287                 case '|':
1288                     stack.push(stack.pop() || top);
1289                     continue;
1290                 case '&':
1291                     stack.push(stack.pop() && top);
1292                     continue;
1293                 case '!':
1294                     stack.push(!top);
1295                     continue;
1296                 default:
1297                     throw new Error(_.str.sprintf(
1298                         _t("Unknown operator %s in domain %s"),
1299                         ex, JSON.stringify(expr)));
1300             }
1301         }
1302
1303         var field = fields[ex[0]];
1304         if (!field) {
1305             throw new Error(_.str.sprintf(
1306                 _t("Unknown field %s in domain %s"),
1307                 ex[0], JSON.stringify(expr)));
1308         }
1309         var field_value = field.get_value ? field.get_value() : field.value;
1310         var op = ex[1];
1311         var val = ex[2];
1312
1313         switch (op.toLowerCase()) {
1314             case '=':
1315             case '==':
1316                 stack.push(field_value == val);
1317                 break;
1318             case '!=':
1319             case '<>':
1320                 stack.push(field_value != val);
1321                 break;
1322             case '<':
1323                 stack.push(field_value < val);
1324                 break;
1325             case '>':
1326                 stack.push(field_value > val);
1327                 break;
1328             case '<=':
1329                 stack.push(field_value <= val);
1330                 break;
1331             case '>=':
1332                 stack.push(field_value >= val);
1333                 break;
1334             case 'in':
1335                 if (!_.isArray(val)) val = [val];
1336                 stack.push(_(val).contains(field_value));
1337                 break;
1338             case 'not in':
1339                 if (!_.isArray(val)) val = [val];
1340                 stack.push(!_(val).contains(field_value));
1341                 break;
1342             default:
1343                 console.warn(
1344                     _t("Unsupported operator %s in domain %s"),
1345                     op, JSON.stringify(expr));
1346         }
1347     }
1348     return _.all(stack, _.identity);
1349 };
1350
1351 /**
1352  * Must be applied over an class already possessing the PropertiesMixin.
1353  *
1354  * Apply the result of the "invisible" domain to this.$element.
1355  */
1356 instance.web.form.InvisibilityChangerMixin = {
1357     init: function(field_manager, invisible_domain) {
1358         this._ic_field_manager = field_manager
1359         this._ic_invisible_modifier = invisible_domain;
1360         this._ic_field_manager.on("view_content_has_changed", this, function() {
1361             var result = this._ic_invisible_modifier === undefined ? false :
1362                 instance.web.form.compute_domain(this._ic_invisible_modifier, this._ic_field_manager.fields);
1363             this.set({"invisible": result});
1364         });
1365         this.set({invisible: this._ic_invisible_modifier === true, force_invisible: false});
1366         var check = function() {
1367             if (this.get("invisible") || this.get('force_invisible')) {
1368                 this.set({"effective_invisible": true});
1369             } else {
1370                 this.set({"effective_invisible": false});
1371             }
1372         };
1373         this.on('change:invisible', this, check);
1374         this.on('change:force_invisible', this, check);
1375         _.bind(check, this)();
1376     },
1377     start: function() {
1378         var check_visibility = function() {
1379             if (this.get("effective_invisible")) {
1380                 this.$element.hide();
1381             } else {
1382                 this.$element.show();
1383             }
1384         };
1385         this.on("change:effective_invisible", this, check_visibility);
1386         _.bind(check_visibility, this)();
1387     },
1388 };
1389
1390 instance.web.form.InvisibilityChanger = instance.web.Class.extend(_.extend({}, instance.web.PropertiesMixin, instance.web.form.InvisibilityChangerMixin, {
1391     init: function(parent, field_manager, invisible_domain, $element) {
1392         this.setParent(parent);
1393         instance.web.PropertiesMixin.init.call(this);
1394         instance.web.form.InvisibilityChangerMixin.init.call(this, field_manager, invisible_domain);
1395         this.$element = $element;
1396         this.start();
1397     },
1398 }));
1399
1400 instance.web.form.FormWidget = instance.web.Widget.extend(_.extend({}, instance.web.form.InvisibilityChangerMixin, {
1401     /**
1402      * @constructs instance.web.form.FormWidget
1403      * @extends instance.web.Widget
1404      *
1405      * @param view
1406      * @param node
1407      */
1408     init: function(view, node) {
1409         this._super(view);
1410         this.view = view;
1411         this.node = node;
1412         this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
1413         instance.web.form.InvisibilityChangerMixin.init.call(this, view, this.modifiers.invisible);
1414
1415         this.view.on("view_content_has_changed", this, this.process_modifiers);
1416     },
1417     renderElement: function() {
1418         this._super();
1419         this.$element.addClass(this.node.attrs["class"] || "");
1420     },
1421     destroy: function() {
1422         $.fn.tipsy.clear();
1423         this._super.apply(this, arguments);
1424     },
1425     process_modifiers: function() {
1426         var compute_domain = instance.web.form.compute_domain;
1427         var to_set = {};
1428         for (var a in this.modifiers) {
1429             if (!_.include(["invisible"], a)) {
1430                 var val = compute_domain(this.modifiers[a], this.view.fields);
1431                 to_set[a] = val;
1432             }
1433         }
1434         this.set(to_set);
1435     },
1436     do_attach_tooltip: function(widget, trigger, options) {
1437         widget = widget || this;
1438         trigger = trigger || this.$element;
1439         options = _.extend({
1440                 delayIn: 500,
1441                 delayOut: 0,
1442                 fade: true,
1443                 title: function() {
1444                     var template = widget.template + '.tooltip';
1445                     if (!QWeb.has_template(template)) {
1446                         template = 'WidgetLabel.tooltip';
1447                     }
1448                     return QWeb.render(template, {
1449                         debug: instance.connection.debug,
1450                         widget: widget
1451                 })},
1452                 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
1453                 html: true,
1454                 opacity: 0.85,
1455                 trigger: 'hover'
1456             }, options || {});
1457         $(trigger).tipsy(options);
1458     },
1459     _build_view_fields_values: function(blacklist) {
1460         var a_dataset = this.view.dataset;
1461         var fields_values = this.view.get_fields_values(blacklist);
1462         var active_id = a_dataset.ids[a_dataset.index];
1463         _.extend(fields_values, {
1464             active_id: active_id || false,
1465             active_ids: active_id ? [active_id] : [],
1466             active_model: a_dataset.model,
1467             parent: {}
1468         });
1469         if (a_dataset.parent_view) {
1470                 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
1471         }
1472         return fields_values;
1473     },
1474     _build_eval_context: function(blacklist) {
1475         var a_dataset = this.view.dataset;
1476         return new instance.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
1477     },
1478     /**
1479      * Builds a new context usable for operations related to fields by merging
1480      * the fields'context with the action's context.
1481      */
1482     build_context: function(blacklist) {
1483         // only use the model's context if there is not context on the node
1484         var v_context = this.node.attrs.context;
1485         if (! v_context) {
1486             v_context = (this.field || {}).context || {};
1487         }
1488         
1489         if (v_context.__ref || true) { //TODO: remove true
1490             var fields_values = this._build_eval_context(blacklist);
1491             v_context = new instance.web.CompoundContext(v_context).set_eval_context(fields_values);
1492         }
1493         return v_context;
1494     },
1495     build_domain: function() {
1496         var f_domain = this.field.domain || [];
1497         var n_domain = this.node.attrs.domain || null;
1498         // if there is a domain on the node, overrides the model's domain
1499         var final_domain = n_domain !== null ? n_domain : f_domain;
1500         if (!(final_domain instanceof Array) || true) { //TODO: remove true
1501             var fields_values = this._build_eval_context();
1502             final_domain = new instance.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1503         }
1504         return final_domain;
1505     }
1506 }));
1507
1508 instance.web.form.WidgetButton = instance.web.form.FormWidget.extend({
1509     template: 'WidgetButton',
1510     init: function(view, node) {
1511         this._super(view, node);
1512         this.force_disabled = false;
1513         this.string = (this.node.attrs.string || '').replace(/_/g, '');
1514         if (this.node.attrs.default_focus == '1') {
1515             // TODO fme: provide enter key binding to widgets
1516             this.view.default_focus_button = this;
1517         }
1518         this.view.on('view_content_has_changed', this, this.check_disable);
1519     },
1520     start: function() {
1521         this._super.apply(this, arguments);
1522         this.$element.click(this.on_click);
1523         if (this.node.attrs.help || instance.connection.debug) {
1524             this.do_attach_tooltip();
1525         }
1526     },
1527     on_click: function() {
1528         var self = this;
1529         this.force_disabled = true;
1530         this.check_disable();
1531         this.execute_action().always(function() {
1532             self.force_disabled = false;
1533             self.check_disable();
1534         });
1535     },
1536     execute_action: function() {
1537         var self = this;
1538         var exec_action = function() {
1539             if (self.node.attrs.confirm) {
1540                 var def = $.Deferred();
1541                 var dialog = instance.web.dialog($('<div/>').text(self.node.attrs.confirm), {
1542                     title: _t('Confirm'),
1543                     modal: true,
1544                     buttons: [
1545                         {text: _t("Cancel"), click: function() {
1546                                 def.resolve();
1547                                 $(this).dialog("close");
1548                             }
1549                         },
1550                         {text: _t("Ok"), click: function() {
1551                                 self.on_confirmed().then(function() {
1552                                     def.resolve();
1553                                 });
1554                                 $(this).dialog("close");
1555                             }
1556                         }
1557                     ]
1558                 });
1559                 return def.promise();
1560             } else {
1561                 return self.on_confirmed();
1562             }
1563         };
1564         if (!this.node.attrs.special) {
1565             this.view.force_dirty = true;
1566             return this.view.recursive_save().pipe(exec_action);
1567         } else {
1568             return exec_action();
1569         }
1570     },
1571     on_confirmed: function() {
1572         var self = this;
1573
1574         var context = this.node.attrs.context;
1575         if (context && context.__ref) {
1576             context = new instance.web.CompoundContext(context);
1577             context.set_eval_context(this._build_eval_context());
1578         }
1579
1580         return this.view.do_execute_action(
1581             _.extend({}, this.node.attrs, {context: context}),
1582             this.view.dataset, this.view.datarecord.id, function () {
1583                 self.view.reload();
1584             });
1585     },
1586     check_disable: function() {
1587         var disabled = (this.force_disabled || !this.view.is_interactible_record());
1588         this.$element.prop('disabled', disabled);
1589         this.$element.css('color', disabled ? 'grey' : '');
1590     }
1591 });
1592
1593 /**
1594  * Interface to be implemented by fields.
1595  * 
1596  * Properties:
1597  *     - readonly: boolean. If set to true the field should appear in readonly mode.
1598  *     - force_readonly: boolean, When it is true, the field should always appear
1599  *      in read only mode, no matter what the value of the "readonly" property can be.
1600  * Events:
1601  *     - changed_value: triggered to inform the view to check on_changes
1602  * 
1603  */
1604 instance.web.form.FieldMixin = {
1605     /**
1606      * Constructor takes 2 arguments:
1607      * - field_manager: Implements FieldManagerMixin
1608      * - node: the "<field>" node in json form
1609      */
1610     init: function(field_manager, node) {},
1611     /**
1612      * Called by the form view to indicate the value of the field.
1613      * 
1614      * set_value() may return an object that can be passed to $.when() that represents the moment when
1615      * the field has finished all operations necessary before the user can effectively use the widget.
1616      * 
1617      * Multiple calls to set_value() can occur at any time and must be handled correctly by the implementation,
1618      * regardless of any asynchronous operation currently running and the status of any promise that a
1619      * previous call to set_value() could have returned.
1620      * 
1621      * set_value() must be able, at any moment, to handle the syntax returned by the "read" method of the
1622      * osv class in the OpenERP server as well as the syntax used by the set_value() (see below). It must
1623      * also be able to handle any other format commonly used in the _defaults key on the models in the addons
1624      * as well as any format commonly returned in a on_change. It must be able to autodetect those formats as
1625      * no information is ever given to know which format is used.
1626      */
1627     set_value: function(value_) {},
1628     /**
1629      * Get the current value of the widget.
1630      * 
1631      * Must always return a syntaxically correct value to be passed to the "write" method of the osv class in
1632      * the OpenERP server, although it is not assumed to respect the constraints applied to the field.
1633      * For example if the field is marqued as "required", a call to get_value() can return false.
1634      * 
1635      * get_value() can also be called *before* a call to set_value() and, in that case, is supposed to
1636      * return a defaut value according to the type of field.
1637      * 
1638      * This method is always assumed to perform synchronously, it can not return a promise.
1639      * 
1640      * If there was no user interaction to modify the value of the field, it is always assumed that
1641      * get_value() return the same semantic value than the one passed in the last call to set_value(),
1642      * altough the syntax can be different. This can be the case for type of fields that have a different
1643      * syntax for "read" and "write" (example: m2o: set_value([0, "Administrator"]), get_value() => 0).
1644      */
1645     get_value: function() {},
1646     /**
1647      * Inform the current object of the id it should use to match a html <label> that exists somewhere in the
1648      * view.
1649      */
1650     set_input_id: function(id) {},
1651     /**
1652      * Returns true if is_syntax_valid() returns true and the value is semantically
1653      * valid too according to the semantic restrictions applied to the field.
1654      */
1655     is_valid: function() {},
1656     /**
1657      * Returns true if the field holds a value which is syntaxically correct, ignoring
1658      * the potential semantic restrictions applied to the field.
1659      */
1660     is_syntax_valid: function() {},
1661     /**
1662      * Must set the focus on the field.
1663      */
1664     focus: function() {},
1665 };
1666
1667 /**
1668  * Abstract class for classes implementing FieldMixin.
1669  * 
1670  * Properties:
1671  *     - effective_readonly: when it is true, the widget is displayed as readonly. Vary depending
1672  *      the values of the "readonly" property and the "force_readonly" property on the field manager.
1673  *     - value: useful property to hold the value of the field. By default, set_value() and get_value()
1674  *     set and retrieve the value property. Changing the value property also triggers automatically
1675  *     a 'changed_value' event that inform the view to trigger on_changes.
1676  * 
1677  */
1678 instance.web.form.AbstractField = instance.web.form.FormWidget.extend(_.extend({}, instance.web.form.FieldMixin, {
1679     /**
1680      * @constructs instance.web.form.AbstractField
1681      * @extends instance.web.form.FormWidget
1682      *
1683      * @param field_manager
1684      * @param node
1685      */
1686     init: function(field_manager, node) {
1687         this._super(field_manager, node);
1688         this.field_manager = field_manager;
1689         this.name = this.node.attrs.name;
1690         this.set({'value': false});
1691         this.field = this.field_manager.get_field(this.name);
1692         this.set({required: this.modifiers['required'] === true});
1693         
1694         // some events to make the property "effective_readonly" sync automatically with "readonly" and
1695         // "force_readonly"
1696         this.set({"readonly": this.modifiers['readonly'] === true});
1697         var test_effective_readonly = function() {
1698             this.set({"effective_readonly": this.get("readonly") || !!this.get("force_readonly")});
1699         };
1700         this.on("change:readonly", this, test_effective_readonly);
1701         this.on("change:force_readonly", this, test_effective_readonly);
1702         _.bind(test_effective_readonly, this)();
1703         
1704         this.on("change:value", this, function() {
1705             if (! this._inhibit_on_change)
1706                 this.trigger('changed_value');
1707             this._check_css_flags();
1708         });
1709     },
1710     renderElement: function() {
1711         var self = this;
1712         this._super();
1713         if (this.field.translate) {
1714             this.$element.addClass('oe_form_field_translatable');
1715             this.$element.find('.oe_field_translate').click(_.bind(function() {
1716                 this.field_manager.open_translate_dialog(this);
1717             }, this));
1718         }
1719         this.$label = this.view.$element.find('label[for=' + this.id_for_label + ']');
1720         if (instance.connection.debug) {
1721             this.do_attach_tooltip(this, this.$label[0] || this.$element);
1722             this.$label.off('dblclick').on('dblclick', function() {
1723                 console.log("Field '%s' of type '%s' in View: %o", self.name, (self.node.attrs.widget || self.field.type), self.view);
1724                 window.w = self;
1725                 console.log("window.w =", window.w);
1726             });
1727         }
1728         if (!this.disable_utility_classes) {
1729             this.off("change:required", this, this._set_required);
1730             this.on("change:required", this, this._set_required);
1731             this._set_required();
1732         }
1733     },
1734     /**
1735      * Private. Do not use.
1736      */
1737     _set_required: function() {
1738         this.$element.toggleClass('oe_form_required', this.get("required"));
1739     },
1740     set_value: function(value_) {
1741         this._inhibit_on_change = true;
1742         this.set({'value': value_});
1743         this._inhibit_on_change = false;
1744     },
1745     get_value: function() {
1746         return this.get('value');
1747     },
1748     is_valid: function() {
1749         return this.is_syntax_valid() && (! this.get('required') || ! this.is_false());
1750     },
1751     is_syntax_valid: function() {
1752         return true;
1753     },
1754     /**
1755      * Method useful to implement to ease validity testing. Must return true if the current
1756      * value is similar to false in OpenERP.
1757      */
1758     is_false: function() {
1759         return this.get('value') === false;
1760     },
1761     _check_css_flags: function(show_invalid) {
1762         if (this.field.translate) {
1763             this.$element.find('.oe_field_translate').toggle(!this.field_manager.is_create_mode());
1764         }
1765         if (!this.disable_utility_classes) {
1766             if (this.field_manager.get('display_invalid_fields')) {
1767                 this.$element.toggleClass('oe_form_invalid', !this.is_valid());
1768             }
1769         }
1770     },
1771     focus: function() {
1772     },
1773     /**
1774      * Utility method to focus an element, but only after a small amount of time.
1775      */
1776     delay_focus: function($elem) {
1777         setTimeout(function() {
1778             $elem.focus();
1779         }, 50);
1780     },
1781     /**
1782      * Utility method to get the widget options defined in the field xml description.
1783      */
1784     get_definition_options: function() {
1785         if (!this.definition_options) {
1786             var str = this.node.attrs.options || '{}';
1787             this.definition_options = JSON.parse(str);
1788         }
1789         return this.definition_options;
1790     },
1791     set_input_id: function(id) {
1792         this.id_for_label = id;
1793     },
1794 }));
1795
1796 /**
1797  * A mixin to apply on any field that has to completely re-render when its readonly state
1798  * switch.
1799  */
1800 instance.web.form.ReinitializeFieldMixin =  {
1801     /**
1802      * Default implementation of start(), use it or call explicitly initialize_field().
1803      */
1804     start: function() {
1805         this._super();
1806         this.initialize_field();
1807     },
1808     initialize_field: function() {
1809         this.on("change:effective_readonly", this, function() {
1810             this.destroy_content();
1811             this.renderElement();
1812             this.initialize_content();
1813             this.render_value();
1814         });
1815         this.initialize_content();
1816         this.render_value();
1817     },
1818     /**
1819      * Called to destroy anything that could have been created previously, called before a
1820      * re-initialization.
1821      */
1822     destroy_content: function() {},
1823     /**
1824      * Called to initialize the content.
1825      */
1826     initialize_content: function() {},
1827     /**
1828      * Called to render the value. Should also be explicitly called at the end of a set_value().
1829      */
1830     render_value: function() {},
1831 };
1832
1833 instance.web.form.FieldChar = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
1834     template: 'FieldChar',
1835     widget_class: 'oe_form_field_char',
1836     init: function (field_manager, node) {
1837         this._super(field_manager, node);
1838         this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1839     },
1840     initialize_content: function() {
1841         var self = this;
1842         this.$element.find('input').change(function() {
1843             self.set({'value': instance.web.parse_value(self.$element.find('input').val(), self)});
1844         });
1845     },
1846     set_value: function(value_) {
1847         this._super(value_);
1848         this.render_value();
1849     },
1850     render_value: function() {
1851         var show_value = instance.web.format_value(this.get('value'), this, '');
1852         if (!this.get("effective_readonly")) {
1853             this.$element.find('input').val(show_value);
1854         } else {
1855             if (this.password) {
1856                 show_value = new Array(show_value.length + 1).join('*');
1857             }
1858             this.$element.text(show_value);
1859         }
1860     },
1861     is_syntax_valid: function() {
1862         if (!this.get("effective_readonly")) {
1863             try {
1864                 var value_ = instance.web.parse_value(this.$element.find('input').val(), this, '');
1865                 return true;
1866             } catch(e) {
1867                 return false;
1868             }
1869         }
1870         return true;
1871     },
1872     is_false: function() {
1873         return this.get('value') === '';
1874     },
1875     focus: function() {
1876         this.delay_focus(this.$element.find('input:first'));
1877     }
1878 }));
1879
1880 instance.web.form.FieldID = instance.web.form.FieldChar.extend({
1881     
1882 });
1883
1884 instance.web.form.FieldEmail = instance.web.form.FieldChar.extend({
1885     template: 'FieldEmail',
1886     initialize_content: function() {
1887         this._super();
1888         this.$element.find('button').click(this.on_button_clicked);
1889     },
1890     render_value: function() {
1891         if (!this.get("effective_readonly")) {
1892             this._super();
1893         } else {
1894             this.$element.find('a')
1895                     .attr('href', 'mailto:' + this.get('value'))
1896                     .text(this.get('value'));
1897         }
1898     },
1899     on_button_clicked: function() {
1900         if (!this.get('value') || !this.is_syntax_valid()) {
1901             this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1902         } else {
1903             location.href = 'mailto:' + this.get('value');
1904         }
1905     }
1906 });
1907
1908 instance.web.form.FieldUrl = instance.web.form.FieldChar.extend({
1909     template: 'FieldUrl',
1910     initialize_content: function() {
1911         this._super();
1912         this.$element.find('button').click(this.on_button_clicked);
1913     },
1914     render_value: function() {
1915         if (!this.get("effective_readonly")) {
1916             this._super();
1917         } else {
1918             var tmp = this.get('value');
1919             var s = /(\w+):(.+)/.exec(tmp);
1920             if (!s) {
1921                 tmp = "http://" + this.get('value');
1922             }
1923             this.$element.find('a').attr('href', tmp).text(tmp);
1924         }
1925     },
1926     on_button_clicked: function() {
1927         if (!this.get('value')) {
1928             this.do_warn("Resource error", "This resource is empty");
1929         } else {
1930             var url = $.trim(this.get('value'));
1931             if(/^www\./i.test(url))
1932                 url = 'http://'+url;
1933             window.open(url);
1934         }
1935     }
1936 });
1937
1938 instance.web.form.FieldFloat = instance.web.form.FieldChar.extend({
1939     is_field_number: true,
1940     widget_class: 'oe_form_field_float',
1941     init: function (field_manager, node) {
1942         this._super(field_manager, node);
1943         this.set({'value': 0});
1944         if (this.node.attrs.digits) {
1945             this.digits = py.eval(node.attrs.digits);
1946         } else {
1947             this.digits = this.field.digits;
1948         }
1949     },
1950     set_value: function(value_) {
1951         if (value_ === false || value_ === undefined) {
1952             // As in GTK client, floats default to 0
1953             value_ = 0;
1954         }
1955         this._super.apply(this, [value_]);
1956     }
1957 });
1958
1959 instance.web.DateTimeWidget = instance.web.OldWidget.extend({
1960     template: "web.datetimepicker",
1961     jqueryui_object: 'datetimepicker',
1962     type_of_date: "datetime",
1963     init: function(parent) {
1964         this._super(parent);
1965         this.name = parent.name;
1966     },
1967     start: function() {
1968         var self = this;
1969         this.$input = this.$element.find('input.oe_datepicker_master');
1970         this.$input_picker = this.$element.find('input.oe_datepicker_container');
1971         this.$input.change(this.on_change);
1972         this.picker({
1973             onSelect: this.on_picker_select,
1974             changeMonth: true,
1975             changeYear: true,
1976             showWeek: true,
1977             showButtonPanel: true
1978         });
1979         this.$element.find('img.oe_datepicker_trigger').click(function() {
1980             if (!self.get("effective_readonly") && !self.picker('widget').is(':visible')) {
1981                 self.picker('setDate', self.get('value') ? instance.web.auto_str_to_date(self.get('value')) : new Date());
1982                 self.$input_picker.show();
1983                 self.picker('show');
1984                 self.$input_picker.hide();
1985             }
1986         });
1987         this.set_readonly(false);
1988         this.set({'value': false});
1989     },
1990     picker: function() {
1991         return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1992     },
1993     on_picker_select: function(text, instance_) {
1994         var date = this.picker('getDate');
1995         this.$input.val(date ? this.format_client(date) : '').change();
1996     },
1997     set_value: function(value_) {
1998         this.set({'value': value_});
1999         this.$input.val(value_ ? this.format_client(value_) : '');
2000     },
2001     get_value: function() {
2002         return this.get('value');
2003     },
2004     set_value_from_ui_: function() {
2005         var value_ = this.$input.val() || false;
2006         this.set({'value': this.parse_client(value_)});
2007     },
2008     set_readonly: function(readonly) {
2009         this.readonly = readonly;
2010         this.$input.prop('readonly', this.readonly);
2011         this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
2012     },
2013     is_valid_: function() {
2014         var value_ = this.$input.val();
2015         if (value_ === "") {
2016             return true;
2017         } else {
2018             try {
2019                 this.parse_client(value_);
2020                 return true;
2021             } catch(e) {
2022                 return false;
2023             }
2024         }
2025     },
2026     parse_client: function(v) {
2027         return instance.web.parse_value(v, {"widget": this.type_of_date});
2028     },
2029     format_client: function(v) {
2030         return instance.web.format_value(v, {"widget": this.type_of_date});
2031     },
2032     on_change: function() {
2033         if (this.is_valid_()) {
2034             this.set_value_from_ui_();
2035         }
2036     }
2037 });
2038
2039 instance.web.DateWidget = instance.web.DateTimeWidget.extend({
2040     jqueryui_object: 'datepicker',
2041     template: "web.datepicker",
2042     type_of_date: "date"
2043 });
2044
2045 instance.web.form.FieldDatetime = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2046     tagName: "span",
2047     build_widget: function() {
2048         return new instance.web.DateTimeWidget(this);
2049     },
2050     destroy_content: function() {
2051         if (this.datewidget) {
2052             this.datewidget.destroy();
2053             this.datewidget = undefined;
2054         }
2055     },
2056     initialize_content: function() {
2057         if (!this.get("effective_readonly")) {
2058             this.datewidget = this.build_widget();
2059             this.datewidget.on_change.add_last(_.bind(function() {
2060                 this.set({'value': this.datewidget.get_value()});
2061             }, this));
2062             this.datewidget.appendTo(this.$element);
2063         }
2064     },
2065     set_value: function(value_) {
2066         this._super(value_);
2067         this.render_value();
2068     },
2069     render_value: function() {
2070         if (!this.get("effective_readonly")) {
2071             this.datewidget.set_value(this.get('value'));
2072         } else {
2073             this.$element.text(instance.web.format_value(this.get('value'), this, ''));
2074         }
2075     },
2076     is_syntax_valid: function() {
2077         if (!this.get("effective_readonly")) {
2078             return this.datewidget.is_valid_();
2079         }
2080         return true;
2081     },
2082     is_false: function() {
2083         return this.get('value') === '';
2084     },
2085     focus: function() {
2086         if (this.datewidget && this.datewidget.$input)
2087             this.delay_focus(this.datewidget.$input);
2088     }
2089 }));
2090
2091 instance.web.form.FieldDate = instance.web.form.FieldDatetime.extend({
2092     build_widget: function() {
2093         return new instance.web.DateWidget(this);
2094     }
2095 });
2096
2097 instance.web.form.FieldText = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2098     template: 'FieldText',
2099     initialize_content: function() {
2100         this.$textarea = this.$element.find('textarea');
2101         if (!this.get("effective_readonly")) {
2102             this.$textarea.change(_.bind(function() {
2103                 this.set({'value': instance.web.parse_value(this.$textarea.val(), this)});
2104             }, this));
2105         } else {
2106             this.$textarea.attr('disabled', 'disabled');
2107         }
2108     },
2109     set_value: function(value_) {
2110         this._super.apply(this, arguments);
2111         this.render_value();
2112     },
2113     render_value: function() {
2114         var show_value = instance.web.format_value(this.get('value'), this, '');
2115         this.$textarea.val(show_value);
2116         if (show_value && this.view.options.resize_textareas) {
2117             this.do_resize(this.view.options.resize_textareas);
2118         }
2119     },
2120     is_syntax_valid: function() {
2121         if (!this.get("effective_readonly")) {
2122             try {
2123                 var value_ = instance.web.parse_value(this.$textarea.val(), this, '');
2124                 return true;
2125             } catch(e) {
2126                 return false;
2127             }
2128         }
2129         return true;
2130     },
2131     is_false: function() {
2132         return this.get('value') === '';
2133     },
2134     focus: function($element) {
2135         this.delay_focus(this.$textarea);
2136     },
2137     do_resize: function(max_height) {
2138         max_height = parseInt(max_height, 10);
2139         var $input = this.$textarea,
2140             $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
2141             new_height;
2142         $div.text($input.val());
2143         _.each('font-family,font-size,white-space'.split(','), function(style) {
2144             $div.css(style, $input.css(style));
2145         });
2146         $div.appendTo($('body'));
2147         new_height = $div.height();
2148         if (new_height < 90) {
2149             new_height = 90;
2150         }
2151         if (!isNaN(max_height) && new_height > max_height) {
2152             new_height = max_height;
2153         }
2154         $div.remove();
2155         $input.height(new_height);
2156     },
2157 }));
2158
2159 instance.web.form.FieldBoolean = instance.web.form.AbstractField.extend({
2160     template: 'FieldBoolean',
2161     start: function() {
2162         this._super.apply(this, arguments);
2163         this.$checkbox = $("input", this.$element);
2164         this.$element.click(_.bind(function() {
2165             this.set({'value': this.$checkbox.is(':checked')});
2166         }, this));
2167         var check_readonly = function() {
2168             this.$checkbox.prop('disabled', this.get("effective_readonly"));
2169         };
2170         this.on("change:effective_readonly", this, check_readonly);
2171         _.bind(check_readonly, this)();
2172     },
2173     set_value: function(value_) {
2174         this._super.apply(this, arguments);
2175         this.$checkbox[0].checked = value_;
2176     },
2177     focus: function() {
2178         this.delay_focus(this.$checkbox);
2179     }
2180 });
2181
2182 instance.web.form.FieldProgressBar = instance.web.form.AbstractField.extend({
2183     template: 'FieldProgressBar',
2184     start: function() {
2185         this._super.apply(this, arguments);
2186         this.$element.progressbar({
2187             value: this.get('value'),
2188             disabled: this.get("effective_readonly")
2189         });
2190     },
2191     set_value: function(value_) {
2192         this._super.apply(this, arguments);
2193         var show_value = Number(value_);
2194         if (isNaN(show_value)) {
2195             show_value = 0;
2196         }
2197         var formatted_value = instance.web.format_value(show_value, { type : 'float' }, '0');
2198         this.$element.progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
2199     }
2200 });
2201
2202 instance.web.form.FieldTextXml = instance.web.form.AbstractField.extend({
2203 // to replace view editor
2204 });
2205
2206 instance.web.form.FieldSelection = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2207     template: 'FieldSelection',
2208     init: function(field_manager, node) {
2209         var self = this;
2210         this._super(field_manager, node);
2211         this.values = _.clone(this.field.selection);
2212         _.each(this.values, function(v, i) {
2213             if (v[0] === false && v[1] === '') {
2214                 self.values.splice(i, 1);
2215             }
2216         });
2217         this.values.unshift([false, '']);
2218     },
2219     initialize_content: function() {
2220         // Flag indicating whether we're in an event chain containing a change
2221         // event on the select, in order to know what to do on keyup[RETURN]:
2222         // * If the user presses [RETURN] as part of changing the value of a
2223         //   selection, we should just let the value change and not let the
2224         //   event broadcast further (e.g. to validating the current state of
2225         //   the form in editable list view, which would lead to saving the
2226         //   current row or switching to the next one)
2227         // * If the user presses [RETURN] with a select closed (side-effect:
2228         //   also if the user opened the select and pressed [RETURN] without
2229         //   changing the selected value), takes the action as validating the
2230         //   row
2231         var ischanging = false;
2232         this.$element.find('select')
2233             .change(_.bind(function() {
2234                 this.set({'value': this.values[this.$element.find('select')[0].selectedIndex][0]});
2235             }, this))
2236             .change(function () { ischanging = true; })
2237             .click(function () { ischanging = false; })
2238             .keyup(function (e) {
2239                 if (e.which !== 13 || !ischanging) { return; }
2240                 e.stopPropagation();
2241                 ischanging = false;
2242             });
2243     },
2244     set_value: function(value_) {
2245         value_ = value_ === null ? false : value_;
2246         value_ = value_ instanceof Array ? value_[0] : value_;
2247         this._super(value_);
2248         this.render_value();
2249     },
2250     render_value: function() {
2251         if (!this.get("effective_readonly")) {
2252             var index = 0;
2253             for (var i = 0, ii = this.values.length; i < ii; i++) {
2254                 if (this.values[i][0] === this.get('value')) index = i;
2255             }
2256             this.$element.find('select')[0].selectedIndex = index;
2257         } else {
2258             var self = this;
2259             var option = _(this.values)
2260                 .detect(function (record) { return record[0] === self.get('value'); }); 
2261             this.$element.text(option ? option[1] : this.values[0][1]);
2262         }
2263     },
2264     is_syntax_valid: function() {
2265         if (this.get("effective_readonly")) {
2266             return true;
2267         }
2268         var value_ = this.values[this.$element.find('select')[0].selectedIndex];
2269         return !! value_;
2270     },
2271     focus: function() {
2272         this.delay_focus(this.$element.find('select:first'));
2273     }
2274 }));
2275
2276 // jquery autocomplete tweak to allow html
2277 (function() {
2278     var proto = $.ui.autocomplete.prototype,
2279         initSource = proto._initSource;
2280
2281     function filter( array, term ) {
2282         var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
2283         return $.grep( array, function(value_) {
2284             return matcher.test( $( "<div>" ).html( value_.label || value_.value || value_ ).text() );
2285         });
2286     }
2287
2288     $.extend( proto, {
2289         _initSource: function() {
2290             if ( this.options.html && $.isArray(this.options.source) ) {
2291                 this.source = function( request, response ) {
2292                     response( filter( this.options.source, request.term ) );
2293                 };
2294             } else {
2295                 initSource.call( this );
2296             }
2297         },
2298
2299         _renderItem: function( ul, item) {
2300             return $( "<li></li>" )
2301                 .data( "item.autocomplete", item )
2302                 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
2303                 .appendTo( ul );
2304         }
2305     });
2306 })();
2307
2308 /**
2309  * A mixin containing some useful methods to handle completion inputs.
2310  */
2311 instance.web.form.CompletionFieldMixin = {
2312     init: function() {
2313         this.limit = 7;
2314         this.orderer = new instance.web.DropMisordered();
2315     },
2316     /**
2317      * Call this method to search using a string.
2318      */
2319     get_search_result: function(search_val) {
2320         var self = this;
2321
2322         var dataset = new instance.web.DataSet(this, this.field.relation, self.build_context());
2323         var blacklist = this.get_search_blacklist();
2324
2325         return this.orderer.add(dataset.name_search(
2326                 search_val, new instance.web.CompoundDomain(self.build_domain(), [["id", "not in", blacklist]]),
2327                 'ilike', this.limit + 1)).pipe(function(data) {
2328             self.last_search = data;
2329             // possible selections for the m2o
2330             var values = _.map(data, function(x) {
2331                 return {
2332                     label: _.str.escapeHTML(x[1]),
2333                     value:x[1],
2334                     name:x[1],
2335                     id:x[0]
2336                 };
2337             });
2338
2339             // search more... if more results that max
2340             if (values.length > self.limit) {
2341                 values = values.slice(0, self.limit);
2342                 values.push({label: _t("<em>   Search More...</em>"), action: function() {
2343                     dataset.name_search(search_val, self.build_domain(), 'ilike'
2344                     , false, function(data) {
2345                         self._search_create_popup("search", data);
2346                     });
2347                 }});
2348             }
2349             // quick create
2350             var raw_result = _(data.result).map(function(x) {return x[1];});
2351             if (search_val.length > 0 && !_.include(raw_result, search_val)) {
2352                 values.push({label: _.str.sprintf(_t('<em>   Create "<strong>%s</strong>"</em>'),
2353                         $('<span />').text(search_val).html()), action: function() {
2354                     self._quick_create(search_val);
2355                 }});
2356             }
2357             // create...
2358             values.push({label: _t("<em>   Create and Edit...</em>"), action: function() {
2359                 self._search_create_popup("form", undefined, {"default_name": search_val});
2360             }});
2361
2362             return values;
2363         });
2364     },
2365     get_search_blacklist: function() {
2366         return [];
2367     },
2368     _quick_create: function(name) {
2369         var self = this;
2370         var slow_create = function () {
2371             self._search_create_popup("form", undefined, {"default_name": name});
2372         };
2373         if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2374             new instance.web.DataSet(this, this.field.relation, self.build_context())
2375                 .name_create(name, function(data) {
2376                     self.add_id(data[0]);
2377                 }).fail(function(error, event) {
2378                     event.preventDefault();
2379                     slow_create();
2380                 });
2381         } else
2382             slow_create();
2383     },
2384     // all search/create popup handling
2385     _search_create_popup: function(view, ids, context) {
2386         var self = this;
2387         var pop = new instance.web.form.SelectCreatePopup(this);
2388         pop.select_element(
2389             self.field.relation,
2390             {
2391                 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2392                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2393                 initial_view: view,
2394                 disable_multiple_selection: true
2395             },
2396             self.build_domain(),
2397             new instance.web.CompoundContext(self.build_context(), context || {})
2398         );
2399         pop.on_select_elements.add(function(element_ids) {
2400             self.add_id(element_ids[0]);
2401         });
2402     },
2403     /**
2404      * To implement.
2405      */
2406     add_id: function(id) {},
2407 };
2408
2409 instance.web.form.FieldMany2One = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin,
2410         instance.web.form.CompletionFieldMixin, {
2411     template: "FieldMany2One",
2412     init: function(field_manager, node) {
2413         this._super(field_manager, node);
2414         instance.web.form.CompletionFieldMixin.init.call(this);
2415         this.set({'value': false});
2416         this.display_value = {};
2417         this.last_search = [];
2418         this.floating = false;
2419         this.inhibit_on_change = false;
2420     },
2421     start: function() {
2422         this._super();
2423         instance.web.form.ReinitializeFieldMixin.start.call(this);
2424         this.on("change:value", this, function() {
2425             this.floating = false;
2426             this.render_value();
2427         });
2428     },
2429     initialize_content: function() {
2430         if (!this.get("effective_readonly"))
2431             this.render_editable();
2432         this.render_value();
2433     },
2434     render_editable: function() {
2435         var self = this;
2436         this.$input = this.$element.find("input");
2437         
2438         self.$input.tipsy({
2439             title: function() {
2440                 return "No element was selected, you should create or select one from the dropdown list.";
2441             },
2442             trigger:'manual',
2443             fade: true,
2444         });
2445         
2446         this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
2447         this.$follow_button = $(".oe-m2o-cm-button", this.$element);
2448         
2449         this.$follow_button.click(function() {
2450             if (!self.get('value')) {
2451                 return;
2452             }
2453             var pop = new instance.web.form.FormOpenPopup(self.view);
2454             pop.show_element(
2455                 self.field.relation,
2456                 self.get("value"),
2457                 self.build_context(),
2458                 {
2459                     title: _t("Open: ") + (self.string || self.name)
2460                 }
2461             );
2462             pop.on_write_completed.add_last(function() {
2463                 self.display_value = {};
2464                 self.render_value();
2465             });
2466         });
2467
2468         // some behavior for input
2469         this.$input.keyup(function() {
2470             if (self.$input.val() === "") {
2471                 self.set({value: false});
2472             } else {
2473                 self.floating = true;
2474             }
2475         });
2476         this.$drop_down.click(function() {
2477             if (self.$input.autocomplete("widget").is(":visible")) {
2478                 self.$input.autocomplete("close");
2479             } else {
2480                 if (self.get("value") && ! self.floating) {
2481                     self.$input.autocomplete("search", "");
2482                 } else {
2483                     self.$input.autocomplete("search");
2484                 }
2485                 self.$input.focus();
2486             }
2487         });
2488         var tip_def = $.Deferred();
2489         var untip_def = $.Deferred();
2490         var tip_delay = 200;
2491         var tip_duration = 3000;
2492         var anyoneLoosesFocus = function() {
2493             if (self.floating) {
2494                 if (self.last_search.length > 0) {
2495                     if (self.last_search[0][0] != self.get("value")) {
2496                         self.display_value = {};
2497                         self.display_value["" + self.last_search[0][0]] = self.last_search[0][1];
2498                         self.set({value: self.last_search[0][0]});
2499                     } else {
2500                         self.render_value();
2501                     }
2502                 } else {
2503                     self.set({value: false});
2504                 }
2505             }
2506             if (! self.get("value")) {
2507                 tip_def.reject();
2508                 untip_def.reject();
2509                 tip_def = $.Deferred();
2510                 tip_def.then(function() {
2511                     self.$input.tipsy("show");
2512                 });
2513                 setTimeout(function() {
2514                     tip_def.resolve();
2515                     untip_def.reject();
2516                     untip_def = $.Deferred();
2517                     untip_def.then(function() {
2518                         self.$input.tipsy("hide");
2519                     });
2520                     setTimeout(function() {untip_def.resolve();}, tip_duration);
2521                 }, tip_delay);
2522             } else {
2523                 tip_def.reject();
2524             }
2525         };
2526         this.$input.focusout(anyoneLoosesFocus);
2527
2528         var isSelecting = false;
2529         // autocomplete
2530         this.$input.autocomplete({
2531             source: function(req, resp) {
2532                 self.get_search_result(req.term).then(function(result) {
2533                     resp(result);
2534                 });
2535             },
2536             select: function(event, ui) {
2537                 isSelecting = true;
2538                 var item = ui.item;
2539                 if (item.id) {
2540                     self.display_value = {};
2541                     self.display_value["" + item.id] = item.name;
2542                     self.set({value: item.id});
2543                 } else if (item.action) {
2544                     self.floating = true;
2545                     item.action();
2546                     return false;
2547                 }
2548             },
2549             focus: function(e, ui) {
2550                 e.preventDefault();
2551             },
2552             html: true,
2553             close: anyoneLoosesFocus,
2554             minLength: 0,
2555             delay: 0
2556         });
2557         this.$input.autocomplete("widget").addClass("openerp");
2558         // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2559         this.$input.keyup(function(e) {
2560             if (e.which === 13) {
2561                 if (isSelecting)
2562                     e.stopPropagation();
2563             }
2564             isSelecting = false;
2565         });
2566     },
2567
2568     render_value: function(no_recurse) {
2569         var self = this;
2570         if (! this.get("value")) {
2571             this.display_string("");
2572             return;
2573         }
2574         var display = this.display_value["" + this.get("value")];
2575         if (display) {
2576             this.display_string(display);
2577             return;
2578         }
2579         if (! no_recurse) {
2580             var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2581             dataset.name_get([self.get("value")], function(data) {
2582                 self.display_value["" + self.get("value")] = data[0][1];
2583                 self.render_value(true);
2584             });
2585         }
2586     },
2587     display_string: function(str) {
2588         var self = this;
2589         if (!this.get("effective_readonly")) {
2590             this.$input.val(str);
2591         } else {
2592             this.$element.find('a')
2593                  .unbind('click')
2594                  .text(str)
2595                  .click(function () {
2596                     self.do_action({
2597                         type: 'ir.actions.act_window',
2598                         res_model: self.field.relation,
2599                         res_id: self.get("value"),
2600                         context: self.build_context(),
2601                         views: [[false, 'form']],
2602                         target: 'current'
2603                     });
2604                     return false;
2605                  });
2606         }
2607     },
2608     set_value: function(value_) {
2609         var self = this;
2610         if (value_ instanceof Array) {
2611             this.display_value = {};
2612             this.display_value["" + value_[0]] = value_[1];
2613             value_ = value_[0];
2614         }
2615         value_ = value_ || false;
2616         this.inhibit_on_change = true;
2617         this._super(value_);
2618         this.inhibit_on_change = false;
2619     },
2620     add_id: function(id) {
2621         this.display_value = {};
2622         this.set({value: id});
2623     },
2624     is_false: function() {
2625         return ! this.get("value");
2626     },
2627     focus: function () {
2628         this.delay_focus(this.$input);
2629     }
2630 }));
2631
2632 /*
2633 # Values: (0, 0,  { fields })    create
2634 #         (1, ID, { fields })    update
2635 #         (2, ID)                remove (delete)
2636 #         (3, ID)                unlink one (target id or target of relation)
2637 #         (4, ID)                link
2638 #         (5)                    unlink all (only valid for one2many)
2639 */
2640 var commands = {
2641     // (0, _, {values})
2642     CREATE: 0,
2643     'create': function (values) {
2644         return [commands.CREATE, false, values];
2645     },
2646     // (1, id, {values})
2647     UPDATE: 1,
2648     'update': function (id, values) {
2649         return [commands.UPDATE, id, values];
2650     },
2651     // (2, id[, _])
2652     DELETE: 2,
2653     'delete': function (id) {
2654         return [commands.DELETE, id, false];
2655     },
2656     // (3, id[, _]) removes relation, but not linked record itself
2657     FORGET: 3,
2658     'forget': function (id) {
2659         return [commands.FORGET, id, false];
2660     },
2661     // (4, id[, _])
2662     LINK_TO: 4,
2663     'link_to': function (id) {
2664         return [commands.LINK_TO, id, false];
2665     },
2666     // (5[, _[, _]])
2667     DELETE_ALL: 5,
2668     'delete_all': function () {
2669         return [5, false, false];
2670     },
2671     // (6, _, ids) replaces all linked records with provided ids
2672     REPLACE_WITH: 6,
2673     'replace_with': function (ids) {
2674         return [6, false, ids];
2675     }
2676 };
2677 instance.web.form.FieldOne2Many = instance.web.form.AbstractField.extend({
2678     multi_selection: false,
2679     disable_utility_classes: true,
2680     init: function(field_manager, node) {
2681         this._super(field_manager, node);
2682         lazy_build_o2m_kanban_view();
2683         this.is_loaded = $.Deferred();
2684         this.initial_is_loaded = this.is_loaded;
2685         this.is_setted = $.Deferred();
2686         this.form_last_update = $.Deferred();
2687         this.init_form_last_update = this.form_last_update;
2688     },
2689     start: function() {
2690         this._super.apply(this, arguments);
2691
2692         var self = this;
2693
2694         this.dataset = new instance.web.form.One2ManyDataSet(this, this.field.relation);
2695         this.dataset.o2m = this;
2696         this.dataset.parent_view = this.view;
2697         this.dataset.child_name = this.name;
2698         //this.dataset.child_name = 
2699         this.dataset.on_change.add_last(function() {
2700             self.trigger_on_change();
2701         });
2702
2703         this.is_setted.then(function() {
2704             self.load_views();
2705         });
2706         this.is_loaded.then(function() {
2707             self.on("change:effective_readonly", self, function() {
2708                 self.is_loaded = self.is_loaded.pipe(function() {
2709                     self.viewmanager.destroy();
2710                     return $.when(self.load_views()).then(function() {
2711                         self.reload_current_view();
2712                     });
2713                 });
2714             });
2715         });
2716     },
2717     trigger_on_change: function() {
2718         var tmp = this.doing_on_change;
2719         this.doing_on_change = true;
2720         this.trigger('changed_value');
2721         this.doing_on_change = tmp;
2722     },
2723     load_views: function() {
2724         var self = this;
2725         
2726         var modes = this.node.attrs.mode;
2727         modes = !!modes ? modes.split(",") : ["tree"];
2728         var views = [];
2729         _.each(modes, function(mode) {
2730             var view = {
2731                 view_id: false,
2732                 view_type: mode == "tree" ? "list" : mode,
2733                 options: {}
2734             };
2735             if (self.field.views && self.field.views[mode]) {
2736                 view.embedded_view = self.field.views[mode];
2737             }
2738             if(view.view_type === "list") {
2739                 view.options.selectable = self.multi_selection;
2740                 if (self.get("effective_readonly")) {
2741                     view.options.addable = null;
2742                     view.options.deletable = null;
2743                 }
2744             } else if (view.view_type === "form") {
2745                 if (self.get("effective_readonly")) {
2746                     view.view_type = 'form';
2747                 }
2748                 view.options.not_interactible_on_create = true;
2749             } else if (view.view_type === "kanban") {
2750                 if (self.get("effective_readonly")) {
2751                     view.options.action_buttons = false;
2752                     view.options.quick_creatable = false;
2753                 }
2754             }
2755             views.push(view);
2756         });
2757         this.views = views;
2758
2759         this.viewmanager = new instance.web.form.One2ManyViewManager(this, this.dataset, views, {});
2760         this.viewmanager.o2m = self;
2761         var once = $.Deferred().then(function() {
2762             self.init_form_last_update.resolve();
2763         });
2764         var def = $.Deferred().then(function() {
2765             self.initial_is_loaded.resolve();
2766         });
2767         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2768             controller.o2m = self;
2769             if (view_type == "list") {
2770                 if (self.get("effective_readonly"))
2771                     controller.set_editable(false);
2772             } else if (view_type === "form") {
2773                 if (self.get("effective_readonly")) {
2774                     $(".oe_form_buttons", controller.$element).children().remove();
2775                 }
2776                 controller.on_record_loaded.add_last(function() {
2777                     once.resolve();
2778                 });
2779                 controller.on_pager_action.add_first(function() {
2780                     self.save_any_view();
2781                 });
2782             } else if (view_type == "graph") {
2783                 self.reload_current_view()
2784             }
2785             def.resolve();
2786         });
2787         this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2788             $.when(self.save_any_view()).then(function() {
2789                 if(n_mode === "list")
2790                     $.async_when().then(function() {self.reload_current_view();});
2791             });
2792         });
2793         this.is_setted.then(function() {
2794             $.async_when().then(function () {
2795                 self.viewmanager.appendTo(self.$element);
2796             });
2797         });
2798         return def;
2799     },
2800     reload_current_view: function() {
2801         var self = this;
2802         return self.is_loaded = self.is_loaded.pipe(function() {
2803             var active_view = self.viewmanager.active_view;
2804             var view = self.viewmanager.views[active_view].controller;
2805             if(active_view === "list") {
2806                 return view.reload_content();
2807             } else if (active_view === "form") {
2808                 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2809                     self.dataset.index = 0;
2810                 }
2811                 var act = function() {
2812                     return view.do_show();
2813                 };
2814                 self.form_last_update = self.form_last_update.pipe(act, act);
2815                 return self.form_last_update;
2816             } else if (view.do_search) {
2817                 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2818             }
2819         }, undefined);
2820     },
2821     set_value: function(value_) {
2822         value_ = value_ || [];
2823         var self = this;
2824         this.dataset.reset_ids([]);
2825         if(value_.length >= 1 && value_[0] instanceof Array) {
2826             var ids = [];
2827             _.each(value_, function(command) {
2828                 var obj = {values: command[2]};
2829                 switch (command[0]) {
2830                     case commands.CREATE:
2831                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2832                         obj.defaults = {};
2833                         self.dataset.to_create.push(obj);
2834                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2835                         ids.push(obj.id);
2836                         return;
2837                     case commands.UPDATE:
2838                         obj['id'] = command[1];
2839                         self.dataset.to_write.push(obj);
2840                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2841                         ids.push(obj.id);
2842                         return;
2843                     case commands.DELETE:
2844                         self.dataset.to_delete.push({id: command[1]});
2845                         return;
2846                     case commands.LINK_TO:
2847                         ids.push(command[1]);
2848                         return;
2849                     case commands.DELETE_ALL:
2850                         self.dataset.delete_all = true;
2851                         return;
2852                 }
2853             });
2854             this._super(ids);
2855             this.dataset.set_ids(ids);
2856         } else if (value_.length >= 1 && typeof(value_[0]) === "object") {
2857             var ids = [];
2858             this.dataset.delete_all = true;
2859             _.each(value_, function(command) {
2860                 var obj = {values: command};
2861                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2862                 obj.defaults = {};
2863                 self.dataset.to_create.push(obj);
2864                 self.dataset.cache.push(_.clone(obj));
2865                 ids.push(obj.id);
2866             });
2867             this._super(ids);
2868             this.dataset.set_ids(ids);
2869         } else {
2870             this._super(value_);
2871             this.dataset.reset_ids(value_);
2872         }
2873         if (this.dataset.index === null && this.dataset.ids.length > 0) {
2874             this.dataset.index = 0;
2875         }
2876         self.is_setted.resolve();
2877         return self.reload_current_view();
2878     },
2879     get_value: function() {
2880         var self = this;
2881         if (!this.dataset)
2882             return [];
2883         this.save_any_view();
2884         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2885         val = val.concat(_.map(this.dataset.ids, function(id) {
2886             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2887             if (alter_order) {
2888                 return commands.create(alter_order.values);
2889             }
2890             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2891             if (alter_order) {
2892                 return commands.update(alter_order.id, alter_order.values);
2893             }
2894             return commands.link_to(id);
2895         }));
2896         return val.concat(_.map(
2897             this.dataset.to_delete, function(x) {
2898                 return commands['delete'](x.id);}));
2899     },
2900     save_any_view: function() {
2901         if (this.doing_on_change)
2902             return false;
2903         return this.session.synchronized_mode(_.bind(function() {
2904                 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2905                     this.viewmanager.views[this.viewmanager.active_view] &&
2906                     this.viewmanager.views[this.viewmanager.active_view].controller) {
2907                     var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2908                     if (this.viewmanager.active_view === "form") {
2909                         if (!view.is_initialized.isResolved()) {
2910                             return false;
2911                         }
2912                         var res = $.when(view.do_save());
2913                         if (!res.isResolved() && !res.isRejected()) {
2914                             console.warn("Asynchronous get_value() is not supported in form view.");
2915                         }
2916                         return res;
2917                     } else if (this.viewmanager.active_view === "list") {
2918                         var res = $.when(view.ensure_saved());
2919                         if (!res.isResolved() && !res.isRejected()) {
2920                             console.warn("Asynchronous get_value() is not supported in list view.");
2921                         }
2922                         return res;
2923                     }
2924                 }
2925                 return false;
2926             }, this));
2927     },
2928     is_syntax_valid: function() {
2929         if (!this.viewmanager.views[this.viewmanager.active_view])
2930             return true;
2931         var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2932         if (this.viewmanager.active_view === "form") {
2933             for (var f in view.fields) {
2934                 f = view.fields[f];
2935                 if (!f.is_valid()) {
2936                     return false;
2937                 }
2938             }
2939         }
2940         return true;
2941     },
2942 });
2943
2944 instance.web.form.One2ManyViewManager = instance.web.ViewManager.extend({
2945     template: 'One2Many.viewmanager',
2946     init: function(parent, dataset, views, flags) {
2947         this._super(parent, dataset, views, _.extend({}, flags, {$sidebar: false}));
2948         this.registry = this.registry.extend({
2949             list: 'instance.web.form.One2ManyListView',
2950             form: 'instance.web.form.One2ManyFormView',
2951             kanban: 'instance.web.form.One2ManyKanbanView',
2952         });
2953     },
2954     switch_view: function(mode, unused) {
2955         if (mode !== 'form') {
2956             return this._super(mode, unused);
2957         }
2958         var self = this;
2959         var id = self.o2m.dataset.index !== null ? self.o2m.dataset.ids[self.o2m.dataset.index] : null;
2960         var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
2961         pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2962             title: _t("Open: ") + self.name,
2963             create_function: function(data) {
2964                 return self.o2m.dataset.create(data).then(function(r) {
2965                     self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2966                     self.o2m.dataset.on_change();
2967                 });
2968             },
2969             write_function: function(id, data, options) {
2970                 return self.o2m.dataset.write(id, data, {}).then(function() {
2971                     self.o2m.reload_current_view();
2972                 });
2973             },
2974             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2975             parent_view: self.o2m.view,
2976             child_name: self.o2m.name,
2977             read_function: function() {
2978                 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2979             },
2980             form_view_options: {'not_interactible_on_create':true},
2981             readonly: self.o2m.get("effective_readonly")
2982         });
2983         pop.on_select_elements.add_last(function() {
2984             self.o2m.reload_current_view();
2985         });
2986     },
2987 });
2988
2989 instance.web.form.One2ManyDataSet = instance.web.BufferedDataSet.extend({
2990     get_context: function() {
2991         this.context = this.o2m.build_context([this.o2m.name]);
2992         return this.context;
2993     }
2994 });
2995
2996 instance.web.form.One2ManyListView = instance.web.ListView.extend({
2997     _template: 'One2Many.listview',
2998     do_add_record: function () {
2999         if (this.options.editable) {
3000             this._super.apply(this, arguments);
3001         } else {
3002             var self = this;
3003             var pop = new instance.web.form.SelectCreatePopup(this);
3004             pop.select_element(
3005                 self.o2m.field.relation,
3006                 {
3007                     title: _t("Create: ") + self.name,
3008                     initial_view: "form",
3009                     alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3010                     create_function: function(data, callback, error_callback) {
3011                         return self.o2m.dataset.create(data).then(function(r) {
3012                             self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
3013                             self.o2m.dataset.on_change();
3014                         }).then(callback, error_callback);
3015                     },
3016                     read_function: function() {
3017                         return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3018                     },
3019                     parent_view: self.o2m.view,
3020                     child_name: self.o2m.name,
3021                     form_view_options: {'not_interactible_on_create':true}
3022                 },
3023                 self.o2m.build_domain(),
3024                 self.o2m.build_context()
3025             );
3026             pop.on_select_elements.add_last(function() {
3027                 self.o2m.reload_current_view();
3028             });
3029         }
3030     },
3031     do_activate_record: function(index, id) {
3032         var self = this;
3033         var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
3034         pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
3035             title: _t("Open: ") + self.name,
3036             write_function: function(id, data) {
3037                 return self.o2m.dataset.write(id, data, {}, function(r) {
3038                     self.o2m.reload_current_view();
3039                 });
3040             },
3041             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3042             parent_view: self.o2m.view,
3043             child_name: self.o2m.name,
3044             read_function: function() {
3045                 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3046             },
3047             form_view_options: {'not_interactible_on_create':true},
3048             readonly: self.o2m.get("effective_readonly")
3049         });
3050     },
3051     do_button_action: function (name, id, callback) {
3052         var self = this;
3053         var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
3054         return this._super(name, id, _.bind(def.resolve, def));
3055     }
3056 });
3057
3058 instance.web.form.One2ManyFormView = instance.web.FormView.extend({
3059     form_template: 'One2Many.formview',
3060     on_loaded: function(data) {
3061         this._super(data);
3062         var self = this;
3063         this.$buttons.find('button.oe_form_button_create').click(function() {
3064             self.do_save().then(self.on_button_new);
3065         });
3066     },
3067     do_notify_change: function() {
3068         if (this.dataset.parent_view) {
3069             this.dataset.parent_view.do_notify_change();
3070         } else {
3071             this._super.apply(this, arguments);
3072         }
3073     }
3074 });
3075
3076 var lazy_build_o2m_kanban_view = function() {
3077 if (! instance.web_kanban || instance.web.form.One2ManyKanbanView)
3078     return;
3079 instance.web.form.One2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3080 });
3081 }
3082
3083 instance.web.form.FieldMany2ManyTags = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin,
3084                                                                                        instance.web.form.ReinitializeFieldMixin, {
3085     template: "FieldMany2ManyTags",
3086     init: function() {
3087         this._super.apply(this, arguments);
3088         instance.web.form.CompletionFieldMixin.init.call(this);
3089         this.set({"value": []});
3090         this._display_orderer = new instance.web.DropMisordered();
3091         this._drop_shown = false;
3092     },
3093     start: function() {
3094         this._super();
3095         instance.web.form.ReinitializeFieldMixin.start.call(this);
3096         this.on("change:value", this, this.render_value);
3097     },
3098     initialize_content: function() {
3099         if (this.get("effective_readonly"))
3100             return;
3101         var self = this;
3102         self. $text = $("textarea", this.$element);
3103         self.$text.textext({
3104             plugins : 'tags arrow autocomplete',
3105             autocomplete: {
3106                 render: function(suggestion) {
3107                     return $('<span class="text-label"/>').
3108                              data('index', suggestion['index']).html(suggestion['label']);
3109                 }
3110             },
3111             ext: {
3112                 autocomplete: {
3113                     selectFromDropdown: function() {
3114                         $(this).trigger('hideDropdown');
3115                         var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3116                         var data = self.search_result[index];
3117                         if (data.id) {
3118                             self.add_id(data.id);
3119                         } else {
3120                             data.action();
3121                         }
3122                     },
3123                 },
3124                 tags: {
3125                     isTagAllowed: function(tag) {
3126                         if (! tag.name)
3127                             return false;
3128                         return true;
3129                     },
3130                     removeTag: function(tag) {
3131                         var id = tag.data("id");
3132                         self.set({"value": _.without(self.get("value"), id)});
3133                     },
3134                     renderTag: function(stuff) {
3135                         return $.fn.textext.TextExtTags.prototype.renderTag.
3136                             call(this, stuff).data("id", stuff.id);
3137                     },
3138                 },
3139                 itemManager: {
3140                     itemToString: function(item) {
3141                         return item.name;
3142                     },
3143                 },
3144             },
3145         }).bind('getSuggestions', function(e, data) {
3146             var _this = this;
3147             var str = !!data ? data.query || '' : '';
3148             self.get_search_result(str).then(function(result) {
3149                 self.search_result = result;
3150                 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3151                     return _.extend(el, {index:i});
3152                 })});
3153             });
3154         }).bind('tagClick', function(e, tag, value, callback) {
3155             var pop = new instance.web.form.FormOpenPopup(self.view);
3156             pop.show_element(
3157                 self.field.relation,
3158                 value.id,
3159                 self.build_context(),
3160                 {
3161                     title: _t("Open: ") + (self.string || self.name)
3162                 }
3163             );
3164             pop.on_write_completed.add_last(function() {
3165                 self.render_value();
3166             });
3167         }).bind('hideDropdown', function() {
3168             self._drop_shown = false;
3169         }).bind('showDropdown', function() {
3170             self._drop_shown = true;
3171         });
3172         self.tags = self.$text.textext()[0].tags();
3173         $("textarea", this.$element).focusout(function() {
3174             $("textarea", this.$element).val("");
3175         }).keydown(function(e) {
3176             if (event.keyCode === 9 && self._drop_shown) {
3177                 self.$text.textext()[0].autocomplete().selectFromDropdown();
3178             }
3179         });
3180     },
3181     set_value: function(value_) {
3182         value_ = value_ || [];
3183         if (value_.length >= 1 && value_[0] instanceof Array) {
3184             value_ = value_[0][2];
3185         }
3186         this._super(value_);
3187     },
3188     get_value: function() {
3189         var tmp = [commands.replace_with(this.get("value"))];
3190         return tmp;
3191     },
3192     get_search_blacklist: function() {
3193         return this.get("value");
3194     },
3195     render_value: function() {
3196         var self = this;
3197         var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
3198         var handle_names = function(data) {
3199             var indexed = {};
3200             _.each(data, function(el) {
3201                 indexed[el[0]] = el;
3202             });
3203             data = _.map(self.get("value"), function(el) { return indexed[el]; });
3204             if (! self.get("effective_readonly")) {
3205                 self.tags.containerElement().children().remove();
3206                 $("textarea", self.$element).css("padding-left", "3px");
3207                 self.tags.addTags(_.map(data, function(el) {return {name: el[1], id:el[0]};}));
3208             } else {
3209                 self.$element.html(QWeb.render("FieldMany2ManyTags.box", {elements: data}));
3210                 $(".oe_form_field_many2manytags_box", self.$element).click(function() {
3211                     var index = Number($(this).data("index"));
3212                     self.do_action({
3213                         type: 'ir.actions.act_window',
3214                         res_model: self.field.relation,
3215                         res_id: self.get("value")[index],
3216                         context: self.build_context(),
3217                         views: [[false, 'form']],
3218                         target: 'current'
3219                     });
3220                 });
3221             }
3222         };
3223         if (! self.get('values') || self.get('values').length > 0) {
3224             this._display_orderer.add(dataset.name_get(self.get("value"))).then(handle_names);
3225         } else {
3226             handle_names([]);
3227         }
3228     },
3229     add_id: function(id) {
3230         this.set({'value': _.uniq(this.get('value').concat([id]))});
3231     },
3232 }));
3233
3234 /*
3235  * TODO niv: clean those deferred stuff, it could be better
3236  */
3237 instance.web.form.FieldMany2Many = instance.web.form.AbstractField.extend({
3238     multi_selection: false,
3239     disable_utility_classes: true,
3240     init: function(field_manager, node) {
3241         this._super(field_manager, node);
3242         this.is_loaded = $.Deferred();
3243         this.initial_is_loaded = this.is_loaded;
3244         this.is_setted = $.Deferred();
3245     },
3246     start: function() {
3247         this._super.apply(this, arguments);
3248
3249         var self = this;
3250
3251         this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3252         this.dataset.m2m = this;
3253         this.dataset.on_unlink.add_last(function(ids) {
3254             self.dataset_changed();
3255         });
3256         
3257         this.is_setted.then(function() {
3258             self.load_view();
3259         });
3260         this.is_loaded.then(function() {
3261             self.on("change:effective_readonly", self, function() {
3262                 self.is_loaded = self.is_loaded.pipe(function() {
3263                     self.list_view.destroy();
3264                     return $.when(self.load_view()).then(function() {
3265                         self.reload_content();
3266                     });
3267                 });
3268             });
3269         })
3270     },
3271     set_value: function(value_) {
3272         value_ = value_ || [];
3273         if (value_.length >= 1 && value_[0] instanceof Array) {
3274             value_ = value_[0][2];
3275         }
3276         this._super(value_);
3277         this.dataset.set_ids(value_);
3278         var self = this;
3279         self.reload_content();
3280         this.is_setted.resolve();
3281     },
3282     load_view: function() {
3283         var self = this;
3284         this.list_view = new instance.web.form.Many2ManyListView(this, this.dataset, false, {
3285                     'addable': self.get("effective_readonly") ? null : _t("Add"),
3286                     'deletable': self.get("effective_readonly") ? false : true,
3287                     'selectable': self.multi_selection,
3288             });
3289         var embedded = (this.field.views || {}).tree;
3290         if (embedded) {
3291             this.list_view.set_embedded_view(embedded);
3292         }
3293         this.list_view.m2m_field = this;
3294         var loaded = $.Deferred();
3295         this.list_view.on_loaded.add_last(function() {
3296             self.initial_is_loaded.resolve();
3297             loaded.resolve();
3298         });
3299         $.async_when().then(function () {
3300             self.list_view.appendTo(self.$element);
3301         });
3302         return loaded;
3303     },
3304     reload_content: function() {
3305         var self = this;
3306         this.is_loaded = this.is_loaded.pipe(function() {
3307             return self.list_view.reload_content();
3308         });
3309     },
3310     dataset_changed: function() {
3311         this.set({'value': [commands.replace_with(this.dataset.ids)]});
3312     },
3313 });
3314
3315 instance.web.form.Many2ManyDataSet = instance.web.DataSetStatic.extend({
3316     get_context: function() {
3317         this.context = this.m2m.build_context();
3318         return this.context;
3319     }
3320 });
3321
3322 /**
3323  * @class
3324  * @extends instance.web.ListView
3325  */
3326 instance.web.form.Many2ManyListView = instance.web.ListView.extend(/** @lends instance.web.form.Many2ManyListView# */{
3327     do_add_record: function () {
3328         var pop = new instance.web.form.SelectCreatePopup(this);
3329         pop.select_element(
3330             this.model,
3331             {
3332                 title: _t("Add: ") + this.name
3333             },
3334             new instance.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
3335             this.m2m_field.build_context()
3336         );
3337         var self = this;
3338         pop.on_select_elements.add(function(element_ids) {
3339             _.each(element_ids, function(one_id) {
3340                 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3341                     self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3342                     self.m2m_field.dataset_changed();
3343                     self.reload_content();
3344                 }
3345             });
3346         });
3347     },
3348     do_activate_record: function(index, id) {
3349         var self = this;
3350         var pop = new instance.web.form.FormOpenPopup(this);
3351         pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
3352             title: _t("Open: ") + this.name,
3353             readonly: this.getParent().get("effective_readonly")
3354         });
3355         pop.on_write_completed.add_last(function() {
3356             self.reload_content();
3357         });
3358     }
3359 });
3360
3361 instance.web.form.FieldMany2ManyKanban = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin, {
3362     disable_utility_classes: true,
3363     init: function(field_manager, node) {
3364         this._super(field_manager, node);
3365         instance.web.form.CompletionFieldMixin.init.call(this);
3366         m2m_kanban_lazy_init();
3367         this.is_loaded = $.Deferred();
3368         this.initial_is_loaded = this.is_loaded;
3369         this.is_setted = $.Deferred();
3370     },
3371     start: function() {
3372         this._super.apply(this, arguments);
3373
3374         var self = this;
3375
3376         this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3377         this.dataset.m2m = this;
3378         this.dataset.on_unlink.add_last(function(ids) {
3379             self.dataset_changed();
3380         });
3381         
3382         this.is_setted.then(function() {
3383             self.load_view();
3384         });
3385         this.is_loaded.then(function() {
3386             self.on("change:effective_readonly", self, function() {
3387                 self.is_loaded = self.is_loaded.pipe(function() {
3388                     self.kanban_view.destroy();
3389                     return $.when(self.load_view()).then(function() {
3390                         self.reload_content();
3391                     });
3392                 });
3393             });
3394         })
3395     },
3396     set_value: function(value_) {
3397         value_ = value_ || [];
3398         if (value_.length >= 1 && value_[0] instanceof Array) {
3399             value_ = value_[0][2];
3400         }
3401         this._super(value_);
3402         this.dataset.set_ids(value_);
3403         var self = this;
3404         self.reload_content();
3405         this.is_setted.resolve();
3406     },
3407     load_view: function() {
3408         var self = this;
3409         this.kanban_view = new instance.web.form.Many2ManyKanbanView(this, this.dataset, false, {
3410                     'create_text': _t("Add"),
3411                     'creatable': self.get("effective_readonly") ? false : true,
3412                     'quick_creatable': self.get("effective_readonly") ? false : true,
3413             });
3414         var embedded = (this.field.views || {}).kanban;
3415         if (embedded) {
3416             this.kanban_view.set_embedded_view(embedded);
3417         }
3418         this.kanban_view.m2m = this;
3419         var loaded = $.Deferred();
3420         this.kanban_view.on_loaded.add_last(function() {
3421             self.initial_is_loaded.resolve();
3422             loaded.resolve();
3423         });
3424         this.kanban_view.do_switch_view.add_last(_.bind(this.open_popup, this));
3425         $.async_when().then(function () {
3426             self.kanban_view.appendTo(self.$element);
3427         });
3428         return loaded;
3429     },
3430     reload_content: function() {
3431         var self = this;
3432         this.is_loaded = this.is_loaded.pipe(function() {
3433             return self.kanban_view.do_search(self.build_domain(), self.dataset.get_context(), []);
3434         });
3435     },
3436     dataset_changed: function() {
3437         this.set({'value': [commands.replace_with(this.dataset.ids)]});
3438     },
3439     open_popup: function(type, unused) {
3440         if (type !== "form")
3441             return;
3442         var self = this;
3443         if (this.dataset.index === null) {
3444             var pop = new instance.web.form.SelectCreatePopup(this);
3445             pop.select_element(
3446                 this.field.relation,
3447                 {
3448                     title: _t("Add: ") + this.name
3449                 },
3450                 new instance.web.CompoundDomain(this.build_domain(), ["!", ["id", "in", this.dataset.ids]]),
3451                 this.build_context()
3452             );
3453             pop.on_select_elements.add(function(element_ids) {
3454                 _.each(element_ids, function(one_id) {
3455                     if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3456                         self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3457                         self.dataset_changed();
3458                         self.reload_content();
3459                     }
3460                 });
3461             });
3462         } else {
3463             var id = self.dataset.ids[self.dataset.index];
3464             var pop = new instance.web.form.FormOpenPopup(self.view);
3465             pop.show_element(self.field.relation, id, self.build_context(), {
3466                 title: _t("Open: ") + self.name,
3467                 write_function: function(id, data, options) {
3468                     return self.dataset.write(id, data, {}).then(function() {
3469                         self.reload_content();
3470                     });
3471                 },
3472                 alternative_form_view: self.field.views ? self.field.views["form"] : undefined,
3473                 parent_view: self.view,
3474                 child_name: self.name,
3475                 readonly: self.get("effective_readonly")
3476             });
3477         }
3478     },
3479     add_id: function(id) {
3480         this.quick_create.add_id(id);
3481     },
3482 }));
3483
3484 function m2m_kanban_lazy_init() {
3485 if (instance.web.form.Many2ManyKanbanView)
3486     return;
3487 instance.web.form.Many2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3488     quick_create_class: 'instance.web.form.Many2ManyQuickCreate',
3489     _is_quick_create_enabled: function() {
3490         return this._super() && ! this.group_by;
3491     },
3492 });
3493 instance.web.form.Many2ManyQuickCreate = instance.web.Widget.extend({
3494     template: 'Many2ManyKanban.quick_create',
3495     
3496     /**
3497      * close_btn: If true, the widget will display a "Close" button able to trigger
3498      * a "close" event.
3499      */
3500     init: function(parent, dataset, context, buttons) {
3501         this._super(parent);
3502         this.m2m = this.getParent().view.m2m;
3503         this.m2m.quick_create = this;
3504         this._dataset = dataset;
3505         this._buttons = buttons || false;
3506         this._context = context || {};
3507     },
3508     start: function () {
3509         var self = this;
3510         self.$text = this.$element.find('input').css("width", "200px");
3511         self.$text.textext({
3512             plugins : 'arrow autocomplete',
3513             autocomplete: {
3514                 render: function(suggestion) {
3515                     return $('<span class="text-label"/>').
3516                              data('index', suggestion['index']).html(suggestion['label']);
3517                 }
3518             },
3519             ext: {
3520                 autocomplete: {
3521                     selectFromDropdown: function() {
3522                         $(this).trigger('hideDropdown');
3523                         var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3524                         var data = self.search_result[index];
3525                         if (data.id) {
3526                             self.add_id(data.id);
3527                         } else {
3528                             data.action();
3529                         }
3530                     },
3531                 },
3532                 itemManager: {
3533                     itemToString: function(item) {
3534                         return item.name;
3535                     },
3536                 },
3537             },
3538         }).bind('getSuggestions', function(e, data) {
3539             var _this = this;
3540             var str = !!data ? data.query || '' : '';
3541             self.m2m.get_search_result(str).then(function(result) {
3542                 self.search_result = result;
3543                 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3544                     return _.extend(el, {index:i});
3545                 })});
3546             });
3547         });
3548         self.$text.focusout(function() {
3549             self.$text.val("");
3550         });
3551     },
3552     focus: function() {
3553         this.$text.focus();
3554     },
3555     add_id: function(id) {
3556         var self = this;
3557         self.$text.val("");
3558         self.trigger('added', id);
3559     },
3560 });
3561 }
3562
3563 /**
3564  * Class with everything which is common between FormOpenPopup and SelectCreatePopup.
3565  */
3566 instance.web.form.AbstractFormPopup = instance.web.OldWidget.extend({
3567     template: "AbstractFormPopup.render",
3568     /**
3569      *  options:
3570      *  -readonly: only applicable when not in creation mode, default to false
3571      * - alternative_form_view
3572      * - write_function
3573      * - read_function
3574      * - create_function
3575      * - parent_view
3576      * - child_name
3577      * - form_view_options
3578      */
3579     init_popup: function(model, row_id, domain, context, options) {
3580         this.row_id = row_id;
3581         this.model = model;
3582         this.domain = domain || [];
3583         this.context = context || {};
3584         this.options = options;
3585         _.defaults(this.options, {
3586         });
3587     },
3588     init_dataset: function() {
3589         var self = this;
3590         this.created_elements = [];
3591         this.dataset = new instance.web.ProxyDataSet(this, this.model, this.context);
3592         this.dataset.read_function = this.options.read_function;
3593         this.dataset.create_function = function(data, sup) {
3594             var fct = self.options.create_function || sup;
3595             return fct.call(this, data).then(function(r) {
3596                 self.created_elements.push(r.result);
3597             });
3598         };
3599         this.dataset.write_function = function(id, data, options, sup) {
3600             var fct = self.options.write_function || sup;
3601             return fct.call(this, id, data, options).then(self.on_write_completed);
3602         };
3603         this.dataset.parent_view = this.options.parent_view;
3604         this.dataset.child_name = this.options.child_name;
3605     },
3606     display_popup: function() {
3607         var self = this;
3608         this.renderElement();
3609         new instance.web.Dialog(this, {
3610             width: '90%',
3611             min_width: '800px',
3612             close: function() {
3613                 self.check_exit();
3614             },
3615             title: this.options.title || "",
3616         }, this.$element).open();
3617         this.start();
3618     },
3619     on_write_completed: function() {},
3620     setup_form_view: function() {
3621         var self = this;
3622         if (this.row_id) {
3623             this.dataset.ids = [this.row_id];
3624             this.dataset.index = 0;
3625         } else {
3626             this.dataset.index = null;
3627         }
3628         var options = _.clone(self.options.form_view_options) || {};
3629         if (this.row_id !== null) {
3630             options.initial_mode = this.options.readonly ? "view" : "edit";
3631         }
3632         this.view_form = new instance.web.FormView(this, this.dataset, false, options);
3633         if (this.options.alternative_form_view) {
3634             this.view_form.set_embedded_view(this.options.alternative_form_view);
3635         }
3636         this.view_form.appendTo(this.$element.find(".oe-form-view-popup-form-placeholder"));
3637         this.view_form.on_loaded.add_last(function() {
3638             var $buttons = self.view_form.$element.find(".oe_form_buttons");
3639             var multi_select = self.row_id === null && ! self.options.disable_multiple_selection;
3640             $buttons.html(QWeb.render("AbstractFormPopup.buttons", {multi_select: multi_select}));
3641             var $snbutton = $buttons.find(".oe_abstractformpopup-form-save-new");
3642             $snbutton.click(function() {
3643                 $.when(self.view_form.do_save()).then(function() {
3644                     self.view_form.reload_mutex.exec(function() {
3645                         self.view_form.on_button_new();
3646                     });
3647                 });
3648             });
3649             var $sbutton = $buttons.find(".oe_abstractformpopup-form-save");
3650             $sbutton.click(function() {
3651                 $.when(self.view_form.do_save()).then(function() {
3652                     self.view_form.reload_mutex.exec(function() {
3653                         self.check_exit();
3654                     });
3655                 });
3656             });
3657             var $cbutton = $buttons.find(".oe_abstractformpopup-form-close");
3658             $cbutton.click(function() {
3659                 self.check_exit();
3660             });
3661             if (self.row_id !== null && self.options.readonly) {
3662                 $snbutton.hide();
3663                 $sbutton.hide();
3664                 $cbutton.text(_t("Close"));
3665             }
3666             self.view_form.do_show();
3667         });
3668     },
3669     on_select_elements: function(element_ids) {
3670     },
3671     check_exit: function() {
3672         if (this.created_elements.length > 0) {
3673             this.on_select_elements(this.created_elements);
3674         }
3675         this.destroy();
3676     },
3677     destroy: function () {
3678         this.$element.dialog('close');
3679         this._super();
3680     },
3681 });
3682
3683 /**
3684  * Class to display a popup containing a form view.
3685  */
3686 instance.web.form.FormOpenPopup = instance.web.form.AbstractFormPopup.extend({
3687     show_element: function(model, row_id, context, options) {
3688         this.init_popup(model, row_id, [], context,  options);
3689         _.defaults(this.options, {
3690         });
3691         this.display_popup();
3692     },
3693     start: function() {
3694         this._super();
3695         this.init_dataset();
3696         this.setup_form_view();
3697     },
3698 });
3699
3700 /**
3701  * Class to display a popup to display a list to search a row. It also allows
3702  * to switch to a form view to create a new row.
3703  */
3704 instance.web.form.SelectCreatePopup = instance.web.form.AbstractFormPopup.extend({
3705     /**
3706      * options:
3707      * - initial_ids
3708      * - initial_view: form or search (default search)
3709      * - disable_multiple_selection
3710      * - list_view_options
3711      */
3712     select_element: function(model, options, domain, context) {
3713         this.init_popup(model, null, domain, context, options);
3714         var self = this;
3715         _.defaults(this.options, {
3716             initial_view: "search",
3717         });
3718         this.initial_ids = this.options.initial_ids;
3719         this.display_popup();
3720     },
3721     start: function() {
3722         var self = this;
3723         this.init_dataset();
3724         if (this.options.initial_view == "search") {
3725             self.rpc('/web/session/eval_domain_and_context', {
3726                 domains: [],
3727                 contexts: [this.context]
3728             }, function (results) {
3729                 var search_defaults = {};
3730                 _.each(results.context, function (value_, key) {
3731                     var match = /^search_default_(.*)$/.exec(key);
3732                     if (match) {
3733                         search_defaults[match[1]] = value_;
3734                     }
3735                 });
3736                 self.setup_search_view(search_defaults);
3737             });
3738         } else { // "form"
3739             this.new_object();
3740         }
3741     },
3742     setup_search_view: function(search_defaults) {
3743         var self = this;
3744         if (this.searchview) {
3745             this.searchview.destroy();
3746         }
3747         this.searchview = new instance.web.SearchView(this,
3748                 this.dataset, false,  search_defaults);
3749         this.searchview.on_search.add(function(domains, contexts, groupbys) {
3750             if (self.initial_ids) {
3751                 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
3752                     contexts, groupbys);
3753                 self.initial_ids = undefined;
3754             } else {
3755                 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
3756             }
3757         });
3758         this.searchview.on_loaded.add_last(function () {
3759             self.view_list = new instance.web.form.SelectCreateListView(self,
3760                     self.dataset, false,
3761                     _.extend({'deletable': false,
3762                         'selectable': !self.options.disable_multiple_selection
3763                     }, self.options.list_view_options || {}));
3764             self.view_list.popup = self;
3765             self.view_list.appendTo($(".oe-select-create-popup-view-list", self.$element)).pipe(function() {
3766                 self.view_list.do_show();
3767             }).pipe(function() {
3768                 self.searchview.do_search();
3769             });
3770             self.view_list.on_loaded.add_last(function() {
3771                 var $buttons = self.view_list.$element.find(".oe-actions");
3772                 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
3773                 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
3774                 $cbutton.click(function() {
3775                     self.destroy();
3776                 });
3777                 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
3778                 if(self.options.disable_multiple_selection) {
3779                     $sbutton.hide();
3780                 }
3781                 $sbutton.click(function() {
3782                     self.on_select_elements(self.selected_ids);
3783                     self.destroy();
3784                 });
3785             });
3786         });
3787         this.searchview.appendTo($(".oe-select-create-popup-view-list", self.$element));
3788     },
3789     do_search: function(domains, contexts, groupbys) {
3790         var self = this;
3791         this.rpc('/web/session/eval_domain_and_context', {
3792             domains: domains || [],
3793             contexts: contexts || [],
3794             group_by_seq: groupbys || []
3795         }, function (results) {
3796             self.view_list.do_search(results.domain, results.context, results.group_by);
3797         });
3798     },
3799     on_click_element: function(ids) {
3800         this.selected_ids = ids || [];
3801         if(this.selected_ids.length > 0) {
3802             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
3803         } else {
3804             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
3805         }
3806     },
3807     new_object: function() {
3808         if (this.searchview) {
3809             this.searchview.hide();
3810         }
3811         if (this.view_list) {
3812             this.view_list.$element.hide();
3813         }
3814         this.setup_form_view();
3815     },
3816 });
3817
3818 instance.web.form.SelectCreateListView = instance.web.ListView.extend({
3819     do_add_record: function () {
3820         this.popup.new_object();
3821     },
3822     select_record: function(index) {
3823         this.popup.on_select_elements([this.dataset.ids[index]]);
3824         this.popup.destroy();
3825     },
3826     do_select: function(ids, records) {
3827         this._super(ids, records);
3828         this.popup.on_click_element(ids);
3829     }
3830 });
3831
3832 instance.web.form.FieldReference = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3833     template: 'FieldReference',
3834     init: function(field_manager, node) {
3835         this._super(field_manager, node);
3836         this.reference_ready = true;
3837     },
3838     on_nop: function() {
3839     },
3840     on_selection_changed: function() {
3841         if (this.reference_ready) {
3842             var sel = this.selection.get_value();
3843             this.m2o.field.relation = sel;
3844             this.m2o.set_value(false);
3845             this.m2o.$element.toggle(sel !== false);
3846         }
3847     },
3848     destroy_content: function() {
3849         if (this.selection) {
3850             this.selection.destroy();
3851             this.selection = undefined;
3852         }
3853         if (this.m2o) {
3854             this.m2o.destroy();
3855             this.m2o = undefined;
3856         }
3857     },
3858     initialize_content: function() {
3859         this.selection = new instance.web.form.FieldSelection(this, { attrs: {
3860             name: 'selection'
3861         }});
3862         this.selection.view = this.view;
3863         this.selection.set({force_readonly: this.get('effective_readonly')});
3864         this.selection.on("change:value", this, this.on_selection_changed);
3865         this.selection.$element = $(".oe_form_view_reference_selection", this.$element);
3866         this.selection.renderElement();
3867         this.selection.start();
3868
3869         this.m2o = new instance.web.form.FieldMany2One(this, { attrs: {
3870             name: 'm2o'
3871         }});
3872         this.m2o.view = this.view;
3873         this.m2o.set({force_readonly: this.get("effective_readonly")});
3874         this.m2o.on("change:value", this, this.data_changed);
3875         this.m2o.$element = $(".oe_form_view_reference_m2o", this.$element);
3876         this.m2o.renderElement();
3877         this.m2o.start();
3878     },
3879     is_false: function() {
3880         return typeof(this.get_value()) !== 'string';
3881     },
3882     set_value: function(value_) {
3883         this._super(value_);
3884         this.render_value();
3885     },
3886     render_value: function() {
3887         this.reference_ready = false;
3888         var vals = [], sel_val, m2o_val;
3889         if (typeof(this.get('value')) === 'string') {
3890             vals = this.get('value').split(',');
3891         }
3892         sel_val = vals[0] || false;
3893         m2o_val = vals[1] ? parseInt(vals[1], 10) : vals[1];
3894         if (!this.get("effective_readonly")) {
3895             this.selection.set_value(sel_val);
3896         }
3897         this.m2o.field.relation = sel_val;
3898         this.m2o.set_value(m2o_val);
3899         this.reference_ready = true;
3900     },
3901     data_changed: function() {
3902         var model = this.selection.get_value(),
3903             id = this.m2o.get_value();
3904         if (typeof(model) === 'string' && typeof(id) === 'number') {
3905             this.set({'value': model + ',' + id});
3906         } else {
3907             this.set({'value': false});
3908         }
3909     },
3910     get_field: function(name) {
3911         if (name === "selection") {
3912             return {
3913                 selection: this.view.fields_view.fields[this.name].selection,
3914                 type: "selection",
3915             };
3916         } else if (name === "m2o") {
3917             return {
3918                 relation: null,
3919                 type: "many2one",
3920             };
3921         }
3922         throw Exception("Should not happen");
3923     },
3924 }));
3925
3926 instance.web.form.FieldBinary = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3927     init: function(field_manager, node) {
3928         this._super(field_manager, node);
3929         this.iframe = this.element_id + '_iframe';
3930         this.binary_value = false;
3931     },
3932     initialize_content: function() {
3933         this.$element.find('input.oe-binary-file').change(this.on_file_change);
3934         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3935         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3936     },
3937     human_filesize : function(size) {
3938         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3939         var i = 0;
3940         while (size >= 1024) {
3941             size /= 1024;
3942             ++i;
3943         }
3944         return size.toFixed(2) + ' ' + units[i];
3945     },
3946     on_file_change: function(e) {
3947         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3948         // http://www.html5rocks.com/tutorials/file/dndfiles/
3949         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3950         window[this.iframe] = this.on_file_uploaded;
3951         if ($(e.target).val() != '') {
3952             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3953             this.$element.find('form.oe-binary-form').submit();
3954             this.$element.find('.oe-binary-progress').show();
3955             this.$element.find('.oe-binary').hide();
3956         }
3957     },
3958     on_file_uploaded: function(size, name, content_type, file_base64) {
3959         delete(window[this.iframe]);
3960         if (size === false) {
3961             this.do_warn("File Upload", "There was a problem while uploading your file");
3962             // TODO: use openerp web crashmanager
3963             console.warn("Error while uploading file : ", name);
3964         } else {
3965             this.on_file_uploaded_and_valid.apply(this, arguments);
3966         }
3967         this.$element.find('.oe-binary-progress').hide();
3968         this.$element.find('.oe-binary').show();
3969     },
3970     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3971     },
3972     on_save_as: function() {
3973         $.blockUI();
3974         this.session.get_file({
3975             url: '/web/binary/saveas_ajax',
3976             data: {data: JSON.stringify({
3977                 model: this.view.dataset.model,
3978                 id: (this.view.datarecord.id || ''),
3979                 field: this.name,
3980                 filename_field: (this.node.attrs.filename || ''),
3981                 context: this.view.dataset.get_context()
3982             })},
3983             complete: $.unblockUI,
3984             error: instance.webclient.crashmanager.on_rpc_error
3985         });
3986     },
3987     on_clear: function() {
3988         if (this.get('value') !== false) {
3989             this.binary_value = false;
3990             this.set({'value': false});
3991         }
3992         return false;
3993     }
3994 }));
3995
3996 instance.web.form.FieldBinaryFile = instance.web.form.FieldBinary.extend({
3997     template: 'FieldBinaryFile',
3998     initialize_content: function() {
3999         this._super();
4000         if (this.get("effective_readonly")) {
4001             var self = this;
4002             this.$element.find('a').click(function() {
4003                 if (self.get('value')) {
4004                     self.on_save_as();
4005                 }
4006                 return false;
4007             });
4008         }
4009     },
4010     set_value: function(value_) {
4011         this._super.apply(this, arguments);
4012         this.render_value();
4013     },
4014     render_value: function() {
4015         if (!this.get("effective_readonly")) {
4016             var show_value;
4017             if (this.node.attrs.filename) {
4018                 show_value = this.view.datarecord[this.node.attrs.filename] || '';
4019             } else {
4020                 show_value = (this.get('value') != null && this.get('value') !== false) ? this.get('value') : '';
4021             }
4022             this.$element.find('input').eq(0).val(show_value);
4023         } else {
4024             this.$element.find('a').show(!!this.get('value'));
4025             if (this.get('value')) {
4026                 var show_value = _t("Download") + " " + (this.view.datarecord[this.node.attrs.filename] || '');
4027                 this.$element.find('a').text(show_value);
4028             }
4029         }
4030     },
4031     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4032         this.binary_value = true;
4033         this.set({'value': file_base64});
4034         var show_value = name + " (" + this.human_filesize(size) + ")";
4035         this.$element.find('input').eq(0).val(show_value);
4036         this.set_filename(name);
4037     },
4038     set_filename: function(value_) {
4039         var filename = this.node.attrs.filename;
4040         if (this.view.fields[filename]) {
4041             this.view.fields[filename].set({value: value_});
4042         }
4043     },
4044     on_clear: function() {
4045         this._super.apply(this, arguments);
4046         this.$element.find('input').eq(0).val('');
4047         this.set_filename('');
4048     }
4049 });
4050
4051 instance.web.form.FieldBinaryImage = instance.web.form.FieldBinary.extend({
4052     template: 'FieldBinaryImage',
4053     initialize_content: function() {
4054         this._super();
4055         this.$placeholder = $(".oe_form_field-binary-image-placeholder", this.$element);
4056         if (!this.get("effective_readonly"))
4057             this.$element.find('.oe-binary').show();
4058         else
4059             this.$element.find('.oe-binary').hide();
4060     },
4061     set_value: function(value_) {
4062         this._super.apply(this, arguments);
4063         this.render_value();
4064     },
4065     render_value: function() {
4066         var url;
4067         if (this.get('value') && this.get('value').substr(0, 10).indexOf(' ') == -1) {
4068             url = 'data:image/png;base64,' + this.get('value');
4069         } else if (this.get('value')) {
4070             url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
4071                 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
4072         } else {
4073             url = "/web/static/src/img/placeholder.png";
4074         }
4075         var rendered = QWeb.render("FieldBinaryImage-img", {widget: this, url: url});;
4076         this.$placeholder.html(rendered);
4077     },
4078     on_file_change: function() {
4079         this.render_value();
4080         this._super.apply(this, arguments);
4081     },
4082     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4083         this.set({'value': file_base64});
4084         this.binary_value = true;
4085         this.render_value();
4086     },
4087     on_clear: function() {
4088         this._super.apply(this, arguments);
4089         this.render_value();
4090     }
4091 });
4092
4093 instance.web.form.FieldStatus = instance.web.form.AbstractField.extend({
4094     tagName: "span",
4095     start: function() {
4096         this._super();
4097         this.selected_value = null;
4098         // preview in start only for selection fields, because of the dynamic behavior of many2one fields.
4099         if (this.field.type in ['selection']) {
4100             this.render_list();
4101         }
4102     },
4103     set_value: function(value_) {
4104         var self = this;
4105         this._super(value_);
4106         // find selected value:
4107         // - many2one: [2, "New"] -> 2
4108         // - selection: new -> new
4109         if (this.field.type == "many2one") {
4110             this.selected_value = value_[0];
4111         } else {
4112             this.selected_value = value_;
4113         }
4114         // trick to be sure all values are loaded in the form, therefore
4115         // enabling the evaluation of dynamic domains
4116         $.async_when().then(function() {
4117             return self.render_list();
4118         });
4119     },
4120
4121     /** Get the status list and render them
4122      *  to_show: [[identifier, value_to_display]] where
4123      *   - identifier = key for a selection, id for a many2one
4124      *   - display_val = label that will be displayed
4125      *   - ex: [[0, "New"]] (many2one) or [["new", "In Progress"]] (selection)
4126      */
4127     render_list: function() {
4128         var self = this;
4129         // get selection values, filter them and render them
4130         var selection_done = this.get_selection().pipe(self.proxy('filter_selection')).pipe(self.proxy('render_elements'));
4131     },
4132
4133     /** Get the selection list to be displayed in the statusbar widget.
4134      *  For selection fields: this is directly given by this.field.selection
4135      *  For many2one fields :
4136      *  - perform a search on the relation of the many2one field (given by
4137      *    field.relation )
4138      *  - get the field domain for the search
4139      *    - self.build_domain() gives the domain given by the view or by
4140      *      the field
4141      *    - if the optional statusbar_fold attribute is set to true, make
4142      *      an AND with build_domain to hide all 'fold=true' columns
4143      *    - make an OR with current value, to be sure it is displayed,
4144      *      with the correct order, even if it is folded
4145      */
4146     get_selection: function() {
4147         var self = this;
4148         if (this.field.type == "many2one") {
4149             this.selection = [];
4150             // get fold information from widget
4151             var fold = ((this.node.attrs || {}).statusbar_fold || true);
4152             // build final domain: if fold option required, add the 
4153             if (fold == true) {
4154                 var domain = new instance.web.CompoundDomain(['|'], ['&'], self.build_domain(), [['fold', '=', false]], [['id', '=', self.selected_value]]);
4155             } else {
4156                 var domain = new instance.web.CompoundDomain(['|'], self.build_domain(), [['id', '=', self.selected_value]]);
4157             }
4158             // get a DataSetSearch on the current field relation (ex: crm.lead.stage_id -> crm.case.stage)
4159             var model_ext = new instance.web.DataSetSearch(this, this.field.relation, self.build_context(), domain);
4160             // fetch selection
4161             var read_defer = model_ext.read_slice(['name'], {}).pipe( function (records) {
4162                 _(records).each(function (record) {
4163                     self.selection.push([record.id, record.name]);
4164                 });
4165             });
4166         } else {
4167             this.selection = this.field.selection;
4168             var read_defer = new $.Deferred().resolve();
4169         }
4170         return read_defer;
4171     },
4172
4173     /** Filters this.selection, according to values coming from the statusbar_visible
4174      *  attribute of the field. For example: statusbar_visible="draft,open"
4175      *  Currently, the key of (key, label) pairs has to be used in the
4176      *  selection of visible items. This feature is not meant to be used
4177      *  with many2one fields.
4178      */
4179     filter_selection: function() {
4180         var self = this;
4181         var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
4182             function(x) { return _.str.trim(x); });
4183         shown = _.select(shown, function(x) { return x.length > 0; });
4184         
4185         if (shown.length == 0) {
4186             this.to_show = this.selection;
4187         } else {
4188             this.to_show = _.select(this.selection, function(x) {
4189                 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
4190             });
4191         }
4192     },
4193
4194     /** Renders the widget. This function also checks for statusbar_colors='{"pending": "blue"}'
4195      *  attribute in the widget. This allows to set a given color to a given
4196      *  state (given by the key of (key, label)).
4197      */
4198     render_elements: function () {
4199         var content = instance.web.qweb.render("FieldStatus.content", {widget: this, _:_});
4200         this.$element.html(content);
4201
4202         var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
4203         var color = colors[this.selected_value];
4204         if (color) {
4205             var elem = this.$element.find("li.oe_form_steps_active span");
4206             elem.css("color", color);
4207         }
4208     },
4209 });
4210
4211 /**
4212  * Registry of form fields, called by :js:`instance.web.FormView`.
4213  *
4214  * All referenced classes must implement FieldMixin. Those represent the classes whose instances
4215  * will substitute to the <field> tags as defined in OpenERP's views.
4216  */
4217 instance.web.form.widgets = new instance.web.Registry({
4218     'char' : 'instance.web.form.FieldChar',
4219     'id' : 'instance.web.form.FieldID',
4220     'email' : 'instance.web.form.FieldEmail',
4221     'url' : 'instance.web.form.FieldUrl',
4222     'text' : 'instance.web.form.FieldText',
4223     'date' : 'instance.web.form.FieldDate',
4224     'datetime' : 'instance.web.form.FieldDatetime',
4225     'selection' : 'instance.web.form.FieldSelection',
4226     'many2one' : 'instance.web.form.FieldMany2One',
4227     'many2many' : 'instance.web.form.FieldMany2Many',
4228     'many2many_tags' : 'instance.web.form.FieldMany2ManyTags',
4229     'many2many_kanban' : 'instance.web.form.FieldMany2ManyKanban',
4230     'one2many' : 'instance.web.form.FieldOne2Many',
4231     'one2many_list' : 'instance.web.form.FieldOne2Many',
4232     'reference' : 'instance.web.form.FieldReference',
4233     'boolean' : 'instance.web.form.FieldBoolean',
4234     'float' : 'instance.web.form.FieldFloat',
4235     'integer': 'instance.web.form.FieldFloat',
4236     'float_time': 'instance.web.form.FieldFloat',
4237     'progressbar': 'instance.web.form.FieldProgressBar',
4238     'image': 'instance.web.form.FieldBinaryImage',
4239     'binary': 'instance.web.form.FieldBinaryFile',
4240     'statusbar': 'instance.web.form.FieldStatus'
4241 });
4242
4243 /**
4244  * Registry of widgets usable in the form view that can substitute to any possible
4245  * tags defined in OpenERP's form views.
4246  *
4247  * Every referenced class should extend FormWidget.
4248  */
4249 instance.web.form.tags = new instance.web.Registry({
4250     'button' : 'instance.web.form.WidgetButton',
4251 });
4252
4253 };
4254
4255 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: