[imp] made o2m capable of giving a correct value for on_change
[odoo/odoo.git] / addons / base / static / src / js / form.js
1 openerp.base.form = function (openerp) {
2
3 openerp.base.views.add('form', 'openerp.base.FormView');
4 openerp.base.FormView =  openerp.base.View.extend( /** @lends openerp.base.FormView# */{
5     /**
6      * Indicates that this view is not searchable, and thus that no search
7      * view should be displayed (if there is one active).
8      */
9     searchable: false,
10     template: "FormView",
11     /**
12      * @constructs
13      * @param {openerp.base.Session} session the current openerp session
14      * @param {String} element_id this view's root element id
15      * @param {openerp.base.DataSet} dataset the dataset this view will work with
16      * @param {String} view_id the identifier of the OpenERP view object
17      *
18      * @property {openerp.base.Registry} registry=openerp.base.form.widgets widgets registry for this form view instance
19      */
20     init: function(view_manager, session, element_id, dataset, view_id) {
21         this._super(session, element_id);
22         this.view_manager = view_manager || new openerp.base.NullViewManager();
23         this.dataset = dataset;
24         this.model = dataset.model;
25         this.view_id = view_id;
26         this.fields_view = {};
27         this.widgets = {};
28         this.widgets_counter = 0;
29         this.fields = {};
30         this.datarecord = {};
31         this.ready = false;
32         this.show_invalid = true;
33         this.touched = false;
34         this.flags = this.view_manager.flags || {};
35         this.default_focus_field = null;
36         this.default_focus_button = null;
37         this.registry = openerp.base.form.widgets;
38         this.has_been_loaded = $.Deferred();
39         this.$form_header = null;
40     },
41     start: function() {
42         //this.log('Starting FormView '+this.model+this.view_id)
43         if (this.embedded_view) {
44             return $.Deferred().then(this.on_loaded).resolve({fields_view: this.embedded_view});
45         } else {
46             var context = new openerp.base.CompoundContext(this.dataset.context);
47             if (this.view_manager.action && this.view_manager.action.context) {
48                 context.add(this.view_manager.action.context);
49             }
50             return this.rpc("/base/formview/load", {"model": this.model, "view_id": this.view_id,
51                 toolbar:!!this.flags.sidebar, context: context}, this.on_loaded);
52         }
53     },
54     on_loaded: function(data) {
55         var self = this;
56         this.fields_view = data.fields_view;
57         var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
58
59         this.$element.html(QWeb.render(this.template, { 'frame': frame, 'view': this }));
60         _.each(this.widgets, function(w) {
61             w.start();
62         });
63         this.$form_header = this.$element.find('#' + this.element_id + '_header');
64         this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
65             var action = $(this).data('pager-action');
66             self.on_pager_action(action);
67         });
68
69         this.$form_header.find('button.oe_form_button_save').click(this.do_save);
70         this.$form_header.find('button.oe_form_button_save_edit').click(this.do_save_edit);
71         this.$form_header.find('button.oe_form_button_cancel').click(this.do_cancel);
72         this.$form_header.find('button.oe_form_button_new').click(this.on_button_new);
73
74         this.view_manager.sidebar.set_toolbar(data.fields_view.toolbar);
75         this.has_been_loaded.resolve();
76     },
77     do_show: function () {
78         var self = this;
79         if (this.dataset.index === null) {
80             // null index means we should start a new record
81             this.on_button_new();
82         } else {
83             this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
84         }
85         self.$element.show();
86         this.view_manager.sidebar.do_refresh(true);
87     },
88     do_hide: function () {
89         this.$element.hide();
90     },
91     on_record_loaded: function(record) {
92         if (!record) {
93             throw("Form: No record received");
94         }
95         if (!record.id) {
96             this.$form_header.find('.oe_form_on_create').show();
97             this.$form_header.find('.oe_form_on_update').hide();
98             this.$form_header.find('button.oe_form_button_new').hide();
99         } else {
100             this.$form_header.find('.oe_form_on_create').hide();
101             this.$form_header.find('.oe_form_on_update').show();
102             this.$form_header.find('button.oe_form_button_new').show();
103         }
104         this.touched = false;
105         this.datarecord = record;
106         for (var f in this.fields) {
107             var field = this.fields[f];
108             field.touched = false;
109             field.set_value(this.datarecord[f] || false);
110             field.validate();
111         }
112         if (!record.id) {
113             // New record: Second pass in order to trigger the onchanges
114             this.touched = true;
115             this.show_invalid = false;
116             for (var f in record) {
117                 var field = this.fields[f];
118                 if (field) {
119                     field.touched = true;
120                     this.do_onchange(field);
121                 }
122             }
123         }
124         this.on_form_changed();
125         this.show_invalid = this.ready = true;
126         this.do_update_pager(record.id == null);
127         this.do_update_sidebar();
128         if (this.default_focus_field) {
129             this.default_focus_field.focus();
130         }
131     },
132     on_form_changed: function() {
133         for (var w in this.widgets) {
134             w = this.widgets[w];
135             w.process_attrs();
136             w.update_dom();
137         }
138     },
139     on_pager_action: function(action) {
140         switch (action) {
141             case 'first':
142                 this.dataset.index = 0;
143                 break;
144             case 'previous':
145                 this.dataset.previous();
146                 break;
147             case 'next':
148                 this.dataset.next();
149                 break;
150             case 'last':
151                 this.dataset.index = this.dataset.ids.length - 1;
152                 break;
153         }
154         this.reload();
155     },
156     do_update_pager: function(hide_index) {
157         var $pager = this.$element.find('#' + this.element_id + '_header div.oe_form_pager');
158         var index = hide_index ? '-' : this.dataset.index + 1;
159         $pager.find('span.oe_pager_index').html(index);
160         $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
161     },
162     do_onchange: function(widget, processed) {
163         processed = processed || [];
164         if (widget.node.attrs.on_change) {
165             var self = this;
166             this.ready = false;
167             var onchange = _.trim(widget.node.attrs.on_change);
168             var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
169             console.log("Onchange triggered for field '%s' -> %s", widget.name, onchange);
170             if (call) {
171                 var method = call[1], args = [];
172                 var argument_replacement = {
173                     'False' : false,
174                     'True' : true,
175                     'None' : null
176                 }
177                 var parent_fields = null;
178                 _.each(call[2].split(','), function(a) {
179                     var field = _.trim(a);
180                     if (field in argument_replacement) {
181                         args.push(argument_replacement[field]);
182                         return;
183                     } else if (self.fields[field]) {
184                         var value = self.fields[field].get_on_change_value();
185                         args.push(value == null ? false : value);
186                         return;
187                     } else {
188                         var splitted = field.split('.');
189                         if (splitted.length > 1 && _.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
190                             if (parent_fields === null) {
191                                 parent_fields = self.dataset.parent_view.get_fields_values();
192                             }
193                             var p_val = parent_fields[_.trim(splitted[1])];
194                             if (p_val !== undefined) {
195                                 args.push(value ? value : false);
196                                 return;
197                             }
198                         }
199                     }
200                     throw "Could not get field with name '" + field +
201                         "' for onchange '" + onchange + "'";
202                 });
203                 var ajax = {
204                     url: '/base/dataset/call',
205                     async: false
206                 };
207                 return this.rpc(ajax, {
208                     model: this.dataset.model,
209                     method: method,
210                     args: [(this.datarecord.id == null ? [] : [this.datarecord.id])].concat(args)
211                 }, function(response) {
212                     self.on_processed_onchange(response, processed);
213                 });
214             } else {
215                 this.log("Wrong on_change format", on_change);
216             }
217         }
218     },
219     on_processed_onchange: function(response, processed) {
220         var result = response.result;
221         if (result.value) {
222             console.log("      |-> Onchange Response :", result.value);
223             for (var f in result.value) {
224                 var field = this.fields[f];
225                 if (field) {
226                     var value = result.value[f];
227                     processed.push(field.name);
228                     if (field.get_value() != value) {
229                         console.log("          |-> Onchange Action :  change '%s' value from '%s' to '%s'", field.name, field.get_value(), value);
230                         field.set_value(value);
231                         if (_.indexOf(processed, field.name) < 0) {
232                             this.do_onchange(field, processed);
233                         }
234                     }
235                 } else {
236                     this.log("warning : on_processed_onchange can't find field " + field, result);
237                 }
238             }
239             this.on_form_changed();
240         }
241         if (result.warning) {
242             $(QWeb.render("DialogWarning", result.warning)).dialog({
243                 modal: true,
244                 buttons: {
245                     Ok: function() {
246                         $(this).dialog("close");
247                     }
248                 }
249             });
250         }
251         if (result.domain) {
252             // Will be removed ?
253         }
254         this.ready = true;
255     },
256     on_button_new: function() {
257         var self = this;
258         $.when(this.has_been_loaded).then(function() {
259             self.dataset.default_get(_.keys(self.fields_view.fields), function(result) {
260                 self.on_record_loaded(result.result);
261             });
262         });
263     },
264     /**
265      * Triggers saving the form's record. Chooses between creating a new
266      * record or saving an existing one depending on whether the record
267      * already has an id property.
268      *
269      * @param {Function} success callback on save success
270      * @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)
271      */
272     do_save: function(success, prepend_on_create) {
273         var self = this;
274         if (!this.ready) {
275             return false;
276         }
277         var invalid = false,
278             values = {},
279             first_invalid_field = null;
280         for (var f in this.fields) {
281             f = this.fields[f];
282             if (f.invalid) {
283                 invalid = true;
284                 f.update_dom();
285                 if (!first_invalid_field) {
286                     first_invalid_field = f;
287                 }
288             } else if (f.touched) {
289                 values[f.name] = f.get_value();
290             }
291         }
292         if (invalid) {
293             first_invalid_field.focus();
294             this.on_invalid();
295             return false;
296         } else {
297             this.log("About to save", values);
298             if (!this.datarecord.id) {
299                 this.dataset.create(values, function(r) {
300                     self.on_created(r, success, prepend_on_create);
301                 });
302             } else {
303                 this.dataset.write(this.datarecord.id, values, function(r) {
304                     self.on_saved(r, success);
305                 });
306             }
307             return true;
308         }
309     },
310     do_save_edit: function() {
311         this.do_save();
312         //this.switch_readonly(); Use promises
313     },
314     switch_readonly: function() {
315     },
316     switch_editable: function() {
317     },
318     on_invalid: function() {
319         var msg = "<ul>";
320         _.each(this.fields, function(f) {
321             if (f.invalid) {
322                 msg += "<li>" + f.string + "</li>";
323             }
324         });
325         msg += "</ul>";
326         this.notification.warn("The following fields are invalid :", msg);
327     },
328     on_saved: function(r, success) {
329         if (!r.result) {
330             this.notification.warn("Record not saved", "Problem while saving record.");
331         } else {
332             this.notification.notify("Record saved", "The record #" + this.datarecord.id + " has been saved.");
333             if (success) {
334                 success(r);
335             }
336             this.reload();
337         }
338     },
339     /**
340      * Updates the form' dataset to contain the new record:
341      *
342      * * Adds the newly created record to the current dataset (at the end by
343      *   default)
344      * * Selects that record (sets the dataset's index to point to the new
345      *   record's id).
346      * * Updates the pager and sidebar displays
347      *
348      * @param {Object} r
349      * @param {Function} success callback to execute after having updated the dataset
350      * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
351      */
352     on_created: function(r, success, prepend_on_create) {
353         if (!r.result) {
354             this.notification.warn("Record not created", "Problem while creating record.");
355         } else {
356             this.datarecord.id = r.result;
357             if (!prepend_on_create) {
358                 this.dataset.ids.push(this.datarecord.id);
359                 this.dataset.index = this.dataset.ids.length - 1;
360             } else {
361                 this.dataset.ids.unshift(this.datarecord.id);
362                 this.dataset.index = 0;
363             }
364             this.do_update_pager();
365             this.do_update_sidebar();
366             this.notification.notify("Record created", "The record has been created with id #" + this.datarecord.id);
367             if (success) {
368                 success(_.extend(r, {created: true}));
369             }
370             this.reload();
371         }
372     },
373     do_search: function (domains, contexts, groupbys) {
374         this.notification.notify("Searching form");
375     },
376     on_action: function (action) {
377         this.notification.notify('Executing action ' + action);
378     },
379     do_cancel: function () {
380         this.notification.notify("Cancelling form");
381     },
382     do_update_sidebar: function() {
383         if (this.flags.sidebar === false) {
384             return;
385         }
386         if (!this.datarecord.id) {
387             this.on_attachments_loaded([]);
388         } else {
389             // TODO fme: modify this so it doesn't try to load attachments when there is not sidebar
390             /*this.rpc('/base/dataset/search_read', {
391                 model: 'ir.attachment',
392                 fields: ['name', 'url', 'type'],
393                 domain: [['res_model', '=', this.dataset.model], ['res_id', '=', this.datarecord.id], ['type', 'in', ['binary', 'url']]],
394                 context: this.dataset.context
395             }, this.on_attachments_loaded);*/
396         }
397     },
398     on_attachments_loaded: function(attachments) {
399         this.$sidebar = this.view_manager.sidebar.$element.find('.sidebar-attachments');
400         this.attachments = attachments;
401         this.$sidebar.html(QWeb.render('FormView.sidebar.attachments', this));
402         this.$sidebar.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
403         this.$sidebar.find('.oe-binary-file').change(this.on_attachment_changed);
404     },
405     on_attachment_changed: function(e) {
406         window[this.element_id + '_iframe'] = this.do_update_sidebar;
407         var $e = $(e.target);
408         if ($e.val() != '') {
409             this.$sidebar.find('form.oe-binary-form').submit();
410             $e.parent().find('input[type=file]').attr('disabled', 'true');
411             $e.parent().find('button').attr('disabled', 'true').find('img, span').toggle();
412         }
413     },
414     on_attachment_delete: function(e) {
415         var self = this, $e = $(e.currentTarget);
416         var name = _.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
417         if (confirm("Do you really want to delete the attachment " + name + " ?")) {
418             this.rpc('/base/dataset/unlink', {
419                 model: 'ir.attachment',
420                 ids: [parseInt($e.attr('data-id'))]
421             }, function(r) {
422                 $e.parent().remove();
423                 self.notification.notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
424             });
425         }
426     },
427     reload: function() {
428         if (this.datarecord.id) {
429             this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
430         } else {
431             this.on_button_new();
432         }
433     },
434     get_fields_values: function() {
435         var values = {};
436         _.each(this.fields, function(value, key) {
437             values[key] = value.get_value();
438         });
439         return values;
440     }
441 });
442
443 /** @namespace */
444 openerp.base.form = {};
445
446 openerp.base.form.compute_domain = function(expr, fields) {
447     var stack = [];
448     for (var i = expr.length - 1; i >= 0; i--) {
449         var ex = expr[i];
450         if (ex.length == 1) {
451             var top = stack.pop();
452             switch (ex) {
453                 case '|':
454                     stack.push(stack.pop() || top);
455                     continue;
456                 case '&':
457                     stack.push(stack.pop() && top);
458                     continue;
459                 case '!':
460                     stack.push(!top);
461                     continue;
462                 default:
463                     throw new Error('Unknown domain operator ' + ex);
464             }
465         }
466
467         var field = fields[ex[0]].get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
468         var op = ex[1];
469         var val = ex[2];
470
471         switch (op.toLowerCase()) {
472             case '=':
473             case '==':
474                 stack.push(field == val);
475                 break;
476             case '!=':
477             case '<>':
478                 stack.push(field != val);
479                 break;
480             case '<':
481                 stack.push(field < val);
482                 break;
483             case '>':
484                 stack.push(field > val);
485                 break;
486             case '<=':
487                 stack.push(field <= val);
488                 break;
489             case '>=':
490                 stack.push(field >= val);
491                 break;
492             case 'in':
493                 stack.push(_(val).contains(field));
494                 break;
495             case 'not in':
496                 stack.push(!_(val).contains(field));
497                 break;
498             default:
499                 this.log("Unsupported operator in attrs :", op);
500         }
501     }
502     return _.all(stack);
503 };
504
505 openerp.base.form.Widget = openerp.base.Controller.extend({
506     template: 'Widget',
507     init: function(view, node) {
508         this.view = view;
509         this.node = node;
510         this.attrs = JSON.parse(this.node.attrs.attrs || '{}');
511         this.type = this.type || node.tag;
512         this.element_name = this.element_name || this.type;
513         this.element_id = [this.view.element_id, this.element_name, this.view.widgets_counter++].join("_");
514
515         this._super(this.view.session, this.element_id);
516
517         this.view.widgets[this.element_id] = this;
518         this.children = node.children;
519         this.colspan = parseInt(node.attrs.colspan || 1);
520
521         this.string = this.string || node.attrs.string;
522         this.help = this.help || node.attrs.help;
523         this.invisible = (node.attrs.invisible == '1');
524     },
525     start: function() {
526         this.$element = $('#' + this.element_id);
527     },
528     process_attrs: function() {
529         var compute_domain = openerp.base.form.compute_domain;
530         for (var a in this.attrs) {
531             this[a] = compute_domain(this.attrs[a], this.view.fields);
532         }
533     },
534     update_dom: function() {
535         this.$element.toggle(!this.invisible);
536     },
537     render: function() {
538         var template = this.template;
539         return QWeb.render(template, { "widget": this });
540     }
541 });
542
543 openerp.base.form.WidgetFrame = openerp.base.form.Widget.extend({
544     template: 'WidgetFrame',
545     init: function(view, node) {
546         this._super(view, node);
547         this.columns = node.attrs.col || 4;
548         this.x = 0;
549         this.y = 0;
550         this.table = [];
551         this.add_row();
552         for (var i = 0; i < node.children.length; i++) {
553             var n = node.children[i];
554             if (n.tag == "newline") {
555                 this.add_row();
556             } else {
557                 this.handle_node(n);
558             }
559         }
560         this.set_row_cells_with(this.table[this.table.length - 1]);
561     },
562     add_row: function(){
563         if (this.table.length) {
564             this.set_row_cells_with(this.table[this.table.length - 1]);
565         }
566         var row = [];
567         this.table.push(row);
568         this.x = 0;
569         this.y += 1;
570         return row;
571     },
572     set_row_cells_with: function(row) {
573         for (var i = 0; i < row.length; i++) {
574             var w = row[i];
575             if (w.is_field_label) {
576                 w.width = "1%";
577                 if (row[i + 1]) {
578                     row[i + 1].width = Math.round((100 / this.columns) * (w.colspan + 1) - 1) + '%';
579                 }
580             } else if (w.width === undefined) {
581                 w.width = Math.round((100 / this.columns) * w.colspan) + '%';
582             }
583         }
584     },
585     handle_node: function(node) {
586         var type = this.view.fields_view.fields[node.attrs.name] || {};
587         var widget = new (this.view.registry.get_any(
588                 [node.attrs.widget, type.type, node.tag])) (this.view, node);
589         if (node.tag == 'field') {
590             if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
591                 this.view.default_focus_field = widget;
592             }
593             if (node.attrs.nolabel != '1') {
594                 var label = new (this.view.registry.get_object('label')) (this.view, node);
595                 label["for"] = widget;
596                 this.add_widget(label);
597             }
598         }
599         this.add_widget(widget);
600     },
601     add_widget: function(widget) {
602         var current_row = this.table[this.table.length - 1];
603         if (current_row.length && (this.x + widget.colspan) > this.columns) {
604             current_row = this.add_row();
605         }
606         current_row.push(widget);
607         this.x += widget.colspan;
608         return widget;
609     }
610 });
611
612 openerp.base.form.WidgetNotebook = openerp.base.form.Widget.extend({
613     init: function(view, node) {
614         this._super(view, node);
615         this.template = "WidgetNotebook";
616         this.pages = [];
617         for (var i = 0; i < node.children.length; i++) {
618             var n = node.children[i];
619             if (n.tag == "page") {
620                 var page = new openerp.base.form.WidgetFrame(this.view, n);
621                 this.pages.push(page);
622             }
623         }
624     },
625     start: function() {
626         this._super.apply(this, arguments);
627         this.$element.tabs();
628     }
629 });
630
631 openerp.base.form.WidgetSeparator = openerp.base.form.Widget.extend({
632     init: function(view, node) {
633         this._super(view, node);
634         this.template = "WidgetSeparator";
635     }
636 });
637
638 openerp.base.form.WidgetButton = openerp.base.form.Widget.extend({
639     init: function(view, node) {
640         this._super(view, node);
641         this.template = "WidgetButton";
642         if (node.attrs.default_focus == '1') {
643             // TODO fme: provide enter key binding to widgets
644             this.view.default_focus_button = this;
645         }
646     },
647     start: function() {
648         this._super.apply(this, arguments);
649         this.$element.click(this.on_click);
650     },
651     on_click: function(saved) {
652         var self = this;
653         if (!this.node.attrs.special && this.view.touched && saved !== true) {
654             this.view.do_save(function() {
655                 self.on_click(true);
656             });
657         } else {
658             if (this.node.attrs.confirm) {
659                 var dialog = $('<div>' + this.node.attrs.confirm + '</div>').dialog({
660                     title: 'Confirm',
661                     modal: true,
662                     buttons: {
663                         Ok: function() {
664                             self.on_confirmed();
665                             $(this).dialog("close");
666                         },
667                         Cancel: function() {
668                             $(this).dialog("close");
669                         }
670                     }
671                 });
672             } else {
673                 this.on_confirmed();
674             }
675         }
676     },
677     on_confirmed: function() {
678         var self = this;
679
680         this.view.execute_action(
681             this.node.attrs, this.view.dataset, this.session.action_manager,
682             this.view.datarecord.id, function (result) {
683                 self.log("Button returned", result);
684                 self.view.reload();
685             }, function() {
686                 self.view.reload();
687             });
688     }
689 });
690
691 openerp.base.form.WidgetLabel = openerp.base.form.Widget.extend({
692     init: function(view, node) {
693         this.element_name = 'label_' + node.attrs.name;
694
695         this._super(view, node);
696
697         // TODO fme: support for attrs.align
698         if (this.node.tag == 'label' && this.node.attrs.colspan) {
699             this.is_field_label = false;
700             this.template = "WidgetParagraph";
701         } else {
702             this.is_field_label = true;
703             this.template = "WidgetLabel";
704         }
705         this.colspan = 1;
706     },
707     render: function () {
708         if (this['for'] && this.type !== 'label') {
709             return QWeb.render(this.template, {widget: this['for']});
710         }
711         // Actual label widgets should not have a false and have type label
712         return QWeb.render(this.template, {widget: this});
713     }
714 });
715
716 openerp.base.form.Field = openerp.base.form.Widget.extend({
717     init: function(view, node) {
718         this.name = node.attrs.name;
719         this.value = undefined;
720         view.fields[this.name] = this;
721         this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
722         this.element_name = "field_" + this.name + "_" + this.type;
723
724         this._super(view, node);
725
726         if (node.attrs.nolabel != '1' && this.colspan > 1) {
727             this.colspan--;
728         }
729         this.field = view.fields_view.fields[node.attrs.name] || {};
730         this.string = node.attrs.string || this.field.string;
731         this.help = node.attrs.help || this.field.help;
732         this.invisible = (this.invisible || this.field.invisible == '1');
733         this.nolabel = (this.field.nolabel || node.attrs.nolabel) == '1';
734         this.readonly = (this.field.readonly || node.attrs.readonly) == '1';
735         this.required = (this.field.required || node.attrs.required) == '1';
736         this.invalid = false;
737         this.touched = false;
738     },
739     set_value: function(value) {
740         this.value = value;
741         this.invalid = false;
742         this.update_dom();
743     },
744     set_value_from_ui: function() {
745         this.value = undefined;
746     },
747     get_value: function() {
748         return this.value;
749     },
750     get_on_change_value: function() {
751         return this.get_value();
752     },
753     update_dom: function() {
754         this._super.apply(this, arguments);
755         this.$element.toggleClass('disabled', this.readonly);
756         this.$element.toggleClass('required', this.required);
757         if (this.view.show_invalid) {
758             this.$element.toggleClass('invalid', this.invalid);
759         }
760     },
761     on_ui_change: function() {
762         this.touched = this.view.touched = true;
763         this.validate();
764         if (!this.invalid) {
765             this.set_value_from_ui();
766             this.view.do_onchange(this);
767             this.view.on_form_changed();
768         } else {
769             this.update_dom();
770         }
771     },
772     validate: function() {
773         this.invalid = false;
774     },
775     focus: function() {
776     }
777 });
778
779 openerp.base.form.FieldChar = openerp.base.form.Field.extend({
780     init: function(view, node) {
781         this._super(view, node);
782         this.template = "FieldChar";
783     },
784     start: function() {
785         this._super.apply(this, arguments);
786         this.$element.find('input').change(this.on_ui_change);
787     },
788     set_value: function(value) {
789         this._super.apply(this, arguments);
790         var show_value = (value != null && value !== false) ? value : '';
791         this.$element.find('input').val(show_value);
792     },
793     update_dom: function() {
794         this._super.apply(this, arguments);
795         this.$element.find('input').attr('disabled', this.readonly);
796     },
797     set_value_from_ui: function() {
798         this.value = this.$element.find('input').val();
799     },
800     validate: function() {
801         this.invalid = false;
802         var value = this.$element.find('input').val();
803         if (value === "") {
804             this.invalid = this.required;
805         } else if (this.validation_regex) {
806             this.invalid = !this.validation_regex.test(value);
807         }
808     },
809     focus: function() {
810         this.$element.find('input').focus();
811     }
812 });
813
814 openerp.base.form.FieldEmail = openerp.base.form.FieldChar.extend({
815     init: function(view, node) {
816         this._super(view, node);
817         this.template = "FieldEmail";
818         this.validation_regex = /@/;
819     },
820     start: function() {
821         this._super.apply(this, arguments);
822         this.$element.find('button').click(this.on_button_clicked);
823     },
824     on_button_clicked: function() {
825         if (!this.value || this.invalid) {
826             this.notification.warn("E-mail error", "Can't send email to invalid e-mail address");
827         } else {
828             location.href = 'mailto:' + this.value;
829         }
830     },
831     set_value: function(value) {
832         this._super.apply(this, arguments);
833         var show_value = (value != null && value !== false) ? value : '';
834         this.$element.find('a').attr('href', 'mailto:' + show_value);
835     }
836 });
837
838 openerp.base.form.FieldUrl = openerp.base.form.FieldChar.extend({
839     init: function(view, node) {
840         this._super(view, node);
841         this.template = "FieldUrl";
842     },
843     start: function() {
844         this._super.apply(this, arguments);
845         this.$element.find('button').click(this.on_button_clicked);
846     },
847     on_button_clicked: function() {
848         if (!this.value) {
849             this.notification.warn("Resource error", "This resource is empty");
850         } else {
851             window.open(this.value);
852         }
853     }
854 });
855
856 openerp.base.form.FieldFloat = openerp.base.form.FieldChar.extend({
857     init: function(view, node) {
858         this._super(view, node);
859         this.validation_regex = /^-?\d+(\.\d+)?$/;
860     },
861     set_value: function(value) {
862         this._super.apply(this, [value]);
863         if (value === false || value === undefined) {
864             // As in GTK client, floats default to 0
865             value = 0;
866         }
867         var show_value = value.toFixed(2);
868         this.$element.find('input').val(show_value);
869     },
870     set_value_from_ui: function() {
871         this.value = Number(this.$element.find('input').val().replace(/,/g, '.'));
872     }
873 });
874
875 openerp.base.form.FieldDatetime = openerp.base.form.Field.extend({
876     init: function(view, node) {
877         this._super(view, node);
878         this.template = "FieldDate";
879         this.jqueryui_object = 'datetimepicker';
880     },
881     start: function() {
882         this._super.apply(this, arguments);
883         this.$element.find('input').change(this.on_ui_change)[this.jqueryui_object]({
884             dateFormat: 'yy-mm-dd',
885             timeFormat: 'hh:mm:ss'
886         });
887     },
888     set_value: function(value) {
889         this._super.apply(this, arguments);
890         if (value == null || value == false) {
891             this.$element.find('input').val('');
892         } else {
893             this.$element.find('input').unbind('change');
894             // jQuery UI date picker wrongly call on_change event herebelow
895             this.$element.find('input')[this.jqueryui_object]('setDate', this.parse(value));
896             this.$element.find('input').change(this.on_ui_change);
897         }
898     },
899     set_value_from_ui: function() {
900         this.value = this.$element.find('input')[this.jqueryui_object]('getDate') || false;
901         if (this.value) {
902             this.value = this.format(this.value);
903         }
904     },
905     validate: function() {
906         this.invalid = this.required && !this.$element.find('input')[this.jqueryui_object]('getDate');
907     },
908     focus: function() {
909         this.$element.find('input').focus();
910     },
911     parse: openerp.base.parse_datetime,
912     format: openerp.base.format_datetime
913 });
914
915 openerp.base.form.FieldDate = openerp.base.form.FieldDatetime.extend({
916     init: function(view, node) {
917         this._super(view, node);
918         this.jqueryui_object = 'datepicker';
919     },
920     parse: openerp.base.parse_date,
921     format: openerp.base.format_date
922 });
923
924 openerp.base.form.FieldFloatTime = openerp.base.form.FieldChar.extend({
925     init: function(view, node) {
926         this._super(view, node);
927         this.validation_regex = /^\d+:\d+$/;
928     },
929     set_value: function(value) {
930         this._super.apply(this, [value]);
931         if (value === false || value === undefined) {
932             // As in GTK client, floats default to 0
933             value = 0;
934         }
935         var show_value = _.sprintf("%02d:%02d", Math.floor(value), Math.round((value % 1) * 60));
936         this.$element.find('input').val(show_value);
937     },
938     set_value_from_ui: function() {
939         var time = this.$element.find('input').val().split(':');
940         this.set_value(parseInt(time[0], 10) + parseInt(time[1], 10) / 60);
941     }
942 });
943
944 openerp.base.form.FieldText = openerp.base.form.Field.extend({
945     init: function(view, node) {
946         this._super(view, node);
947         this.template = "FieldText";
948         this.validation_regex = null;
949     },
950     start: function() {
951         this._super.apply(this, arguments);
952         this.$element.find('textarea').change(this.on_ui_change);
953     },
954     set_value: function(value) {
955         this._super.apply(this, arguments);
956         var show_value = (value != null && value !== false) ? value : '';
957         this.$element.find('textarea').val(show_value);
958     },
959     update_dom: function() {
960         this._super.apply(this, arguments);
961         this.$element.find('textarea').attr('disabled', this.readonly);
962     },
963     set_value_from_ui: function() {
964         this.value = this.$element.find('textarea').val();
965     },
966     validate: function() {
967         this.invalid = false;
968         var value = this.$element.find('textarea').val();
969         if (value === "") {
970             this.invalid = this.required;
971         } else if (this.validation_regex) {
972             this.invalid = !this.validation_regex.test(value);
973         }
974     },
975     focus: function() {
976         this.$element.find('textarea').focus();
977     }
978 });
979
980 openerp.base.form.FieldBoolean = openerp.base.form.Field.extend({
981     init: function(view, node) {
982         this._super(view, node);
983         this.template = "FieldBoolean";
984     },
985     start: function() {
986         var self = this;
987         this._super.apply(this, arguments);
988         this.$element.find('input').click(function() {
989             if ($(this).is(':checked') != self.value) {
990                 self.on_ui_change();
991             }
992         });
993     },
994     set_value: function(value) {
995         this._super.apply(this, arguments);
996         this.$element.find('input')[0].checked = value;
997     },
998     set_value_from_ui: function() {
999         this.value = this.$element.find('input').is(':checked');
1000     },
1001     update_dom: function() {
1002         this._super.apply(this, arguments);
1003         this.$element.find('input').attr('disabled', this.readonly);
1004     },
1005     validate: function() {
1006         this.invalid = this.required && !this.$element.find('input').is(':checked');
1007     },
1008     focus: function() {
1009         this.$element.find('input').focus();
1010     }
1011 });
1012
1013 openerp.base.form.FieldProgressBar = openerp.base.form.Field.extend({
1014     init: function(view, node) {
1015         this._super(view, node);
1016         this.template = "FieldProgressBar";
1017     },
1018     start: function() {
1019         this._super.apply(this, arguments);
1020         this.$element.find('div').progressbar({
1021             value: this.value,
1022             disabled: this.readonly
1023         });
1024     },
1025     set_value: function(value) {
1026         this._super.apply(this, arguments);
1027         var show_value = Number(value);
1028         if (show_value === NaN) {
1029             show_value = 0;
1030         }
1031         this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1032     }
1033 });
1034
1035 openerp.base.form.FieldTextXml = openerp.base.form.Field.extend({
1036 // to replace view editor
1037 });
1038
1039 openerp.base.form.FieldSelection = openerp.base.form.Field.extend({
1040     init: function(view, node) {
1041         this._super(view, node);
1042         this.template = "FieldSelection";
1043     },
1044     start: function() {
1045         this._super.apply(this, arguments);
1046         this.$element.find('select').change(this.on_ui_change);
1047     },
1048     set_value: function(value) {
1049         this._super.apply(this, arguments);
1050         if (value != null && value !== false) {
1051             this.$element.find('select').val(value);
1052         } else {
1053             this.$element.find('select').val('false');
1054         }
1055     },
1056     set_value_from_ui: function() {
1057         this.value = this.$element.find('select').val();
1058     },
1059     update_dom: function() {
1060         this._super.apply(this, arguments);
1061         this.$element.find('select').attr('disabled', this.readonly);
1062     },
1063     validate: function() {
1064         this.invalid = this.required && this.$element.find('select').val() === "";
1065     },
1066     focus: function() {
1067         this.$element.find('select').focus();
1068     }
1069 });
1070
1071 // jquery autocomplete tweak to allow html
1072 (function() {
1073     var proto = $.ui.autocomplete.prototype,
1074         initSource = proto._initSource;
1075
1076     function filter( array, term ) {
1077         var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1078         return $.grep( array, function(value) {
1079             return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1080         });
1081     }
1082
1083     $.extend( proto, {
1084         _initSource: function() {
1085             if ( this.options.html && $.isArray(this.options.source) ) {
1086                 this.source = function( request, response ) {
1087                     response( filter( this.options.source, request.term ) );
1088                 };
1089             } else {
1090                 initSource.call( this );
1091             }
1092         },
1093
1094         _renderItem: function( ul, item) {
1095             return $( "<li></li>" )
1096                 .data( "item.autocomplete", item )
1097                 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1098                 .appendTo( ul );
1099         }
1100     });
1101 })();
1102
1103 var build_view_fields_values = function(view) {
1104     var a_dataset = view.dataset || {};
1105     var fields_values = view.get_fields_values();
1106     var parent_values = a_dataset.parent_view ? a_dataset.parent_view.get_fields_values() : {};
1107     fields_values.parent = parent_values;
1108     return fields_values;
1109 }
1110 /**
1111  * Builds a new context usable for operations related to fields by merging
1112  * the fields'context with the action's context.
1113  */
1114 var build_relation_context = function(relation_field) {
1115     var a_context = relation_field.view.dataset.get_context() || {};
1116     var fields_values = build_view_fields_values(relation_field.view);
1117     var f_context = new openerp.base.CompoundContext(relation_field.field.context || {}).set_eval_context(fields_values);
1118     var ctx = new openerp.base.CompoundContext(a_context, f_context);
1119     return ctx;
1120 }
1121 var build_relation_domain = function(relation_field) {
1122     var fields_values = build_view_fields_values(relation_field.view);
1123     var f_domain = new openerp.base.CompoundDomain(relation_field.field.domain || []).set_eval_context(fields_values);
1124     return f_domain;
1125 }
1126
1127 openerp.base.form.FieldMany2One = openerp.base.form.Field.extend({
1128     init: function(view, node) {
1129         this._super(view, node);
1130         this.template = "FieldMany2One";
1131         this.limit = 7;
1132         this.value = null;
1133         this.cm_id = _.uniqueId('m2o_cm_');
1134         this.last_search = [];
1135         this.tmp_value = undefined;
1136     },
1137     start: function() {
1138         this._super();
1139         var self = this;
1140         this.$input = this.$element.find("input");
1141         this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1142         this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1143
1144         // context menu
1145         var bindings = {};
1146         bindings[this.cm_id + "_search"] = function() {
1147             self._search_create_popup("search");
1148         };
1149         bindings[this.cm_id + "_create"] = function() {
1150             self._search_create_popup("form");
1151         };
1152         bindings[this.cm_id + "_open"] = function() {
1153             if (!self.value) {
1154                 return;
1155             }
1156             self.session.action_manager.do_action({
1157                 "res_model": self.field.relation,
1158                 "views":[[false,"form"]],
1159                 "res_id": self.value[0],
1160                 "type":"ir.actions.act_window",
1161                 "view_type":"form",
1162                 "view_mode":"form",
1163                 "target":"new",
1164                 "context": build_relation_context(self)
1165             });
1166         };
1167         var cmenu = this.$menu_btn.contextMenu(this.cm_id, {'leftClickToo': true,
1168             bindings: bindings, itemStyle: {"color": ""},
1169             onContextMenu: function() {
1170                 if(self.value) {
1171                     $("#" + self.cm_id + "_open").removeClass("oe-m2o-disabled-cm");
1172                 } else {
1173                     $("#" + self.cm_id + "_open").addClass("oe-m2o-disabled-cm");
1174                 }
1175                 return true;
1176             }
1177         });
1178
1179         // some behavior for input
1180         this.$input.keyup(function() {
1181             if (self.$input.val() === "") {
1182                 self._change_int_value(null);
1183             } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1184                 self._change_int_value(undefined);
1185             }
1186         });
1187         this.$drop_down.click(function() {
1188             if (self.$input.autocomplete("widget").is(":visible")) {
1189                 self.$input.autocomplete("close");
1190             } else {
1191                 if (self.value) {
1192                     self.$input.autocomplete("search", "");
1193                 } else {
1194                     self.$input.autocomplete("search");
1195                 }
1196                 self.$input.focus();
1197             }
1198         });
1199         var anyoneLoosesFocus = function() {
1200             if (!self.$input.is(":focus") &&
1201                     !self.$input.autocomplete("widget").is(":visible") &&
1202                     !self.value) {
1203                 if(self.value === undefined && self.last_search.length > 0) {
1204                     self._change_int_ext_value(self.last_search[0]);
1205                 } else {
1206                     self._change_int_ext_value(null);
1207                 }
1208             }
1209         }
1210         this.$input.focusout(anyoneLoosesFocus);
1211
1212         // autocomplete
1213         this.$input.autocomplete({
1214             source: function(req, resp) { self.get_search_result(req, resp); },
1215             select: function(event, ui) {
1216                 var item = ui.item;
1217                 if (item.id) {
1218                     self._change_int_value([item.id, item.name]);
1219                 } else if (item.action) {
1220                     self._change_int_value(undefined);
1221                     item.action();
1222                     return false;
1223                 }
1224             },
1225             focus: function(e, ui) {
1226                 e.preventDefault();
1227             },
1228             html: true,
1229             close: anyoneLoosesFocus,
1230             minLength: 0,
1231             delay: 0
1232         });
1233     },
1234     // autocomplete component content handling
1235     get_search_result: function(request, response) {
1236         var search_val = request.term;
1237         var self = this;
1238
1239         var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1240
1241         dataset.name_search(search_val, build_relation_domain(self), 'ilike',
1242                 this.limit + 1, function(data) {
1243             self.last_search = data.result;
1244             // possible selections for the m2o
1245             var values = _.map(data.result, function(x) {
1246                 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1247             });
1248
1249             // search more... if more results that max
1250             if (values.length > self.limit) {
1251                 values = values.slice(0, self.limit);
1252                 values.push({label: "<em>   Search More...</em>", action: function() {
1253                     dataset.name_search(search_val, build_relation_domain(self), 'ilike'
1254                     , false, function(data) {
1255                         self._change_int_value(null);
1256                         self._search_create_popup("search", data.result);
1257                     });
1258                 }});
1259             }
1260             // quick create
1261             var raw_result = _(data.result).map(function(x) {return x[1];})
1262             if (search_val.length > 0 &&
1263                 !_.include(raw_result, search_val) &&
1264                 (!self.value || search_val !== self.value[1])) {
1265                 values.push({label: '<em>   Create "<strong>' +
1266                         $('<span />').text(search_val).html() + '</strong>"</em>', action: function() {
1267                     self._quick_create(search_val);
1268                 }});
1269             }
1270             // create...
1271             values.push({label: "<em>   Create and Edit...</em>", action: function() {
1272                 self._change_int_value(null);
1273                 self._search_create_popup("form");
1274             }});
1275
1276             response(values);
1277         });
1278     },
1279     _quick_create: function(name) {
1280         var self = this;
1281         var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1282         dataset.name_create(name, function(data) {
1283             self._change_int_ext_value(data.result);
1284         }).fail(function(error, event) {
1285             event.preventDefault();
1286             self._change_int_value(null);
1287             self._search_create_popup("form", undefined, {"default_name": name});
1288         });
1289     },
1290     // all search/create popup handling
1291     _search_create_popup: function(view, ids, context) {
1292         var self = this;
1293         var pop = new openerp.base.form.SelectCreatePopup(null, self.view.session);
1294         pop.select_element(self.field.relation,{
1295                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1296                 initial_view: view,
1297                 disable_multiple_selection: true
1298                 }, build_relation_domain(self),
1299                 new openerp.base.CompoundContext(build_relation_context(self), context || {}));
1300         pop.on_select_elements.add(function(element_ids) {
1301             var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1302             dataset.name_get([element_ids[0]], function(data) {
1303                 self._change_int_ext_value(data.result[0]);
1304                 pop.stop();
1305             });
1306         });
1307     },
1308     _change_int_ext_value: function(value) {
1309         this._change_int_value(value);
1310         this.$input.val(this.value ? this.value[1] : "");
1311     },
1312     _change_int_value: function(value) {
1313         this.value = value;
1314         var back_orig_value = this.original_value;
1315         if (this.value === null || this.value) {
1316             this.original_value = this.value;
1317         }
1318         if (back_orig_value === undefined) { // first use after a set_value()
1319             return;
1320         }
1321         if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1322                 !== (this.value ? this.value[0] : null))) {
1323             this.on_ui_change();
1324         }
1325     },
1326     set_value_from_ui: function() {},
1327     set_value: function(value) {
1328         value = value || null;
1329         var self = this;
1330         var _super = this._super;
1331         this.tmp_value = value;
1332         var real_set_value = function(rval) {
1333             self.tmp_value = undefined;
1334             _super.apply(self, rval);
1335             self.original_value = undefined;
1336             self._change_int_ext_value(rval);
1337         };
1338         if(typeof(value) === "number") {
1339             var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, build_relation_context(self));
1340             dataset.name_get([value], function(data) {
1341                 real_set_value(data.result[0]);
1342             }).fail(function() {self.tmp_value = undefined;});
1343         } else {
1344             setTimeout(function() {real_set_value(value);}, 0);
1345         }
1346     },
1347     get_value: function() {
1348         if (this.tmp_value !== undefined) {
1349             if (this.tmp_value instanceof Array) {
1350                 return this.tmp_value[0];
1351             }
1352             return this.tmp_value ? this.tmp_value : false;
1353         }
1354         if (this.value === undefined)
1355             return this.original_value ? this.original_value[0] : false;
1356         return this.value ? this.value[0] : false;
1357     },
1358     validate: function() {
1359         this.invalid = false;
1360         if (this.value === null) {
1361             this.invalid = this.required;
1362         }
1363     }
1364 });
1365
1366 /*
1367 # Values: (0, 0,  { fields })    create
1368 #         (1, ID, { fields })    update
1369 #         (2, ID)                remove (delete)
1370 #         (3, ID)                unlink one (target id or target of relation)
1371 #         (4, ID)                link
1372 #         (5)                    unlink all (only valid for one2many)
1373 */
1374 var commands = {
1375     // (0, _, {values})
1376     CREATE: 0,
1377     'create': function (values) {
1378         return [commands.CREATE, false, values];
1379     },
1380     // (1, id, {values})
1381     UPDATE: 1,
1382     'update': function (id, values) {
1383         return [commands.UPDATE, id, values];
1384     },
1385     // (2, id[, _])
1386     DELETE: 2,
1387     'delete': function (id) {
1388         return [commands.DELETE, id, false];
1389     },
1390     // (3, id[, _]) removes relation, but not linked record itself
1391     FORGET: 3,
1392     'forget': function (id) {
1393         return [commands.FORGET, id, false];
1394     },
1395     // (4, id[, _])
1396     LINK_TO: 4,
1397     'link_to': function (id) {
1398         return [commands.LINK_TO, id, false];
1399     },
1400     // (5[, _[, _]])
1401     DELETE_ALL: 5,
1402     'delete_all': function () {
1403         return [5, false, false];
1404     },
1405     // (6, _, ids) replaces all linked records with provided ids
1406     REPLACE_WITH: 6,
1407     'replace_with': function (ids) {
1408         return [6, false, ids];
1409     }
1410 };
1411 openerp.base.form.FieldOne2Many = openerp.base.form.Field.extend({
1412     init: function(view, node) {
1413         this._super(view, node);
1414         this.template = "FieldOne2Many";
1415         this.is_started = $.Deferred();
1416     },
1417     start: function() {
1418         this._super.apply(this, arguments);
1419
1420         var self = this;
1421
1422         this.dataset = new openerp.base.form.One2ManyDataSet(this.session, this.field.relation);
1423         this.dataset.o2m = this;
1424         this.dataset.parent_view = this.view;
1425         this.dataset.on_change.add_last(function() {
1426             self.on_ui_change();
1427         });
1428
1429         var modes = this.node.attrs.mode;
1430         modes = !!modes ? modes.split(",") : ["tree", "form"];
1431         var views = [];
1432         _.each(modes, function(mode) {
1433             var view = {view_id: false, view_type: mode == "tree" ? "list" : mode};
1434             if (self.field.views && self.field.views[mode]) {
1435                 view.embedded_view = self.field.views[mode];
1436             }
1437             if(view.view_type === "list") {
1438                 view.options = {
1439                 };
1440             }
1441             views.push(view);
1442         });
1443         this.views = views;
1444
1445         this.viewmanager = new openerp.base.ViewManager(this.view.session,
1446             this.element_id, this.dataset, views);
1447         this.viewmanager.registry = openerp.base.views.clone({
1448             list: 'openerp.base.form.One2ManyListView'
1449         });
1450
1451         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
1452             if (view_type == "list") {
1453                 controller.o2m = self;
1454             } else if (view_type == "form") {
1455                 // TODO niv
1456             }
1457             self.is_started.resolve();
1458         });
1459         this.viewmanager.start();
1460     },
1461     reload_current_view: function() {
1462         var self = this;
1463         var view = self.viewmanager.views[self.viewmanager.active_view].controller;
1464         if(self.viewmanager.active_view === "list") {
1465             view.reload_content();
1466         } else if (self.viewmanager.active_view === "form") {
1467             // TODO niv: implement
1468         }
1469     },
1470     set_value_from_ui: function() {},
1471     set_value: function(value) {
1472         value = value || [];
1473         var self = this;
1474         this.dataset.reset_ids([]);
1475         if(value.length >= 1 && value[0] instanceof Array) {
1476             var ids = [];
1477             _.each(value, function(command) {
1478                 var obj = {values: command[2]};
1479                 switch (command[0]) {
1480                     case commands.CREATE:
1481                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1482                         self.dataset.to_create.push(obj);
1483                         self.dataset.cache.push(_.clone(obj));
1484                         ids.push(obj.id);
1485                         return;
1486                     case commands.UPDATE:
1487                         obj['id'] = command[1];
1488                         self.dataset.to_write.push(obj);
1489                         self.dataset.cache.push(_.clone(obj));
1490                         ids.push(obj.id);
1491                         return;
1492                     case commands.DELETE:
1493                         self.dataset.to_delete.push({id: command[1]});
1494                         return;
1495                     case commands.LINK_TO:
1496                         ids.push(command[1]);
1497                         return;
1498                     case commands.DELETE_ALL:
1499                         self.dataset.delete_all = true;
1500                         return;
1501                 }
1502             });
1503             this._super(ids);
1504             this.dataset.set_ids(ids);
1505         } else if (value.length >= 1 && typeof(value[0]) === "object") {
1506             var ids = [];
1507             this.dataset.delete_all = true;
1508             _.each(value, function(command) {
1509                 var obj = {values: command};
1510                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1511                 self.dataset.to_create.push(obj);
1512                 self.dataset.cache.push(_.clone(obj));
1513                 ids.push(obj.id);
1514             });
1515             this._super(ids);
1516             this.dataset.set_ids(ids);
1517         } else {
1518             this._super(value);
1519             this.dataset.reset_ids(value);
1520         }
1521         $.when(this.is_started).then(function() {
1522             self.reload_current_view();
1523         });
1524     },
1525     get_value: function() {
1526         var self = this;
1527         if (!this.dataset)
1528             return [];
1529         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
1530         val = val.concat(_.map(this.dataset.ids, function(id) {
1531             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
1532             if (alter_order) {
1533                 return commands.create(alter_order.values);
1534             }
1535             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
1536             if (alter_order) {
1537                 return commands.update(alter_order.id, alter_order.values);
1538             }
1539             return commands.link_to(id);
1540         }));
1541         return val.concat(_.map(
1542             this.dataset.to_delete, function(x) {
1543                 return commands['delete'](x.id);}));
1544     },
1545     get_on_change_value: function() {
1546         var self;
1547         return _.map(this.dataset.ids, function(id) {
1548             var values = _.detect(self.dataset.cache, function(x) {return x.id === id});
1549             if (values) {
1550                 values = _.clone(values);
1551                 delete values["id"];
1552                 return values;
1553             } else {
1554                 console.info("trying to get value in a o2m before that value is loaded");
1555                 return {};
1556             }
1557         });
1558     },
1559     validate: function() {
1560         this.invalid = false;
1561         // TODO niv
1562     }
1563 });
1564
1565 openerp.base.form.One2ManyDataSet = openerp.base.BufferedDataSet.extend({
1566     get_context: function() {
1567         this.context = build_relation_context(this.o2m);
1568         return this.context;
1569     }
1570 });
1571
1572 openerp.base.form.One2ManyListView = openerp.base.ListView.extend({
1573     do_add_record: function () {
1574         var self = this;
1575         var pop = new openerp.base.form.SelectCreatePopup(null, self.o2m.view.session);
1576         pop.select_element(self.o2m.field.relation,{
1577             initial_view: "form",
1578             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
1579             auto_create: false,
1580             parent_view: self.o2m.view
1581         }, build_relation_domain(self.o2m), build_relation_context(self.o2m));
1582         pop.on_create.add(function(data) {
1583             self.o2m.dataset.create(data, function(r) {
1584                 self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
1585                 pop.stop();
1586                 self.o2m.reload_current_view();
1587             });
1588         });
1589     }
1590 });
1591
1592 openerp.base.form.FieldMany2Many = openerp.base.form.Field.extend({
1593     init: function(view, node) {
1594         this._super(view, node);
1595         this.template = "FieldMany2Many";
1596         this.list_id = _.uniqueId("many2many");
1597         this.is_started = $.Deferred();
1598     },
1599     start: function() {
1600         this._super.apply(this, arguments);
1601
1602         var self = this;
1603
1604         this.dataset = new openerp.base.DataSetStatic(
1605                 this.session, this.field.relation);
1606         this.dataset.on_unlink.add_last(function(ids) {
1607             //TODO niv: should check this for other cases
1608             self.on_ui_change();
1609         });
1610
1611         this.list_view = new openerp.base.form.Many2ManyListView(
1612                 null, this.view.session, this.list_id, this.dataset, false, {
1613                     'addable': 'Add'
1614             });
1615         this.list_view.m2m_field = this;
1616         this.list_view.on_loaded.add_last(function() {
1617             self.is_started.resolve();
1618         });
1619         this.list_view.start();
1620     },
1621     set_value: function(value) {
1622         value = value || [];
1623         if (value.length >= 1 && value[0] instanceof Array) {
1624             value = value[0][2];
1625         }
1626         this._super(value);
1627         this.dataset.set_ids(value);
1628         var self = this;
1629         $.when(this.is_started).then(function() {
1630             self.list_view.reload_content();
1631         });
1632     },
1633     get_value: function() {
1634         return [commands.replace_with(this.dataset.ids)];
1635     }
1636 });
1637
1638 openerp.base.form.Many2ManyListView = openerp.base.ListView.extend({
1639     do_add_record: function () {
1640         var pop = new openerp.base.form.SelectCreatePopup(
1641                 null, this.m2m_field.view.session);
1642         pop.select_element(this.model);
1643         var self = this;
1644         pop.on_select_elements.add(function(element_ids) {
1645             _.each(element_ids, function(element_id) {
1646                 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
1647                     self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
1648                     self.reload_content();
1649                 }
1650             });
1651             pop.stop();
1652         });
1653     },
1654     do_activate_record: function(index, id) {
1655         this.m2m_field.view.session.action_manager.do_action({
1656             "res_model": this.dataset.model,
1657             "views":[[false,"form"]],
1658             "res_id": id,
1659             "type":"ir.actions.act_window",
1660             "view_type":"form",
1661             "view_mode":"form",
1662             "target":"new"
1663         });
1664     }
1665 });
1666
1667 openerp.base.form.SelectCreatePopup = openerp.base.BaseWidget.extend({
1668     identifier_prefix: "selectcreatepopup",
1669     template: "SelectCreatePopup",
1670     /**
1671      * options:
1672      * - initial_ids
1673      * - initial_view: form or search (default search)
1674      * - disable_multiple_selection
1675      * - alternative_form_view
1676      * - auto_create (default true)
1677      * - parent_view
1678      */
1679     select_element: function(model, options, domain, context) {
1680         this.model = model;
1681         this.domain = domain || [];
1682         this.context = context || {};
1683         this.options = _.defaults(options || {}, {"initial_view": "search", "auto_create": true});
1684         this.initial_ids = this.options.initial_ids;
1685         jQuery(this.render()).dialog({title: '',
1686                     modal: true,
1687                     minWidth: 800});
1688         this.start();
1689     },
1690     start: function() {
1691         this._super();
1692         this.dataset = new openerp.base.ReadOnlyDataSetSearch(this.session, this.model,
1693             this.context, this.domain);
1694         this.dataset.parent_view = this.options.parent_view;
1695         if (this.options.initial_view == "search") {
1696             this.setup_search_view();
1697         } else { // "form"
1698             this.new_object();
1699         }
1700     },
1701     setup_search_view: function() {
1702         var self = this;
1703         if (this.searchview) {
1704             this.searchview.stop();
1705         }
1706         this.searchview = new openerp.base.SearchView(null, this.session,
1707                 this.element_id + "_search", this.dataset, false, {
1708                     "selectable": !this.options.disable_multiple_selection,
1709                     "deletable": false
1710                 });
1711         this.searchview.on_search.add(function(domains, contexts, groupbys) {
1712             if (self.initial_ids) {
1713                 self.view_list.do_search.call(self, domains.concat([[["id", "in", self.initial_ids]]]),
1714                     contexts, groupbys);
1715                 self.initial_ids = undefined;
1716             } else {
1717                 self.view_list.do_search.call(self, domains, contexts, groupbys);
1718             }
1719         });
1720         this.searchview.on_loaded.add_last(function () {
1721             var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
1722             $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
1723             var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
1724             $cbutton.click(function() {
1725                 self.stop();
1726             });
1727             var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
1728             if(self.options.disable_multiple_selection) {
1729                 $sbutton.hide();
1730             }
1731             $sbutton.click(function() {
1732                 self.on_select_elements(self.selected_ids);
1733             });
1734             self.view_list = new openerp.base.form.SelectCreateListView( null, self.session,
1735                     self.element_id + "_view_list", self.dataset, false,
1736                     {'deletable': false});
1737             self.view_list.popup = self;
1738             self.view_list.do_show();
1739             self.view_list.start().then(function() {
1740                 self.searchview.do_search();
1741             });
1742         });
1743         this.searchview.start();
1744     },
1745     on_create: function(data) {
1746         if (!this.options.auto_create)
1747             return;
1748         var self = this;
1749         var wdataset = new openerp.base.DataSetSearch(this.session, this.model, this.context, this.domain);
1750         wdataset = this.options.parent_view;
1751         wdataset.create(data, function(r) {
1752             self.on_select_elements([r.result]);
1753         });
1754     },
1755     on_select_elements: function(element_ids) {
1756     },
1757     on_click_element: function(ids) {
1758         this.selected_ids = ids || [];
1759         if(this.selected_ids.length > 0) {
1760             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
1761         } else {
1762             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
1763         }
1764     },
1765     new_object: function() {
1766         var self = this;
1767         if (this.searchview) {
1768             this.searchview.hide();
1769         }
1770         if (this.view_list) {
1771             this.view_list.$element.hide();
1772         }
1773         this.dataset.index = null;
1774         this.view_form = new openerp.base.FormView(null, this.session,
1775                 this.element_id + "_view_form", this.dataset, false);
1776         if (this.options.alternative_form_view) {
1777             this.view_form.set_embedded_view(this.options.alternative_form_view);
1778         }
1779         this.view_form.start();
1780         this.view_form.on_loaded.add_last(function() {
1781             var $buttons = self.view_form.$element.find(".oe_form_buttons");
1782             $buttons.html(QWeb.render("SelectCreatePopup.form.buttons"));
1783             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
1784             $nbutton.click(function() {
1785                 self.view_form.do_save();
1786             });
1787             var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
1788             $cbutton.click(function() {
1789                 self.stop();
1790             });
1791         });
1792         this.dataset.on_create.add(this.on_create);
1793         this.view_form.do_show();
1794     }
1795 });
1796
1797 openerp.base.form.SelectCreateListView = openerp.base.ListView.extend({
1798     do_add_record: function () {
1799         this.popup.new_object();
1800     },
1801     select_record: function(index) {
1802         this.popup.on_select_elements([this.dataset.ids[index]]);
1803     },
1804     do_select: function(ids, records) {
1805         this._super(ids, records);
1806         this.popup.on_click_element(ids);
1807     }
1808 });
1809
1810 openerp.base.form.FieldReference = openerp.base.form.Field.extend({
1811     init: function(view, node) {
1812         this._super(view, node);
1813         this.template = "FieldReference";
1814     }
1815 });
1816
1817 openerp.base.form.FieldBinary = openerp.base.form.Field.extend({
1818     init: function(view, node) {
1819         this._super(view, node);
1820         this.iframe = this.element_id + '_iframe';
1821         this.binary_value = false;
1822     },
1823     start: function() {
1824         this._super.apply(this, arguments);
1825         this.$element.find('input.oe-binary-file').change(this.on_file_change);
1826         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
1827         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
1828     },
1829     set_value_from_ui: function() {
1830     },
1831     human_filesize : function(size) {
1832         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
1833         var i = 0;
1834         while (size >= 1024) {
1835             size /= 1024;
1836             ++i;
1837         }
1838         return size.toFixed(2) + ' ' + units[i];
1839     },
1840     on_file_change: function(e) {
1841         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
1842         // http://www.html5rocks.com/tutorials/file/dndfiles/
1843         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
1844         window[this.iframe] = this.on_file_uploaded;
1845         if ($(e.target).val() != '') {
1846             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
1847             this.$element.find('form.oe-binary-form').submit();
1848             this.toggle_progress();
1849         }
1850     },
1851     toggle_progress: function() {
1852         this.$element.find('.oe-binary-progress, .oe-binary').toggle();
1853     },
1854     on_file_uploaded: function(size, name, content_type, file_base64) {
1855         delete(window[this.iframe]);
1856         if (size === false) {
1857             this.notification.warn("File Upload", "There was a problem while uploading your file");
1858             // TODO: use openerp web exception handler
1859             console.log("Error while uploading file : ", name);
1860         } else {
1861             this.on_file_uploaded_and_valid.apply(this, arguments);
1862             this.on_ui_change();
1863         }
1864         this.toggle_progress();
1865     },
1866     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1867     },
1868     on_save_as: function() {
1869         if (!this.view.datarecord.id) {
1870             this.notification.warn("Can't save file", "The record has not yet been saved");
1871         } else {
1872             var url = '/base/binary/saveas?session_id=' + this.session.session_id + '&model=' +
1873                 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
1874                 '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime())
1875             window.open(url);
1876         }
1877     },
1878     on_clear: function() {
1879         if (this.value !== false) {
1880             this.value = false;
1881             this.binary_value = false;
1882             this.on_ui_change();
1883         }
1884         return false;
1885     }
1886 });
1887
1888 openerp.base.form.FieldBinaryFile = openerp.base.form.FieldBinary.extend({
1889     init: function(view, node) {
1890         this._super(view, node);
1891         this.template = "FieldBinaryFile";
1892     },
1893     set_value: function(value) {
1894         this._super.apply(this, arguments);
1895         var show_value = (value != null && value !== false) ? value : '';
1896         this.$element.find('input').eq(0).val(show_value);
1897     },
1898     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1899         this.value = file_base64;
1900         this.binary_value = true;
1901         var show_value = this.human_filesize(size);
1902         this.$element.find('input').eq(0).val(show_value);
1903         this.set_filename(name);
1904     },
1905     set_filename: function(value) {
1906         var filename = this.node.attrs.filename;
1907         if (this.view.fields[filename]) {
1908             this.view.fields[filename].set_value(value);
1909             this.view.fields[filename].on_ui_change();
1910         }
1911     },
1912     on_clear: function() {
1913         this._super.apply(this, arguments);
1914         this.$element.find('input').eq(0).val('');
1915         this.set_filename('');
1916     }
1917 });
1918
1919 openerp.base.form.FieldBinaryImage = openerp.base.form.FieldBinary.extend({
1920     init: function(view, node) {
1921         this._super(view, node);
1922         this.template = "FieldBinaryImage";
1923     },
1924     start: function() {
1925         this._super.apply(this, arguments);
1926         this.$image = this.$element.find('img.oe-binary-image');
1927     },
1928     set_image_maxwidth: function() {
1929         this.$image.css('max-width', this.$element.width());
1930     },
1931     on_file_change: function() {
1932         this.set_image_maxwidth();
1933         this._super.apply(this, arguments);
1934     },
1935     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1936         this.value = file_base64;
1937         this.binary_value = true;
1938         this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
1939     },
1940     on_clear: function() {
1941         this._super.apply(this, arguments);
1942         this.$image.attr('src', '/base/static/src/img/placeholder.png');
1943     },
1944     set_value: function(value) {
1945         this._super.apply(this, arguments);
1946         this.set_image_maxwidth();
1947         var url = '/base/binary/image?session_id=' + this.session.session_id + '&model=' +
1948             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime())
1949         this.$image.attr('src', url);
1950     }
1951 });
1952
1953 /**
1954  * Registry of form widgets, called by :js:`openerp.base.FormView`
1955  */
1956 openerp.base.form.widgets = new openerp.base.Registry({
1957     'frame' : 'openerp.base.form.WidgetFrame',
1958     'group' : 'openerp.base.form.WidgetFrame',
1959     'notebook' : 'openerp.base.form.WidgetNotebook',
1960     'separator' : 'openerp.base.form.WidgetSeparator',
1961     'label' : 'openerp.base.form.WidgetLabel',
1962     'button' : 'openerp.base.form.WidgetButton',
1963     'char' : 'openerp.base.form.FieldChar',
1964     'email' : 'openerp.base.form.FieldEmail',
1965     'url' : 'openerp.base.form.FieldUrl',
1966     'text' : 'openerp.base.form.FieldText',
1967     'text_wiki' : 'openerp.base.form.FieldText',
1968     'date' : 'openerp.base.form.FieldDate',
1969     'datetime' : 'openerp.base.form.FieldDatetime',
1970     'selection' : 'openerp.base.form.FieldSelection',
1971     'many2one' : 'openerp.base.form.FieldMany2One',
1972     'many2many' : 'openerp.base.form.FieldMany2Many',
1973     'one2many' : 'openerp.base.form.FieldOne2Many',
1974     'one2many_list' : 'openerp.base.form.FieldOne2Many',
1975     'reference' : 'openerp.base.form.FieldReference',
1976     'boolean' : 'openerp.base.form.FieldBoolean',
1977     'float' : 'openerp.base.form.FieldFloat',
1978     'integer': 'openerp.base.form.FieldFloat',
1979     'progressbar': 'openerp.base.form.FieldProgressBar',
1980     'float_time': 'openerp.base.form.FieldFloatTime',
1981     'image': 'openerp.base.form.FieldBinaryImage',
1982     'binary': 'openerp.base.form.FieldBinaryFile'
1983 });
1984
1985 };
1986
1987 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: