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