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