[MERGE] menu possible to reload only a submenu
[odoo/odoo.git] / addons / web / static / src / js / chrome.js
1 /*---------------------------------------------------------
2  * OpenERP Web chrome
3  *---------------------------------------------------------*/
4 openerp.web.chrome = function(instance) {
5 var QWeb = instance.web.qweb,
6     _t = instance.web._t;
7
8 instance.web.Notification =  instance.web.Widget.extend({
9     template: 'Notification',
10     init: function() {
11         this._super.apply(this, arguments);
12         instance.web.notification = this;
13     },
14     start: function() {
15         this._super.apply(this, arguments);
16         this.$el.notify({
17             speed: 500,
18             expires: 2500
19         });
20     },
21     notify: function(title, text, sticky) {
22         sticky = !!sticky;
23         var opts = {};
24         if (sticky) {
25             opts.expires = false;
26         }
27         this.$el.notify('create', {
28             title: title,
29             text: text
30         }, opts);
31     },
32     warn: function(title, text, sticky) {
33         sticky = !!sticky;
34         var opts = {};
35         if (sticky) {
36             opts.expires = false;
37         }
38         this.$el.notify('create', 'oe_notification_alert', {
39             title: title,
40             text: text
41         }, opts);
42     }
43 });
44
45 /**
46  * The very minimal function everything should call to create a dialog
47  * in OpenERP Web Client.
48  */
49 instance.web.dialog = function(element) {
50     var result = element.dialog.apply(element, _.rest(_.toArray(arguments)));
51     result.dialog("widget").addClass("openerp");
52     return result;
53 };
54
55 instance.web.Dialog = instance.web.Widget.extend({
56     dialog_title: "",
57     init: function (parent, options, content) {
58         var self = this;
59         this._super(parent);
60         this.content_to_set = content;
61         this.dialog_options = {
62             modal: true,
63             destroy_on_close: true,
64             width: 900,
65             min_width: 0,
66             max_width: '95%',
67             height: 'auto',
68             min_height: 0,
69             max_height: this.get_height('100%') - 200,
70             autoOpen: false,
71             position: [false, 40],
72             buttons: {},
73             beforeClose: function () {
74                 self.trigger("closing");
75             },
76             resizeStop: this.on_resized
77         };
78         for (var f in this) {
79             if (f.substr(0, 10) == 'on_button_') {
80                 this.dialog_options.buttons[f.substr(10)] = this[f];
81             }
82         }
83         if (options) {
84             _.extend(this.dialog_options, options);
85         }
86         this.on("closing", this, this._closing);
87     },
88     get_options: function(options) {
89         var self = this,
90             o = _.extend({}, this.dialog_options, options || {});
91         _.each(['width', 'height'], function(unit) {
92             o[unit] = self['get_' + unit](o[unit]);
93             o['min_' + unit] = self['get_' + unit](o['min_' + unit] || 0);
94             o['max_' + unit] = self['get_' + unit](o['max_' + unit] || 0);
95             if (o[unit] !== 'auto' && o['min_' + unit] && o[unit] < o['min_' + unit]) o[unit] = o['min_' + unit];
96             if (o[unit] !== 'auto' && o['max_' + unit] && o[unit] > o['max_' + unit]) o[unit] = o['max_' + unit];
97         });
98         if (!o.title && this.dialog_title) {
99             o.title = this.dialog_title;
100         }
101         return o;
102     },
103     get_width: function(val) {
104         return this.get_size(val.toString(), $(window.top).width());
105     },
106     get_height: function(val) {
107         return this.get_size(val.toString(), $(window.top).height());
108     },
109     get_size: function(val, available_size) {
110         if (val === 'auto') {
111             return val;
112         } else if (val.slice(-1) == "%") {
113             return Math.round(available_size / 100 * parseInt(val.slice(0, -1), 10));
114         } else {
115             return parseInt(val, 10);
116         }
117     },
118     renderElement: function() {
119         if (this.content_to_set) {
120             this.setElement(this.content_to_set);
121         } else if (this.template) {
122             this._super();
123         }
124     },
125     open: function(options) {
126         if (! this.dialog_inited)
127             this.init_dialog();
128         var o = this.get_options(options);
129         this.add_buttons(o.buttons);
130         delete(o.buttons);
131         this.$buttons.appendTo($("body"));
132         instance.web.dialog(this.$el, o).dialog('open');
133         this.$el.dialog("widget").find(".ui-dialog-buttonpane").remove();
134         this.$buttons.appendTo(this.$el.dialog("widget"));
135         if (o.height === 'auto' && o.max_height) {
136             this.$el.css({ 'max-height': o.max_height, 'overflow-y': 'auto' });
137         }
138         return this;
139     },
140     add_buttons: function(buttons) {
141         var self = this;
142         _.each(buttons, function(fn, but) {
143             var $but = $(QWeb.render('WidgetButton', { widget : { string: but, node: { attrs: {} }}}));
144             self.$buttons.append($but);
145             $but.on('click', function(ev) {
146                 fn.call(self.$el, ev);
147             });
148         });
149     },
150     init_dialog: function(options) {
151         this.renderElement();
152         var o = this.get_options(options);
153         instance.web.dialog(this.$el, o);
154         this.$buttons = $('<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" />');
155         this.$el.dialog("widget").append(this.$buttons);
156         this.dialog_inited = true;
157         var res = this.start();
158         return res;
159     },
160     close: function() {
161         if (this.dialog_inited && this.$el.is(":data(dialog)")) {
162             this.$el.dialog('close');
163         }
164     },
165     _closing: function() {
166         if (this.__tmp_dialog_destroying)
167             return;
168         if (this.dialog_options.destroy_on_close) {
169             this.__tmp_dialog_closing = true;
170             this.destroy();
171             this.__tmp_dialog_closing = undefined;
172         }
173     },
174     on_resized: function() {
175     },
176     destroy: function () {
177         _.each(this.getChildren(), function(el) {
178             el.destroy();
179         });
180         if (! this.__tmp_dialog_closing) {
181             this.__tmp_dialog_destroying = true;
182             this.close();
183             this.__tmp_dialog_destroying = undefined;
184         }
185         if (this.dialog_inited && !this.isDestroyed()) {
186             this.$el.dialog('destroy');
187         }
188         this._super();
189     }
190 });
191
192 instance.web.CrashManager = instance.web.Class.extend({
193     rpc_error: function(error) {
194         if (error.data.fault_code) {
195             var split = ("" + error.data.fault_code).split('\n')[0].split(' -- ');
196             if (split.length > 1) {
197                 error.type = split.shift();
198                 error.data.fault_code = error.data.fault_code.substr(error.type.length + 4);
199             }
200         }
201         if (error.code === 200 && error.type) {
202             this.show_warning(error);
203         } else {
204             this.show_error(error);
205         }
206     },
207     show_warning: function(error) {
208         instance.web.dialog($('<div>' + QWeb.render('CrashManager.warning', {error: error}) + '</div>'), {
209             title: "OpenERP " + _.str.capitalize(error.type),
210             buttons: [
211                 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
212             ]
213         });
214     },
215     show_error: function(error) {
216         var self = this;
217         var buttons = {};
218         buttons[_t("Ok")] = function() {
219             $(this).dialog("close");
220         };
221         var dialog = new instance.web.Dialog(this, {
222             title: "OpenERP " + _.str.capitalize(error.type),
223             width: '80%',
224             height: '50%',
225             min_width: '800px',
226             min_height: '600px',
227             buttons: buttons
228         }).open();
229         dialog.$el.html(QWeb.render('CrashManager.error', {session: instance.session, error: error}));
230     },
231     show_message: function(exception) {
232         this.show_error({
233             type: _t("Client Error"),
234             message: exception,
235             data: {debug: ""}
236         });
237     },
238 });
239
240 instance.web.Loading = instance.web.Widget.extend({
241     template: 'Loading',
242     init: function(parent) {
243         this._super(parent);
244         this.count = 0;
245         this.blocked_ui = false;
246         this.session.on("request", this, this.request_call);
247         this.session.on("response", this, this.response_call);
248         this.session.on("response_failed", this, this.response_call);
249     },
250     destroy: function() {
251         this.on_rpc_event(-this.count);
252         this._super();
253     },
254     request_call: function() {
255         this.on_rpc_event(1);
256     },
257     response_call: function() {
258         this.on_rpc_event(-1);
259     },
260     on_rpc_event : function(increment) {
261         var self = this;
262         if (!this.count && increment === 1) {
263             // Block UI after 3s
264             this.long_running_timer = setTimeout(function () {
265                 self.blocked_ui = true;
266                 instance.web.blockUI();
267             }, 3000);
268         }
269
270         this.count += increment;
271         if (this.count > 0) {
272             if (instance.session.debug) {
273                 this.$el.text(_.str.sprintf( _t("Loading (%d)"), this.count));
274             } else {
275                 this.$el.text(_t("Loading"));
276             }
277             this.$el.show();
278             this.getParent().$el.addClass('oe_wait');
279         } else {
280             this.count = 0;
281             clearTimeout(this.long_running_timer);
282             // Don't unblock if blocked by somebody else
283             if (self.blocked_ui) {
284                 this.blocked_ui = false;
285                 instance.web.unblockUI();
286             }
287             this.$el.fadeOut();
288             this.getParent().$el.removeClass('oe_wait');
289         }
290     }
291 });
292
293 instance.web.DatabaseManager = instance.web.Widget.extend({
294     init: function(parent) {
295         this._super(parent);
296         this.unblockUIFunction = instance.web.unblockUI;
297         $.validator.addMethod('matches', function (s, _, re) {
298             return new RegExp(re).test(s);
299         }, _t("Invalid database name"));
300     },
301     start: function() {
302         var self = this;
303         $('.oe_secondary_menus_container,.oe_user_menu_placeholder').empty();
304         var fetch_db = this.rpc("/web/database/get_list", {}).then(
305             function(result) {
306                 self.db_list = result;
307             },
308             function (_, ev) {
309                 ev.preventDefault();
310                 self.db_list = null;
311             });
312         var fetch_langs = this.rpc("/web/session/get_lang_list", {}).done(function(result) {
313             self.lang_list = result.lang_list;
314         });
315         return $.when(fetch_db, fetch_langs).done(self.do_render);
316     },
317     do_render: function() {
318         var self = this;
319         instance.webclient.toggle_bars(true);
320         self.$el.html(QWeb.render("DatabaseManager", { widget : self }));
321         $('.oe_user_menu_placeholder').append(QWeb.render("DatabaseManager.user_menu",{ widget : self }));
322         $('.oe_secondary_menus_container').append(QWeb.render("DatabaseManager.menu",{ widget : self }));
323         $('ul.oe_secondary_submenu > li:first').addClass('oe_active')
324         $('ul.oe_secondary_submenu > li').bind('click', function (event) {
325             var menuitem = $(this);
326             menuitem.addClass('oe_active').siblings().removeClass('oe_active');
327             var form_id =menuitem.find('a').attr('href');
328             $(form_id).show().siblings().hide();
329             event.preventDefault();
330         });
331         $('#back-to-login').click(self.do_exit);
332         self.$el.find("td").addClass("oe_form_group_cell");
333         self.$el.find("tr td:first-child").addClass("oe_form_group_cell_label");
334         self.$el.find("label").addClass("oe_form_label");
335         self.$el.find("form[name=create_db_form]").validate({ submitHandler: self.do_create });
336         self.$el.find("form[name=drop_db_form]").validate({ submitHandler: self.do_drop });
337         self.$el.find("form[name=backup_db_form]").validate({ submitHandler: self.do_backup });
338         self.$el.find("form[name=restore_db_form]").validate({ submitHandler: self.do_restore });
339         self.$el.find("form[name=change_pwd_form]").validate({
340             messages: {
341                 old_pwd: "Please enter your previous password",
342                 new_pwd: "Please enter your new password",
343                 confirm_pwd: {
344                     required: "Please confirm your new password",
345                     equalTo: "The confirmation does not match the password"
346                 }
347             },
348             submitHandler: self.do_change_password
349         });
350     },
351     destroy: function () {
352         this.$el.find('#db-create, #db-drop, #db-backup, #db-restore, #db-change-password, #back-to-login').unbind('click').end().empty();
353         this._super();
354     },
355     /**
356      * Converts a .serializeArray() result into a dict. Does not bother folding
357      * multiple identical keys into an array, last key wins.
358      *
359      * @param {Array} array
360      */
361     to_object: function (array) {
362         var result = {};
363         _(array).each(function (record) {
364             result[record.name] = record.value;
365         });
366         return result;
367     },
368     /**
369      * Blocks UI and replaces $.unblockUI by a noop to prevent third parties
370      * from unblocking the UI
371      */
372     blockUI: function () {
373         instance.web.blockUI();
374         instance.web.unblockUI = function () {};
375     },
376     /**
377      * Reinstates $.unblockUI so third parties can play with blockUI, and
378      * unblocks the UI
379      */
380     unblockUI: function () {
381         instance.web.unblockUI = this.unblockUIFunction;
382         instance.web.unblockUI();
383     },
384     /**
385      * Displays an error dialog resulting from the various RPC communications
386      * failing over themselves
387      *
388      * @param {Object} error error description
389      * @param {String} error.title title of the error dialog
390      * @param {String} error.error message of the error dialog
391      */
392     display_error: function (error) {
393         return instance.web.dialog($('<div>'), {
394             modal: true,
395             title: error.title,
396             buttons: [
397                 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
398             ]
399         }).html(error.error);
400     },
401     do_create: function(form) {
402         var self = this;
403         var fields = $(form).serializeArray();
404         self.rpc("/web/database/create", {'fields': fields}).done(function(result) {
405             var form_obj = self.to_object(fields);
406             var client_action = {
407                 type: 'ir.actions.client',
408                 tag: 'login',
409                 params: {
410                     'db': form_obj['db_name'],
411                     'login': 'admin',
412                     'password': form_obj['create_admin_pwd'],
413                     'login_successful': function() {
414                         self.do_action("reload");
415                     },
416                 },
417             };
418             self.do_action(client_action);
419         });
420     },
421     do_drop: function(form) {
422         var self = this;
423         var $form = $(form),
424             fields = $form.serializeArray(),
425             $db_list = $form.find('[name=drop_db]'),
426             db = $db_list.val();
427         if (!db || !confirm("Do you really want to delete the database: " + db + " ?")) {
428             return;
429         }
430         self.rpc("/web/database/drop", {'fields': fields}).done(function(result) {
431             if (result.error) {
432                 self.display_error(result);
433                 return;
434             }
435             self.do_notify("Dropping database", "The database '" + db + "' has been dropped");
436             self.start();
437         });
438     },
439     do_backup: function(form) {
440         var self = this;
441         self.blockUI();
442         self.session.get_file({
443             form: form,
444             success: function () {
445                 self.do_notify(_t("Backed"), _t("Database backed up successfully"));
446             },
447             error: function(error){
448                if(error){
449                   self.display_error({
450                         title: 'Backup Database',
451                         error: 'AccessDenied'
452                   });
453                }
454             },
455             complete: function() {
456                 self.unblockUI();
457             }
458         });
459     },
460     do_restore: function(form) {
461         var self = this;
462         self.blockUI();
463         $(form).ajaxSubmit({
464             url: '/web/database/restore',
465             type: 'POST',
466             resetForm: true,
467             success: function (body) {
468                 // If empty body, everything went fine
469                 if (!body) { return; }
470
471                 if (body.indexOf('403 Forbidden') !== -1) {
472                     self.display_error({
473                         title: 'Access Denied',
474                         error: 'Incorrect super-administrator password'
475                     });
476                 } else {
477                     self.display_error({
478                         title: 'Restore Database',
479                         error: 'Could not restore the database'
480                     });
481                 }
482             },
483             complete: function() {
484                 self.unblockUI();
485                 self.do_notify(_t("Restored"), _t("Database restored successfully"));
486             }
487         });
488     },
489     do_change_password: function(form) {
490         var self = this;
491         self.rpc("/web/database/change_password", {
492             'fields': $(form).serializeArray()
493         }).done(function(result) {
494             if (result.error) {
495                 self.display_error(result);
496                 return;
497             }
498             self.unblockUI();
499             self.do_notify("Changed Password", "Password has been changed successfully");
500         });
501     },
502     do_exit: function () {
503         this.$el.remove();
504         instance.webclient.toggle_bars(false);
505         this.do_action('login');
506     }
507 });
508 instance.web.client_actions.add("database_manager", "instance.web.DatabaseManager");
509
510 instance.web.Login =  instance.web.Widget.extend({
511     template: "Login",
512     remember_credentials: true,
513
514     init: function(parent, action) {
515         this._super(parent);
516         this.has_local_storage = typeof(localStorage) != 'undefined';
517         this.db_list = null;
518         this.selected_db = null;
519         this.selected_login = null;
520         this.params = action.params || {};
521
522         if (this.params.login_successful) {
523             this.on('login_successful', this, this.params.login_successful);
524         }
525
526         if (this.has_local_storage && this.remember_credentials) {
527             this.selected_db = localStorage.getItem('last_db_login_success');
528             this.selected_login = localStorage.getItem('last_login_login_success');
529             if (jQuery.deparam(jQuery.param.querystring()).debug !== undefined) {
530                 this.selected_password = localStorage.getItem('last_password_login_success');
531             }
532         }
533     },
534     start: function() {
535         var self = this;
536         self.$el.find("form").submit(self.on_submit);
537         self.$el.find('.oe_login_manage_db').click(function() {
538             self.do_action("database_manager");
539         });
540         var d;
541         if (self.params.db) {
542             if (self.params.login && self.params.password) {
543                 d = self.do_login(self.params.db, self.params.login, self.params.password);
544             }
545         } else {
546             d = self.rpc("/web/database/get_list", {}).done(self.on_db_loaded).fail(self.on_db_failed);
547         }
548         return d;
549     },
550     on_db_loaded: function (result) {
551         this.db_list = result;
552         this.$("[name=db]").replaceWith(QWeb.render('Login.dblist', { db_list: this.db_list, selected_db: this.selected_db}));
553         if(this.db_list.length === 0) {
554             this.do_action("database_manager");
555         } else if(this.db_list.length === 1) {
556             this.$('div.oe_login_dbpane').hide();
557         } else {
558             this.$('div.oe_login_dbpane').show();
559         }
560     },
561     on_db_failed: function (error, event) {
562         if (error.data.fault_code === 'AccessDenied') {
563             event.preventDefault();
564         }
565     },
566     on_submit: function(ev) {
567         if(ev) {
568             ev.preventDefault();
569         }
570         var db = this.$("form [name=db]").val();
571         if (!db) {
572             this.do_warn("Login", "No database selected !");
573             return false;
574         }
575         var login = this.$("form input[name=login]").val();
576         var password = this.$("form input[name=password]").val();
577
578         this.do_login(db, login, password);
579     },
580     /**
581      * Performs actual login operation, and UI-related stuff
582      *
583      * @param {String} db database to log in
584      * @param {String} login user login
585      * @param {String} password user password
586      */
587     do_login: function (db, login, password) {
588         var self = this;
589         self.hide_error();
590         self.$(".oe_login_pane").fadeOut("slow");
591         return this.session.session_authenticate(db, login, password).then(function() {
592             if (self.has_local_storage) {
593                 if(self.remember_credentials) {
594                     localStorage.setItem('last_db_login_success', db);
595                     localStorage.setItem('last_login_login_success', login);
596                     if (jQuery.deparam(jQuery.param.querystring()).debug !== undefined) {
597                         localStorage.setItem('last_password_login_success', password);
598                     }
599                 } else {
600                     localStorage.setItem('last_db_login_success', '');
601                     localStorage.setItem('last_login_login_success', '');
602                     localStorage.setItem('last_password_login_success', '');
603                 }
604             }
605             self.trigger('login_successful');
606         }, function () {
607             self.$(".oe_login_pane").fadeIn("fast", function() {
608                 self.show_error("Invalid username or password");
609             });
610         });
611     },
612     show_error: function(message) {
613         this.$el.addClass("oe_login_invalid");
614         this.$(".oe_login_error_message").text(message);
615     },
616     hide_error: function() {
617         this.$el.removeClass('oe_login_invalid');
618     },
619 });
620 instance.web.client_actions.add("login", "instance.web.Login");
621
622 /**
623  * Client action to reload the whole interface.
624  * If params has an entry 'menu_id', it opens the given menu entry.
625  */
626 instance.web.Reload = function(parent, action) {
627     var params = action.params || {};
628     var menu_id = params.menu_id || false;
629     var l = window.location;
630
631     var sobj = $.deparam(l.search.substr(1));
632     sobj.ts = new Date().getTime();
633     var search = '?' + $.param(sobj);
634
635     var hash = l.hash;
636     if (menu_id) {
637         hash = "#menu_id=" + menu_id;
638     }
639     var url = l.protocol + "//" + l.host + l.pathname + search + hash;
640     window.onerror = function() {};
641     window.location = url;
642 };
643 instance.web.client_actions.add("reload", "instance.web.Reload");
644
645 /**
646  * Client action to go back in breadcrumb history.
647  * If can't go back in history stack, will go back to home.
648  */
649 instance.web.HistoryBack = function(parent) {
650     if (!parent.history_back()) {
651         window.location = '/' + (window.location.search || '');
652     }
653 };
654 instance.web.client_actions.add("history_back", "instance.web.HistoryBack");
655
656 /**
657  * Client action to go back home.
658  */
659 instance.web.Home = instance.web.Widget.extend({
660     init: function(parent) {
661         window.location = '/' + (window.location.search || '');
662     }
663 });
664 instance.web.client_actions.add("home", "instance.web.Home");
665
666 instance.web.ChangePassword =  instance.web.Widget.extend({
667     template: "ChangePassword",
668     start: function() {
669         var self = this;
670         self.$el.validate({
671             submitHandler: function (form) {
672                 self.rpc("/web/session/change_password",{
673                     'fields': $(form).serializeArray()
674                 }).done(function(result) {
675                     if (result.error) {
676                         self.display_error(result);
677                         return;
678                     } else {
679                         instance.webclient.on_logout();
680                     }
681                 });
682             }
683         });
684     },
685     display_error: function (error) {
686         return instance.web.dialog($('<div>'), {
687             modal: true,
688             title: error.title,
689             buttons: [
690                 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
691             ]
692         }).html(error.error);
693     },
694 })
695 instance.web.client_actions.add("change_password", "instance.web.ChangePassword");
696
697 instance.web.Menu =  instance.web.Widget.extend({
698     template: 'Menu',
699     init: function() {
700         this._super.apply(this, arguments);
701         this.has_been_loaded = $.Deferred();
702         this.maximum_visible_links = 'auto'; // # of menu to show. 0 = do not crop, 'auto' = algo
703         this.data = {data:{children:[]}};
704     },
705     start: function() {
706         this._super.apply(this, arguments);
707         this.$secondary_menus = this.getParent().$el.find('.oe_secondary_menus_container');
708         this.$secondary_menus.on('click', 'a[data-menu]', this.on_menu_click);
709         return this.do_reload();
710     },
711     do_reload: function() {
712         var self = this;
713         return this.rpc("/web/menu/load", {}).done(function(r) {
714             self.menu_loaded(r);
715         });
716     },
717     menu_loaded: function(data) {
718         var self = this;
719         // TODO remove data.data
720         this.data = {"data": data};
721         this.renderElement();
722         this.limit_entries();
723         // Hide toplevel item if there is only one
724         var $toplevel = this.$("li")
725         if($toplevel.length == 1) {
726             $toplevel.hide();
727         }
728         this.$secondary_menus.html(QWeb.render("Menu.secondary", { widget : this }));
729         this.$el.on('click', 'a[data-menu]', this.on_menu_click);
730         // Hide second level submenus
731         this.$secondary_menus.find('.oe_menu_toggler').siblings('.oe_secondary_submenu').hide();
732         if (self.current_menu) {
733             self.open_menu(self.current_menu);
734         }
735         this.trigger('menu_loaded', data);
736         this.has_been_loaded.resolve();
737     },
738     limit_entries: function() {
739         var maximum_visible_links = this.maximum_visible_links;
740         if (maximum_visible_links === 'auto') {
741             maximum_visible_links = this.auto_limit_entries();
742         }
743         if (maximum_visible_links < this.data.data.children.length) {
744             var $more = $(QWeb.render('Menu.more')),
745                 $index = this.$el.find('li').eq(maximum_visible_links - 1);
746             $index.after($more);
747             //$('.oe_topbar').append($more);
748             $more.find('.oe_menu_more').append($index.next().nextAll());
749         }
750     },
751     auto_limit_entries: function() {
752         // TODO: auto detect overflow and bind window on resize
753         var width = $(window).width();
754         return Math.floor(width / 125);
755     },
756     /**
757      * Opens a given menu by id, as if a user had browsed to that menu by hand
758      * except does not trigger any event on the way
759      *
760      * @param {Number} id database id of the terminal menu to select
761      */
762     open_menu: function (id) {
763         this.current_menu = id;
764         this.session.active_id = id;
765         var $clicked_menu, $sub_menu, $main_menu;
766         $clicked_menu = this.$el.add(this.$secondary_menus).find('a[data-menu=' + id + ']');
767         this.trigger('open_menu', id, $clicked_menu);
768
769         if (this.$secondary_menus.has($clicked_menu).length) {
770             $sub_menu = $clicked_menu.parents('.oe_secondary_menu');
771             $main_menu = this.$el.find('a[data-menu=' + $sub_menu.data('menu-parent') + ']');
772         } else {
773             $sub_menu = this.$secondary_menus.find('.oe_secondary_menu[data-menu-parent=' + $clicked_menu.attr('data-menu') + ']');
774             $main_menu = $clicked_menu;
775         }
776
777         // Activate current main menu
778         this.$el.find('.oe_active').removeClass('oe_active');
779         $main_menu.addClass('oe_active');
780
781         // Show current sub menu
782         this.$secondary_menus.find('.oe_secondary_menu').hide();
783         $sub_menu.show();
784
785         // Hide/Show the leftbar menu depending of the presence of sub-items
786         this.$secondary_menus.parent('.oe_leftbar').toggle(!!$sub_menu.children().length);
787
788         // Activate current menu item and show parents
789         this.$secondary_menus.find('.oe_active').removeClass('oe_active');
790         if ($main_menu !== $clicked_menu) {
791             $clicked_menu.parents().show();
792             if ($clicked_menu.is('.oe_menu_toggler')) {
793                 $clicked_menu.toggleClass('oe_menu_opened').siblings('.oe_secondary_submenu:first').toggle();
794             } else {
795                 $clicked_menu.parent().addClass('oe_active');
796             }
797         }
798     },
799     /**
800      * Call open_menu with the first menu_item matching an action_id
801      *
802      * @param {Number} id the action_id to match
803      */
804     open_action: function (id) {
805         var $menu = this.$el.add(this.$secondary_menus).find('a[data-action-id="' + id + '"]');
806         var menu_id = $menu.data('menu');
807         if (menu_id) {
808             this.open_menu(menu_id);
809         }
810     },
811     /**
812      * Process a click on a menu item
813      *
814      * @param {Number} id the menu_id
815      * @param {Boolean} [needaction=false] whether the triggered action should execute in a `needs action` context
816      */
817     menu_click: function(id, needaction) {
818         if (!id) { return; }
819
820         // find back the menuitem in dom to get the action
821         var $item = this.$el.find('a[data-menu=' + id + ']');
822         if (!$item.length) {
823             $item = this.$secondary_menus.find('a[data-menu=' + id + ']');
824         }
825         var action_id = $item.data('action-id');
826         // If first level menu doesnt have action trigger first leaf
827         if (!action_id) {
828             if(this.$el.has($item).length) {
829                 var $sub_menu = this.$secondary_menus.find('.oe_secondary_menu[data-menu-parent=' + id + ']');
830                 var $items = $sub_menu.find('a[data-action-id]').filter('[data-action-id!=""]');
831                 if($items.length) {
832                     action_id = $items.data('action-id');
833                     id = $items.data('menu');
834                 }
835             }
836         }
837         if (action_id) {
838             this.trigger('menu_click', {
839                 action_id: action_id,
840                 needaction: needaction,
841                 id: id,
842                 previous_menu_id: this.current_menu // Here we don't know if action will fail (in which case we have to revert menu)
843             }, $item);
844         }
845         this.open_menu(id);
846     },
847     /**
848      * Jquery event handler for menu click
849      *
850      * @param {Event} ev the jquery event
851      */
852     on_menu_click: function(ev) {
853         ev.preventDefault();
854         var needaction = $(ev.target).is('div.oe_menu_counter');
855         this.menu_click($(ev.currentTarget).data('menu'), needaction);
856     },
857 });
858
859 instance.web.UserMenu =  instance.web.Widget.extend({
860     template: "UserMenu",
861     init: function(parent) {
862         this._super(parent);
863         this.update_promise = $.Deferred().resolve();
864     },
865     start: function() {
866         var self = this;
867         this._super.apply(this, arguments);
868         this.$el.on('click', '.oe_dropdown_menu li a[data-menu]', function(ev) {
869             ev.preventDefault();
870             var f = self['on_menu_' + $(this).data('menu')];
871             if (f) {
872                 f($(this));
873             }
874         });
875     },
876     do_update: function () {
877         var self = this;
878         var fct = function() {
879             var $avatar = self.$el.find('.oe_topbar_avatar');
880             $avatar.attr('src', $avatar.data('default-src'));
881             if (!self.session.uid)
882                 return;
883             var func = new instance.web.Model("res.users").get_func("read");
884             return func(self.session.uid, ["name", "company_id"]).then(function(res) {
885                 var topbar_name = res.name;
886                 if(instance.session.debug)
887                     topbar_name = _.str.sprintf("%s (%s)", topbar_name, instance.session.db);
888                 if(res.company_id[0] > 1)
889                     topbar_name = _.str.sprintf("%s (%s)", topbar_name, res.company_id[1]);
890                 self.$el.find('.oe_topbar_name').text(topbar_name);
891                 var avatar_src = _.str.sprintf('%s/web/binary/image?session_id=%s&model=res.users&field=image_small&id=%s', self.session.prefix, self.session.session_id, self.session.uid);
892                 $avatar.attr('src', avatar_src);
893             });
894         };
895         this.update_promise = this.update_promise.then(fct, fct);
896     },
897     on_menu_logout: function() {
898         this.trigger('user_logout');
899     },
900     on_menu_settings: function() {
901         var self = this;
902         if (!this.getParent().has_uncommitted_changes()) {
903             self.rpc("/web/action/load", { action_id: "base.action_res_users_my" }, function(result) {
904                 result.res_id = instance.session.uid;
905                 self.getParent().action_manager.do_action(result);
906             });
907         }
908     },
909     on_menu_about: function() {
910         var self = this;
911         self.rpc("/web/webclient/version_info", {}).done(function(res) {
912             var $help = $(QWeb.render("UserMenu.about", {version_info: res}));
913             $help.find('a.oe_activate_debug_mode').click(function (e) {
914                 e.preventDefault();
915                 window.location = $.param.querystring( window.location.href, 'debug');
916             });
917             instance.web.dialog($help, {autoOpen: true,
918                 modal: true, width: 507, height: 290, resizable: false, title: _t("About")});
919         });
920     },
921 });
922
923 instance.web.Client = instance.web.Widget.extend({
924     init: function(parent, origin) {
925         instance.client = instance.webclient = this;
926         this._super(parent);
927         this.origin = origin;
928     },
929     start: function() {
930         var self = this;
931         return instance.session.session_bind(this.origin).then(function() {
932             var $e = $(QWeb.render(self._template, {}));
933             self.replaceElement($e);
934             self.bind_events();
935             return self.show_common();
936         });
937     },
938     bind_events: function() {
939         var self = this;
940         this.$el.on('mouseenter', '.oe_systray > div:not([data-tipsy=true])', function() {
941             $(this).attr('data-tipsy', 'true').tipsy().trigger('mouseenter');
942         });
943         this.$el.on('click', '.oe_dropdown_toggle', function(ev) {
944             ev.preventDefault();
945             var $toggle = $(this);
946             var $menu = $toggle.siblings('.oe_dropdown_menu');
947             $menu = $menu.size() >= 1 ? $menu : $toggle.find('.oe_dropdown_menu');
948             var state = $menu.is('.oe_opened');
949             setTimeout(function() {
950                 // Do not alter propagation
951                 $toggle.add($menu).toggleClass('oe_opened', !state);
952                 if (!state) {
953                     // Move $menu if outside window's edge
954                     var doc_width = $(document).width();
955                     var offset = $menu.offset();
956                     var menu_width = $menu.width();
957                     var x = doc_width - offset.left - menu_width - 2;
958                     if (x < 0) {
959                         $menu.offset({ left: offset.left + x }).width(menu_width);
960                     }
961                 }
962             }, 0);
963         });
964         instance.web.bus.on('click', this, function(ev) {
965             $.fn.tipsy.clear();
966             if (!$(ev.target).is('input[type=file]')) {
967                 self.$el.find('.oe_dropdown_menu.oe_opened, .oe_dropdown_toggle.oe_opened').removeClass('oe_opened');
968             }
969         });
970     },
971     show_common: function() {
972         var self = this;
973         this.crashmanager =  new instance.web.CrashManager();
974         instance.session.on('error', this.crashmanager, this.crashmanager.rpc_error);
975         self.notification = new instance.web.Notification(this);
976         self.notification.appendTo(self.$el);
977         self.loading = new instance.web.Loading(self);
978         self.loading.appendTo(self.$el);
979         self.action_manager = new instance.web.ActionManager(self);
980         self.action_manager.appendTo(self.$('.oe_application'));
981     },
982     toggle_bars: function(value) {
983         this.$('tr:has(td.oe_topbar),.oe_leftbar').toggle(value);
984     },
985     has_uncommitted_changes: function() {
986         return false;
987     },
988 });
989
990 instance.web.WebClient = instance.web.Client.extend({
991     _template: 'WebClient',
992     init: function(parent) {
993         this._super(parent);
994         this._current_state = null;
995     },
996     start: function() {
997         var self = this;
998         return $.when(this._super()).then(function() {
999             self.$el.on('click', '.oe_logo', function() {
1000                 self.action_manager.do_action('home');
1001             });
1002             if (jQuery.param !== undefined && jQuery.deparam(jQuery.param.querystring()).kitten !== undefined) {
1003                 $("body").addClass("kitten-mode-activated");
1004                 if ($.blockUI) {
1005                     $.blockUI.defaults.message = '<img src="http://www.amigrave.com/kitten.gif">';
1006                 }
1007             }
1008             if (!self.session.session_is_valid()) {
1009                 self.show_login();
1010             } else {
1011                 self.show_application();
1012             }
1013         });
1014     },
1015     set_title: function(title) {
1016         title = _.str.clean(title);
1017         var sep = _.isEmpty(title) ? '' : ' - ';
1018         document.title = title + sep + 'OpenERP';
1019     },
1020     show_common: function() {
1021         var self = this;
1022         this._super();
1023         window.onerror = function (message, file, line) {
1024             self.crashmanager.show_error({
1025                 type: _t("Client Error"),
1026                 message: message,
1027                 data: {debug: file + ':' + line}
1028             });
1029         };
1030     },
1031     show_login: function() {
1032         this.toggle_bars(false);
1033
1034         var state = $.bbq.getState(true);
1035         var action = {
1036             type: 'ir.actions.client',
1037             tag: 'login',
1038             _push_me: false,
1039         };
1040
1041         this.action_manager.do_action(action);
1042         this.action_manager.inner_widget.on('login_successful', this, function() {
1043             this.show_application();        // will load the state we just pushed
1044         });
1045     },
1046     show_application: function() {
1047         var self = this;
1048         self.toggle_bars(true);
1049         self.menu = new instance.web.Menu(self);
1050         self.menu.replace(this.$el.find('.oe_menu_placeholder'));
1051         self.menu.on('menu_click', this, this.on_menu_action);
1052         self.user_menu = new instance.web.UserMenu(self);
1053         self.user_menu.replace(this.$el.find('.oe_user_menu_placeholder'));
1054         self.user_menu.on('user_logout', self, self.on_logout);
1055         self.user_menu.do_update();
1056         self.bind_hashchange();
1057         self.set_title();
1058     },
1059     destroy_content: function() {
1060         _.each(_.clone(this.getChildren()), function(el) {
1061             el.destroy();
1062         });
1063         this.$el.children().remove();
1064     },
1065     do_reload: function() {
1066         var self = this;
1067         return this.session.session_reload().then(function () {
1068             instance.session.load_modules(true).then(
1069                 self.menu.proxy('do_reload')); });
1070
1071     },
1072     do_notify: function() {
1073         var n = this.notification;
1074         n.notify.apply(n, arguments);
1075     },
1076     do_warn: function() {
1077         var n = this.notification;
1078         n.warn.apply(n, arguments);
1079     },
1080     on_logout: function() {
1081         var self = this;
1082         if (!this.has_uncommitted_changes()) {
1083             this.session.session_logout().done(function () {
1084                 $(window).unbind('hashchange', self.on_hashchange);
1085                 self.do_push_state({});
1086                 window.location.reload();
1087             });
1088         }
1089     },
1090     bind_hashchange: function() {
1091         var self = this;
1092         $(window).bind('hashchange', this.on_hashchange);
1093
1094         var state = $.bbq.getState(true);
1095         if (_.isEmpty(state) || state.action == "login") {
1096             self.menu.has_been_loaded.done(function() {
1097                 var first_menu_id = self.menu.$el.find("a:first").data("menu");
1098                 if(first_menu_id) {
1099                     self.menu.menu_click(first_menu_id);
1100                 }
1101             });
1102         } else {
1103             $(window).trigger('hashchange');
1104         }
1105     },
1106     on_hashchange: function(event) {
1107         var self = this;
1108         var state = event.getState(true);
1109         if (!_.isEqual(this._current_state, state)) {
1110             if(state.action_id === undefined && state.menu_id) {
1111                 self.menu.has_been_loaded.done(function() {
1112                     self.menu.do_reload().done(function() {
1113                         self.menu.menu_click(state.menu_id)
1114                     });
1115                 });
1116             } else {
1117                 state._push_me = false;  // no need to push state back...
1118                 this.action_manager.do_load_state(state, !!this._current_state);
1119             }
1120         }
1121         this._current_state = state;
1122     },
1123     do_push_state: function(state) {
1124         this.set_title(state.title);
1125         delete state.title;
1126         var url = '#' + $.param(state);
1127         this._current_state = _.clone(state);
1128         $.bbq.pushState(url);
1129         this.trigger('state_pushed', state);
1130     },
1131     on_menu_action: function(options) {
1132         var self = this;
1133         return this.rpc("/web/action/load", { action_id: options.action_id })
1134             .then(function (result) {
1135                 var action = result;
1136                 if (options.needaction) {
1137                     action.context.search_default_message_unread = true;
1138                 }
1139                 return $.when(self.action_manager.do_action(action, {
1140                     clear_breadcrumbs: true,
1141                     action_menu_id: self.menu.current_menu,
1142                 })).fail(function() {
1143                     self.menu.open_menu(options.previous_menu_id);
1144                 });
1145             });
1146     },
1147     set_content_full_screen: function(fullscreen) {
1148         if (fullscreen) {
1149             $(".oe_webclient", this.$el).addClass("oe_content_full_screen");
1150             $("body").css({'overflow-y':'hidden'});
1151         } else {
1152             $(".oe_webclient", this.$el).removeClass("oe_content_full_screen");
1153             $("body").css({'overflow-y':'scroll'});
1154         }
1155     },
1156     has_uncommitted_changes: function() {
1157         var $e = $.Event('clear_uncommitted_changes');
1158         instance.web.bus.trigger('clear_uncommitted_changes', $e);
1159         if ($e.isDefaultPrevented()) {
1160             return true;
1161         } else {
1162             return this._super.apply(this, arguments);
1163         }
1164     },
1165 });
1166
1167 instance.web.EmbeddedClient = instance.web.Client.extend({
1168     _template: 'EmbedClient',
1169     init: function(parent, origin, dbname, login, key, action_id, options) {
1170         this._super(parent, origin);
1171
1172         this.dbname = dbname;
1173         this.login = login;
1174         this.key = key;
1175         this.action_id = action_id;
1176         this.options = options || {};
1177     },
1178     start: function() {
1179         var self = this;
1180         return $.when(this._super()).then(function() {
1181             return instance.session.session_authenticate(self.dbname, self.login, self.key, true).then(function() {
1182                 return self.rpc("/web/action/load", { action_id: self.action_id }).done(function(result) {
1183                     var action = result;
1184                     action.flags = _.extend({
1185                         //views_switcher : false,
1186                         search_view : false,
1187                         action_buttons : false,
1188                         sidebar : false
1189                         //pager : false
1190                     }, self.options, action.flags || {});
1191
1192                     self.action_manager.do_action(action);
1193                 });
1194             });
1195         });
1196     },
1197 });
1198
1199 instance.web.embed = function (origin, dbname, login, key, action, options) {
1200     $('head').append($('<link>', {
1201         'rel': 'stylesheet',
1202         'type': 'text/css',
1203         'href': origin +'/web/webclient/css'
1204     }));
1205     var currentScript = document.currentScript;
1206     if (!currentScript) {
1207         var sc = document.getElementsByTagName('script');
1208         currentScript = sc[sc.length-1];
1209     }
1210     var client = new instance.web.EmbeddedClient(null, origin, dbname, login, key, action, options);
1211     client.insertAfter(currentScript);
1212 };
1213
1214 };
1215
1216 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: