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