[ADD] Add class on oe_form when no <sheet> is present
[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         if ($form.find('> sheet').length == 0) {
1008             $form.addClass('oe_form_nosheet');
1009         }
1010         var $new_form = this.render_element('FormRenderingForm', $form.getAttributes());
1011         this.handle_common_properties($new_form, $form);
1012         $form.contents().appendTo($new_form);
1013         if ($form[0] === this.$form[0]) {
1014             // If root element, replace it
1015             this.$form = $new_form;
1016         } else {
1017             $form.before($new_form).remove();
1018         }
1019         this.process($new_form);
1020     },
1021     /*
1022      * Used by direct <field> children of a <group> tag only
1023      * This method will add the implicit <label...> for every field
1024      * in the <group>
1025     */
1026     preprocess_field: function($field) {
1027         var self = this;
1028         var name = $field.attr('name'),
1029             field_colspan = parseInt($field.attr('colspan'), 10),
1030             field_modifiers = JSON.parse($field.attr('modifiers') || '{}');
1031
1032         if ($field.attr('nolabel') === '1')
1033             return;
1034         $field.attr('nolabel', '1');
1035         var found = false;
1036         this.$form.find('label[for="' + name + '"]').each(function(i ,el) {
1037             $(el).parents().each(function(unused, tag) {
1038                 var name = tag.tagName.toLowerCase();
1039                 if (name === "field" || name in self.tags_registry.map)
1040                     found = true;
1041             });
1042         });
1043         if (found)
1044             return;
1045
1046         $label = $('<label/>').attr({
1047             'for' : name,
1048             "modifiers": JSON.stringify({invisible: field_modifiers.invisible}),
1049             "string": $field.attr('string'),
1050             "help": $field.attr('help'),
1051         });
1052         $label.insertBefore($field);
1053         if (field_colspan > 1) {
1054             $field.attr('colspan', field_colspan - 1);
1055         }
1056         return $label;
1057     },
1058     process_field: function($field) {
1059         if ($field.parent().is('group')) {
1060             // No implicit labels for normal fields, only for <group> direct children
1061             var $label = this.preprocess_field($field);
1062             if ($label) {
1063                 this.process($label);
1064             }
1065         }
1066         this.fields_to_init.push($field);
1067         return $field;
1068     },
1069     process_group: function($group) {
1070         var self = this;
1071         $group.children('field').each(function() {
1072             self.preprocess_field($(this));
1073         });
1074         var $new_group = this.render_element('FormRenderingGroup', $group.getAttributes());
1075         var $table;
1076         if ($new_group.first().is('table.oe_form_group')) {
1077             $table = $new_group;
1078         } else if ($new_group.filter('table.oe_form_group').length) {
1079             $table = $new_group.filter('table.oe_form_group').first();
1080         } else {
1081             $table = $new_group.find('table.oe_form_group').first();
1082         }
1083
1084         var $tr, $td,
1085             cols = parseInt($group.attr('col') || 2, 10),
1086             row_cols = cols;
1087
1088         var children = [];
1089         $group.children().each(function(a,b,c) {
1090             var $child = $(this);
1091             var colspan = parseInt($child.attr('colspan') || 1, 10);
1092             var tagName = $child[0].tagName.toLowerCase();
1093             var $td = $('<td/>').addClass('oe_form_group_cell').attr('colspan', colspan);
1094             var newline = tagName === 'newline';
1095
1096             // Note FME: those classes are used in layout debug mode
1097             if ($tr && row_cols > 0 && (newline || row_cols < colspan)) {
1098                 $tr.addClass('oe_form_group_row_incomplete');
1099                 if (newline) {
1100                     $tr.addClass('oe_form_group_row_newline');
1101                 }
1102             }
1103             if (newline) {
1104                 $tr = null;
1105                 return;
1106             }
1107             if (!$tr || row_cols < colspan) {
1108                 $tr = $('<tr/>').addClass('oe_form_group_row').appendTo($table);
1109                 row_cols = cols;
1110             }
1111             row_cols -= colspan;
1112
1113             // invisibility transfer
1114             var field_modifiers = JSON.parse($child.attr('modifiers') || '{}');
1115             var invisible = field_modifiers.invisible;
1116             self.handle_common_properties($td, $("<dummy>").attr("modifiers", JSON.stringify({invisible: invisible})));
1117
1118             $tr.append($td.append($child));
1119             children.push($child[0]);
1120         });
1121         if (row_cols && $td) {
1122             $td.attr('colspan', parseInt($td.attr('colspan'), 10) + row_cols);
1123         }
1124         $group.before($new_group).remove();
1125
1126         $table.find('> tbody > tr').each(function() {
1127             var to_compute = [],
1128                 row_cols = cols,
1129                 total = 100;
1130             $(this).children().each(function() {
1131                 var $td = $(this),
1132                     $child = $td.children(':first');
1133                 switch ($child[0].tagName.toLowerCase()) {
1134                     case 'separator':
1135                         if ($child.attr('orientation') === 'vertical') {
1136                             $td.addClass('oe_vertical_separator').attr('width', '1');
1137                             $td.empty();
1138                             row_cols--;
1139                         }
1140                         break;
1141                     case 'label':
1142                         if ($child.attr('for')) {
1143                             $td.attr('width', '1%').addClass('oe_form_group_cell_label');
1144                             row_cols--;
1145                             total--;
1146                         }
1147                         break;
1148                     default:
1149                         var width = _.str.trim($child.attr('width') || ''),
1150                             iwidth = parseInt(width, 10);
1151                         if (iwidth) {
1152                             if (width.substr(-1) === '%') {
1153                                 total -= iwidth;
1154                                 width = iwidth + '%';
1155                             } else {
1156                                 // Absolute width
1157                                 $td.css('min-width', width + 'px');
1158                             }
1159                             $td.attr('width', width);
1160                             $child.removeAttr('width');
1161                             row_cols--;
1162                         } else {
1163                             to_compute.push($td);
1164                         }
1165
1166                 }
1167             });
1168             var unit = Math.floor(total / row_cols);
1169             if (!$(this).is('.oe_form_group_row_incomplete')) {
1170                 _.each(to_compute, function($td, i) {
1171                     var width = parseInt($td.attr('colspan'), 10) * unit;
1172                     $td.attr('width', ((i == to_compute.length - 1) ? total : width) + '%');
1173                     total -= width;
1174                 });
1175             }
1176         });
1177         _.each(children, function(el) {
1178             self.process($(el));
1179         });
1180         this.handle_common_properties($new_group, $group);
1181         return $new_group;
1182     },
1183     process_notebook: function($notebook) {
1184         var self = this;
1185         var pages = [];
1186         $notebook.find('> page').each(function() {
1187             var $page = $(this);
1188             var page_attrs = $page.getAttributes();
1189             page_attrs.id = _.uniqueId('notebook_page_');
1190             pages.push(page_attrs);
1191             var $new_page = self.render_element('FormRenderingNotebookPage', page_attrs);
1192             $page.contents().appendTo($new_page);
1193             $page.before($new_page).remove();
1194             self.handle_common_properties($new_page, $page);
1195         });
1196         var $new_notebook = this.render_element('FormRenderingNotebook', { pages : pages });
1197         $notebook.contents().appendTo($new_notebook);
1198         $notebook.before($new_notebook).remove();
1199         $new_notebook.children().each(function() {
1200             self.process($(this));
1201         });
1202         $new_notebook.tabs();
1203         this.handle_common_properties($new_notebook, $notebook);
1204         return $new_notebook;
1205     },
1206     process_separator: function($separator) {
1207         var $new_separator = this.render_element('FormRenderingSeparator', $separator.getAttributes());
1208         $separator.before($new_separator).remove();
1209         this.handle_common_properties($new_separator, $separator);
1210         return $new_separator;
1211     },
1212     process_label: function($label) {
1213         var name = $label.attr("for"),
1214             field_orm = this.fvg.fields[name];
1215         var dict = {
1216             string: $label.attr('string') || (field_orm || {}).string || '',
1217             help: $label.attr('help') || (field_orm || {}).help || '',
1218             _for: name ? _.uniqueId('oe-field-input-') : undefined,
1219         };
1220         var align = parseFloat(dict.align);
1221         if (isNaN(align) || align === 1) {
1222             align = 'right';
1223         } else if (align === 0) {
1224             align = 'left';
1225         } else {
1226             align = 'center';
1227         }
1228         dict.align = align;
1229         var $new_label = this.render_element('FormRenderingLabel', dict);
1230         $label.before($new_label).remove();
1231         this.handle_common_properties($new_label, $label);
1232         if (name) {
1233             this.labels[name] = $new_label;
1234         }
1235         return $new_label;
1236     },
1237     handle_common_properties: function($new_element, $node) {
1238         var str_modifiers = $node.attr("modifiers") || "{}"
1239         var modifiers = JSON.parse(str_modifiers);
1240         if (modifiers.invisible !== undefined)
1241             new instance.web.form.InvisibilityChanger(this.view, this.view, modifiers.invisible, $new_element);
1242         $new_element.addClass($node.attr("class") || "");
1243         $new_element.attr('style', $node.attr('style'));
1244     },
1245 });
1246
1247 instance.web.form.FormRenderingEngineReadonly = instance.web.form.FormRenderingEngine.extend({
1248     alter_field: function(field) {
1249         field.set({"force_readonly": true});
1250     },
1251 });
1252
1253 instance.web.form.FormDialog = instance.web.Dialog.extend({
1254     init: function(parent, options, view_id, dataset) {
1255         this._super(parent, options);
1256         this.dataset = dataset;
1257         this.view_id = view_id;
1258         return this;
1259     },
1260     start: function() {
1261         this._super();
1262         this.form = new instance.web.FormView(this, this.dataset, this.view_id, {
1263             pager: false
1264         });
1265         this.form.appendTo(this.$element);
1266         this.form.on_created.add_last(this.on_form_dialog_saved);
1267         this.form.on_saved.add_last(this.on_form_dialog_saved);
1268         return this;
1269     },
1270     select_id: function(id) {
1271         if (this.form.dataset.select_id(id)) {
1272             return this.form.do_show();
1273         } else {
1274             this.do_warn("Could not find id in dataset");
1275             return $.Deferred().reject();
1276         }
1277     },
1278     on_form_dialog_saved: function(r) {
1279         this.close();
1280     }
1281 });
1282
1283 instance.web.form.compute_domain = function(expr, fields) {
1284     var stack = [];
1285     for (var i = expr.length - 1; i >= 0; i--) {
1286         var ex = expr[i];
1287         if (ex.length == 1) {
1288             var top = stack.pop();
1289             switch (ex) {
1290                 case '|':
1291                     stack.push(stack.pop() || top);
1292                     continue;
1293                 case '&':
1294                     stack.push(stack.pop() && top);
1295                     continue;
1296                 case '!':
1297                     stack.push(!top);
1298                     continue;
1299                 default:
1300                     throw new Error(_.str.sprintf(
1301                         _t("Unknown operator %s in domain %s"),
1302                         ex, JSON.stringify(expr)));
1303             }
1304         }
1305
1306         var field = fields[ex[0]];
1307         if (!field) {
1308             throw new Error(_.str.sprintf(
1309                 _t("Unknown field %s in domain %s"),
1310                 ex[0], JSON.stringify(expr)));
1311         }
1312         var field_value = field.get_value ? field.get_value() : field.value;
1313         var op = ex[1];
1314         var val = ex[2];
1315
1316         switch (op.toLowerCase()) {
1317             case '=':
1318             case '==':
1319                 stack.push(field_value == val);
1320                 break;
1321             case '!=':
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 '>=':
1335                 stack.push(field_value >= val);
1336                 break;
1337             case 'in':
1338                 if (!_.isArray(val)) val = [val];
1339                 stack.push(_(val).contains(field_value));
1340                 break;
1341             case 'not in':
1342                 if (!_.isArray(val)) val = [val];
1343                 stack.push(!_(val).contains(field_value));
1344                 break;
1345             default:
1346                 console.warn(
1347                     _t("Unsupported operator %s in domain %s"),
1348                     op, JSON.stringify(expr));
1349         }
1350     }
1351     return _.all(stack, _.identity);
1352 };
1353
1354 /**
1355  * Must be applied over an class already possessing the PropertiesMixin.
1356  *
1357  * Apply the result of the "invisible" domain to this.$element.
1358  */
1359 instance.web.form.InvisibilityChangerMixin = {
1360     init: function(field_manager, invisible_domain) {
1361         this._ic_field_manager = field_manager
1362         this._ic_invisible_modifier = invisible_domain;
1363         this._ic_field_manager.on("view_content_has_changed", this, function() {
1364             var result = this._ic_invisible_modifier === undefined ? false :
1365                 instance.web.form.compute_domain(this._ic_invisible_modifier, this._ic_field_manager.fields);
1366             this.set({"invisible": result});
1367         });
1368         this.set({invisible: this._ic_invisible_modifier === true, force_invisible: false});
1369         var check = function() {
1370             if (this.get("invisible") || this.get('force_invisible')) {
1371                 this.set({"effective_invisible": true});
1372             } else {
1373                 this.set({"effective_invisible": false});
1374             }
1375         };
1376         this.on('change:invisible', this, check);
1377         this.on('change:force_invisible', this, check);
1378         _.bind(check, this)();
1379     },
1380     start: function() {
1381         var check_visibility = function() {
1382             if (this.get("effective_invisible")) {
1383                 this.$element.hide();
1384             } else {
1385                 this.$element.show();
1386             }
1387         };
1388         this.on("change:effective_invisible", this, check_visibility);
1389         _.bind(check_visibility, this)();
1390     },
1391 };
1392
1393 instance.web.form.InvisibilityChanger = instance.web.Class.extend(_.extend({}, instance.web.PropertiesMixin, instance.web.form.InvisibilityChangerMixin, {
1394     init: function(parent, field_manager, invisible_domain, $element) {
1395         this.setParent(parent);
1396         instance.web.PropertiesMixin.init.call(this);
1397         instance.web.form.InvisibilityChangerMixin.init.call(this, field_manager, invisible_domain);
1398         this.$element = $element;
1399         this.start();
1400     },
1401 }));
1402
1403 instance.web.form.FormWidget = instance.web.Widget.extend(_.extend({}, instance.web.form.InvisibilityChangerMixin, {
1404     /**
1405      * @constructs instance.web.form.FormWidget
1406      * @extends instance.web.Widget
1407      *
1408      * @param view
1409      * @param node
1410      */
1411     init: function(view, node) {
1412         this._super(view);
1413         this.view = view;
1414         this.node = node;
1415         this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
1416         instance.web.form.InvisibilityChangerMixin.init.call(this, view, this.modifiers.invisible);
1417
1418         this.view.on("view_content_has_changed", this, this.process_modifiers);
1419     },
1420     renderElement: function() {
1421         this._super();
1422         this.$element.addClass(this.node.attrs["class"] || "");
1423     },
1424     destroy: function() {
1425         $.fn.tipsy.clear();
1426         this._super.apply(this, arguments);
1427     },
1428     process_modifiers: function() {
1429         var compute_domain = instance.web.form.compute_domain;
1430         var to_set = {};
1431         for (var a in this.modifiers) {
1432             if (!_.include(["invisible"], a)) {
1433                 var val = compute_domain(this.modifiers[a], this.view.fields);
1434                 to_set[a] = val;
1435             }
1436         }
1437         this.set(to_set);
1438     },
1439     do_attach_tooltip: function(widget, trigger, options) {
1440         widget = widget || this;
1441         trigger = trigger || this.$element;
1442         options = _.extend({
1443                 delayIn: 500,
1444                 delayOut: 0,
1445                 fade: true,
1446                 title: function() {
1447                     var template = widget.template + '.tooltip';
1448                     if (!QWeb.has_template(template)) {
1449                         template = 'WidgetLabel.tooltip';
1450                     }
1451                     return QWeb.render(template, {
1452                         debug: instance.connection.debug,
1453                         widget: widget
1454                 })},
1455                 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
1456                 html: true,
1457                 opacity: 0.85,
1458                 trigger: 'hover'
1459             }, options || {});
1460         $(trigger).tipsy(options);
1461     },
1462     _build_view_fields_values: function(blacklist) {
1463         var a_dataset = this.view.dataset;
1464         var fields_values = this.view.get_fields_values(blacklist);
1465         var active_id = a_dataset.ids[a_dataset.index];
1466         _.extend(fields_values, {
1467             active_id: active_id || false,
1468             active_ids: active_id ? [active_id] : [],
1469             active_model: a_dataset.model,
1470             parent: {}
1471         });
1472         if (a_dataset.parent_view) {
1473                 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
1474         }
1475         return fields_values;
1476     },
1477     _build_eval_context: function(blacklist) {
1478         var a_dataset = this.view.dataset;
1479         return new instance.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
1480     },
1481     /**
1482      * Builds a new context usable for operations related to fields by merging
1483      * the fields'context with the action's context.
1484      */
1485     build_context: function(blacklist) {
1486         // only use the model's context if there is not context on the node
1487         var v_context = this.node.attrs.context;
1488         if (! v_context) {
1489             v_context = (this.field || {}).context || {};
1490         }
1491         
1492         if (v_context.__ref || true) { //TODO: remove true
1493             var fields_values = this._build_eval_context(blacklist);
1494             v_context = new instance.web.CompoundContext(v_context).set_eval_context(fields_values);
1495         }
1496         return v_context;
1497     },
1498     build_domain: function() {
1499         var f_domain = this.field.domain || [];
1500         var n_domain = this.node.attrs.domain || null;
1501         // if there is a domain on the node, overrides the model's domain
1502         var final_domain = n_domain !== null ? n_domain : f_domain;
1503         if (!(final_domain instanceof Array) || true) { //TODO: remove true
1504             var fields_values = this._build_eval_context();
1505             final_domain = new instance.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1506         }
1507         return final_domain;
1508     }
1509 }));
1510
1511 instance.web.form.WidgetButton = instance.web.form.FormWidget.extend({
1512     template: 'WidgetButton',
1513     init: function(view, node) {
1514         this._super(view, node);
1515         this.force_disabled = false;
1516         this.string = (this.node.attrs.string || '').replace(/_/g, '');
1517         if (this.node.attrs.default_focus == '1') {
1518             // TODO fme: provide enter key binding to widgets
1519             this.view.default_focus_button = this;
1520         }
1521         this.view.on('view_content_has_changed', this, this.check_disable);
1522     },
1523     start: function() {
1524         this._super.apply(this, arguments);
1525         this.$element.click(this.on_click);
1526         if (this.node.attrs.help || instance.connection.debug) {
1527             this.do_attach_tooltip();
1528         }
1529     },
1530     on_click: function() {
1531         var self = this;
1532         this.force_disabled = true;
1533         this.check_disable();
1534         this.execute_action().always(function() {
1535             self.force_disabled = false;
1536             self.check_disable();
1537         });
1538     },
1539     execute_action: function() {
1540         var self = this;
1541         var exec_action = function() {
1542             if (self.node.attrs.confirm) {
1543                 var def = $.Deferred();
1544                 var dialog = instance.web.dialog($('<div/>').text(self.node.attrs.confirm), {
1545                     title: _t('Confirm'),
1546                     modal: true,
1547                     buttons: [
1548                         {text: _t("Cancel"), click: function() {
1549                                 def.resolve();
1550                                 $(this).dialog("close");
1551                             }
1552                         },
1553                         {text: _t("Ok"), click: function() {
1554                                 self.on_confirmed().then(function() {
1555                                     def.resolve();
1556                                 });
1557                                 $(this).dialog("close");
1558                             }
1559                         }
1560                     ]
1561                 });
1562                 return def.promise();
1563             } else {
1564                 return self.on_confirmed();
1565             }
1566         };
1567         if (!this.node.attrs.special) {
1568             this.view.force_dirty = true;
1569             return this.view.recursive_save().pipe(exec_action);
1570         } else {
1571             return exec_action();
1572         }
1573     },
1574     on_confirmed: function() {
1575         var self = this;
1576
1577         var context = this.node.attrs.context;
1578         if (context && context.__ref) {
1579             context = new instance.web.CompoundContext(context);
1580             context.set_eval_context(this._build_eval_context());
1581         }
1582
1583         return this.view.do_execute_action(
1584             _.extend({}, this.node.attrs, {context: context}),
1585             this.view.dataset, this.view.datarecord.id, function () {
1586                 self.view.reload();
1587             });
1588     },
1589     check_disable: function() {
1590         var disabled = (this.force_disabled || !this.view.is_interactible_record());
1591         this.$element.prop('disabled', disabled);
1592         this.$element.css('color', disabled ? 'grey' : '');
1593     }
1594 });
1595
1596 /**
1597  * Interface to be implemented by fields.
1598  * 
1599  * Properties:
1600  *     - readonly: boolean. If set to true the field should appear in readonly mode.
1601  *     - force_readonly: boolean, When it is true, the field should always appear
1602  *      in read only mode, no matter what the value of the "readonly" property can be.
1603  * Events:
1604  *     - changed_value: triggered to inform the view to check on_changes
1605  * 
1606  */
1607 instance.web.form.FieldMixin = {
1608     /**
1609      * Constructor takes 2 arguments:
1610      * - field_manager: Implements FieldManagerMixin
1611      * - node: the "<field>" node in json form
1612      */
1613     init: function(field_manager, node) {},
1614     /**
1615      * Called by the form view to indicate the value of the field.
1616      * 
1617      * set_value() may return an object that can be passed to $.when() that represents the moment when
1618      * the field has finished all operations necessary before the user can effectively use the widget.
1619      * 
1620      * Multiple calls to set_value() can occur at any time and must be handled correctly by the implementation,
1621      * regardless of any asynchronous operation currently running and the status of any promise that a
1622      * previous call to set_value() could have returned.
1623      * 
1624      * set_value() must be able, at any moment, to handle the syntax returned by the "read" method of the
1625      * osv class in the OpenERP server as well as the syntax used by the set_value() (see below). It must
1626      * also be able to handle any other format commonly used in the _defaults key on the models in the addons
1627      * as well as any format commonly returned in a on_change. It must be able to autodetect those formats as
1628      * no information is ever given to know which format is used.
1629      */
1630     set_value: function(value_) {},
1631     /**
1632      * Get the current value of the widget.
1633      * 
1634      * Must always return a syntaxically correct value to be passed to the "write" method of the osv class in
1635      * the OpenERP server, although it is not assumed to respect the constraints applied to the field.
1636      * For example if the field is marqued as "required", a call to get_value() can return false.
1637      * 
1638      * get_value() can also be called *before* a call to set_value() and, in that case, is supposed to
1639      * return a defaut value according to the type of field.
1640      * 
1641      * This method is always assumed to perform synchronously, it can not return a promise.
1642      * 
1643      * If there was no user interaction to modify the value of the field, it is always assumed that
1644      * get_value() return the same semantic value than the one passed in the last call to set_value(),
1645      * altough the syntax can be different. This can be the case for type of fields that have a different
1646      * syntax for "read" and "write" (example: m2o: set_value([0, "Administrator"]), get_value() => 0).
1647      */
1648     get_value: function() {},
1649     /**
1650      * Inform the current object of the id it should use to match a html <label> that exists somewhere in the
1651      * view.
1652      */
1653     set_input_id: function(id) {},
1654     /**
1655      * Returns true if is_syntax_valid() returns true and the value is semantically
1656      * valid too according to the semantic restrictions applied to the field.
1657      */
1658     is_valid: function() {},
1659     /**
1660      * Returns true if the field holds a value which is syntaxically correct, ignoring
1661      * the potential semantic restrictions applied to the field.
1662      */
1663     is_syntax_valid: function() {},
1664     /**
1665      * Must set the focus on the field.
1666      */
1667     focus: function() {},
1668 };
1669
1670 /**
1671  * Abstract class for classes implementing FieldMixin.
1672  * 
1673  * Properties:
1674  *     - effective_readonly: when it is true, the widget is displayed as readonly. Vary depending
1675  *      the values of the "readonly" property and the "force_readonly" property on the field manager.
1676  *     - value: useful property to hold the value of the field. By default, set_value() and get_value()
1677  *     set and retrieve the value property. Changing the value property also triggers automatically
1678  *     a 'changed_value' event that inform the view to trigger on_changes.
1679  * 
1680  */
1681 instance.web.form.AbstractField = instance.web.form.FormWidget.extend(_.extend({}, instance.web.form.FieldMixin, {
1682     /**
1683      * @constructs instance.web.form.AbstractField
1684      * @extends instance.web.form.FormWidget
1685      *
1686      * @param field_manager
1687      * @param node
1688      */
1689     init: function(field_manager, node) {
1690         this._super(field_manager, node);
1691         this.field_manager = field_manager;
1692         this.name = this.node.attrs.name;
1693         this.set({'value': false});
1694         this.field = this.field_manager.get_field(this.name);
1695         this.set({required: this.modifiers['required'] === true});
1696         
1697         // some events to make the property "effective_readonly" sync automatically with "readonly" and
1698         // "force_readonly"
1699         this.set({"readonly": this.modifiers['readonly'] === true});
1700         var test_effective_readonly = function() {
1701             this.set({"effective_readonly": this.get("readonly") || !!this.get("force_readonly")});
1702         };
1703         this.on("change:readonly", this, test_effective_readonly);
1704         this.on("change:force_readonly", this, test_effective_readonly);
1705         _.bind(test_effective_readonly, this)();
1706         
1707         this.on("change:value", this, function() {
1708             if (! this._inhibit_on_change)
1709                 this.trigger('changed_value');
1710             this._check_css_flags();
1711         });
1712     },
1713     renderElement: function() {
1714         var self = this;
1715         this._super();
1716         if (this.field.translate) {
1717             this.$element.addClass('oe_form_field_translatable');
1718             this.$element.find('.oe_field_translate').click(_.bind(function() {
1719                 this.field_manager.open_translate_dialog(this);
1720             }, this));
1721         }
1722         this.$label = this.view.$element.find('label[for=' + this.id_for_label + ']');
1723         if (instance.connection.debug) {
1724             this.do_attach_tooltip(this, this.$label[0] || this.$element);
1725             this.$label.off('dblclick').on('dblclick', function() {
1726                 console.log("Field '%s' of type '%s' in View: %o", self.name, (self.node.attrs.widget || self.field.type), self.view);
1727                 window.w = self;
1728                 console.log("window.w =", window.w);
1729             });
1730         }
1731         if (!this.disable_utility_classes) {
1732             this.off("change:required", this, this._set_required);
1733             this.on("change:required", this, this._set_required);
1734             this._set_required();
1735         }
1736     },
1737     /**
1738      * Private. Do not use.
1739      */
1740     _set_required: function() {
1741         this.$element.toggleClass('oe_form_required', this.get("required"));
1742     },
1743     set_value: function(value_) {
1744         this._inhibit_on_change = true;
1745         this.set({'value': value_});
1746         this._inhibit_on_change = false;
1747     },
1748     get_value: function() {
1749         return this.get('value');
1750     },
1751     is_valid: function() {
1752         return this.is_syntax_valid() && (! this.get('required') || ! this.is_false());
1753     },
1754     is_syntax_valid: function() {
1755         return true;
1756     },
1757     /**
1758      * Method useful to implement to ease validity testing. Must return true if the current
1759      * value is similar to false in OpenERP.
1760      */
1761     is_false: function() {
1762         return this.get('value') === false;
1763     },
1764     _check_css_flags: function(show_invalid) {
1765         if (this.field.translate) {
1766             this.$element.find('.oe_field_translate').toggle(!this.field_manager.is_create_mode());
1767         }
1768         if (!this.disable_utility_classes) {
1769             if (this.field_manager.get('display_invalid_fields')) {
1770                 this.$element.toggleClass('oe_form_invalid', !this.is_valid());
1771             }
1772         }
1773     },
1774     focus: function() {
1775     },
1776     /**
1777      * Utility method to focus an element, but only after a small amount of time.
1778      */
1779     delay_focus: function($elem) {
1780         setTimeout(function() {
1781             $elem.focus();
1782         }, 50);
1783     },
1784     /**
1785      * Utility method to get the widget options defined in the field xml description.
1786      */
1787     get_definition_options: function() {
1788         if (!this.definition_options) {
1789             var str = this.node.attrs.options || '{}';
1790             this.definition_options = JSON.parse(str);
1791         }
1792         return this.definition_options;
1793     },
1794     set_input_id: function(id) {
1795         this.id_for_label = id;
1796     },
1797 }));
1798
1799 /**
1800  * A mixin to apply on any field that has to completely re-render when its readonly state
1801  * switch.
1802  */
1803 instance.web.form.ReinitializeFieldMixin =  {
1804     /**
1805      * Default implementation of start(), use it or call explicitly initialize_field().
1806      */
1807     start: function() {
1808         this._super();
1809         this.initialize_field();
1810     },
1811     initialize_field: function() {
1812         this.on("change:effective_readonly", this, function() {
1813             this.destroy_content();
1814             this.renderElement();
1815             this.initialize_content();
1816             this.render_value();
1817         });
1818         this.initialize_content();
1819         this.render_value();
1820     },
1821     /**
1822      * Called to destroy anything that could have been created previously, called before a
1823      * re-initialization.
1824      */
1825     destroy_content: function() {},
1826     /**
1827      * Called to initialize the content.
1828      */
1829     initialize_content: function() {},
1830     /**
1831      * Called to render the value. Should also be explicitly called at the end of a set_value().
1832      */
1833     render_value: function() {},
1834 };
1835
1836 instance.web.form.FieldChar = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
1837     template: 'FieldChar',
1838     widget_class: 'oe_form_field_char',
1839     init: function (field_manager, node) {
1840         this._super(field_manager, node);
1841         this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1842     },
1843     initialize_content: function() {
1844         var self = this;
1845         this.$element.find('input').change(function() {
1846             self.set({'value': instance.web.parse_value(self.$element.find('input').val(), self)});
1847         });
1848     },
1849     set_value: function(value_) {
1850         this._super(value_);
1851         this.render_value();
1852     },
1853     render_value: function() {
1854         var show_value = instance.web.format_value(this.get('value'), this, '');
1855         if (!this.get("effective_readonly")) {
1856             this.$element.find('input').val(show_value);
1857         } else {
1858             if (this.password) {
1859                 show_value = new Array(show_value.length + 1).join('*');
1860             }
1861             this.$element.text(show_value);
1862         }
1863     },
1864     is_syntax_valid: function() {
1865         if (!this.get("effective_readonly")) {
1866             try {
1867                 var value_ = instance.web.parse_value(this.$element.find('input').val(), this, '');
1868                 return true;
1869             } catch(e) {
1870                 return false;
1871             }
1872         }
1873         return true;
1874     },
1875     is_false: function() {
1876         return this.get('value') === '';
1877     },
1878     focus: function() {
1879         this.delay_focus(this.$element.find('input:first'));
1880     }
1881 }));
1882
1883 instance.web.form.FieldID = instance.web.form.FieldChar.extend({
1884     
1885 });
1886
1887 instance.web.form.FieldEmail = instance.web.form.FieldChar.extend({
1888     template: 'FieldEmail',
1889     initialize_content: function() {
1890         this._super();
1891         this.$element.find('button').click(this.on_button_clicked);
1892     },
1893     render_value: function() {
1894         if (!this.get("effective_readonly")) {
1895             this._super();
1896         } else {
1897             this.$element.find('a')
1898                     .attr('href', 'mailto:' + this.get('value'))
1899                     .text(this.get('value'));
1900         }
1901     },
1902     on_button_clicked: function() {
1903         if (!this.get('value') || !this.is_syntax_valid()) {
1904             this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1905         } else {
1906             location.href = 'mailto:' + this.get('value');
1907         }
1908     }
1909 });
1910
1911 instance.web.form.FieldUrl = instance.web.form.FieldChar.extend({
1912     template: 'FieldUrl',
1913     initialize_content: function() {
1914         this._super();
1915         this.$element.find('button').click(this.on_button_clicked);
1916     },
1917     render_value: function() {
1918         if (!this.get("effective_readonly")) {
1919             this._super();
1920         } else {
1921             var tmp = this.get('value');
1922             var s = /(\w+):(.+)/.exec(tmp);
1923             if (!s) {
1924                 tmp = "http://" + this.get('value');
1925             }
1926             this.$element.find('a').attr('href', tmp).text(tmp);
1927         }
1928     },
1929     on_button_clicked: function() {
1930         if (!this.get('value')) {
1931             this.do_warn("Resource error", "This resource is empty");
1932         } else {
1933             var url = $.trim(this.get('value'));
1934             if(/^www\./i.test(url))
1935                 url = 'http://'+url;
1936             window.open(url);
1937         }
1938     }
1939 });
1940
1941 instance.web.form.FieldFloat = instance.web.form.FieldChar.extend({
1942     is_field_number: true,
1943     widget_class: 'oe_form_field_float',
1944     init: function (field_manager, node) {
1945         this._super(field_manager, node);
1946         this.set({'value': 0});
1947         if (this.node.attrs.digits) {
1948             this.digits = py.eval(node.attrs.digits);
1949         } else {
1950             this.digits = this.field.digits;
1951         }
1952     },
1953     set_value: function(value_) {
1954         if (value_ === false || value_ === undefined) {
1955             // As in GTK client, floats default to 0
1956             value_ = 0;
1957         }
1958         this._super.apply(this, [value_]);
1959     }
1960 });
1961
1962 instance.web.DateTimeWidget = instance.web.OldWidget.extend({
1963     template: "web.datepicker",
1964     jqueryui_object: 'datetimepicker',
1965     type_of_date: "datetime",
1966     init: function(parent) {
1967         this._super(parent);
1968         this.name = parent.name;
1969     },
1970     start: function() {
1971         var self = this;
1972         this.$input = this.$element.find('input.oe_datepicker_master');
1973         this.$input_picker = this.$element.find('input.oe_datepicker_container');
1974         this.$input.change(this.on_change);
1975         this.picker({
1976             onSelect: this.on_picker_select,
1977             changeMonth: true,
1978             changeYear: true,
1979             showWeek: true,
1980             showButtonPanel: true
1981         });
1982         this.$element.find('img.oe_datepicker_trigger').click(function() {
1983             if (!self.get("effective_readonly") && !self.picker('widget').is(':visible')) {
1984                 self.picker('setDate', self.get('value') ? instance.web.auto_str_to_date(self.get('value')) : new Date());
1985                 self.$input_picker.show();
1986                 self.picker('show');
1987                 self.$input_picker.hide();
1988             }
1989         });
1990         this.set_readonly(false);
1991         this.set({'value': false});
1992     },
1993     picker: function() {
1994         return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1995     },
1996     on_picker_select: function(text, instance_) {
1997         var date = this.picker('getDate');
1998         this.$input.val(date ? this.format_client(date) : '').change();
1999     },
2000     set_value: function(value_) {
2001         this.set({'value': value_});
2002         this.$input.val(value_ ? this.format_client(value_) : '');
2003     },
2004     get_value: function() {
2005         return this.get('value');
2006     },
2007     set_value_from_ui_: function() {
2008         var value_ = this.$input.val() || false;
2009         this.set({'value': this.parse_client(value_)});
2010     },
2011     set_readonly: function(readonly) {
2012         this.readonly = readonly;
2013         this.$input.prop('readonly', this.readonly);
2014         this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
2015     },
2016     is_valid_: function() {
2017         var value_ = this.$input.val();
2018         if (value_ === "") {
2019             return true;
2020         } else {
2021             try {
2022                 this.parse_client(value_);
2023                 return true;
2024             } catch(e) {
2025                 return false;
2026             }
2027         }
2028     },
2029     parse_client: function(v) {
2030         return instance.web.parse_value(v, {"widget": this.type_of_date});
2031     },
2032     format_client: function(v) {
2033         return instance.web.format_value(v, {"widget": this.type_of_date});
2034     },
2035     on_change: function() {
2036         if (this.is_valid_()) {
2037             this.set_value_from_ui_();
2038         }
2039     }
2040 });
2041
2042 instance.web.DateWidget = instance.web.DateTimeWidget.extend({
2043     jqueryui_object: 'datepicker',
2044     type_of_date: "date"
2045 });
2046
2047 instance.web.form.FieldDatetime = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2048     template: "FieldDatetime",
2049     build_widget: function() {
2050         return new instance.web.DateTimeWidget(this);
2051     },
2052     destroy_content: function() {
2053         if (this.datewidget) {
2054             this.datewidget.destroy();
2055             this.datewidget = undefined;
2056         }
2057     },
2058     initialize_content: function() {
2059         if (!this.get("effective_readonly")) {
2060             this.datewidget = this.build_widget();
2061             this.datewidget.on_change.add_last(_.bind(function() {
2062                 this.set({'value': this.datewidget.get_value()});
2063             }, this));
2064             this.datewidget.appendTo(this.$element);
2065         }
2066     },
2067     set_value: function(value_) {
2068         this._super(value_);
2069         this.render_value();
2070     },
2071     render_value: function() {
2072         if (!this.get("effective_readonly")) {
2073             this.datewidget.set_value(this.get('value'));
2074         } else {
2075             this.$element.text(instance.web.format_value(this.get('value'), this, ''));
2076         }
2077     },
2078     is_syntax_valid: function() {
2079         if (!this.get("effective_readonly")) {
2080             return this.datewidget.is_valid_();
2081         }
2082         return true;
2083     },
2084     is_false: function() {
2085         return this.get('value') === '';
2086     },
2087     focus: function() {
2088         if (this.datewidget && this.datewidget.$input)
2089             this.delay_focus(this.datewidget.$input);
2090     }
2091 }));
2092
2093 instance.web.form.FieldDate = instance.web.form.FieldDatetime.extend({
2094     template: "FieldDate",
2095     build_widget: function() {
2096         return new instance.web.DateWidget(this);
2097     }
2098 });
2099
2100 instance.web.form.FieldText = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2101     template: 'FieldText',
2102     initialize_content: function() {
2103         this.$textarea = this.$element.find('textarea');
2104         if (!this.get("effective_readonly")) {
2105             this.$textarea.change(_.bind(function() {
2106                 this.set({'value': instance.web.parse_value(this.$textarea.val(), this)});
2107             }, this));
2108         } else {
2109             this.$textarea.attr('disabled', 'disabled');
2110         }
2111     },
2112     set_value: function(value_) {
2113         this._super.apply(this, arguments);
2114         this.render_value();
2115     },
2116     render_value: function() {
2117         var show_value = instance.web.format_value(this.get('value'), this, '');
2118         this.$textarea.val(show_value);
2119         if (show_value && this.view.options.resize_textareas) {
2120             this.do_resize(this.view.options.resize_textareas);
2121         }
2122     },
2123     is_syntax_valid: function() {
2124         if (!this.get("effective_readonly")) {
2125             try {
2126                 var value_ = instance.web.parse_value(this.$textarea.val(), this, '');
2127                 return true;
2128             } catch(e) {
2129                 return false;
2130             }
2131         }
2132         return true;
2133     },
2134     is_false: function() {
2135         return this.get('value') === '';
2136     },
2137     focus: function($element) {
2138         this.delay_focus(this.$textarea);
2139     },
2140     do_resize: function(max_height) {
2141         max_height = parseInt(max_height, 10);
2142         var $input = this.$textarea,
2143             $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
2144             new_height;
2145         $div.text($input.val());
2146         _.each('font-family,font-size,white-space'.split(','), function(style) {
2147             $div.css(style, $input.css(style));
2148         });
2149         $div.appendTo($('body'));
2150         new_height = $div.height();
2151         if (new_height < 90) {
2152             new_height = 90;
2153         }
2154         if (!isNaN(max_height) && new_height > max_height) {
2155             new_height = max_height;
2156         }
2157         $div.remove();
2158         $input.height(new_height);
2159     },
2160 }));
2161
2162 instance.web.form.FieldBoolean = instance.web.form.AbstractField.extend({
2163     template: 'FieldBoolean',
2164     start: function() {
2165         this._super.apply(this, arguments);
2166         this.$checkbox = $("input", this.$element);
2167         this.$element.click(_.bind(function() {
2168             this.set({'value': this.$checkbox.is(':checked')});
2169         }, this));
2170         var check_readonly = function() {
2171             this.$checkbox.prop('disabled', this.get("effective_readonly"));
2172         };
2173         this.on("change:effective_readonly", this, check_readonly);
2174         _.bind(check_readonly, this)();
2175     },
2176     set_value: function(value_) {
2177         this._super.apply(this, arguments);
2178         this.$checkbox[0].checked = value_;
2179     },
2180     focus: function() {
2181         this.delay_focus(this.$checkbox);
2182     }
2183 });
2184
2185 instance.web.form.FieldProgressBar = instance.web.form.AbstractField.extend({
2186     template: 'FieldProgressBar',
2187     start: function() {
2188         this._super.apply(this, arguments);
2189         this.$element.progressbar({
2190             value: this.get('value'),
2191             disabled: this.get("effective_readonly")
2192         });
2193     },
2194     set_value: function(value_) {
2195         this._super.apply(this, arguments);
2196         var show_value = Number(value_);
2197         if (isNaN(show_value)) {
2198             show_value = 0;
2199         }
2200         var formatted_value = instance.web.format_value(show_value, { type : 'float' }, '0');
2201         this.$element.progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
2202     }
2203 });
2204
2205 instance.web.form.FieldTextXml = instance.web.form.AbstractField.extend({
2206 // to replace view editor
2207 });
2208
2209 instance.web.form.FieldSelection = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
2210     template: 'FieldSelection',
2211     init: function(field_manager, node) {
2212         var self = this;
2213         this._super(field_manager, node);
2214         this.values = _.clone(this.field.selection);
2215         _.each(this.values, function(v, i) {
2216             if (v[0] === false && v[1] === '') {
2217                 self.values.splice(i, 1);
2218             }
2219         });
2220         this.values.unshift([false, '']);
2221     },
2222     initialize_content: function() {
2223         // Flag indicating whether we're in an event chain containing a change
2224         // event on the select, in order to know what to do on keyup[RETURN]:
2225         // * If the user presses [RETURN] as part of changing the value of a
2226         //   selection, we should just let the value change and not let the
2227         //   event broadcast further (e.g. to validating the current state of
2228         //   the form in editable list view, which would lead to saving the
2229         //   current row or switching to the next one)
2230         // * If the user presses [RETURN] with a select closed (side-effect:
2231         //   also if the user opened the select and pressed [RETURN] without
2232         //   changing the selected value), takes the action as validating the
2233         //   row
2234         var ischanging = false;
2235         this.$element.find('select')
2236             .change(_.bind(function() {
2237                 this.set({'value': this.values[this.$element.find('select')[0].selectedIndex][0]});
2238             }, this))
2239             .change(function () { ischanging = true; })
2240             .click(function () { ischanging = false; })
2241             .keyup(function (e) {
2242                 if (e.which !== 13 || !ischanging) { return; }
2243                 e.stopPropagation();
2244                 ischanging = false;
2245             });
2246     },
2247     set_value: function(value_) {
2248         value_ = value_ === null ? false : value_;
2249         value_ = value_ instanceof Array ? value_[0] : value_;
2250         this._super(value_);
2251         this.render_value();
2252     },
2253     render_value: function() {
2254         if (!this.get("effective_readonly")) {
2255             var index = 0;
2256             for (var i = 0, ii = this.values.length; i < ii; i++) {
2257                 if (this.values[i][0] === this.get('value')) index = i;
2258             }
2259             this.$element.find('select')[0].selectedIndex = index;
2260         } else {
2261             var self = this;
2262             var option = _(this.values)
2263                 .detect(function (record) { return record[0] === self.get('value'); }); 
2264             this.$element.text(option ? option[1] : this.values[0][1]);
2265         }
2266     },
2267     is_syntax_valid: function() {
2268         if (this.get("effective_readonly")) {
2269             return true;
2270         }
2271         var value_ = this.values[this.$element.find('select')[0].selectedIndex];
2272         return !! value_;
2273     },
2274     focus: function() {
2275         this.delay_focus(this.$element.find('select:first'));
2276     }
2277 }));
2278
2279 // jquery autocomplete tweak to allow html
2280 (function() {
2281     var proto = $.ui.autocomplete.prototype,
2282         initSource = proto._initSource;
2283
2284     function filter( array, term ) {
2285         var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
2286         return $.grep( array, function(value_) {
2287             return matcher.test( $( "<div>" ).html( value_.label || value_.value || value_ ).text() );
2288         });
2289     }
2290
2291     $.extend( proto, {
2292         _initSource: function() {
2293             if ( this.options.html && $.isArray(this.options.source) ) {
2294                 this.source = function( request, response ) {
2295                     response( filter( this.options.source, request.term ) );
2296                 };
2297             } else {
2298                 initSource.call( this );
2299             }
2300         },
2301
2302         _renderItem: function( ul, item) {
2303             return $( "<li></li>" )
2304                 .data( "item.autocomplete", item )
2305                 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
2306                 .appendTo( ul );
2307         }
2308     });
2309 })();
2310
2311 /**
2312  * A mixin containing some useful methods to handle completion inputs.
2313  */
2314 instance.web.form.CompletionFieldMixin = {
2315     init: function() {
2316         this.limit = 7;
2317         this.orderer = new instance.web.DropMisordered();
2318     },
2319     /**
2320      * Call this method to search using a string.
2321      */
2322     get_search_result: function(search_val) {
2323         var self = this;
2324
2325         var dataset = new instance.web.DataSet(this, this.field.relation, self.build_context());
2326         var blacklist = this.get_search_blacklist();
2327
2328         return this.orderer.add(dataset.name_search(
2329                 search_val, new instance.web.CompoundDomain(self.build_domain(), [["id", "not in", blacklist]]),
2330                 'ilike', this.limit + 1)).pipe(function(data) {
2331             self.last_search = data;
2332             // possible selections for the m2o
2333             var values = _.map(data, function(x) {
2334                 return {
2335                     label: _.str.escapeHTML(x[1]),
2336                     value:x[1],
2337                     name:x[1],
2338                     id:x[0]
2339                 };
2340             });
2341
2342             // search more... if more results that max
2343             if (values.length > self.limit) {
2344                 values = values.slice(0, self.limit);
2345                 values.push({label: _t("<em>   Search More...</em>"), action: function() {
2346                     dataset.name_search(search_val, self.build_domain(), 'ilike'
2347                     , false, function(data) {
2348                         self._search_create_popup("search", data);
2349                     });
2350                 }});
2351             }
2352             // quick create
2353             var raw_result = _(data.result).map(function(x) {return x[1];});
2354             if (search_val.length > 0 && !_.include(raw_result, search_val)) {
2355                 values.push({label: _.str.sprintf(_t('<em>   Create "<strong>%s</strong>"</em>'),
2356                         $('<span />').text(search_val).html()), action: function() {
2357                     self._quick_create(search_val);
2358                 }});
2359             }
2360             // create...
2361             values.push({label: _t("<em>   Create and Edit...</em>"), action: function() {
2362                 self._search_create_popup("form", undefined, {"default_name": search_val});
2363             }});
2364
2365             return values;
2366         });
2367     },
2368     get_search_blacklist: function() {
2369         return [];
2370     },
2371     _quick_create: function(name) {
2372         var self = this;
2373         var slow_create = function () {
2374             self._search_create_popup("form", undefined, {"default_name": name});
2375         };
2376         if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2377             new instance.web.DataSet(this, this.field.relation, self.build_context())
2378                 .name_create(name, function(data) {
2379                     self.add_id(data[0]);
2380                 }).fail(function(error, event) {
2381                     event.preventDefault();
2382                     slow_create();
2383                 });
2384         } else
2385             slow_create();
2386     },
2387     // all search/create popup handling
2388     _search_create_popup: function(view, ids, context) {
2389         var self = this;
2390         var pop = new instance.web.form.SelectCreatePopup(this);
2391         pop.select_element(
2392             self.field.relation,
2393             {
2394                 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2395                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2396                 initial_view: view,
2397                 disable_multiple_selection: true
2398             },
2399             self.build_domain(),
2400             new instance.web.CompoundContext(self.build_context(), context || {})
2401         );
2402         pop.on_select_elements.add(function(element_ids) {
2403             self.add_id(element_ids[0]);
2404         });
2405     },
2406     /**
2407      * To implement.
2408      */
2409     add_id: function(id) {},
2410 };
2411
2412 instance.web.form.FieldMany2One = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin,
2413         instance.web.form.CompletionFieldMixin, {
2414     template: "FieldMany2One",
2415     init: function(field_manager, node) {
2416         this._super(field_manager, node);
2417         instance.web.form.CompletionFieldMixin.init.call(this);
2418         this.set({'value': false});
2419         this.display_value = {};
2420         this.last_search = [];
2421         this.floating = false;
2422         this.inhibit_on_change = false;
2423     },
2424     start: function() {
2425         this._super();
2426         instance.web.form.ReinitializeFieldMixin.start.call(this);
2427         this.on("change:value", this, function() {
2428             this.floating = false;
2429             this.render_value();
2430         });
2431     },
2432     initialize_content: function() {
2433         if (!this.get("effective_readonly"))
2434             this.render_editable();
2435         this.render_value();
2436     },
2437     render_editable: function() {
2438         var self = this;
2439         this.$input = this.$element.find("input");
2440         
2441         self.$input.tipsy({
2442             title: function() {
2443                 return "No element was selected, you should create or select one from the dropdown list.";
2444             },
2445             trigger:'manual',
2446             fade: true,
2447         });
2448         
2449         this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
2450         this.$follow_button = $(".oe-m2o-cm-button", this.$element);
2451         
2452         this.$follow_button.click(function() {
2453             if (!self.get('value')) {
2454                 return;
2455             }
2456             var pop = new instance.web.form.FormOpenPopup(self.view);
2457             pop.show_element(
2458                 self.field.relation,
2459                 self.get("value"),
2460                 self.build_context(),
2461                 {
2462                     title: _t("Open: ") + (self.string || self.name)
2463                 }
2464             );
2465             pop.on_write_completed.add_last(function() {
2466                 self.display_value = {};
2467                 self.render_value();
2468             });
2469         });
2470
2471         // some behavior for input
2472         this.$input.keyup(function() {
2473             if (self.$input.val() === "") {
2474                 self.set({value: false});
2475             } else {
2476                 self.floating = true;
2477             }
2478         });
2479         this.$drop_down.click(function() {
2480             if (self.$input.autocomplete("widget").is(":visible")) {
2481                 self.$input.autocomplete("close");
2482             } else {
2483                 if (self.get("value") && ! self.floating) {
2484                     self.$input.autocomplete("search", "");
2485                 } else {
2486                     self.$input.autocomplete("search");
2487                 }
2488                 self.$input.focus();
2489             }
2490         });
2491         var tip_def = $.Deferred();
2492         var untip_def = $.Deferred();
2493         var tip_delay = 200;
2494         var tip_duration = 3000;
2495         var anyoneLoosesFocus = function() {
2496             if (self.floating) {
2497                 if (self.last_search.length > 0) {
2498                     if (self.last_search[0][0] != self.get("value")) {
2499                         self.display_value = {};
2500                         self.display_value["" + self.last_search[0][0]] = self.last_search[0][1];
2501                         self.set({value: self.last_search[0][0]});
2502                     } else {
2503                         self.render_value();
2504                     }
2505                 } else {
2506                     self.set({value: false});
2507                 }
2508             }
2509             if (! self.get("value")) {
2510                 tip_def.reject();
2511                 untip_def.reject();
2512                 tip_def = $.Deferred();
2513                 tip_def.then(function() {
2514                     self.$input.tipsy("show");
2515                 });
2516                 setTimeout(function() {
2517                     tip_def.resolve();
2518                     untip_def.reject();
2519                     untip_def = $.Deferred();
2520                     untip_def.then(function() {
2521                         self.$input.tipsy("hide");
2522                     });
2523                     setTimeout(function() {untip_def.resolve();}, tip_duration);
2524                 }, tip_delay);
2525             } else {
2526                 tip_def.reject();
2527             }
2528         };
2529         this.$input.focusout(anyoneLoosesFocus);
2530
2531         var isSelecting = false;
2532         // autocomplete
2533         this.$input.autocomplete({
2534             source: function(req, resp) {
2535                 self.get_search_result(req.term).then(function(result) {
2536                     resp(result);
2537                 });
2538             },
2539             select: function(event, ui) {
2540                 isSelecting = true;
2541                 var item = ui.item;
2542                 if (item.id) {
2543                     self.display_value = {};
2544                     self.display_value["" + item.id] = item.name;
2545                     self.set({value: item.id});
2546                 } else if (item.action) {
2547                     self.floating = true;
2548                     item.action();
2549                     return false;
2550                 }
2551             },
2552             focus: function(e, ui) {
2553                 e.preventDefault();
2554             },
2555             html: true,
2556             close: anyoneLoosesFocus,
2557             minLength: 0,
2558             delay: 0
2559         });
2560         this.$input.autocomplete("widget").addClass("openerp");
2561         // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2562         this.$input.keyup(function(e) {
2563             if (e.which === 13) {
2564                 if (isSelecting)
2565                     e.stopPropagation();
2566             }
2567             isSelecting = false;
2568         });
2569     },
2570
2571     render_value: function(no_recurse) {
2572         var self = this;
2573         if (! this.get("value")) {
2574             this.display_string("");
2575             return;
2576         }
2577         var display = this.display_value["" + this.get("value")];
2578         if (display) {
2579             this.display_string(display);
2580             return;
2581         }
2582         if (! no_recurse) {
2583             var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2584             dataset.name_get([self.get("value")], function(data) {
2585                 self.display_value["" + self.get("value")] = data[0][1];
2586                 self.render_value(true);
2587             });
2588         }
2589     },
2590     display_string: function(str) {
2591         var self = this;
2592         if (!this.get("effective_readonly")) {
2593             this.$input.val(str);
2594         } else {
2595             this.$element.find('a')
2596                  .unbind('click')
2597                  .text(str)
2598                  .click(function () {
2599                     self.do_action({
2600                         type: 'ir.actions.act_window',
2601                         res_model: self.field.relation,
2602                         res_id: self.get("value"),
2603                         context: self.build_context(),
2604                         views: [[false, 'form']],
2605                         target: 'current'
2606                     });
2607                     return false;
2608                  });
2609         }
2610     },
2611     set_value: function(value_) {
2612         var self = this;
2613         if (value_ instanceof Array) {
2614             this.display_value = {};
2615             this.display_value["" + value_[0]] = value_[1];
2616             value_ = value_[0];
2617         }
2618         value_ = value_ || false;
2619         this.inhibit_on_change = true;
2620         this._super(value_);
2621         this.inhibit_on_change = false;
2622     },
2623     add_id: function(id) {
2624         this.display_value = {};
2625         this.set({value: id});
2626     },
2627     is_false: function() {
2628         return ! this.get("value");
2629     },
2630     focus: function () {
2631         this.delay_focus(this.$input);
2632     }
2633 }));
2634
2635 /*
2636 # Values: (0, 0,  { fields })    create
2637 #         (1, ID, { fields })    update
2638 #         (2, ID)                remove (delete)
2639 #         (3, ID)                unlink one (target id or target of relation)
2640 #         (4, ID)                link
2641 #         (5)                    unlink all (only valid for one2many)
2642 */
2643 var commands = {
2644     // (0, _, {values})
2645     CREATE: 0,
2646     'create': function (values) {
2647         return [commands.CREATE, false, values];
2648     },
2649     // (1, id, {values})
2650     UPDATE: 1,
2651     'update': function (id, values) {
2652         return [commands.UPDATE, id, values];
2653     },
2654     // (2, id[, _])
2655     DELETE: 2,
2656     'delete': function (id) {
2657         return [commands.DELETE, id, false];
2658     },
2659     // (3, id[, _]) removes relation, but not linked record itself
2660     FORGET: 3,
2661     'forget': function (id) {
2662         return [commands.FORGET, id, false];
2663     },
2664     // (4, id[, _])
2665     LINK_TO: 4,
2666     'link_to': function (id) {
2667         return [commands.LINK_TO, id, false];
2668     },
2669     // (5[, _[, _]])
2670     DELETE_ALL: 5,
2671     'delete_all': function () {
2672         return [5, false, false];
2673     },
2674     // (6, _, ids) replaces all linked records with provided ids
2675     REPLACE_WITH: 6,
2676     'replace_with': function (ids) {
2677         return [6, false, ids];
2678     }
2679 };
2680 instance.web.form.FieldOne2Many = instance.web.form.AbstractField.extend({
2681     multi_selection: false,
2682     disable_utility_classes: true,
2683     init: function(field_manager, node) {
2684         this._super(field_manager, node);
2685         lazy_build_o2m_kanban_view();
2686         this.is_loaded = $.Deferred();
2687         this.initial_is_loaded = this.is_loaded;
2688         this.is_setted = $.Deferred();
2689         this.form_last_update = $.Deferred();
2690         this.init_form_last_update = this.form_last_update;
2691     },
2692     start: function() {
2693         this._super.apply(this, arguments);
2694
2695         var self = this;
2696
2697         this.dataset = new instance.web.form.One2ManyDataSet(this, this.field.relation);
2698         this.dataset.o2m = this;
2699         this.dataset.parent_view = this.view;
2700         this.dataset.child_name = this.name;
2701         //this.dataset.child_name = 
2702         this.dataset.on_change.add_last(function() {
2703             self.trigger_on_change();
2704         });
2705
2706         this.is_setted.then(function() {
2707             self.load_views();
2708         });
2709         this.is_loaded.then(function() {
2710             self.on("change:effective_readonly", self, function() {
2711                 self.is_loaded = self.is_loaded.pipe(function() {
2712                     self.viewmanager.destroy();
2713                     return $.when(self.load_views()).then(function() {
2714                         self.reload_current_view();
2715                     });
2716                 });
2717             });
2718         });
2719     },
2720     trigger_on_change: function() {
2721         var tmp = this.doing_on_change;
2722         this.doing_on_change = true;
2723         this.trigger('changed_value');
2724         this.doing_on_change = tmp;
2725     },
2726     load_views: function() {
2727         var self = this;
2728         
2729         var modes = this.node.attrs.mode;
2730         modes = !!modes ? modes.split(",") : ["tree"];
2731         var views = [];
2732         _.each(modes, function(mode) {
2733             var view = {
2734                 view_id: false,
2735                 view_type: mode == "tree" ? "list" : mode,
2736                 options: {}
2737             };
2738             if (self.field.views && self.field.views[mode]) {
2739                 view.embedded_view = self.field.views[mode];
2740             }
2741             if(view.view_type === "list") {
2742                 view.options.selectable = self.multi_selection;
2743                 if (self.get("effective_readonly")) {
2744                     view.options.addable = null;
2745                     view.options.deletable = null;
2746                 }
2747             } else if (view.view_type === "form") {
2748                 if (self.get("effective_readonly")) {
2749                     view.view_type = 'form';
2750                 }
2751                 view.options.not_interactible_on_create = true;
2752             } else if (view.view_type === "kanban") {
2753                 if (self.get("effective_readonly")) {
2754                     view.options.action_buttons = false;
2755                     view.options.quick_creatable = false;
2756                 }
2757             }
2758             views.push(view);
2759         });
2760         this.views = views;
2761
2762         this.viewmanager = new instance.web.form.One2ManyViewManager(this, this.dataset, views, {});
2763         this.viewmanager.o2m = self;
2764         var once = $.Deferred().then(function() {
2765             self.init_form_last_update.resolve();
2766         });
2767         var def = $.Deferred().then(function() {
2768             self.initial_is_loaded.resolve();
2769         });
2770         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2771             controller.o2m = self;
2772             if (view_type == "list") {
2773                 if (self.get("effective_readonly"))
2774                     controller.set_editable(false);
2775             } else if (view_type === "form") {
2776                 if (self.get("effective_readonly")) {
2777                     $(".oe_form_buttons", controller.$element).children().remove();
2778                 }
2779                 controller.on_record_loaded.add_last(function() {
2780                     once.resolve();
2781                 });
2782                 controller.on_pager_action.add_first(function() {
2783                     self.save_any_view();
2784                 });
2785             } else if (view_type == "graph") {
2786                 self.reload_current_view()
2787             }
2788             def.resolve();
2789         });
2790         this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2791             $.when(self.save_any_view()).then(function() {
2792                 if(n_mode === "list")
2793                     $.async_when().then(function() {self.reload_current_view();});
2794             });
2795         });
2796         this.is_setted.then(function() {
2797             $.async_when().then(function () {
2798                 self.viewmanager.appendTo(self.$element);
2799             });
2800         });
2801         return def;
2802     },
2803     reload_current_view: function() {
2804         var self = this;
2805         return self.is_loaded = self.is_loaded.pipe(function() {
2806             var active_view = self.viewmanager.active_view;
2807             var view = self.viewmanager.views[active_view].controller;
2808             if(active_view === "list") {
2809                 return view.reload_content();
2810             } else if (active_view === "form") {
2811                 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2812                     self.dataset.index = 0;
2813                 }
2814                 var act = function() {
2815                     return view.do_show();
2816                 };
2817                 self.form_last_update = self.form_last_update.pipe(act, act);
2818                 return self.form_last_update;
2819             } else if (view.do_search) {
2820                 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2821             }
2822         }, undefined);
2823     },
2824     set_value: function(value_) {
2825         value_ = value_ || [];
2826         var self = this;
2827         this.dataset.reset_ids([]);
2828         if(value_.length >= 1 && value_[0] instanceof Array) {
2829             var ids = [];
2830             _.each(value_, function(command) {
2831                 var obj = {values: command[2]};
2832                 switch (command[0]) {
2833                     case commands.CREATE:
2834                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2835                         obj.defaults = {};
2836                         self.dataset.to_create.push(obj);
2837                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2838                         ids.push(obj.id);
2839                         return;
2840                     case commands.UPDATE:
2841                         obj['id'] = command[1];
2842                         self.dataset.to_write.push(obj);
2843                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2844                         ids.push(obj.id);
2845                         return;
2846                     case commands.DELETE:
2847                         self.dataset.to_delete.push({id: command[1]});
2848                         return;
2849                     case commands.LINK_TO:
2850                         ids.push(command[1]);
2851                         return;
2852                     case commands.DELETE_ALL:
2853                         self.dataset.delete_all = true;
2854                         return;
2855                 }
2856             });
2857             this._super(ids);
2858             this.dataset.set_ids(ids);
2859         } else if (value_.length >= 1 && typeof(value_[0]) === "object") {
2860             var ids = [];
2861             this.dataset.delete_all = true;
2862             _.each(value_, function(command) {
2863                 var obj = {values: command};
2864                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2865                 obj.defaults = {};
2866                 self.dataset.to_create.push(obj);
2867                 self.dataset.cache.push(_.clone(obj));
2868                 ids.push(obj.id);
2869             });
2870             this._super(ids);
2871             this.dataset.set_ids(ids);
2872         } else {
2873             this._super(value_);
2874             this.dataset.reset_ids(value_);
2875         }
2876         if (this.dataset.index === null && this.dataset.ids.length > 0) {
2877             this.dataset.index = 0;
2878         }
2879         self.is_setted.resolve();
2880         return self.reload_current_view();
2881     },
2882     get_value: function() {
2883         var self = this;
2884         if (!this.dataset)
2885             return [];
2886         this.save_any_view();
2887         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2888         val = val.concat(_.map(this.dataset.ids, function(id) {
2889             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2890             if (alter_order) {
2891                 return commands.create(alter_order.values);
2892             }
2893             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2894             if (alter_order) {
2895                 return commands.update(alter_order.id, alter_order.values);
2896             }
2897             return commands.link_to(id);
2898         }));
2899         return val.concat(_.map(
2900             this.dataset.to_delete, function(x) {
2901                 return commands['delete'](x.id);}));
2902     },
2903     save_any_view: function() {
2904         if (this.doing_on_change)
2905             return false;
2906         return this.session.synchronized_mode(_.bind(function() {
2907                 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2908                     this.viewmanager.views[this.viewmanager.active_view] &&
2909                     this.viewmanager.views[this.viewmanager.active_view].controller) {
2910                     var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2911                     if (this.viewmanager.active_view === "form") {
2912                         if (!view.is_initialized.isResolved()) {
2913                             return false;
2914                         }
2915                         var res = $.when(view.do_save());
2916                         if (!res.isResolved() && !res.isRejected()) {
2917                             console.warn("Asynchronous get_value() is not supported in form view.");
2918                         }
2919                         return res;
2920                     } else if (this.viewmanager.active_view === "list") {
2921                         var res = $.when(view.ensure_saved());
2922                         if (!res.isResolved() && !res.isRejected()) {
2923                             console.warn("Asynchronous get_value() is not supported in list view.");
2924                         }
2925                         return res;
2926                     }
2927                 }
2928                 return false;
2929             }, this));
2930     },
2931     is_syntax_valid: function() {
2932         if (!this.viewmanager.views[this.viewmanager.active_view])
2933             return true;
2934         var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2935         if (this.viewmanager.active_view === "form") {
2936             for (var f in view.fields) {
2937                 f = view.fields[f];
2938                 if (!f.is_valid()) {
2939                     return false;
2940                 }
2941             }
2942         }
2943         return true;
2944     },
2945 });
2946
2947 instance.web.form.One2ManyViewManager = instance.web.ViewManager.extend({
2948     template: 'One2Many.viewmanager',
2949     init: function(parent, dataset, views, flags) {
2950         this._super(parent, dataset, views, _.extend({}, flags, {$sidebar: false}));
2951         this.registry = this.registry.extend({
2952             list: 'instance.web.form.One2ManyListView',
2953             form: 'instance.web.form.One2ManyFormView',
2954             kanban: 'instance.web.form.One2ManyKanbanView',
2955         });
2956     },
2957     switch_view: function(mode, unused) {
2958         if (mode !== 'form') {
2959             return this._super(mode, unused);
2960         }
2961         var self = this;
2962         var id = self.o2m.dataset.index !== null ? self.o2m.dataset.ids[self.o2m.dataset.index] : null;
2963         var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
2964         pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2965             title: _t("Open: ") + self.name,
2966             create_function: function(data) {
2967                 return self.o2m.dataset.create(data).then(function(r) {
2968                     self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2969                     self.o2m.dataset.on_change();
2970                 });
2971             },
2972             write_function: function(id, data, options) {
2973                 return self.o2m.dataset.write(id, data, {}).then(function() {
2974                     self.o2m.reload_current_view();
2975                 });
2976             },
2977             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2978             parent_view: self.o2m.view,
2979             child_name: self.o2m.name,
2980             read_function: function() {
2981                 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2982             },
2983             form_view_options: {'not_interactible_on_create':true},
2984             readonly: self.o2m.get("effective_readonly")
2985         });
2986         pop.on_select_elements.add_last(function() {
2987             self.o2m.reload_current_view();
2988         });
2989     },
2990 });
2991
2992 instance.web.form.One2ManyDataSet = instance.web.BufferedDataSet.extend({
2993     get_context: function() {
2994         this.context = this.o2m.build_context([this.o2m.name]);
2995         return this.context;
2996     }
2997 });
2998
2999 instance.web.form.One2ManyListView = instance.web.ListView.extend({
3000     _template: 'One2Many.listview',
3001     do_add_record: function () {
3002         if (this.options.editable) {
3003             this._super.apply(this, arguments);
3004         } else {
3005             var self = this;
3006             var pop = new instance.web.form.SelectCreatePopup(this);
3007             pop.select_element(
3008                 self.o2m.field.relation,
3009                 {
3010                     title: _t("Create: ") + self.name,
3011                     initial_view: "form",
3012                     alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3013                     create_function: function(data, callback, error_callback) {
3014                         return self.o2m.dataset.create(data).then(function(r) {
3015                             self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
3016                             self.o2m.dataset.on_change();
3017                         }).then(callback, error_callback);
3018                     },
3019                     read_function: function() {
3020                         return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3021                     },
3022                     parent_view: self.o2m.view,
3023                     child_name: self.o2m.name,
3024                     form_view_options: {'not_interactible_on_create':true}
3025                 },
3026                 self.o2m.build_domain(),
3027                 self.o2m.build_context()
3028             );
3029             pop.on_select_elements.add_last(function() {
3030                 self.o2m.reload_current_view();
3031             });
3032         }
3033     },
3034     do_activate_record: function(index, id) {
3035         var self = this;
3036         var pop = new instance.web.form.FormOpenPopup(self.o2m.view);
3037         pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
3038             title: _t("Open: ") + self.name,
3039             write_function: function(id, data) {
3040                 return self.o2m.dataset.write(id, data, {}, function(r) {
3041                     self.o2m.reload_current_view();
3042                 });
3043             },
3044             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
3045             parent_view: self.o2m.view,
3046             child_name: self.o2m.name,
3047             read_function: function() {
3048                 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
3049             },
3050             form_view_options: {'not_interactible_on_create':true},
3051             readonly: self.o2m.get("effective_readonly")
3052         });
3053     },
3054     do_button_action: function (name, id, callback) {
3055         var self = this;
3056         var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
3057         return this._super(name, id, _.bind(def.resolve, def));
3058     }
3059 });
3060
3061 instance.web.form.One2ManyFormView = instance.web.FormView.extend({
3062     form_template: 'One2Many.formview',
3063     on_loaded: function(data) {
3064         this._super(data);
3065         var self = this;
3066         this.$buttons.find('button.oe_form_button_create').click(function() {
3067             self.do_save().then(self.on_button_new);
3068         });
3069     },
3070     do_notify_change: function() {
3071         if (this.dataset.parent_view) {
3072             this.dataset.parent_view.do_notify_change();
3073         } else {
3074             this._super.apply(this, arguments);
3075         }
3076     }
3077 });
3078
3079 var lazy_build_o2m_kanban_view = function() {
3080 if (! instance.web_kanban || instance.web.form.One2ManyKanbanView)
3081     return;
3082 instance.web.form.One2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3083 });
3084 }
3085
3086 instance.web.form.FieldMany2ManyTags = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin,
3087                                                                                        instance.web.form.ReinitializeFieldMixin, {
3088     template: "FieldMany2ManyTags",
3089     init: function() {
3090         this._super.apply(this, arguments);
3091         instance.web.form.CompletionFieldMixin.init.call(this);
3092         this.set({"value": []});
3093         this._display_orderer = new instance.web.DropMisordered();
3094         this._drop_shown = false;
3095     },
3096     start: function() {
3097         this._super();
3098         instance.web.form.ReinitializeFieldMixin.start.call(this);
3099         this.on("change:value", this, this.render_value);
3100     },
3101     initialize_content: function() {
3102         if (this.get("effective_readonly"))
3103             return;
3104         var self = this;
3105         self. $text = $("textarea", this.$element);
3106         self.$text.textext({
3107             plugins : 'tags arrow autocomplete',
3108             autocomplete: {
3109                 render: function(suggestion) {
3110                     return $('<span class="text-label"/>').
3111                              data('index', suggestion['index']).html(suggestion['label']);
3112                 }
3113             },
3114             ext: {
3115                 autocomplete: {
3116                     selectFromDropdown: function() {
3117                         $(this).trigger('hideDropdown');
3118                         var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3119                         var data = self.search_result[index];
3120                         if (data.id) {
3121                             self.add_id(data.id);
3122                         } else {
3123                             data.action();
3124                         }
3125                     },
3126                 },
3127                 tags: {
3128                     isTagAllowed: function(tag) {
3129                         if (! tag.name)
3130                             return false;
3131                         return true;
3132                     },
3133                     removeTag: function(tag) {
3134                         var id = tag.data("id");
3135                         self.set({"value": _.without(self.get("value"), id)});
3136                     },
3137                     renderTag: function(stuff) {
3138                         return $.fn.textext.TextExtTags.prototype.renderTag.
3139                             call(this, stuff).data("id", stuff.id);
3140                     },
3141                 },
3142                 itemManager: {
3143                     itemToString: function(item) {
3144                         return item.name;
3145                     },
3146                 },
3147             },
3148         }).bind('getSuggestions', function(e, data) {
3149             var _this = this;
3150             var str = !!data ? data.query || '' : '';
3151             self.get_search_result(str).then(function(result) {
3152                 self.search_result = result;
3153                 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3154                     return _.extend(el, {index:i});
3155                 })});
3156             });
3157         }).bind('tagClick', function(e, tag, value, callback) {
3158             var pop = new instance.web.form.FormOpenPopup(self.view);
3159             pop.show_element(
3160                 self.field.relation,
3161                 value.id,
3162                 self.build_context(),
3163                 {
3164                     title: _t("Open: ") + (self.string || self.name)
3165                 }
3166             );
3167             pop.on_write_completed.add_last(function() {
3168                 self.render_value();
3169             });
3170         }).bind('hideDropdown', function() {
3171             self._drop_shown = false;
3172         }).bind('showDropdown', function() {
3173             self._drop_shown = true;
3174         });
3175         self.tags = self.$text.textext()[0].tags();
3176         $("textarea", this.$element).focusout(function() {
3177             $("textarea", this.$element).val("");
3178         }).keydown(function(e) {
3179             if (event.keyCode === 9 && self._drop_shown) {
3180                 self.$text.textext()[0].autocomplete().selectFromDropdown();
3181             }
3182         });
3183     },
3184     set_value: function(value_) {
3185         value_ = value_ || [];
3186         if (value_.length >= 1 && value_[0] instanceof Array) {
3187             value_ = value_[0][2];
3188         }
3189         this._super(value_);
3190     },
3191     get_value: function() {
3192         var tmp = [commands.replace_with(this.get("value"))];
3193         return tmp;
3194     },
3195     get_search_blacklist: function() {
3196         return this.get("value");
3197     },
3198     render_value: function() {
3199         var self = this;
3200         var dataset = new instance.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
3201         var handle_names = function(data) {
3202             var indexed = {};
3203             _.each(data, function(el) {
3204                 indexed[el[0]] = el;
3205             });
3206             data = _.map(self.get("value"), function(el) { return indexed[el]; });
3207             if (! self.get("effective_readonly")) {
3208                 self.tags.containerElement().children().remove();
3209                 $("textarea", self.$element).css("padding-left", "3px");
3210                 self.tags.addTags(_.map(data, function(el) {return {name: el[1], id:el[0]};}));
3211             } else {
3212                 self.$element.html(QWeb.render("FieldMany2ManyTags.box", {elements: data}));
3213                 $(".oe_form_field_many2manytags_box", self.$element).click(function() {
3214                     var index = Number($(this).data("index"));
3215                     self.do_action({
3216                         type: 'ir.actions.act_window',
3217                         res_model: self.field.relation,
3218                         res_id: self.get("value")[index],
3219                         context: self.build_context(),
3220                         views: [[false, 'form']],
3221                         target: 'current'
3222                     });
3223                 });
3224             }
3225         };
3226         if (! self.get('values') || self.get('values').length > 0) {
3227             this._display_orderer.add(dataset.name_get(self.get("value"))).then(handle_names);
3228         } else {
3229             handle_names([]);
3230         }
3231     },
3232     add_id: function(id) {
3233         this.set({'value': _.uniq(this.get('value').concat([id]))});
3234     },
3235 }));
3236
3237 /*
3238  * TODO niv: clean those deferred stuff, it could be better
3239  */
3240 instance.web.form.FieldMany2Many = instance.web.form.AbstractField.extend({
3241     multi_selection: false,
3242     disable_utility_classes: true,
3243     init: function(field_manager, node) {
3244         this._super(field_manager, node);
3245         this.is_loaded = $.Deferred();
3246         this.initial_is_loaded = this.is_loaded;
3247         this.is_setted = $.Deferred();
3248     },
3249     start: function() {
3250         this._super.apply(this, arguments);
3251
3252         var self = this;
3253
3254         this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3255         this.dataset.m2m = this;
3256         this.dataset.on_unlink.add_last(function(ids) {
3257             self.dataset_changed();
3258         });
3259         
3260         this.is_setted.then(function() {
3261             self.load_view();
3262         });
3263         this.is_loaded.then(function() {
3264             self.on("change:effective_readonly", self, function() {
3265                 self.is_loaded = self.is_loaded.pipe(function() {
3266                     self.list_view.destroy();
3267                     return $.when(self.load_view()).then(function() {
3268                         self.reload_content();
3269                     });
3270                 });
3271             });
3272         })
3273     },
3274     set_value: function(value_) {
3275         value_ = value_ || [];
3276         if (value_.length >= 1 && value_[0] instanceof Array) {
3277             value_ = value_[0][2];
3278         }
3279         this._super(value_);
3280         this.dataset.set_ids(value_);
3281         var self = this;
3282         self.reload_content();
3283         this.is_setted.resolve();
3284     },
3285     load_view: function() {
3286         var self = this;
3287         this.list_view = new instance.web.form.Many2ManyListView(this, this.dataset, false, {
3288                     'addable': self.get("effective_readonly") ? null : _t("Add"),
3289                     'deletable': self.get("effective_readonly") ? false : true,
3290                     'selectable': self.multi_selection,
3291             });
3292         var embedded = (this.field.views || {}).tree;
3293         if (embedded) {
3294             this.list_view.set_embedded_view(embedded);
3295         }
3296         this.list_view.m2m_field = this;
3297         var loaded = $.Deferred();
3298         this.list_view.on_loaded.add_last(function() {
3299             self.initial_is_loaded.resolve();
3300             loaded.resolve();
3301         });
3302         $.async_when().then(function () {
3303             self.list_view.appendTo(self.$element);
3304         });
3305         return loaded;
3306     },
3307     reload_content: function() {
3308         var self = this;
3309         this.is_loaded = this.is_loaded.pipe(function() {
3310             return self.list_view.reload_content();
3311         });
3312     },
3313     dataset_changed: function() {
3314         this.set({'value': [commands.replace_with(this.dataset.ids)]});
3315     },
3316 });
3317
3318 instance.web.form.Many2ManyDataSet = instance.web.DataSetStatic.extend({
3319     get_context: function() {
3320         this.context = this.m2m.build_context();
3321         return this.context;
3322     }
3323 });
3324
3325 /**
3326  * @class
3327  * @extends instance.web.ListView
3328  */
3329 instance.web.form.Many2ManyListView = instance.web.ListView.extend(/** @lends instance.web.form.Many2ManyListView# */{
3330     do_add_record: function () {
3331         var pop = new instance.web.form.SelectCreatePopup(this);
3332         pop.select_element(
3333             this.model,
3334             {
3335                 title: _t("Add: ") + this.name
3336             },
3337             new instance.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
3338             this.m2m_field.build_context()
3339         );
3340         var self = this;
3341         pop.on_select_elements.add(function(element_ids) {
3342             _.each(element_ids, function(one_id) {
3343                 if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3344                     self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3345                     self.m2m_field.dataset_changed();
3346                     self.reload_content();
3347                 }
3348             });
3349         });
3350     },
3351     do_activate_record: function(index, id) {
3352         var self = this;
3353         var pop = new instance.web.form.FormOpenPopup(this);
3354         pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
3355             title: _t("Open: ") + this.name,
3356             readonly: this.getParent().get("effective_readonly")
3357         });
3358         pop.on_write_completed.add_last(function() {
3359             self.reload_content();
3360         });
3361     }
3362 });
3363
3364 instance.web.form.FieldMany2ManyKanban = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.CompletionFieldMixin, {
3365     disable_utility_classes: true,
3366     init: function(field_manager, node) {
3367         this._super(field_manager, node);
3368         instance.web.form.CompletionFieldMixin.init.call(this);
3369         m2m_kanban_lazy_init();
3370         this.is_loaded = $.Deferred();
3371         this.initial_is_loaded = this.is_loaded;
3372         this.is_setted = $.Deferred();
3373     },
3374     start: function() {
3375         this._super.apply(this, arguments);
3376
3377         var self = this;
3378
3379         this.dataset = new instance.web.form.Many2ManyDataSet(this, this.field.relation);
3380         this.dataset.m2m = this;
3381         this.dataset.on_unlink.add_last(function(ids) {
3382             self.dataset_changed();
3383         });
3384         
3385         this.is_setted.then(function() {
3386             self.load_view();
3387         });
3388         this.is_loaded.then(function() {
3389             self.on("change:effective_readonly", self, function() {
3390                 self.is_loaded = self.is_loaded.pipe(function() {
3391                     self.kanban_view.destroy();
3392                     return $.when(self.load_view()).then(function() {
3393                         self.reload_content();
3394                     });
3395                 });
3396             });
3397         })
3398     },
3399     set_value: function(value_) {
3400         value_ = value_ || [];
3401         if (value_.length >= 1 && value_[0] instanceof Array) {
3402             value_ = value_[0][2];
3403         }
3404         this._super(value_);
3405         this.dataset.set_ids(value_);
3406         var self = this;
3407         self.reload_content();
3408         this.is_setted.resolve();
3409     },
3410     load_view: function() {
3411         var self = this;
3412         this.kanban_view = new instance.web.form.Many2ManyKanbanView(this, this.dataset, false, {
3413                     'create_text': _t("Add"),
3414                     'creatable': self.get("effective_readonly") ? false : true,
3415                     'quick_creatable': self.get("effective_readonly") ? false : true,
3416             });
3417         var embedded = (this.field.views || {}).kanban;
3418         if (embedded) {
3419             this.kanban_view.set_embedded_view(embedded);
3420         }
3421         this.kanban_view.m2m = this;
3422         var loaded = $.Deferred();
3423         this.kanban_view.on_loaded.add_last(function() {
3424             self.initial_is_loaded.resolve();
3425             loaded.resolve();
3426         });
3427         this.kanban_view.do_switch_view.add_last(_.bind(this.open_popup, this));
3428         $.async_when().then(function () {
3429             self.kanban_view.appendTo(self.$element);
3430         });
3431         return loaded;
3432     },
3433     reload_content: function() {
3434         var self = this;
3435         this.is_loaded = this.is_loaded.pipe(function() {
3436             return self.kanban_view.do_search(self.build_domain(), self.dataset.get_context(), []);
3437         });
3438     },
3439     dataset_changed: function() {
3440         this.set({'value': [commands.replace_with(this.dataset.ids)]});
3441     },
3442     open_popup: function(type, unused) {
3443         if (type !== "form")
3444             return;
3445         var self = this;
3446         if (this.dataset.index === null) {
3447             var pop = new instance.web.form.SelectCreatePopup(this);
3448             pop.select_element(
3449                 this.field.relation,
3450                 {
3451                     title: _t("Add: ") + this.name
3452                 },
3453                 new instance.web.CompoundDomain(this.build_domain(), ["!", ["id", "in", this.dataset.ids]]),
3454                 this.build_context()
3455             );
3456             pop.on_select_elements.add(function(element_ids) {
3457                 _.each(element_ids, function(one_id) {
3458                     if(! _.detect(self.dataset.ids, function(x) {return x == one_id;})) {
3459                         self.dataset.set_ids([].concat(self.dataset.ids, [one_id]));
3460                         self.dataset_changed();
3461                         self.reload_content();
3462                     }
3463                 });
3464             });
3465         } else {
3466             var id = self.dataset.ids[self.dataset.index];
3467             var pop = new instance.web.form.FormOpenPopup(self.view);
3468             pop.show_element(self.field.relation, id, self.build_context(), {
3469                 title: _t("Open: ") + self.name,
3470                 write_function: function(id, data, options) {
3471                     return self.dataset.write(id, data, {}).then(function() {
3472                         self.reload_content();
3473                     });
3474                 },
3475                 alternative_form_view: self.field.views ? self.field.views["form"] : undefined,
3476                 parent_view: self.view,
3477                 child_name: self.name,
3478                 readonly: self.get("effective_readonly")
3479             });
3480         }
3481     },
3482     add_id: function(id) {
3483         this.quick_create.add_id(id);
3484     },
3485 }));
3486
3487 function m2m_kanban_lazy_init() {
3488 if (instance.web.form.Many2ManyKanbanView)
3489     return;
3490 instance.web.form.Many2ManyKanbanView = instance.web_kanban.KanbanView.extend({
3491     quick_create_class: 'instance.web.form.Many2ManyQuickCreate',
3492     _is_quick_create_enabled: function() {
3493         return this._super() && ! this.group_by;
3494     },
3495 });
3496 instance.web.form.Many2ManyQuickCreate = instance.web.Widget.extend({
3497     template: 'Many2ManyKanban.quick_create',
3498     
3499     /**
3500      * close_btn: If true, the widget will display a "Close" button able to trigger
3501      * a "close" event.
3502      */
3503     init: function(parent, dataset, context, buttons) {
3504         this._super(parent);
3505         this.m2m = this.getParent().view.m2m;
3506         this.m2m.quick_create = this;
3507         this._dataset = dataset;
3508         this._buttons = buttons || false;
3509         this._context = context || {};
3510     },
3511     start: function () {
3512         var self = this;
3513         self.$text = this.$element.find('input').css("width", "200px");
3514         self.$text.textext({
3515             plugins : 'arrow autocomplete',
3516             autocomplete: {
3517                 render: function(suggestion) {
3518                     return $('<span class="text-label"/>').
3519                              data('index', suggestion['index']).html(suggestion['label']);
3520                 }
3521             },
3522             ext: {
3523                 autocomplete: {
3524                     selectFromDropdown: function() {
3525                         $(this).trigger('hideDropdown');
3526                         var index = Number(this.selectedSuggestionElement().children().children().data('index'));
3527                         var data = self.search_result[index];
3528                         if (data.id) {
3529                             self.add_id(data.id);
3530                         } else {
3531                             data.action();
3532                         }
3533                     },
3534                 },
3535                 itemManager: {
3536                     itemToString: function(item) {
3537                         return item.name;
3538                     },
3539                 },
3540             },
3541         }).bind('getSuggestions', function(e, data) {
3542             var _this = this;
3543             var str = !!data ? data.query || '' : '';
3544             self.m2m.get_search_result(str).then(function(result) {
3545                 self.search_result = result;
3546                 $(_this).trigger('setSuggestions', {result : _.map(result, function(el, i) {
3547                     return _.extend(el, {index:i});
3548                 })});
3549             });
3550         });
3551         self.$text.focusout(function() {
3552             self.$text.val("");
3553         });
3554     },
3555     focus: function() {
3556         this.$text.focus();
3557     },
3558     add_id: function(id) {
3559         var self = this;
3560         self.$text.val("");
3561         self.trigger('added', id);
3562     },
3563 });
3564 }
3565
3566 /**
3567  * Class with everything which is common between FormOpenPopup and SelectCreatePopup.
3568  */
3569 instance.web.form.AbstractFormPopup = instance.web.OldWidget.extend({
3570     template: "AbstractFormPopup.render",
3571     /**
3572      *  options:
3573      *  -readonly: only applicable when not in creation mode, default to false
3574      * - alternative_form_view
3575      * - write_function
3576      * - read_function
3577      * - create_function
3578      * - parent_view
3579      * - child_name
3580      * - form_view_options
3581      */
3582     init_popup: function(model, row_id, domain, context, options) {
3583         this.row_id = row_id;
3584         this.model = model;
3585         this.domain = domain || [];
3586         this.context = context || {};
3587         this.options = options;
3588         _.defaults(this.options, {
3589         });
3590     },
3591     init_dataset: function() {
3592         var self = this;
3593         this.created_elements = [];
3594         this.dataset = new instance.web.ProxyDataSet(this, this.model, this.context);
3595         this.dataset.read_function = this.options.read_function;
3596         this.dataset.create_function = function(data, sup) {
3597             var fct = self.options.create_function || sup;
3598             return fct.call(this, data).then(function(r) {
3599                 self.created_elements.push(r.result);
3600             });
3601         };
3602         this.dataset.write_function = function(id, data, options, sup) {
3603             var fct = self.options.write_function || sup;
3604             return fct.call(this, id, data, options).then(self.on_write_completed);
3605         };
3606         this.dataset.parent_view = this.options.parent_view;
3607         this.dataset.child_name = this.options.child_name;
3608     },
3609     display_popup: function() {
3610         var self = this;
3611         this.renderElement();
3612         new instance.web.Dialog(this, {
3613             width: '90%',
3614             min_width: '800px',
3615             close: function() {
3616                 self.check_exit();
3617             },
3618             title: this.options.title || "",
3619         }, this.$element).open();
3620         this.start();
3621     },
3622     on_write_completed: function() {},
3623     setup_form_view: function() {
3624         var self = this;
3625         if (this.row_id) {
3626             this.dataset.ids = [this.row_id];
3627             this.dataset.index = 0;
3628         } else {
3629             this.dataset.index = null;
3630         }
3631         var options = _.clone(self.options.form_view_options) || {};
3632         if (this.row_id !== null) {
3633             options.initial_mode = this.options.readonly ? "view" : "edit";
3634         }
3635         this.view_form = new instance.web.FormView(this, this.dataset, false, options);
3636         if (this.options.alternative_form_view) {
3637             this.view_form.set_embedded_view(this.options.alternative_form_view);
3638         }
3639         this.view_form.appendTo(this.$element.find(".oe-form-view-popup-form-placeholder"));
3640         this.view_form.on_loaded.add_last(function() {
3641             var $buttons = self.view_form.$element.find(".oe_form_buttons");
3642             var multi_select = self.row_id === null && ! self.options.disable_multiple_selection;
3643             $buttons.html(QWeb.render("AbstractFormPopup.buttons", {multi_select: multi_select}));
3644             var $snbutton = $buttons.find(".oe_abstractformpopup-form-save-new");
3645             $snbutton.click(function() {
3646                 $.when(self.view_form.do_save()).then(function() {
3647                     self.view_form.reload_mutex.exec(function() {
3648                         self.view_form.on_button_new();
3649                     });
3650                 });
3651             });
3652             var $sbutton = $buttons.find(".oe_abstractformpopup-form-save");
3653             $sbutton.click(function() {
3654                 $.when(self.view_form.do_save()).then(function() {
3655                     self.view_form.reload_mutex.exec(function() {
3656                         self.check_exit();
3657                     });
3658                 });
3659             });
3660             var $cbutton = $buttons.find(".oe_abstractformpopup-form-close");
3661             $cbutton.click(function() {
3662                 self.check_exit();
3663             });
3664             if (self.row_id !== null && self.options.readonly) {
3665                 $snbutton.hide();
3666                 $sbutton.hide();
3667                 $cbutton.text(_t("Close"));
3668             }
3669             self.view_form.do_show();
3670         });
3671     },
3672     on_select_elements: function(element_ids) {
3673     },
3674     check_exit: function() {
3675         if (this.created_elements.length > 0) {
3676             this.on_select_elements(this.created_elements);
3677         }
3678         this.destroy();
3679     },
3680     destroy: function () {
3681         this.$element.dialog('close');
3682         this._super();
3683     },
3684 });
3685
3686 /**
3687  * Class to display a popup containing a form view.
3688  */
3689 instance.web.form.FormOpenPopup = instance.web.form.AbstractFormPopup.extend({
3690     show_element: function(model, row_id, context, options) {
3691         this.init_popup(model, row_id, [], context,  options);
3692         _.defaults(this.options, {
3693         });
3694         this.display_popup();
3695     },
3696     start: function() {
3697         this._super();
3698         this.init_dataset();
3699         this.setup_form_view();
3700     },
3701 });
3702
3703 /**
3704  * Class to display a popup to display a list to search a row. It also allows
3705  * to switch to a form view to create a new row.
3706  */
3707 instance.web.form.SelectCreatePopup = instance.web.form.AbstractFormPopup.extend({
3708     /**
3709      * options:
3710      * - initial_ids
3711      * - initial_view: form or search (default search)
3712      * - disable_multiple_selection
3713      * - list_view_options
3714      */
3715     select_element: function(model, options, domain, context) {
3716         this.init_popup(model, null, domain, context, options);
3717         var self = this;
3718         _.defaults(this.options, {
3719             initial_view: "search",
3720         });
3721         this.initial_ids = this.options.initial_ids;
3722         this.display_popup();
3723     },
3724     start: function() {
3725         var self = this;
3726         this.init_dataset();
3727         if (this.options.initial_view == "search") {
3728             self.rpc('/web/session/eval_domain_and_context', {
3729                 domains: [],
3730                 contexts: [this.context]
3731             }, function (results) {
3732                 var search_defaults = {};
3733                 _.each(results.context, function (value_, key) {
3734                     var match = /^search_default_(.*)$/.exec(key);
3735                     if (match) {
3736                         search_defaults[match[1]] = value_;
3737                     }
3738                 });
3739                 self.setup_search_view(search_defaults);
3740             });
3741         } else { // "form"
3742             this.new_object();
3743         }
3744     },
3745     setup_search_view: function(search_defaults) {
3746         var self = this;
3747         if (this.searchview) {
3748             this.searchview.destroy();
3749         }
3750         this.searchview = new instance.web.SearchView(this,
3751                 this.dataset, false,  search_defaults);
3752         this.searchview.on_search.add(function(domains, contexts, groupbys) {
3753             if (self.initial_ids) {
3754                 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
3755                     contexts, groupbys);
3756                 self.initial_ids = undefined;
3757             } else {
3758                 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
3759             }
3760         });
3761         this.searchview.on_loaded.add_last(function () {
3762             self.view_list = new instance.web.form.SelectCreateListView(self,
3763                     self.dataset, false,
3764                     _.extend({'deletable': false,
3765                         'selectable': !self.options.disable_multiple_selection
3766                     }, self.options.list_view_options || {}));
3767             self.view_list.popup = self;
3768             self.view_list.appendTo($(".oe-select-create-popup-view-list", self.$element)).pipe(function() {
3769                 self.view_list.do_show();
3770             }).pipe(function() {
3771                 self.searchview.do_search();
3772             });
3773             self.view_list.on_loaded.add_last(function() {
3774                 var $buttons = self.view_list.$element.find(".oe-actions");
3775                 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
3776                 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
3777                 $cbutton.click(function() {
3778                     self.destroy();
3779                 });
3780                 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
3781                 if(self.options.disable_multiple_selection) {
3782                     $sbutton.hide();
3783                 }
3784                 $sbutton.click(function() {
3785                     self.on_select_elements(self.selected_ids);
3786                     self.destroy();
3787                 });
3788             });
3789         });
3790         this.searchview.appendTo($(".oe-select-create-popup-view-list", self.$element));
3791     },
3792     do_search: function(domains, contexts, groupbys) {
3793         var self = this;
3794         this.rpc('/web/session/eval_domain_and_context', {
3795             domains: domains || [],
3796             contexts: contexts || [],
3797             group_by_seq: groupbys || []
3798         }, function (results) {
3799             self.view_list.do_search(results.domain, results.context, results.group_by);
3800         });
3801     },
3802     on_click_element: function(ids) {
3803         this.selected_ids = ids || [];
3804         if(this.selected_ids.length > 0) {
3805             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
3806         } else {
3807             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
3808         }
3809     },
3810     new_object: function() {
3811         if (this.searchview) {
3812             this.searchview.hide();
3813         }
3814         if (this.view_list) {
3815             this.view_list.$element.hide();
3816         }
3817         this.setup_form_view();
3818     },
3819 });
3820
3821 instance.web.form.SelectCreateListView = instance.web.ListView.extend({
3822     do_add_record: function () {
3823         this.popup.new_object();
3824     },
3825     select_record: function(index) {
3826         this.popup.on_select_elements([this.dataset.ids[index]]);
3827         this.popup.destroy();
3828     },
3829     do_select: function(ids, records) {
3830         this._super(ids, records);
3831         this.popup.on_click_element(ids);
3832     }
3833 });
3834
3835 instance.web.form.FieldReference = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3836     template: 'FieldReference',
3837     init: function(field_manager, node) {
3838         this._super(field_manager, node);
3839         this.reference_ready = true;
3840     },
3841     on_nop: function() {
3842     },
3843     on_selection_changed: function() {
3844         if (this.reference_ready) {
3845             var sel = this.selection.get_value();
3846             this.m2o.field.relation = sel;
3847             this.m2o.set_value(false);
3848             this.m2o.$element.toggle(sel !== false);
3849         }
3850     },
3851     destroy_content: function() {
3852         if (this.selection) {
3853             this.selection.destroy();
3854             this.selection = undefined;
3855         }
3856         if (this.m2o) {
3857             this.m2o.destroy();
3858             this.m2o = undefined;
3859         }
3860     },
3861     initialize_content: function() {
3862         this.selection = new instance.web.form.FieldSelection(this, { attrs: {
3863             name: 'selection'
3864         }});
3865         this.selection.view = this.view;
3866         this.selection.set({force_readonly: this.get('effective_readonly')});
3867         this.selection.on("change:value", this, this.on_selection_changed);
3868         this.selection.$element = $(".oe_form_view_reference_selection", this.$element);
3869         this.selection.renderElement();
3870         this.selection.start();
3871
3872         this.m2o = new instance.web.form.FieldMany2One(this, { attrs: {
3873             name: 'm2o'
3874         }});
3875         this.m2o.view = this.view;
3876         this.m2o.set({force_readonly: this.get("effective_readonly")});
3877         this.m2o.on("change:value", this, this.data_changed);
3878         this.m2o.$element = $(".oe_form_view_reference_m2o", this.$element);
3879         this.m2o.renderElement();
3880         this.m2o.start();
3881     },
3882     is_false: function() {
3883         return typeof(this.get_value()) !== 'string';
3884     },
3885     set_value: function(value_) {
3886         this._super(value_);
3887         this.render_value();
3888     },
3889     render_value: function() {
3890         this.reference_ready = false;
3891         var vals = [], sel_val, m2o_val;
3892         if (typeof(this.get('value')) === 'string') {
3893             vals = this.get('value').split(',');
3894         }
3895         sel_val = vals[0] || false;
3896         m2o_val = vals[1] ? parseInt(vals[1], 10) : vals[1];
3897         if (!this.get("effective_readonly")) {
3898             this.selection.set_value(sel_val);
3899         }
3900         this.m2o.field.relation = sel_val;
3901         this.m2o.set_value(m2o_val);
3902         this.reference_ready = true;
3903     },
3904     data_changed: function() {
3905         var model = this.selection.get_value(),
3906             id = this.m2o.get_value();
3907         if (typeof(model) === 'string' && typeof(id) === 'number') {
3908             this.set({'value': model + ',' + id});
3909         } else {
3910             this.set({'value': false});
3911         }
3912     },
3913     get_field: function(name) {
3914         if (name === "selection") {
3915             return {
3916                 selection: this.view.fields_view.fields[this.name].selection,
3917                 type: "selection",
3918             };
3919         } else if (name === "m2o") {
3920             return {
3921                 relation: null,
3922                 type: "many2one",
3923             };
3924         }
3925         throw Exception("Should not happen");
3926     },
3927 }));
3928
3929 instance.web.form.FieldBinary = instance.web.form.AbstractField.extend(_.extend({}, instance.web.form.ReinitializeFieldMixin, {
3930     init: function(field_manager, node) {
3931         this._super(field_manager, node);
3932         this.iframe = this.element_id + '_iframe';
3933         this.binary_value = false;
3934     },
3935     initialize_content: function() {
3936         this.$element.find('input.oe-binary-file').change(this.on_file_change);
3937         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3938         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3939     },
3940     human_filesize : function(size) {
3941         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3942         var i = 0;
3943         while (size >= 1024) {
3944             size /= 1024;
3945             ++i;
3946         }
3947         return size.toFixed(2) + ' ' + units[i];
3948     },
3949     on_file_change: function(e) {
3950         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3951         // http://www.html5rocks.com/tutorials/file/dndfiles/
3952         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3953         window[this.iframe] = this.on_file_uploaded;
3954         if ($(e.target).val() != '') {
3955             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3956             this.$element.find('form.oe-binary-form').submit();
3957             this.$element.find('.oe-binary-progress').show();
3958             this.$element.find('.oe-binary').hide();
3959         }
3960     },
3961     on_file_uploaded: function(size, name, content_type, file_base64) {
3962         delete(window[this.iframe]);
3963         if (size === false) {
3964             this.do_warn("File Upload", "There was a problem while uploading your file");
3965             // TODO: use openerp web crashmanager
3966             console.warn("Error while uploading file : ", name);
3967         } else {
3968             this.on_file_uploaded_and_valid.apply(this, arguments);
3969         }
3970         this.$element.find('.oe-binary-progress').hide();
3971         this.$element.find('.oe-binary').show();
3972     },
3973     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3974     },
3975     on_save_as: function() {
3976         $.blockUI();
3977         this.session.get_file({
3978             url: '/web/binary/saveas_ajax',
3979             data: {data: JSON.stringify({
3980                 model: this.view.dataset.model,
3981                 id: (this.view.datarecord.id || ''),
3982                 field: this.name,
3983                 filename_field: (this.node.attrs.filename || ''),
3984                 context: this.view.dataset.get_context()
3985             })},
3986             complete: $.unblockUI,
3987             error: instance.webclient.crashmanager.on_rpc_error
3988         });
3989     },
3990     on_clear: function() {
3991         if (this.get('value') !== false) {
3992             this.binary_value = false;
3993             this.set({'value': false});
3994         }
3995         return false;
3996     }
3997 }));
3998
3999 instance.web.form.FieldBinaryFile = instance.web.form.FieldBinary.extend({
4000     template: 'FieldBinaryFile',
4001     initialize_content: function() {
4002         this._super();
4003         if (this.get("effective_readonly")) {
4004             var self = this;
4005             this.$element.find('a').click(function() {
4006                 if (self.get('value')) {
4007                     self.on_save_as();
4008                 }
4009                 return false;
4010             });
4011         }
4012     },
4013     set_value: function(value_) {
4014         this._super.apply(this, arguments);
4015         this.render_value();
4016     },
4017     render_value: function() {
4018         if (!this.get("effective_readonly")) {
4019             var show_value;
4020             if (this.node.attrs.filename) {
4021                 show_value = this.view.datarecord[this.node.attrs.filename] || '';
4022             } else {
4023                 show_value = (this.get('value') != null && this.get('value') !== false) ? this.get('value') : '';
4024             }
4025             this.$element.find('input').eq(0).val(show_value);
4026         } else {
4027             this.$element.find('a').show(!!this.get('value'));
4028             if (this.get('value')) {
4029                 var show_value = _t("Download") + " " + (this.view.datarecord[this.node.attrs.filename] || '');
4030                 this.$element.find('a').text(show_value);
4031             }
4032         }
4033     },
4034     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4035         this.binary_value = true;
4036         this.set({'value': file_base64});
4037         var show_value = name + " (" + this.human_filesize(size) + ")";
4038         this.$element.find('input').eq(0).val(show_value);
4039         this.set_filename(name);
4040     },
4041     set_filename: function(value_) {
4042         var filename = this.node.attrs.filename;
4043         if (this.view.fields[filename]) {
4044             this.view.fields[filename].set({value: value_});
4045         }
4046     },
4047     on_clear: function() {
4048         this._super.apply(this, arguments);
4049         this.$element.find('input').eq(0).val('');
4050         this.set_filename('');
4051     }
4052 });
4053
4054 instance.web.form.FieldBinaryImage = instance.web.form.FieldBinary.extend({
4055     template: 'FieldBinaryImage',
4056     initialize_content: function() {
4057         this._super();
4058         this.$placeholder = $(".oe_form_field-binary-image-placeholder", this.$element);
4059         if (!this.get("effective_readonly"))
4060             this.$element.find('.oe-binary').show();
4061         else
4062             this.$element.find('.oe-binary').hide();
4063     },
4064     set_value: function(value_) {
4065         this._super.apply(this, arguments);
4066         this.render_value();
4067     },
4068     render_value: function() {
4069         var url;
4070         if (this.get('value') && this.get('value').substr(0, 10).indexOf(' ') == -1) {
4071             url = 'data:image/png;base64,' + this.get('value');
4072         } else if (this.get('value')) {
4073             url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
4074                 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
4075         } else {
4076             url = "/web/static/src/img/placeholder.png";
4077         }
4078         var rendered = QWeb.render("FieldBinaryImage-img", {widget: this, url: url});;
4079         this.$placeholder.html(rendered);
4080     },
4081     on_file_change: function() {
4082         this.render_value();
4083         this._super.apply(this, arguments);
4084     },
4085     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
4086         this.set({'value': file_base64});
4087         this.binary_value = true;
4088         this.render_value();
4089     },
4090     on_clear: function() {
4091         this._super.apply(this, arguments);
4092         this.render_value();
4093     }
4094 });
4095
4096 instance.web.form.FieldStatus = instance.web.form.AbstractField.extend({
4097     tagName: "span",
4098     start: function() {
4099         this._super();
4100         this.selected_value = null;
4101         // preview in start only for selection fields, because of the dynamic behavior of many2one fields.
4102         if (this.field.type in ['selection']) {
4103             this.render_list();
4104         }
4105     },
4106     set_value: function(value_) {
4107         var self = this;
4108         this._super(value_);
4109         // find selected value:
4110         // - many2one: [2, "New"] -> 2
4111         // - selection: new -> new
4112         if (this.field.type == "many2one") {
4113             this.selected_value = value_[0];
4114         } else {
4115             this.selected_value = value_;
4116         }
4117         // trick to be sure all values are loaded in the form, therefore
4118         // enabling the evaluation of dynamic domains
4119         $.async_when().then(function() {
4120             return self.render_list();
4121         });
4122     },
4123
4124     /** Get the status list and render them
4125      *  to_show: [[identifier, value_to_display]] where
4126      *   - identifier = key for a selection, id for a many2one
4127      *   - display_val = label that will be displayed
4128      *   - ex: [[0, "New"]] (many2one) or [["new", "In Progress"]] (selection)
4129      */
4130     render_list: function() {
4131         var self = this;
4132         // get selection values, filter them and render them
4133         var selection_done = this.get_selection().pipe(self.proxy('filter_selection')).pipe(self.proxy('render_elements'));
4134     },
4135
4136     /** Get the selection list to be displayed in the statusbar widget.
4137      *  For selection fields: this is directly given by this.field.selection
4138      *  For many2one fields :
4139      *  - perform a search on the relation of the many2one field (given by
4140      *    field.relation )
4141      *  - get the field domain for the search
4142      *    - self.build_domain() gives the domain given by the view or by
4143      *      the field
4144      *    - if the optional statusbar_fold attribute is set to true, make
4145      *      an AND with build_domain to hide all 'fold=true' columns
4146      *    - make an OR with current value, to be sure it is displayed,
4147      *      with the correct order, even if it is folded
4148      */
4149     get_selection: function() {
4150         var self = this;
4151         if (this.field.type == "many2one") {
4152             this.selection = [];
4153             // get fold information from widget
4154             var fold = ((this.node.attrs || {}).statusbar_fold || true);
4155             // build final domain: if fold option required, add the 
4156             if (fold == true) {
4157                 var domain = new instance.web.CompoundDomain(['|'], ['&'], self.build_domain(), [['fold', '=', false]], [['id', '=', self.selected_value]]);
4158             } else {
4159                 var domain = new instance.web.CompoundDomain(['|'], self.build_domain(), [['id', '=', self.selected_value]]);
4160             }
4161             // get a DataSetSearch on the current field relation (ex: crm.lead.stage_id -> crm.case.stage)
4162             var model_ext = new instance.web.DataSetSearch(this, this.field.relation, self.build_context(), domain);
4163             // fetch selection
4164             var read_defer = model_ext.read_slice(['name'], {}).pipe( function (records) {
4165                 _(records).each(function (record) {
4166                     self.selection.push([record.id, record.name]);
4167                 });
4168             });
4169         } else {
4170             this.selection = this.field.selection;
4171             var read_defer = new $.Deferred().resolve();
4172         }
4173         return read_defer;
4174     },
4175
4176     /** Filters this.selection, according to values coming from the statusbar_visible
4177      *  attribute of the field. For example: statusbar_visible="draft,open"
4178      *  Currently, the key of (key, label) pairs has to be used in the
4179      *  selection of visible items. This feature is not meant to be used
4180      *  with many2one fields.
4181      */
4182     filter_selection: function() {
4183         var self = this;
4184         var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
4185             function(x) { return _.str.trim(x); });
4186         shown = _.select(shown, function(x) { return x.length > 0; });
4187         
4188         if (shown.length == 0) {
4189             this.to_show = this.selection;
4190         } else {
4191             this.to_show = _.select(this.selection, function(x) {
4192                 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
4193             });
4194         }
4195     },
4196
4197     /** Renders the widget. This function also checks for statusbar_colors='{"pending": "blue"}'
4198      *  attribute in the widget. This allows to set a given color to a given
4199      *  state (given by the key of (key, label)).
4200      */
4201     render_elements: function () {
4202         var content = instance.web.qweb.render("FieldStatus.content", {widget: this, _:_});
4203         this.$element.html(content);
4204
4205         var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
4206         var color = colors[this.selected_value];
4207         if (color) {
4208             var elem = this.$element.find("li.oe_form_steps_active span");
4209             elem.css("color", color);
4210         }
4211     },
4212 });
4213
4214 /**
4215  * Registry of form fields, called by :js:`instance.web.FormView`.
4216  *
4217  * All referenced classes must implement FieldMixin. Those represent the classes whose instances
4218  * will substitute to the <field> tags as defined in OpenERP's views.
4219  */
4220 instance.web.form.widgets = new instance.web.Registry({
4221     'char' : 'instance.web.form.FieldChar',
4222     'id' : 'instance.web.form.FieldID',
4223     'email' : 'instance.web.form.FieldEmail',
4224     'url' : 'instance.web.form.FieldUrl',
4225     'text' : 'instance.web.form.FieldText',
4226     'date' : 'instance.web.form.FieldDate',
4227     'datetime' : 'instance.web.form.FieldDatetime',
4228     'selection' : 'instance.web.form.FieldSelection',
4229     'many2one' : 'instance.web.form.FieldMany2One',
4230     'many2many' : 'instance.web.form.FieldMany2Many',
4231     'many2many_tags' : 'instance.web.form.FieldMany2ManyTags',
4232     'many2many_kanban' : 'instance.web.form.FieldMany2ManyKanban',
4233     'one2many' : 'instance.web.form.FieldOne2Many',
4234     'one2many_list' : 'instance.web.form.FieldOne2Many',
4235     'reference' : 'instance.web.form.FieldReference',
4236     'boolean' : 'instance.web.form.FieldBoolean',
4237     'float' : 'instance.web.form.FieldFloat',
4238     'integer': 'instance.web.form.FieldFloat',
4239     'float_time': 'instance.web.form.FieldFloat',
4240     'progressbar': 'instance.web.form.FieldProgressBar',
4241     'image': 'instance.web.form.FieldBinaryImage',
4242     'binary': 'instance.web.form.FieldBinaryFile',
4243     'statusbar': 'instance.web.form.FieldStatus'
4244 });
4245
4246 /**
4247  * Registry of widgets usable in the form view that can substitute to any possible
4248  * tags defined in OpenERP's form views.
4249  *
4250  * Every referenced class should extend FormWidget.
4251  */
4252 instance.web.form.tags = new instance.web.Registry({
4253     'button' : 'instance.web.form.WidgetButton',
4254 });
4255
4256 };
4257
4258 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: