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