[MERGE] lp:openobject-addons
[odoo/odoo.git] / addons / web / static / src / js / views.js
1 /*---------------------------------------------------------
2  * OpenERP web library
3  *---------------------------------------------------------*/
4
5 openerp.web.views = function(instance) {
6 var QWeb = instance.web.qweb,
7     _t = instance.web._t;
8
9 instance.web.ActionManager = instance.web.Widget.extend({
10     init: function(parent) {
11         this._super(parent);
12         this.inner_action = null;
13         this.inner_widget = null;
14         this.dialog = null;
15         this.dialog_widget = null;
16         this.breadcrumbs = [];
17     },
18     start: function() {
19         this._super.apply(this, arguments);
20         this.$element.on('click', '.oe_breadcrumb_item', this.on_breadcrumb_clicked);
21     },
22     dialog_stop: function () {
23         if (this.dialog) {
24             this.dialog_widget.destroy();
25             this.dialog_widget = null;
26             this.dialog.destroy();
27             this.dialog = null;
28         }
29     },
30     /**
31      * Add a new item to the breadcrumb
32      *
33      * If the title of an item is an array, the multiple title mode is in use.
34      * (eg: a widget with multiple views might need to display a title for each view)
35      * In multiple title mode, the show() callback can check the index it receives
36      * in order to detect which of its titles has been clicked on by the user.
37      *
38      * @param {Object} item breadcrumb item
39      * @param {Object} item.widget widget containing the view(s) to be added to the breadcrumb added
40      * @param {Function} [item.show] triggered whenever the widget should be shown back
41      * @param {Function} [item.hide] triggered whenever the widget should be shown hidden
42      * @param {Function} [item.destroy] triggered whenever the widget should be destroyed
43      * @param {String|Array} [item.title] title(s) of the view(s) to be displayed in the breadcrumb
44      * @param {Function} [item.get_title] should return the title(s) of the view(s) to be displayed in the breadcrumb
45      */
46     push_breadcrumb: function(item) {
47         var last = this.breadcrumbs.slice(-1)[0];
48         if (last) {
49             last.hide();
50         }
51         var item = _.extend({
52             show: function(index) {
53                 this.widget.$element.show();
54             },
55             hide: function() {
56                 this.widget.$element.hide();
57             },
58             destroy: function() {
59                 this.widget.destroy();
60             },
61             get_title: function() {
62                 return this.title || this.widget.get('title');
63             }
64         }, item);
65         item.id = _.uniqueId('breadcrumb_');
66         this.breadcrumbs.push(item);
67     },
68     on_breadcrumb_clicked: function(ev) {
69         var $e = $(ev.target);
70         var id = $e.data('id');
71         var item;
72         for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
73             var it = this.breadcrumbs[i];
74             if (it.id == id) {
75                 item = it;
76                 break;
77             }
78             this.remove_breadcrumb(i);
79         }
80         var index = $e.parent().find('.oe_breadcrumb_item[data-id=' + $e.data('id') + ']').index($e);
81         item.show(index, $e);
82         this.inner_widget = item.widget;
83     },
84     clear_breadcrumbs: function() {
85         while (this.breadcrumbs.length) {
86             this.remove_breadcrumb(0);
87         }
88     },
89     remove_breadcrumb: function(index) {
90         var item = this.breadcrumbs.splice(index, 1)[0];
91         if (item) {
92             var dups = _.filter(this.breadcrumbs, function(it) {
93                 return item.widget === it.widget;
94             });
95             if (!dups.length) {
96                 item.destroy();
97             }
98         }
99     },
100     get_title: function() {
101         var titles = [];
102         for (var i = 0; i < this.breadcrumbs.length; i += 1) {
103             var item = this.breadcrumbs[i];
104             var tit = item.get_title();
105             if (!_.isArray(tit)) {
106                 tit = [tit];
107             }
108             for (var j = 0; j < tit.length; j += 1) {
109                 var label = _.escape(tit[j]);
110                 if (i === this.breadcrumbs.length - 1 && j === tit.length - 1) {
111                     titles.push(label);
112                 } else {
113                     titles.push(_.str.sprintf('<a href="#" class="oe_breadcrumb_item" data-id="%s">%s</a>', item.id, label));
114                 }
115             }
116         }
117         return titles.join(' <span class="oe_fade">/</span> ');
118     },
119     do_push_state: function(state) {
120         if (this.getParent() && this.getParent().do_push_state) {
121             if (this.inner_action) {
122                 state['title'] = this.inner_action.name;
123                 state['model'] = this.inner_action.res_model;
124                 if (this.inner_action.id) {
125                     state['action_id'] = this.inner_action.id;
126                 }
127             }
128             this.getParent().do_push_state(state);
129         }
130     },
131     do_load_state: function(state, warm) {
132         var self = this,
133             action_loaded;
134         if (state.action_id) {
135             var run_action = (!this.inner_widget || !this.inner_widget.action) || this.inner_widget.action.id !== state.action_id;
136             if (run_action) {
137                 this.null_action();
138                 action_loaded = this.do_action(state.action_id);
139                 instance.webclient.menu.has_been_loaded.then(function() {
140                     instance.webclient.menu.open_action(state.action_id);
141                 });
142             }
143         } else if (state.model && state.id) {
144             // TODO handle context & domain ?
145             this.null_action();
146             var action = {
147                 res_model: state.model,
148                 res_id: state.id,
149                 type: 'ir.actions.act_window',
150                 views: [[false, 'form']]
151             };
152             action_loaded = this.do_action(action);
153         } else if (state.sa) {
154             // load session action
155             var self = this;
156             this.null_action();
157             action_loaded = this.rpc('/web/session/get_session_action',  {key: state.sa}).pipe(function(action) {
158                 if (action) {
159                     return self.do_action(action);
160                 }
161             });
162         } else if (state.client_action) {
163             this.null_action();
164             var action = state.client_action;
165             if(_.isString(action)) {
166                 action = {
167                     tag: action,
168                     params: state,
169                 };
170             }
171             this.ir_actions_client(action);
172         }
173
174         $.when(action_loaded || null).then(function() {
175             if (self.inner_widget && self.inner_widget.do_load_state) {
176                 self.inner_widget.do_load_state(state, warm);
177             }
178         });
179     },
180     do_action: function(action, on_close) {
181         if (_.isNumber(action) || _.isString(action)) {
182             var self = this;
183             return self.rpc("/web/action/load", { action_id: action }, function(result) {
184                 self.do_action(result.result, on_close);
185             });
186         }
187         if (!action.type) {
188             console.error("No type for action", action);
189             return;
190         }
191         var type = action.type.replace(/\./g,'_');
192         var popup = action.target === 'new';
193         var inline = action.target === 'inline';
194         action.flags = _.extend({
195             views_switcher : !popup && !inline,
196             search_view : !popup && !inline,
197             action_buttons : !popup && !inline,
198             sidebar : !popup && !inline,
199             pager : !popup && !inline,
200             display_title : !popup
201         }, action.flags || {});
202         if (!(type in this)) {
203             console.error("Action manager can't handle action of type " + action.type, action);
204             return;
205         }
206         return this[type](action, on_close);
207     },
208     null_action: function() {
209         this.dialog_stop();
210         this.clear_breadcrumbs();
211     },
212     ir_actions_act_window: function (action, on_close) {
213         var self = this;
214         if (_(['base.module.upgrade', 'base.setup.installer'])
215                 .contains(action.res_model)) {
216             var old_close = on_close;
217             on_close = function () {
218                 instance.webclient.do_reload().then(old_close);
219             };
220         }
221         if (action.target === 'new') {
222             if (this.dialog === null) {
223                 // These buttons will be overwrited by <footer> if any
224                 this.dialog = new instance.web.Dialog(this, {
225                     buttons: { "Close": function() { $(this).dialog("close"); }},
226                     dialogClass: 'oe_act_window'
227                 });
228                 if(on_close)
229                     this.dialog.on_close.add(on_close);
230             } else {
231                 this.dialog_widget.destroy();
232             }
233             this.dialog.dialog_title = action.name;
234             this.dialog_widget = new instance.web.ViewManagerAction(this, action);
235             this.dialog_widget.appendTo(this.dialog.$element);
236             this.dialog.open();
237         } else  {
238             this.dialog_stop();
239             if(action.menu_id) {
240                 return this.getParent().do_action(action, function () {
241                     instance.webclient.menu.open_menu(action.menu_id);
242                 });
243             }
244             this.inner_action = action;
245             var inner_widget = this.inner_widget = new instance.web.ViewManagerAction(this, action);
246             inner_widget.add_breadcrumb();
247             this.inner_widget.appendTo(this.$element);
248         }
249     },
250     ir_actions_act_window_close: function (action, on_closed) {
251         if (!this.dialog && on_closed) {
252             on_closed();
253         }
254         this.dialog_stop();
255     },
256     ir_actions_server: function (action, on_closed) {
257         var self = this;
258         this.rpc('/web/action/run', {
259             action_id: action.id,
260             context: action.context || {}
261         }).then(function (action) {
262             self.do_action(action, on_closed)
263         });
264     },
265     ir_actions_client: function (action) {
266         this.dialog_stop();
267         var ClientWidget = instance.web.client_actions.get_object(action.tag);
268         this.inner_widget = new ClientWidget(this, action.params);
269         this.push_breadcrumb({
270             widget: this.inner_widget,
271             title: action.name
272         });
273         this.inner_widget.appendTo(this.$element);
274     },
275     ir_actions_report_xml: function(action, on_closed) {
276         var self = this;
277         $.blockUI();
278         self.rpc("/web/session/eval_domain_and_context", {
279             contexts: [action.context],
280             domains: []
281         }).then(function(res) {
282             action = _.clone(action);
283             action.context = res.context;
284             self.session.get_file({
285                 url: '/web/report',
286                 data: {action: JSON.stringify(action)},
287                 complete: $.unblockUI,
288                 success: function(){
289                     if (!self.dialog && on_closed) {
290                         on_closed();
291                     }
292                     self.dialog_stop();
293                 },
294                 error: instance.webclient.crashmanager.on_rpc_error
295             })
296         });
297     },
298     ir_actions_act_url: function (action) {
299         window.open(action.url, action.target === 'self' ? '_self' : '_blank');
300     },
301     ir_ui_menu: function (action) {
302         this.getParent().do_action(action);
303     }
304 });
305
306 instance.web.ViewManager =  instance.web.Widget.extend({
307     template: "ViewManager",
308     init: function(parent, dataset, views, flags) {
309         this._super(parent);
310         this.model = dataset ? dataset.model : undefined;
311         this.dataset = dataset;
312         this.searchview = null;
313         this.active_view = null;
314         this.views_src = _.map(views, function(x) {
315             if (x instanceof Array) {
316                 var View = instance.web.views.get_object(x[1], true);
317                 return {
318                     view_id: x[0],
319                     view_type: x[1],
320                     label: View ? View.prototype.display_name : (void 'nope')
321                 };
322             } else {
323                 return x;
324             }
325         });
326         this.views = {};
327         this.flags = flags || {};
328         this.registry = instance.web.views;
329         this.views_history = [];
330     },
331     /**
332      * @returns {jQuery.Deferred} initial view loading promise
333      */
334     start: function() {
335         this._super();
336         var self = this;
337         this.$element.find('.oe_view_manager_switch a').click(function() {
338             self.on_mode_switch($(this).data('view-type'));
339         }).tipsy();
340         var views_ids = {};
341         _.each(this.views_src, function(view) {
342             self.views[view.view_type] = $.extend({}, view, {
343                 deferred : $.Deferred(),
344                 controller : null,
345                 options : _.extend({
346                     $buttons : self.$element.find('.oe_view_manager_buttons'),
347                     $sidebar : self.flags.sidebar ? self.$element.find('.oe_view_manager_sidebar') : undefined,
348                     $pager : self.$element.find('.oe_view_manager_pager'),
349                     action : self.action,
350                     action_views_ids : views_ids
351                 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
352             });
353             views_ids[view.view_type] = view.view_id;
354         });
355         if (this.flags.views_switcher === false) {
356             this.$element.find('.oe_view_manager_switch').hide();
357         }
358         // If no default view defined, switch to the first one in sequence
359         var default_view = this.flags.default_view || this.views_src[0].view_type;
360         return this.on_mode_switch(default_view);
361     },
362     /**
363      * Asks the view manager to switch visualization mode.
364      *
365      * @param {String} view_type type of view to display
366      * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
367      * @returns {jQuery.Deferred} new view loading promise
368      */
369     on_mode_switch: function(view_type, no_store, view_options) {
370         var self = this;
371         var view = this.views[view_type];
372         var view_promise;
373         if(!view)
374             return $.Deferred().reject();
375
376         if (!no_store) {
377             this.views_history.push(view_type);
378         }
379         this.active_view = view_type;
380
381         if (!view.controller) {
382             view_promise = this.do_create_view(view_type);
383         } else if (this.searchview
384                 && self.flags.auto_search
385                 && view.controller.searchable !== false) {
386             this.searchview.ready.then(this.searchview.do_search);
387         }
388
389         if (this.searchview) {
390             this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
391         }
392
393         this.$element
394             .find('.oe_view_manager_switch a').parent().removeClass('active');
395         this.$element
396             .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
397             .parent().addClass('active');
398
399         $.when(view_promise).then(function () {
400             _.each(_.keys(self.views), function(view_name) {
401                 var controller = self.views[view_name].controller;
402                 if (controller) {
403                     var container = self.$element.find(".oe_view_manager_view_" + view_name + ":first");
404                     if (view_name === view_type) {
405                         container.show();
406                         controller.do_show(view_options || {});
407                     } else {
408                         container.hide();
409                         controller.do_hide();
410                     }
411                     // put the <footer> in the dialog's buttonpane
412                     if (self.$element.parent('.ui-dialog-content') && self.$element.find('footer')) {
413                         self.$element.parent('.ui-dialog-content').parent().find('div.ui-dialog-buttonset').hide()
414                         self.$element.find('footer').appendTo(
415                             self.$element.parent('.ui-dialog-content').parent().find('div.ui-dialog-buttonpane')
416                         );
417                     }
418                 }
419             });
420         });
421         return view_promise;
422     },
423     do_create_view: function(view_type) {
424         // Lazy loading of views
425         var self = this;
426         var view = this.views[view_type];
427         var controllerclass = this.registry.get_object(view_type);
428         var options = _.clone(view.options);
429         if (view_type === "form" && this.action) {
430             switch (this.action.target) {
431                 case 'new':
432                 case 'inline':
433                     options.initial_mode = 'edit';
434                     break;
435             }
436         }
437         var controller = new controllerclass(this, this.dataset, view.view_id, options);
438
439         controller.on("change:title", this, function() {
440             if (self.active_view === view_type) {
441                 self.set_title(controller.get('title'));
442             }
443         });
444
445         if (view.embedded_view) {
446             controller.set_embedded_view(view.embedded_view);
447         }
448         controller.do_switch_view.add_last(_.bind(this.switch_view, this));
449
450         controller.do_prev_view.add_last(this.on_prev_view);
451         var container = this.$element.find(".oe_view_manager_view_" + view_type);
452         var view_promise = controller.appendTo(container);
453         this.views[view_type].controller = controller;
454         this.views[view_type].deferred.resolve(view_type);
455         return $.when(view_promise).then(function() {
456             self.on_controller_inited(view_type, controller);
457             if (self.searchview
458                     && self.flags.auto_search
459                     && view.controller.searchable !== false) {
460                 self.searchview.ready.then(self.searchview.do_search);
461             }
462         });
463     },
464     set_title: function(title) {
465         this.$element.find('.oe_view_title_text:first').text(title);
466     },
467     add_breadcrumb: function() {
468         var self = this;
469         var views = [this.active_view || this.views_src[0].view_type];
470         this.on_mode_switch.add(function(mode) {
471             var last = views.slice(-1)[0];
472             if (mode !== last) {
473                 if (mode !== 'form') {
474                     views.length = 0;
475                 }
476                 views.push(mode);
477             }
478         });
479         this.getParent().push_breadcrumb({
480             widget: this,
481             show: function(index, $e) {
482                 var view_to_select = views[index];
483                 self.$element.show();
484                 if (self.active_view !== view_to_select) {
485                     self.on_mode_switch(view_to_select);
486                 }
487             },
488             get_title: function() {
489                 return _.map(views, function(v) {
490                     return self.views[v].controller.get('title');
491                 });
492             }
493         });
494     },
495     /**
496      * Method used internally when a view asks to switch view. This method is meant
497      * to be extended by child classes to change the default behavior, which simply
498      * consist to switch to the asked view.
499      */
500     switch_view: function(view_type, no_store, options) {
501         return this.on_mode_switch(view_type, no_store, options);
502     },
503     /**
504      * Returns to the view preceding the caller view in this manager's
505      * navigation history (the navigation history is appended to via
506      * on_mode_switch)
507      *
508      * @param {Object} [options]
509      * @param {Boolean} [options.created=false] resource was created
510      * @param {String} [options.default=null] view to switch to if no previous view
511      * @returns {$.Deferred} switching end signal
512      */
513     on_prev_view: function (options) {
514         options = options || {};
515         var current_view = this.views_history.pop();
516         var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
517         if (options.created && current_view === 'form' && previous_view === 'list') {
518             // APR special case: "If creation mode from list (and only from a list),
519             // after saving, go to page view (don't come back in list)"
520             return this.on_mode_switch('form');
521         } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
522             // APR special case: "If creation from dashboard, we have no previous view
523             return this.on_mode_switch('form');
524         }
525         return this.on_mode_switch(previous_view, true);
526     },
527     /**
528      * Sets up the current viewmanager's search view.
529      *
530      * @param {Number|false} view_id the view to use or false for a default one
531      * @returns {jQuery.Deferred} search view startup deferred
532      */
533     setup_search_view: function(view_id, search_defaults) {
534         var self = this;
535         if (this.searchview) {
536             this.searchview.destroy();
537         }
538         this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
539
540         this.searchview.on_search.add(this.do_searchview_search);
541         return this.searchview.appendTo(this.$element.find(".oe_view_manager_view_search"));
542     },
543     do_searchview_search: function(domains, contexts, groupbys) {
544         var self = this,
545             controller = this.views[this.active_view].controller,
546             action_context = this.action.context || {};
547         this.rpc('/web/session/eval_domain_and_context', {
548             domains: [this.action.domain || []].concat(domains || []),
549             contexts: [action_context].concat(contexts || []),
550             group_by_seq: groupbys || []
551         }, function (results) {
552             self.dataset._model = new instance.web.Model(
553                 self.dataset.model, results.context, results.domain);
554             var groupby = results.group_by.length
555                         ? results.group_by
556                         : action_context.group_by;
557             if (_.isString(groupby)) {
558                 groupby = [groupby];
559             }
560             controller.do_search(results.domain, results.context, groupby || []);
561         });
562     },
563     /**
564      * Event launched when a controller has been inited.
565      *
566      * @param {String} view_type type of view
567      * @param {String} view the inited controller
568      */
569     on_controller_inited: function(view_type, view) {
570     },
571     /**
572      * Called when one of the view want to execute an action
573      */
574     on_action: function(action) {
575     },
576     on_create: function() {
577     },
578     on_remove: function() {
579     },
580     on_edit: function() {
581     },
582     /**
583      * Called by children view after executing an action
584      */
585     on_action_executed: function () {
586     },
587 });
588
589 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
590     template:"ViewManagerAction",
591     /**
592      * @constructs instance.web.ViewManagerAction
593      * @extends instance.web.ViewManager
594      *
595      * @param {instance.web.ActionManager} parent parent object/widget
596      * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
597      */
598     init: function(parent, action) {
599         // dataset initialization will take the session from ``this``, so if we
600         // do not have it yet (and we don't, because we've not called our own
601         // ``_super()``) rpc requests will blow up.
602         var flags = action.flags || {};
603         if (!('auto_search' in flags)) {
604             flags.auto_search = action.auto_search !== false;
605         }
606         if (action.res_model == 'board.board' && action.view_mode === 'form') {
607             // Special case for Dashboards
608             _.extend(flags, {
609                 views_switcher : false,
610                 display_title : false,
611                 search_view : false,
612                 pager : false,
613                 sidebar : false,
614                 action_buttons : false
615             });
616         }
617         this._super(parent, null, action.views, flags);
618         this.session = parent.session;
619         this.action = action;
620         var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
621         if (action.res_id) {
622             dataset.ids.push(action.res_id);
623             dataset.index = 0;
624         }
625         this.dataset = dataset;
626
627         // setup storage for session-wise menu hiding
628         if (this.session.hidden_menutips) {
629             return;
630         }
631         this.session.hidden_menutips = {};
632     },
633     /**
634      * Initializes the ViewManagerAction: sets up the searchview (if the
635      * searchview is enabled in the manager's action flags), calls into the
636      * parent to initialize the primary view and (if the VMA has a searchview)
637      * launches an initial search after both views are done rendering.
638      */
639     start: function() {
640         var self = this,
641             searchview_loaded,
642             search_defaults = {};
643         _.each(this.action.context, function (value, key) {
644             var match = /^search_default_(.*)$/.exec(key);
645             if (match) {
646                 search_defaults[match[1]] = value;
647             }
648         });
649         // init search view
650         var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
651
652         searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
653
654         var main_view_loaded = this._super();
655
656         var manager_ready = $.when(searchview_loaded, main_view_loaded);
657
658         this.$element.find('.oe_debug_view').change(this.on_debug_changed);
659         this.$element.addClass("oe_view_manager_" + (this.action.target || 'current'));
660
661         if (this.action.help && !this.flags.low_profile) {
662             var Users = new instance.web.DataSet(self, 'res.users'),
663                 $tips = this.$element.find('.oe_view_manager_menu_tips');
664             $tips.delegate('blockquote button', 'click', function() {
665                 var $this = $(this);
666                 //noinspection FallthroughInSwitchStatementJS
667                 switch ($this.attr('name')) {
668                 case 'disable':
669                     Users.write(self.session.uid, {menu_tips:false});
670                 case 'hide':
671                     $this.closest('blockquote').hide();
672                     self.session.hidden_menutips[self.action.id] = true;
673                 }
674             });
675             if (!(self.action.id in self.session.hidden_menutips)) {
676                 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
677                     var user = users[0];
678                     if (!(user && user.id === self.session.uid)) {
679                         return;
680                     }
681                     $tips.find('blockquote').toggle(user.menu_tips);
682                 });
683             }
684         }
685
686         return manager_ready;
687     },
688     on_debug_changed: function (evt) {
689         var self = this,
690             $sel = $(evt.currentTarget),
691             $option = $sel.find('option:selected'),
692             val = $sel.val(),
693             current_view = this.views[this.active_view].controller;
694         switch (val) {
695             case 'fvg':
696                 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
697                 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
698                 break;
699             case 'perm_read':
700                 var ids = current_view.get_selected_ids();
701                 if (ids.length === 1) {
702                     this.dataset.call('perm_read', [ids]).then(function(result) {
703                         var dialog = new instance.web.Dialog(this, {
704                             title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
705                             width: 400
706                         }, QWeb.render('ViewManagerDebugViewLog', {
707                             perm : result[0],
708                             format : instance.web.format_value
709                         })).open();
710                     });
711                 }
712                 break;
713             case 'toggle_layout_outline':
714                 current_view.rendering_engine.toggle_layout_debugging();
715                 break;
716             case 'fields':
717                 this.dataset.call_and_eval(
718                         'fields_get', [false, {}], null, 1).then(function (fields) {
719                     var $root = $('<dl>');
720                     _(fields).each(function (attributes, name) {
721                         $root.append($('<dt>').append($('<h4>').text(name)));
722                         var $attrs = $('<dl>').appendTo(
723                                 $('<dd>').appendTo($root));
724                         _(attributes).each(function (def, name) {
725                             if (def instanceof Object) {
726                                 def = JSON.stringify(def);
727                             }
728                             $attrs
729                                 .append($('<dt>').text(name))
730                                 .append($('<dd style="white-space: pre-wrap;">').text(def));
731                         });
732                     });
733                     new instance.web.Dialog(self, {
734                         title: _.str.sprintf(_t("Model %s fields"),
735                                              self.dataset.model),
736                         width: '95%'}, $root).open();
737                 });
738                 break;
739             case 'manage_views':
740                 if (current_view.fields_view && current_view.fields_view.arch) {
741                     var view_editor = new instance.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
742                     view_editor.start();
743                 } else {
744                     this.do_warn(_t("Manage Views"),
745                             _t("Could not find current view declaration"));
746                 }
747                 break;
748             case 'edit_workflow':
749                 return this.do_action({
750                     res_model : 'workflow',
751                     domain : [['osv', '=', this.dataset.model]],
752                     views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
753                     type : 'ir.actions.act_window',
754                     view_type : 'list',
755                     view_mode : 'list'
756                 });
757                 break;
758             case 'edit':
759                 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
760                 break;
761             case 'manage_filters':
762                 this.do_action({
763                     res_model: 'ir.filters',
764                     views: [[false, 'list'], [false, 'form']],
765                     type: 'ir.actions.act_window',
766                     context: {
767                         search_default_my_filters: true,
768                         search_default_model_id: this.dataset.model
769                     }
770                 });
771                 break;
772             default:
773                 if (val) {
774                     console.log("No debug handler for ", val);
775                 }
776         }
777         evt.currentTarget.selectedIndex = 0;
778     },
779     do_edit_resource: function(model, id, action) {
780         var action = _.extend({
781             res_model : model,
782             res_id : id,
783             type : 'ir.actions.act_window',
784             view_type : 'form',
785             view_mode : 'form',
786             views : [[false, 'form']],
787             target : 'new',
788             flags : {
789                 action_buttons : true,
790                 form : {
791                     resize_textareas : true
792                 }
793             }
794         }, action || {});
795         this.do_action(action);
796     },
797     on_mode_switch: function (view_type, no_store, options) {
798         var self = this;
799
800         return $.when(this._super.apply(this, arguments)).then(function () {
801             var controller = self.views[self.active_view].controller,
802                 fvg = controller.fields_view,
803                 view_id = (fvg && fvg.view_id) || '--';
804             self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
805                 view: controller,
806                 view_manager: self
807             }));
808             self.set_title();
809         });
810     },
811     do_create_view: function(view_type) {
812         var r = this._super.apply(this, arguments);
813         var view = this.views[view_type].controller;
814         view.set({ 'title': this.action.name });
815         return r;
816     },
817     set_title: function(title) {
818         this.$element.find('.oe_breadcrumb_title:first').html(this.getParent().get_title());
819     },
820     do_push_state: function(state) {
821         if (this.getParent() && this.getParent().do_push_state) {
822             state["view_type"] = this.active_view;
823             this.getParent().do_push_state(state);
824         }
825     },
826     do_load_state: function(state, warm) {
827         var self = this,
828             defs = [];
829         if (state.view_type && state.view_type !== this.active_view) {
830             defs.push(
831                 this.views[this.active_view].deferred.pipe(function() {
832                     return self.on_mode_switch(state.view_type, true);
833                 })
834             );
835         } 
836
837         $.when(defs).then(function() {
838             self.views[self.active_view].controller.do_load_state(state, warm);
839         });
840     },
841 });
842
843 instance.web.Sidebar = instance.web.Widget.extend({
844     init: function(parent) {
845         var self = this;
846         this._super(parent);
847         var view = this.getParent();
848         this.sections = [
849             { 'name' : 'print', 'label' : _t('Print'), },
850             { 'name' : 'files', 'label' : _t('Attachment'), },
851             { 'name' : 'other', 'label' : _t('More'), }
852         ];
853         this.items = {
854             'print' : [],
855             'files' : [],
856             'other' : []
857         };
858         if (this.session.uid === 1) {
859             var item = { label: _t("Translate"), callback: view.on_sidebar_translate, title: _t("Technical translation") };
860             this.items.other.push(item);
861         }
862         this.fileupload_id = _.uniqueId('oe_fileupload');
863         $(window).on(this.fileupload_id, function() {
864             var args = [].slice.call(arguments).slice(1);
865             if (args[0] && args[0].error) {
866                 alert(args[0].error);
867             } else {
868                 self.do_attachement_update(self.dataset, self.model_id);
869             }
870             $.unblockUI();
871         });
872     },
873     start: function() {
874         var self = this;
875         this._super(this);
876         this.redraw();
877         this.$element.on('click','.oe_dropdown_menu li a', function(event) {
878             var section = $(this).data('section');
879             var index = $(this).data('index');
880             var item = self.items[section][index];
881             if (item.callback) {
882                 item.callback.apply(self, [item]);
883             } else if (item.action) {
884                 self.on_item_action_clicked(item);
885             } else if (item.url) {
886                 return true;
887             }
888             event.preventDefault();
889         });
890     },
891     redraw: function() {
892         var self = this;
893         self.$element.html(QWeb.render('Sidebar', {widget: self}));
894
895         // Hides Sidebar sections when item list is empty
896         this.$('.oe_form_dropdown_section').each(function() {
897             $(this).toggle(!!$(this).find('li').length);
898         });
899     },
900     /**
901      * For each item added to the section:
902      *
903      * ``label``
904      *     will be used as the item's name in the sidebar, can be html
905      *
906      * ``action``
907      *     descriptor for the action which will be executed, ``action`` and
908      *     ``callback`` should be exclusive
909      *
910      * ``callback``
911      *     function to call when the item is clicked in the sidebar, called
912      *     with the item descriptor as its first argument (so information
913      *     can be stored as additional keys on the object passed to
914      *     ``add_items``)
915      *
916      * ``classname`` (optional)
917      *     ``@class`` set on the sidebar serialization of the item
918      *
919      * ``title`` (optional)
920      *     will be set as the item's ``@title`` (tooltip)
921      *
922      * @param {String} section_code
923      * @param {Array<{label, action | callback[, classname][, title]}>} items
924      */
925     add_items: function(section_code, items) {
926         var self = this;
927         if (items) {
928             this.items[section_code].push.apply(this.items[section_code],items);
929             this.redraw();
930         }
931     },
932     add_toolbar: function(toolbar) {
933         var self = this;
934         _.each(['print','action','relate'], function(type) {
935             var items = toolbar[type];
936             if (items) {
937                 for (var i = 0; i < items.length; i++) {
938                     items[i] = {
939                         label: items[i]['name'],
940                         action: items[i],
941                         classname: 'oe_sidebar_' + type
942                     }
943                 }
944                 self.add_items(type=='print' ? 'print' : 'other', items);
945             }
946         });
947     },
948     on_item_action_clicked: function(item) {
949         var self = this;
950         self.getParent().sidebar_context().then(function (context) {
951             var ids = self.getParent().get_selected_ids();
952             if (ids.length == 0) {
953                 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
954                 return false;
955             }
956             var additional_context = _.extend({
957                 active_id: ids[0],
958                 active_ids: ids,
959                 active_model: self.getParent().dataset.model
960             }, context);
961             self.rpc("/web/action/load", {
962                 action_id: item.action.id,
963                 context: additional_context
964             }, function(result) {
965                 result.result.context = _.extend(result.result.context || {},
966                     additional_context);
967                 result.result.flags = result.result.flags || {};
968                 result.result.flags.new_window = true;
969                 self.do_action(result.result, function () {
970                     // reload view
971                     self.getParent().reload();
972                 });
973             });
974         });
975     },
976     do_attachement_update: function(dataset, model_id) {
977         this.dataset = dataset;
978         this.model_id = model_id;
979         if (!model_id) {
980             this.on_attachments_loaded([]);
981         } else {
982             var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
983             var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
984             ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
985         }
986     },
987     on_attachments_loaded: function(attachments) {
988         var self = this;
989         var items = [];
990         var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
991         _.each(attachments,function(a) {
992             a.label = a.name;
993             if(a.type === "binary") {
994                 a.url = prefix  + a.id + '&t=' + (new Date().getTime());
995             }
996         });
997         self.items['files'] = attachments;
998         self.redraw();
999         this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
1000         this.$element.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
1001     },
1002     on_attachment_changed: function(e) {
1003         var $e = $(e.target);
1004         if ($e.val() !== '') {
1005             this.$element.find('form.oe_form_binary_form').submit();
1006             $e.parent().find('input[type=file]').prop('disabled', true);
1007             $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
1008             this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
1009             $.blockUI();
1010         }
1011     },
1012     on_attachment_delete: function(e) {
1013         var self = this;
1014         e.preventDefault();
1015         e.stopPropagation();
1016         var self = this;
1017         var $e = $(e.currentTarget);
1018         if (confirm(_t("Do you really want to delete this attachment ?"))) {
1019             (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
1020                 self.do_attachement_update(self.dataset, self.model_id);
1021             });
1022         }
1023     }
1024 });
1025
1026 instance.web.TranslateDialog = instance.web.Dialog.extend({
1027     dialog_title: {toString: function () { return _t("Translations"); }},
1028     init: function(view) {
1029         // TODO fme: should add the language to fields_view_get because between the fields view get
1030         // and the moment the user opens the translation dialog, the user language could have been changed
1031         this.view_language = view.session.user_context.lang;
1032         this['on_button_' + _t("Save")] = this.on_btn_save;
1033         this['on_button_' + _t("Close")] = this.on_btn_close;
1034         this._super(view, {
1035             width: '80%',
1036             height: '80%'
1037         });
1038         this.view = view;
1039         this.view_type = view.fields_view.type || '';
1040         this.$fields_form = null;
1041         this.$view_form = null;
1042         this.$sidebar_form = null;
1043         this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
1044         this.languages = null;
1045         this.languages_loaded = $.Deferred();
1046         (new instance.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
1047             [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
1048     },
1049     start: function() {
1050         var self = this;
1051         this._super();
1052         $.when(this.languages_loaded).then(function() {
1053             self.$element.html(instance.web.qweb.render('TranslateDialog', { widget: self }));
1054             self.$fields_form = self.$element.find('.oe_translation_form');
1055             self.$fields_form.find('.oe_trad_field').change(function() {
1056                 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
1057             });
1058         });
1059         return this;
1060     },
1061     on_languages_loaded: function(langs) {
1062         this.languages = langs;
1063         this.languages_loaded.resolve();
1064     },
1065     do_load_fields_values: function(callback) {
1066         var self = this,
1067             deffered = [];
1068         this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
1069         _.each(self.languages, function(lg) {
1070             var deff = $.Deferred();
1071             deffered.push(deff);
1072             var callback = function(values) {
1073                 _.each(self.translatable_fields_keys, function(f) {
1074                     self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
1075                 });
1076                 deff.resolve();
1077             };
1078             if (lg.code === self.view_language) {
1079                 var values = {};
1080                 _.each(self.translatable_fields_keys, function(field) {
1081                     values[field] = self.view.fields[field].get_value();
1082                 });
1083                 callback([values]);
1084             } else {
1085                 self.rpc('/web/dataset/get', {
1086                     model: self.view.dataset.model,
1087                     ids: [self.view.datarecord.id],
1088                     fields: self.translatable_fields_keys,
1089                     context: self.view.dataset.get_context({
1090                         'lang': lg.code
1091                     })}, callback);
1092             }
1093         });
1094         $.when.apply(null, deffered).then(callback);
1095     },
1096     open: function(field) {
1097         var self = this,
1098             sup = this._super;
1099         $.when(this.languages_loaded).then(function() {
1100             if (self.view.translatable_fields && self.view.translatable_fields.length) {
1101                 self.do_load_fields_values(function() {
1102                     sup.call(self);
1103                     if (field) {
1104                         var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
1105                         self.$element.scrollTo($field_input);
1106                         $field_input.focus();
1107                     }
1108                 });
1109             } else {
1110                 sup.call(self);
1111             }
1112         });
1113     },
1114     on_btn_save: function() {
1115         var trads = {},
1116             self = this,
1117             trads_mutex = new $.Mutex();
1118         self.$fields_form.find('.oe_trad_field.touched').each(function() {
1119             var field = $(this).attr('name').split('-');
1120             if (!trads[field[0]]) {
1121                 trads[field[0]] = {};
1122             }
1123             trads[field[0]][field[1]] = $(this).val();
1124         });
1125         _.each(trads, function(data, code) {
1126             if (code === self.view_language) {
1127                 _.each(data, function(value, field) {
1128                     self.view.fields[field].set_value(value);
1129                 });
1130             }
1131             trads_mutex.exec(function() {
1132                 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
1133             });
1134         });
1135         this.close();
1136     },
1137     on_btn_close: function() {
1138         this.close();
1139     }
1140 });
1141
1142 instance.web.View = instance.web.Widget.extend({
1143     template: "EmptyComponent",
1144     // name displayed in view switchers
1145     display_name: '',
1146     /**
1147      * Define a view type for each view to allow automatic call to fields_view_get.
1148      */
1149     view_type: undefined,
1150     init: function(parent, dataset, view_id, options) {
1151         this._super(parent);
1152         this.dataset = dataset;
1153         this.view_id = view_id;
1154         this.set_default_options(options);
1155     },
1156     start: function() {
1157         return this.load_view();
1158     },
1159     load_view: function() {
1160         if (this.embedded_view) {
1161             var def = $.Deferred();
1162             var self = this;
1163             $.async_when().then(function() {def.resolve(self.embedded_view);});
1164             return def.pipe(this.on_loaded);
1165         } else {
1166             var context = new instance.web.CompoundContext(this.dataset.get_context());
1167             if (! this.view_type)
1168                 console.warn("view_type is not defined", this);
1169             return this.rpc("/web/view/load", {
1170                 "model": this.dataset.model,
1171                 "view_id": this.view_id,
1172                 "view_type": this.view_type,
1173                 toolbar: !!this.options.$sidebar,
1174                 context: context
1175                 }).pipe(this.on_loaded);
1176         }
1177     },
1178     /**
1179      * Called after a successful call to fields_view_get.
1180      * Must return a promise.
1181      */
1182     on_loaded: function(fields_view_get) {
1183     },
1184     set_default_options: function(options) {
1185         this.options = options || {};
1186         _.defaults(this.options, {
1187             // All possible views options should be defaulted here
1188             $sidebar: null,
1189             sidebar_id: null,
1190             action: null,
1191             action_views_ids: {}
1192         });
1193     },
1194     open_translate_dialog: function(field) {
1195         if (!this.translate_dialog) {
1196             this.translate_dialog = new instance.web.TranslateDialog(this).start();
1197         }
1198         this.translate_dialog.open(field);
1199     },
1200     /**
1201      * Fetches and executes the action identified by ``action_data``.
1202      *
1203      * @param {Object} action_data the action descriptor data
1204      * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1205      * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1206      * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1207      * @param {Object} [action_data.context=null] additional action context, to add to the current context
1208      * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1209      * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1210      * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1211      */
1212     do_execute_action: function (action_data, dataset, record_id, on_closed) {
1213         var self = this;
1214         var result_handler = function () {
1215             if (on_closed) { on_closed.apply(null, arguments); }
1216             if (self.getParent() && self.getParent().on_action_executed) {
1217                 return self.getParent().on_action_executed.apply(null, arguments);
1218             }
1219         };
1220         var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1221
1222         var handler = function (r) {
1223             var action = r.result;
1224             if (action && action.constructor == Object) {
1225                 var ncontext = new instance.web.CompoundContext(context);
1226                 if (record_id) {
1227                     ncontext.add({
1228                         active_id: record_id,
1229                         active_ids: [record_id],
1230                         active_model: dataset.model
1231                     });
1232                 }
1233                 ncontext.add(action.context || {});
1234                 return self.rpc('/web/session/eval_domain_and_context', {
1235                     contexts: [ncontext],
1236                     domains: []
1237                 }).pipe(function (results) {
1238                     action.context = results.context;
1239                     /* niv: previously we were overriding once more with action_data.context,
1240                      * I assumed this was not a correct behavior and removed it
1241                      */
1242                     return self.do_action(action, result_handler);
1243                 }, null);
1244             } else {
1245                 return result_handler();
1246             }
1247         };
1248
1249         if (action_data.special) {
1250             return handler({result: {"type":"ir.actions.act_window_close"}});
1251         } else if (action_data.type=="object") {
1252             var args = [[record_id]], additional_args = [];
1253             if (action_data.args) {
1254                 try {
1255                     // Warning: quotes and double quotes problem due to json and xml clash
1256                     // Maybe we should force escaping in xml or do a better parse of the args array
1257                     additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1258                     args = args.concat(additional_args);
1259                 } catch(e) {
1260                     console.error("Could not JSON.parse arguments", action_data.args);
1261                 }
1262             }
1263             args.push(context);
1264             return dataset.call_button(action_data.name, args, handler);
1265         } else if (action_data.type=="action") {
1266             return this.rpc('/web/action/load', { action_id: action_data.name, context: context, do_not_eval: true}, handler);
1267         } else  {
1268             return dataset.exec_workflow(record_id, action_data.name, handler);
1269         }
1270     },
1271     /**
1272      * Directly set a view to use instead of calling fields_view_get. This method must
1273      * be called before start(). When an embedded view is set, underlying implementations
1274      * of instance.web.View must use the provided view instead of any other one.
1275      *
1276      * @param embedded_view A view.
1277      */
1278     set_embedded_view: function(embedded_view) {
1279         this.embedded_view = embedded_view;
1280     },
1281     do_show: function () {
1282         this.$element.show();
1283     },
1284     do_hide: function () {
1285         this.$element.hide();
1286     },
1287     do_push_state: function(state) {
1288         if (this.getParent() && this.getParent().do_push_state) {
1289             this.getParent().do_push_state(state);
1290         }
1291     },
1292     do_load_state: function(state, warm) {
1293     },
1294     /**
1295      * Switches to a specific view type
1296      *
1297      * @param {String} view view type to switch to
1298      */
1299     do_switch_view: function(view) { 
1300     },
1301     /**
1302      * Cancels the switch to the current view, switches to the previous one
1303      *
1304      * @param {Object} [options]
1305      * @param {Boolean} [options.created=false] resource was created
1306      * @param {String} [options.default=null] view to switch to if no previous view
1307      */
1308     do_prev_view: function (options) {
1309     },
1310     do_search: function(view) {
1311     },
1312     on_sidebar_import: function() {
1313         var import_view = new instance.web.DataImport(this, this.dataset);
1314         import_view.start();
1315     },
1316     on_sidebar_export: function() {
1317         var export_view = new instance.web.DataExport(this, this.dataset);
1318         export_view.start();
1319     },
1320     on_sidebar_translate: function() {
1321         return this.do_action({
1322             res_model : 'ir.translation',
1323             domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1324             views: [[false, 'list'], [false, 'form']],
1325             type : 'ir.actions.act_window',
1326             view_type : "list",
1327             view_mode : "list"
1328         });
1329     },
1330     sidebar_context: function () {
1331         return $.when();
1332     },
1333     /**
1334      * Asks the view to reload itself, if the reloading is asynchronous should
1335      * return a {$.Deferred} indicating when the reloading is done.
1336      */
1337     reload: function () {
1338         return $.when();
1339     }
1340 });
1341
1342 instance.web.xml_to_json = function(node) {
1343     switch (node.nodeType) {
1344         case 3:
1345         case 4:
1346             return node.data;
1347         break;
1348         case 1:
1349             var attrs = $(node).getAttributes();
1350             _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1351                 if (attrs[key]) {
1352                     try {
1353                         attrs[key] = JSON.parse(attrs[key]);
1354                     } catch(e) { }
1355                 }
1356             });
1357             return {
1358                 tag: node.tagName.toLowerCase(),
1359                 attrs: attrs,
1360                 children: _.map(node.childNodes, instance.web.xml_to_json)
1361             }
1362     }
1363 }
1364 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1365     // For debugging purpose, this function will convert a json node back to xml
1366     // Maybe useful for xml view editor
1367     indent = indent || 0;
1368     var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1369         r = sindent + '<' + node.tag,
1370         cr = human_readable ? '\n' : '';
1371
1372     if (typeof(node) === 'string') {
1373         return sindent + node;
1374     } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1375         throw("Node a json node");
1376     }
1377     for (var attr in node.attrs) {
1378         var vattr = node.attrs[attr];
1379         if (typeof(vattr) !== 'string') {
1380             // domains, ...
1381             vattr = JSON.stringify(vattr);
1382         }
1383         vattr = vattr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1384         if (human_readable) {
1385             vattr = vattr.replace(/&quot;/g, "'");
1386         }
1387         r += ' ' + attr + '="' + vattr + '"';
1388     }
1389     if (node.children && node.children.length) {
1390         r += '>' + cr;
1391         var childs = [];
1392         for (var i = 0, ii = node.children.length; i < ii; i++) {
1393             childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1394         }
1395         r += childs.join(cr);
1396         r += cr + sindent + '</' + node.tag + '>';
1397         return r;
1398     } else {
1399         return r + '/>';
1400     }
1401 }
1402 instance.web.xml_to_str = function(node) {
1403     if (window.ActiveXObject) {
1404         return node.xml;
1405     } else {
1406         return (new XMLSerializer()).serializeToString(node);
1407     }
1408 }
1409 instance.web.str_to_xml = function(s) {
1410     if (window.DOMParser) {
1411         var dp = new DOMParser();
1412         var r = dp.parseFromString(s, "text/xml");
1413         if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1414             throw new Error("Could not parse string to xml");
1415         }
1416         return r;
1417     }
1418     var xDoc;
1419     try {
1420         xDoc = new ActiveXObject("MSXML2.DOMDocument");
1421     } catch (e) {
1422         throw new Error("Could not find a DOM Parser: " + e.message);
1423     }
1424     xDoc.async = false;
1425     xDoc.preserveWhiteSpace = true;
1426     xDoc.loadXML(s);
1427     return xDoc;
1428 }
1429
1430 /**
1431  * Registry for all the main views
1432  */
1433 instance.web.views = new instance.web.Registry();
1434
1435 };
1436
1437 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: