[IMP] Major improvement to kitten mode
[odoo/odoo.git] / addons / web / static / src / js / chrome.js
index 8978561..76a6b56 100644 (file)
@@ -1,18 +1,16 @@
 /*---------------------------------------------------------
  * OpenERP Web chrome
  *---------------------------------------------------------*/
-openerp.web.chrome = function(openerp) {
-var QWeb = openerp.web.qweb,
-    _t = openerp.web._t;
+openerp.web.chrome = function(instance) {
+var QWeb = instance.web.qweb,
+    _t = instance.web._t;
 
-openerp.web.Notification =  openerp.web.OldWidget.extend(/** @lends openerp.web.Notification# */{
+instance.web.Notification =  instance.web.Widget.extend({
     template: 'Notification',
-
     init: function() {
         this._super.apply(this, arguments);
-        openerp.notification = this;
+        instance.web.notification = this;
     },
-
     start: function() {
         this._super.apply(this, arguments);
         this.$element.notify({
@@ -42,18 +40,20 @@ openerp.web.Notification =  openerp.web.OldWidget.extend(/** @lends openerp.web.
             text: text
         }, opts);
     }
-
 });
 
-openerp.web.Dialog = openerp.web.OldWidget.extend(/** @lends openerp.web.Dialog# */{
+/**
+ * The very minimal function everything should call to create a dialog
+ * in OpenERP Web Client.
+ */
+instance.web.dialog = function(element) {
+    var result = element.dialog.apply(element, _.rest(_.toArray(arguments)));
+    result.dialog("widget").addClass("openerp");
+    return result;
+};
+
+instance.web.Dialog = instance.web.Widget.extend({
     dialog_title: "",
-    /**
-     * @constructs openerp.web.Dialog
-     * @extends openerp.web.OldWidget
-     *
-     * @param parent
-     * @param options
-     */
     init: function (parent, options, content) {
         var self = this;
         this._super(parent);
@@ -77,7 +77,7 @@ openerp.web.Dialog = openerp.web.OldWidget.extend(/** @lends openerp.web.Dialog#
         };
         for (var f in this) {
             if (f.substr(0, 10) == 'on_button_') {
-                this.dialog_options.buttons[_t(f.substr(10))] = this[f];
+                this.dialog_options.buttons[f.substr(10)] = this[f];
             }
         }
         if (options) {
@@ -86,7 +86,7 @@ openerp.web.Dialog = openerp.web.OldWidget.extend(/** @lends openerp.web.Dialog#
         if (this.dialog_options.autoOpen) {
             this.open();
         } else {
-            this.$element.dialog(this.get_options());
+            instance.web.dialog(this.$element, this.get_options());
         }
     },
     get_options: function(options) {
@@ -122,10 +122,10 @@ openerp.web.Dialog = openerp.web.OldWidget.extend(/** @lends openerp.web.Dialog#
     open: function(options) {
         // TODO fme: bind window on resize
         if (this.template) {
-            this.$element.html(this.render());
+            this.$element.html(this.renderElement());
         }
         var o = this.get_options(options);
-        this.$element.dialog(o).dialog('open');
+        instance.web.dialog(this.$element, o).dialog('open');
         if (o.height === 'auto' && o.max_height) {
             this.$element.css({ 'max-height': o.max_height, 'overflow-y': 'auto' });
         }
@@ -140,17 +140,15 @@ openerp.web.Dialog = openerp.web.OldWidget.extend(/** @lends openerp.web.Dialog#
         }
     },
     on_resized: function() {
-        //openerp.log("Dialog resized to %d x %d", this.$element.width(), this.$element.height());
     },
-    stop: function () {
-        // Destroy widget
+    destroy: function () {
         this.close();
         this.$element.dialog('destroy');
         this._super();
     }
 });
 
-openerp.web.CrashManager = openerp.web.CallbackEnabled.extend({
+instance.web.CrashManager = instance.web.CallbackEnabled.extend({
     on_rpc_error: function(error) {
         if (error.data.fault_code) {
             var split = ("" + error.data.fault_code).split('\n')[0].split(' -- ');
@@ -166,7 +164,7 @@ openerp.web.CrashManager = openerp.web.CallbackEnabled.extend({
         }
     },
     on_managed_error: function(error) {
-        $('<div>' + QWeb.render('CrashManagerWarning', {error: error}) + '</div>').dialog({
+        instance.web.dialog($('<div>' + QWeb.render('CrashManager.warning', {error: error}) + '</div>'), {
             title: "OpenERP " + _.str.capitalize(error.type),
             buttons: [
                 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
@@ -176,16 +174,16 @@ openerp.web.CrashManager = openerp.web.CallbackEnabled.extend({
     on_traceback: function(error) {
         var self = this;
         var buttons = {};
-        if (openerp.connection.openerp_entreprise) {
+        if (instance.connection.openerp_entreprise) {
             buttons[_t("Send OpenERP Enterprise Report")] = function() {
                 var $this = $(this);
                 var issuename = $('#issuename').val();
                 var explanation = $('#explanation').val();
                 var remark = $('#remark').val();
                 // Call the send method from server to send mail with details
-                new openerp.web.DataSet(self, 'publisher_warranty.contract').call_and_eval('send', [error.data,explanation,remark,issuename]).then(function(result){
+                new instance.web.DataSet(self, 'publisher_warranty.contract').call_and_eval('send', [error.data,explanation,remark,issuename]).then(function(result){
                     if (result === false) {
-                        alert('There was a communication error.')
+                        alert('There was a communication error.');
                     } else {
                         $this.dialog('close');
                     }
@@ -199,7 +197,7 @@ openerp.web.CrashManager = openerp.web.CallbackEnabled.extend({
                 $(this).dialog("close");
             };
         }
-        var dialog = new openerp.web.Dialog(this, {
+        var dialog = new instance.web.Dialog(this, {
             title: "OpenERP " + _.str.capitalize(error.type),
             width: '80%',
             height: '50%',
@@ -207,19 +205,19 @@ openerp.web.CrashManager = openerp.web.CallbackEnabled.extend({
             min_height: '600px',
             buttons: buttons
         }).open();
-        dialog.$element.html(QWeb.render('CrashManagerError', {session: openerp.connection, error: error}));
-    }
+        dialog.$element.html(QWeb.render('CrashManager.error', {session: instance.connection, error: error}));
+    },
+    on_javascript_exception: function(exception) {
+       this.on_traceback({
+           type: _t("Client Error"),
+           message: exception,
+           data: {debug: ""}
+       });
+    },
 });
 
-openerp.web.Loading = openerp.web.OldWidget.extend(/** @lends openerp.web.Loading# */{
+instance.web.Loading = instance.web.Widget.extend({
     template: 'Loading',
-    /**
-     * @constructs openerp.web.Loading
-     * @extends openerp.web.OldWidget
-     *
-     * @param parent
-     * @param element_id
-     */
     init: function(parent) {
         this._super(parent);
         this.count = 0;
@@ -234,7 +232,7 @@ openerp.web.Loading = openerp.web.OldWidget.extend(/** @lends openerp.web.Loadin
         this.session.on_rpc_request.add_first(this.request_call);
         this.session.on_rpc_response.add_last(this.response_call);
     },
-    stop: function() {
+    destroy: function() {
         this.session.on_rpc_request.remove(this.request_call);
         this.session.on_rpc_response.remove(this.response_call);
         this.on_rpc_event(-this.count);
@@ -252,10 +250,9 @@ openerp.web.Loading = openerp.web.OldWidget.extend(/** @lends openerp.web.Loadin
 
         this.count += increment;
         if (this.count > 0) {
-            $(".loading",this.$element).text(_.str.sprintf(
-                _t("Loading (%d)"), this.count));
-            $(".loading",this.$element).show();
-            this.widget_parent.$element.addClass('loading');
+            this.$element.text(_.str.sprintf( _t("Loading (%d)"), this.count));
+            this.$element.show();
+            this.getParent().$element.addClass('oe_wait');
         } else {
             this.count = 0;
             clearTimeout(this.long_running_timer);
@@ -264,73 +261,64 @@ openerp.web.Loading = openerp.web.OldWidget.extend(/** @lends openerp.web.Loadin
                 this.blocked_ui = false;
                 $.unblockUI();
             }
-            $(".loading",this.$element).fadeOut();
-            this.widget_parent.$element.removeClass('loading');
+            this.$element.fadeOut();
+            this.getParent().$element.removeClass('oe_wait');
         }
     }
 });
 
-openerp.web.Database = openerp.web.OldWidget.extend(/** @lends openerp.web.Database# */{
-    template: "DatabaseManager",
-    /**
-     * @constructs openerp.web.Database
-     * @extends openerp.web.OldWidget
-     *
-     * @param parent
-     * @param element_id
-     * @param option_id
-     */
-    init: function(parent, element_id, option_id) {
-        this._super(parent, element_id);
+instance.web.DatabaseManager = instance.web.Widget.extend({
+    init: function(parent) {
+        this._super(parent);
         this.unblockUIFunction = $.unblockUI;
         $.validator.addMethod('matches', function (s, _, re) {
             return new RegExp(re).test(s);
         }, _t("Invalid database name"));
     },
     start: function() {
-        this.$option_id = $("#oe_db_options");
-
         var self = this;
         var fetch_db = this.rpc("/web/database/get_list", {}).pipe(
-            function(result) { self.db_list = result.db_list; },
-            function (_, ev) { ev.preventDefault(); self.db_list = null; });
-        var fetch_langs = this.rpc("/web/session/get_lang_list", {}, function(result) {
-            if (result.error) {
-                self.display_error(result);
-                return;
-            }
+            function(result) {
+                self.db_list = result.db_list;
+            },
+            function (_, ev) {
+                ev.preventDefault();
+                self.db_list = null;
+            });
+        var fetch_langs = this.rpc("/web/session/get_lang_list", {}).then(function(result) {
             self.lang_list = result.lang_list;
         });
-        $.when(fetch_db, fetch_langs).then(function () {self.do_create();});
-
-        this.$element.find('#db-create').click(this.do_create);
-        this.$element.find('#db-drop').click(this.do_drop);
-        this.$element.find('#db-backup').click(this.do_backup);
-        this.$element.find('#db-restore').click(this.do_restore);
-        this.$element.find('#db-change-password').click(this.do_change_password);
-               this.$element.find('#back-to-login').click(function() {
-            self.hide();
+        return $.when(fetch_db, fetch_langs).then(self.do_render);
+    },
+    do_render: function() {
+        var self = this;
+        self.$element.html(QWeb.render("DatabaseManager", { widget : self }));
+        self.$element.find(".oe_database_manager_menu").tabs({
+            show: function(event, ui) {
+                $('*[autofocus]:first', ui.panel).focus();
+            }
+        });
+        self.$element.find("form[name=create_db_form]").validate({ submitHandler: self.do_create });
+        self.$element.find("form[name=drop_db_form]").validate({ submitHandler: self.do_drop });
+        self.$element.find("form[name=backup_db_form]").validate({ submitHandler: self.do_backup });
+        self.$element.find("form[name=restore_db_form]").validate({ submitHandler: self.do_restore });
+        self.$element.find("form[name=change_pwd_form]").validate({
+            messages: {
+                old_pwd: "Please enter your previous password",
+                new_pwd: "Please enter your new password",
+                confirm_pwd: {
+                    required: "Please confirm your new password",
+                    equalTo: "The confirmation does not match the password"
+                }
+            },
+            submitHandler: self.do_change_password
         });
+        self.$element.find("#back_to_login").click(self.do_exit);
     },
-    stop: function () {
-        this.hide();
-        this.$option_id.empty();
-
-        this.$element
-            .find('#db-create, #db-drop, #db-backup, #db-restore, #db-change-password, #back-to-login')
-                .unbind('click')
-            .end()
-            .empty();
+    destroy: function () {
+        this.$element.find('#db-create, #db-drop, #db-backup, #db-restore, #db-change-password, #back-to-login').unbind('click').end().empty();
         this._super();
     },
-    show: function () {
-        this.$element.closest(".login")
-                .addClass("database_block");
-    },
-    hide: function () {
-        this.$element.closest(".login")
-                .removeClass("database_block")
-    },
     /**
      * Converts a .serializeArray() result into a dict. Does not bother folding
      * multiple identical keys into an array, last key wins.
@@ -369,7 +357,7 @@ openerp.web.Database = openerp.web.OldWidget.extend(/** @lends openerp.web.Datab
      * @param {String} error.error message of the error dialog
      */
     display_error: function (error) {
-        return $('<div>').dialog({
+        return instance.web.dialog($('<div>'), {
             modal: true,
             title: error.title,
             buttons: [
@@ -377,156 +365,97 @@ openerp.web.Database = openerp.web.OldWidget.extend(/** @lends openerp.web.Datab
             ]
         }).html(error.error);
     },
-    do_create: function() {
+    do_create: function(form) {
         var self = this;
-               self.$option_id.html(QWeb.render("Database.CreateDB", self));
-        self.$option_id.find("form[name=create_db_form]").validate({
-            submitHandler: function (form) {
-                var fields = $(form).serializeArray();
-                self.rpc("/web/database/create", {'fields': fields}, function(result) {
-                    if (self.db_list) {
-                        self.db_list.push(self.to_object(fields)['db_name']);
-                        self.db_list.sort();
-                        self.widget_parent.set_db_list(self.db_list);
-                    }
-
-                    var form_obj = self.to_object(fields);
-                    self.widget_parent.do_login(
-                            form_obj['db_name'],
-                            'admin',
-                            form_obj['create_admin_pwd']);
-                    self.stop();
-                });
-            }
+        var fields = $(form).serializeArray();
+        self.rpc("/web/database/create", {'fields': fields}, function(result) {
+            var form_obj = self.to_object(fields);
+            self.getParent().do_login( form_obj['db_name'], 'admin', form_obj['create_admin_pwd']);
+            self.destroy();
         });
+
     },
-    do_drop: function() {
+    do_drop: function(form) {
         var self = this;
-               self.$option_id.html(QWeb.render("DropDB", self));
-               self.$option_id.find("form[name=drop_db_form]").validate({
-            submitHandler: function (form) {
-                var $form = $(form),
-                    fields = $form.serializeArray(),
-                    $db_list = $form.find('[name=drop_db]'),
-                    db = $db_list.val();
-
-                if (!db || !confirm("Do you really want to delete the database: " + db + " ?")) {
-                    return;
-                }
-                self.rpc("/web/database/drop", {'fields': fields}, function(result) {
-                    if (result.error) {
-                        self.display_error(result);
-                        return;
-                    }
-                    $db_list.find(':selected').remove();
-                    if (self.db_list) {
-                        self.db_list.splice(_.indexOf(self.db_list, db, true), 1);
-                        self.widget_parent.set_db_list(self.db_list);
-                    }
-                    self.do_notify("Dropping database", "The database '" + db + "' has been dropped");
-                });
+        var $form = $(form),
+            fields = $form.serializeArray(),
+            $db_list = $form.find('[name=drop_db]'),
+            db = $db_list.val();
+        if (!db || !confirm("Do you really want to delete the database: " + db + " ?")) {
+            return;
+        }
+        self.rpc("/web/database/drop", {'fields': fields}, function(result) {
+            if (result.error) {
+                self.display_error(result);
+                return;
             }
+            self.do_notify("Dropping database", "The database '" + db + "' has been dropped");
+            self.start();
         });
     },
-    do_backup: function() {
+    do_backup: function(form) {
         var self = this;
-               self.$option_id
-            .html(QWeb.render("BackupDB", self))
-            .find("form[name=backup_db_form]").validate({
-            submitHandler: function (form) {
-                self.blockUI();
-                self.session.get_file({
-                    form: form,
-                    success: function () {
-                        self.do_notify(_t("Backed"),
-                            _t("Database backed up successfully"));
-                    },
-                    error: openerp.webclient.crashmanager.on_rpc_error,
-                    complete: function() {
-                        self.unblockUI();
-                    }
-                });
+        self.blockUI();
+        self.session.get_file({
+            form: form,
+            success: function () {
+                self.do_notify(_t("Backed"), _t("Database backed up successfully"));
+            },
+            error: instance.webclient.crashmanager.on_rpc_error,
+            complete: function() {
+                self.unblockUI();
             }
         });
     },
-    do_restore: function() {
+    do_restore: function(form) {
         var self = this;
-               self.$option_id.html(QWeb.render("RestoreDB", self));
+        self.blockUI();
+        $(form).ajaxSubmit({
+            url: '/web/database/restore',
+            type: 'POST',
+            resetForm: true,
+            success: function (body) {
+                // If empty body, everything went fine
+                if (!body) { return; }
 
-               self.$option_id.find("form[name=restore_db_form]").validate({
-            submitHandler: function (form) {
-                self.blockUI();
-                $(form).ajaxSubmit({
-                    url: '/web/database/restore',
-                    type: 'POST',
-                    resetForm: true,
-                    success: function (body) {
-                        // TODO: ui manipulations
-                        // note: response objects don't work, but we have the
-                        // HTTP body of the response~~
-
-                        // If empty body, everything went fine
-                        if (!body) { return; }
-
-                        if (body.indexOf('403 Forbidden') !== -1) {
-                            self.display_error({
-                                title: 'Access Denied',
-                                error: 'Incorrect super-administrator password'
-                            })
-                        } else {
-                            self.display_error({
-                                title: 'Restore Database',
-                                error: 'Could not restore the database'
-                            })
-                        }
-                    },
-                    complete: function() {
-                        self.unblockUI();
-                        self.do_notify(_t("Restored"), _t("Database restored successfully"));
-                    }
-                });
+                if (body.indexOf('403 Forbidden') !== -1) {
+                    self.display_error({
+                        title: 'Access Denied',
+                        error: 'Incorrect super-administrator password'
+                    });
+                } else {
+                    self.display_error({
+                        title: 'Restore Database',
+                        error: 'Could not restore the database'
+                    });
+                }
+            },
+            complete: function() {
+                self.unblockUI();
+                self.do_notify(_t("Restored"), _t("Database restored successfully"));
             }
         });
     },
-    do_change_password: function() {
+    do_change_password: function(form) {
         var self = this;
-               self.$option_id.html(QWeb.render("Change_DB_Pwd", self));
-
-        self.$option_id.find("form[name=change_pwd_form]").validate({
-            messages: {
-                old_pwd: "Please enter your previous password",
-                new_pwd: "Please enter your new password",
-                confirm_pwd: {
-                    required: "Please confirm your new password",
-                    equalTo: "The confirmation does not match the password"
-                }
-            },
-            submitHandler: function (form) {
-                self.rpc("/web/database/change_password", {
-                    'fields': $(form).serializeArray()
-                }, function(result) {
-                    if (result.error) {
-                        self.display_error(result);
-                        return;
-                    }
-                    self.do_notify("Changed Password", "Password has been changed successfully");
-                });
+        self.rpc("/web/database/change_password", {
+            'fields': $(form).serializeArray()
+        }, function(result) {
+            if (result.error) {
+                self.display_error(result);
+                return;
             }
+            self.do_notify("Changed Password", "Password has been changed successfully");
         });
+    },
+    do_exit: function () {
     }
 });
 
-openerp.web.Login =  openerp.web.OldWidget.extend(/** @lends openerp.web.Login# */{
-    remember_credentials: true,
-    
+instance.web.Login =  instance.web.Widget.extend({
     template: "Login",
-    /**
-     * @constructs openerp.web.Login
-     * @extends openerp.web.OldWidget
-     *
-     * @param parent
-     * @param element_id
-     */
+    remember_credentials: true,
+    _db_list: null,
 
     init: function(parent) {
         this._super(parent);
@@ -537,36 +466,52 @@ openerp.web.Login =  openerp.web.OldWidget.extend(/** @lends openerp.web.Login#
         if (this.has_local_storage && this.remember_credentials) {
             this.selected_db = localStorage.getItem('last_db_login_success');
             this.selected_login = localStorage.getItem('last_login_login_success');
-            if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
+            if (jQuery.deparam(jQuery.param.querystring()).debug !== undefined) {
                 this.selected_password = localStorage.getItem('last_password_login_success');
             }
         }
     },
     start: function() {
         var self = this;
-        this.database = new openerp.web.Database(this);
-        this.database.appendTo(this.$element);
 
-        this.$element.find('#oe-db-config').click(function() {
-            self.database.show();
-        });
-
-        this.$element.find("form").submit(this.on_submit);
+        self.$element.find("form").submit(self.on_submit);
 
-        this.rpc("/web/database/get_list", {}, function(result) {
-            self.set_db_list(result.db_list);
-        }, 
-        function(error, event) {
-            if (error.data.fault_code === 'AccessDenied') {
-                event.preventDefault();
-            }
+        self.$element.find('.oe_login_manage_db').click(function() {
+            self.$element.find('.oe_login_bottom').hide();
+            self.$element.find('.oe_login_pane').hide();
+            self.databasemanager = new instance.web.DatabaseManager(self);
+            self.databasemanager.appendTo(self.$element);
+            self.databasemanager.do_exit.add_last(function() {
+                self.databasemanager.destroy();
+                self.$element.find('.oe_login_bottom').show();
+                self.$element.find('.oe_login_pane').show();
+                self.load_db_list(true).then(self.proxy('_db_list_loaded'));
+            });
         });
-
-    },
-    set_db_list: function (list) {
-        this.$element.find("[name=db]").replaceWith(
-            openerp.web.qweb.render('Login_dblist', {
-                db_list: list, selected_db: this.selected_db}))
+        return self.load_db_list().then(self.proxy('_db_list_loaded'));
+    },
+    load_db_list: function (force) {
+        var d = $.when(), self = this;
+        if (_.isNull(this._db_list) || force) {
+            d = self.rpc("/web/database/get_list", {}, function(result) {
+                self._db_list = _.clone(result.db_list);
+            }, function(error, event) {
+                if (error.data.fault_code === 'AccessDenied') {
+                    event.preventDefault();
+                }
+            });
+        }
+        return d;
+    },
+    _db_list_loaded: function () {
+        var list = this._db_list,
+            dbdiv = this.$element.find('div.oe_login_dbpane');
+        this.$element.find("[name=db]").replaceWith(instance.web.qweb.render('Login.dblist', { db_list: list, selected_db: this.selected_db}));
+        if(list && list.length === 1) {
+            dbdiv.hide();
+        } else {
+            dbdiv.show();
+        }
     },
     on_submit: function(ev) {
         if(ev) {
@@ -592,20 +537,13 @@ openerp.web.Login =  openerp.web.OldWidget.extend(/** @lends openerp.web.Login#
      */
     do_login: function (db, login, password) {
         var self = this;
-        this.$element.removeClass('login_invalid');
-        this.session.on_session_invalid.add({
-            callback: function () {
-                self.$element.addClass("login_invalid");
-            },
-            unique: true
-        });
-        this.session.session_authenticate(db, login, password).then(function() {
-            self.$element.removeClass("login_invalid");
+        this.$element.removeClass('oe_login_invalid');
+        return this.session.session_authenticate(db, login, password).pipe(function() {
             if (self.has_local_storage) {
                 if(self.remember_credentials) {
                     localStorage.setItem('last_db_login_success', db);
                     localStorage.setItem('last_login_login_success', login);
-                    if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
+                    if (jQuery.deparam(jQuery.param.querystring()).debug !== undefined) {
                         localStorage.setItem('last_password_login_success', password);
                     }
                 } else {
@@ -614,121 +552,239 @@ openerp.web.Login =  openerp.web.OldWidget.extend(/** @lends openerp.web.Login#
                     localStorage.setItem('last_password_login_success', '');
                 }
             }
+            self.$(".oe_login_pane").fadeOut("slow");
+            self.trigger("login");
+        },function () {
+            self.$element.addClass("oe_login_invalid");
         });
     }
 });
 
-openerp.web.Header =  openerp.web.OldWidget.extend(/** @lends openerp.web.Header# */{
-    template: "Header",
+instance.web.Menu =  instance.web.Widget.extend({
+    template: 'Menu',
+    init: function() {
+        this._super.apply(this, arguments);
+        this.has_been_loaded = $.Deferred();
+        this.maximum_visible_links = 'auto'; // # of menu to show. 0 = do not crop, 'auto' = algo
+        this.data = {data:{children:[]}};
+    },
+    start: function() {
+        this._super.apply(this, arguments);
+        this.$secondary_menus = this.getParent().$element.find('.oe_secondary_menus_container');
+        return this.do_reload();
+    },
+    do_reload: function() {
+        return this.rpc("/web/menu/load", {}).then(this.on_loaded);
+    },
+    on_loaded: function(data) {
+        var self = this;
+        this.data = data;
+        this.renderElement();
+        this.limit_entries();
+        this.$secondary_menus.html(QWeb.render("Menu.secondary", { widget : this }));
+        this.$element.on('click', 'a[data-menu]', this.on_menu_click);
+        this.$secondary_menus.on('click', 'a[data-menu]', this.on_menu_click);
+        // Hide second level submenus
+        this.$secondary_menus.find('.oe_menu_toggler').siblings('.oe_secondary_submenu').hide();
+        if (self.current_menu) {
+            self.open_menu(self.current_menu);
+        }
+        this.has_been_loaded.resolve();
+    },
+    limit_entries: function() {
+        var maximum_visible_links = this.maximum_visible_links;
+        if (maximum_visible_links === 'auto') {
+            maximum_visible_links = this.auto_limit_entries();
+        }
+        if (maximum_visible_links < this.data.data.children.length) {
+            var $more = $(QWeb.render('Menu.more')),
+                $index = this.$element.find('li').eq(maximum_visible_links - 1);
+            $index.after($more);
+            $more.find('.oe_menu_more').append($index.next().nextAll());
+        }
+    },
+    auto_limit_entries: function() {
+        // TODO: auto detect overflow and bind window on resize
+        var width = $(window).width();
+        return Math.floor(width / 125);
+    },
     /**
-     * @constructs openerp.web.Header
-     * @extends openerp.web.OldWidget
+     * Opens a given menu by id, as if a user had browsed to that menu by hand
+     * except does not trigger any event on the way
      *
-     * @param parent
+     * @param {Number} id database id of the terminal menu to select
      */
+    open_menu: function (id) {
+        var $clicked_menu, $sub_menu, $main_menu;
+        $clicked_menu = this.$element.add(this.$secondary_menus).find('a[data-menu=' + id + ']');
+        this.trigger('open_menu', id, $clicked_menu);
+
+        if (this.$secondary_menus.has($clicked_menu).length) {
+            $sub_menu = $clicked_menu.parents('.oe_secondary_menu');
+            $main_menu = this.$element.find('a[data-menu=' + $sub_menu.data('menu-parent') + ']');
+        } else {
+            $sub_menu = this.$secondary_menus.find('.oe_secondary_menu[data-menu-parent=' + $clicked_menu.attr('data-menu') + ']');
+            $main_menu = $clicked_menu;
+        }
+
+        // Activate current main menu
+        this.$element.find('.oe_active').removeClass('oe_active');
+        $main_menu.addClass('oe_active');
+
+        // Show current sub menu
+        this.$secondary_menus.find('.oe_secondary_menu').hide();
+        $sub_menu.show();
+
+        // Hide/Show the leftbar menu depending of the presence of sub-items
+        this.$secondary_menus.parent('.oe_leftbar').toggle(!!$sub_menu.children().length);
+
+        // Activate current menu item and show parents
+        this.$secondary_menus.find('.oe_active').removeClass('oe_active');
+        if ($main_menu !== $clicked_menu) {
+            $clicked_menu.parents().show();
+            if ($clicked_menu.is('.oe_menu_toggler')) {
+                $clicked_menu.toggleClass('oe_menu_opened').siblings('.oe_secondary_submenu:first').toggle();
+            } else {
+                $clicked_menu.parent().addClass('oe_active');
+            }
+        }
+    },
+    /**
+     * Call open_menu with the first menu_item matching an action_id
+     *
+     * @param {Number} id the action_id to match
+     */
+    open_action: function (id) {
+        var $menu = this.$element.add(this.$secondary_menus).find('a[data-action-id=' + id + ']');
+        var menu_id = $menu.data('menu');
+        if (menu_id) {
+            this.open_menu(menu_id);
+        }
+    },
+    /**
+     * Process a click on a menu item
+     *
+     * @param {Number} id the menu_id
+     */
+    menu_click: function(id) {
+        if (id) {
+            // find back the menuitem in dom to get the action
+            var $item = this.$element.find('a[data-menu=' + id + ']');
+            if (!$item.length) {
+                $item = this.$secondary_menus.find('a[data-menu=' + id + ']');
+            }
+            var action_id = $item.data('action-id');
+            // If first level menu doesnt have action trigger first leaf
+            if (!action_id) {
+                if(this.$element.has($item).length) {
+                    $sub_menu = this.$secondary_menus.find('.oe_secondary_menu[data-menu-parent=' + id + ']');
+                    $items = $sub_menu.find('a[data-action-id]').filter('[data-action-id!=""]');
+                    if($items.length) {
+                        action_id = $items.data('action-id');
+                        id = $items.data('menu');
+                    }
+                }
+            }
+            this.open_menu(id);
+            this.current_menu = id;
+            this.session.active_id = id;
+            if (action_id) {
+                this.trigger('menu_click', action_id, id, $item);
+            }
+        }
+    },
+    /**
+     * Jquery event handler for menu click
+     *
+     * @param {Event} ev the jquery event
+     */
+    on_menu_click: function(ev) {
+        ev.preventDefault();
+        this.menu_click($(ev.currentTarget).data('menu'));
+    },
+});
+
+instance.web.UserMenu =  instance.web.Widget.extend({
+    template: "UserMenu",
     init: function(parent) {
         this._super(parent);
-        this.qs = "?" + jQuery.param.querystring();
-        this.$content = $();
         this.update_promise = $.Deferred().resolve();
     },
     start: function() {
-        this._super();
+        var self = this;
+        this._super.apply(this, arguments);
+        this.$element.on('click', '.oe_dropdown_menu li a[data-menu]', function(ev) {
+            ev.preventDefault();
+            var f = self['on_menu_' + $(this).data('menu')];
+            if (f) {
+                f($(this));
+            }
+        });
+    },
+    change_password :function() {
+        var self = this;
+        this.dialog = new instance.web.Dialog(this, {
+            title: _t("Change Password"),
+            width : 'auto'
+        }).open();
+        this.dialog.$element.html(QWeb.render("UserMenu.password", self));
+        this.dialog.$element.find("form[name=change_password_form]").validate({
+            submitHandler: function (form) {
+                self.rpc("/web/session/change_password",{
+                    'fields': $(form).serializeArray()
+                }, function(result) {
+                    if (result.error) {
+                        self.display_error(result);
+                        return;
+                    } else {
+                        instance.webclient.on_logout();
+                    }
+                });
+            }
+        });
+    },
+    display_error: function (error) {
+        return instance.web.dialog($('<div>'), {
+            modal: true,
+            title: error.title,
+            buttons: [
+                {text: _("Ok"), click: function() { $(this).dialog("close"); }}
+            ]
+        }).html(error.error);
     },
     do_update: function () {
         var self = this;
         var fct = function() {
-            self.$content.remove();
+            var $avatar = self.$element.find('.oe_topbar_avatar');
+            $avatar.attr('src', $avatar.data('default-src'));
             if (!self.session.uid)
                 return;
-            var func = new openerp.web.Model("res.users").get_func("read");
+            var func = new instance.web.Model("res.users").get_func("read");
             return func(self.session.uid, ["name", "company_id"]).pipe(function(res) {
-                self.$content = $(QWeb.render("Header-content", {widget: self, user: res}));
-                self.$content.appendTo(self.$element);
-                self.$element.find(".logout").click(self.on_logout);
-                self.$element.find("a.preferences").click(self.on_preferences);
-                self.$element.find(".about").click(self.on_about);
-                return self.shortcut_load();
+                var topbar_name = res.name;
+                if(instance.connection.debug)
+                    topbar_name = _.str.sprintf("%s (%s)", topbar_name, instance.connection.db);
+                if(res.company_id[0] > 1)
+                    topbar_name = _.str.sprintf("%s (%s)", topbar_name, res.company_id[1]);
+                self.$element.find('.oe_topbar_name').text(topbar_name);
+                var avatar_src = _.str.sprintf('%s/web/binary/image?session_id=%s&model=res.users&field=avatar&id=%s', self.session.prefix, self.session.session_id, self.session.uid);
+                $avatar.attr('src', avatar_src);
             });
         };
         this.update_promise = this.update_promise.pipe(fct, fct);
     },
-    on_about: function() {
-        var self = this;
-        self.rpc("/web/webclient/version_info", {}).then(function(res) {
-            var $help = $(QWeb.render("About-Page", {version_info: res}));
-            $help.find('a.oe_activate_debug_mode').click(function (e) {
-                e.preventDefault();
-                window.location = $.param.querystring(
-                        window.location.href, 'debug');
-            });
-            $help.dialog({autoOpen: true,
-                modal: true, width: 960, title: _t("About")});
-        });
-    },
-    shortcut_load :function(){
-        var self = this,
-            sc = self.session.shortcuts,
-            shortcuts_ds = new openerp.web.DataSet(this, 'ir.ui.view_sc');
-        // TODO: better way to communicate between sections.
-        // sc.bindings, because jquery does not bind/trigger on arrays...
-        if (!sc.binding) {
-            sc.binding = {};
-            $(sc.binding).bind({
-                'add': function (e, attrs) {
-                    shortcuts_ds.create(attrs, function (out) {
-                        $('<li>', {
-                            'data-shortcut-id':out.result,
-                            'data-id': attrs.res_id
-                        }).text(attrs.name)
-                          .appendTo(self.$element.find('.oe-shortcuts ul'));
-                        attrs.id = out.result;
-                        sc.push(attrs);
-                    });
-                },
-                'remove-current': function () {
-                    var menu_id = self.session.active_id;
-                    var $shortcut = self.$element
-                        .find('.oe-shortcuts li[data-id=' + menu_id + ']');
-                    var shortcut_id = $shortcut.data('shortcut-id');
-                    $shortcut.remove();
-                    shortcuts_ds.unlink([shortcut_id]);
-                    var sc_new = _.reject(sc, function(shortcut){ return shortcut_id === shortcut.id});
-                    sc.splice(0, sc.length);
-                    sc.push.apply(sc, sc_new);
-                    }
-            });
-        }
-        return this.rpc('/web/session/sc_list', {}, function(shortcuts) {
-            sc.splice(0, sc.length);
-            sc.push.apply(sc, shortcuts);
-
-            self.$element.find('.oe-shortcuts')
-                .html(QWeb.render('Shortcuts', {'shortcuts': shortcuts}))
-                .undelegate('li', 'click')
-
-                .delegate('li', 'click', function(e) {
-                    e.stopPropagation();
-                    var id = $(this).data('id');
-                    self.session.active_id = id;
-                    self.rpc('/web/menu/action', {'menu_id':id}, function(ir_menu_data) {
-                        if (ir_menu_data.action.length){
-                            self.on_action(ir_menu_data.action[0][2]);
-                        }
-                    });
-                });
-        });
+    on_action: function() {
     },
-
-    on_action: function(action) {
+    on_menu_logout: function() {
     },
-    on_preferences: function(){
+    on_menu_settings: function() {
         var self = this;
-        var action_manager = new openerp.web.ActionManager(this);
-        var dataset = new openerp.web.DataSet (this,'res.users',this.context);
+        var action_manager = new instance.web.ActionManager(this);
+        var dataset = new instance.web.DataSet (this,'res.users',this.context);
         dataset.call ('action_get','',function (result){
             self.rpc('/web/action/load', {action_id:result}, function(result){
                 action_manager.do_action(_.extend(result['result'], {
+                    target: 'inline',
                     res_id: self.session.uid,
                     res_model: 'res.users',
                     flags: {
@@ -741,17 +797,17 @@ openerp.web.Header =  openerp.web.OldWidget.extend(/** @lends openerp.web.Header
                 }));
             });
         });
-        this.dialog = new openerp.web.Dialog(this,{
+        this.dialog = new instance.web.Dialog(this,{
             title: _t("Preferences"),
             width: '700px',
             buttons: [
-                {text: _t("Cancel"), click: function(){ $(this).dialog('destroy'); }},
                 {text: _t("Change password"), click: function(){ self.change_password(); }},
+                {text: _t("Cancel"), click: function(){ $(this).dialog('destroy'); }},
                 {text: _t("Save"), click: function(){
                         var inner_viewmanager = action_manager.inner_viewmanager;
                         inner_viewmanager.views[inner_viewmanager.active_view].controller.do_save()
                         .then(function() {
-                            self.dialog.stop();
+                            self.dialog.destroy();
                             // needs to refresh interface in case language changed
                             window.location.reload();
                         });
@@ -759,358 +815,142 @@ openerp.web.Header =  openerp.web.OldWidget.extend(/** @lends openerp.web.Header
                 }
             ]
         }).open();
-       action_manager.appendTo(this.dialog);
-       action_manager.render(this.dialog);
+       action_manager.appendTo(this.dialog.$element);
+       action_manager.renderElement(this.dialog);
     },
-
-    change_password :function() {
+    on_menu_about: function() {
         var self = this;
-        this.dialog = new openerp.web.Dialog(this, {
-            title: _t("Change Password"),
-            width : 'auto'
-        }).open();
-        this.dialog.$element.html(QWeb.render("Change_Pwd", self));
-        this.dialog.$element.find("form[name=change_password_form]").validate({
-            submitHandler: function (form) {
-                self.rpc("/web/session/change_password",{
-                    'fields': $(form).serializeArray()
-                }, function(result) {
-                    if (result.error) {
-                        self.display_error(result);
-                        return;
-                    } else {
-                        openerp.webclient.on_logout();
-                    }
-                });
-            }
+        self.rpc("/web/webclient/version_info", {}).then(function(res) {
+            var $help = $(QWeb.render("UserMenu.about", {version_info: res}));
+            $help.find('a.oe_activate_debug_mode').click(function (e) {
+                e.preventDefault();
+                window.location = $.param.querystring(
+                        window.location.href, 'debug');
+            });
+            instance.web.dialog($help, {autoOpen: true,
+                modal: true, width: 960, title: _t("About")});
         });
     },
-    display_error: function (error) {
-        return $('<div>').dialog({
-            modal: true,
-            title: error.title,
-            buttons: [
-                {text: _("Ok"), click: function() { $(this).dialog("close"); }}
-            ]
-        }).html(error.error);
-    },
-    on_logout: function() {
-    }
 });
 
-openerp.web.Menu =  openerp.web.OldWidget.extend(/** @lends openerp.web.Menu# */{
-    /**
-     * @constructs openerp.web.Menu
-     * @extends openerp.web.OldWidget
-     *
-     * @param parent
-     * @param element_id
-     * @param secondary_menu_id
-     */
-    init: function(parent, element_id, secondary_menu_id) {
-        this._super(parent, element_id);
-        this.secondary_menu_id = secondary_menu_id;
-        this.$secondary_menu = $("#" + secondary_menu_id);
-        this.menu = false;
-        this.folded = false;
-        if (window.localStorage) {
-            this.folded = localStorage.getItem('oe_menu_folded') === 'true';
-        }
-        this.float_timeout = 700;
-    },
-    start: function() {
-        this.$secondary_menu.addClass(this.folded ? 'oe_folded' : 'oe_unfolded');
-    },
-    do_reload: function() {
-        var self = this;
-        return this.rpc("/web/menu/load", {}, this.on_loaded).then(function () {
-            if (self.current_menu) {
-                self.open_menu(self.current_menu);
-            }
-        });
-    },
-    on_loaded: function(data) {
-        this.data = data;
-        this.$element.html(QWeb.render("Menu", { widget : this }));
-        this.$secondary_menu.html(QWeb.render("Menu.secondary", { widget : this }));
-        this.$element.add(this.$secondary_menu).find("a").click(this.on_menu_click);
-        this.$secondary_menu.find('.oe_toggle_secondary_menu').click(this.on_toggle_fold);
-    },
-    on_toggle_fold: function() {
-        this.$secondary_menu.toggleClass('oe_folded').toggleClass('oe_unfolded');
-        if (this.folded) {
-            this.$secondary_menu.find('.oe_secondary_menu.active').show();
-        } else {
-            this.$secondary_menu.find('.oe_secondary_menu').hide();
-        }
-        this.folded = !this.folded;
-        if (window.localStorage) {
-            localStorage.setItem('oe_menu_folded', this.folded.toString());
-        }
-    },
-    /**
-     * Opens a given menu by id, as if a user had browsed to that menu by hand
-     * except does not trigger any event on the way
-     *
-     * @param {Number} menu_id database id of the terminal menu to select
-     */
-    open_menu: function (menu_id) {
-        this.$element.add(this.$secondary_menu).find('.active')
-                .removeClass('active');
-        this.$secondary_menu.find('> .oe_secondary_menu').hide();
-
-        var $primary_menu;
-        var $secondary_submenu = this.$secondary_menu.find(
-                'a[data-menu=' + menu_id +']');
-        if ($secondary_submenu.length) {
-            for(;;) {
-                if ($secondary_submenu.hasClass('leaf')) {
-                    $secondary_submenu.addClass('active');
-                } else if ($secondary_submenu.hasClass('submenu')) {
-                    $secondary_submenu.addClass('opened')
-                }
-                var $parent = $secondary_submenu.parent().show();
-                if ($parent.hasClass('oe_secondary_menu')) {
-                    var primary_id = $parent.data('menu-parent');
-                    $primary_menu = this.$element.find(
-                            'a[data-menu=' + primary_id + ']');
-                    break;
-                }
-                $secondary_submenu = $parent.prev();
-            }
-        } else {
-            $primary_menu = this.$element.find('a[data-menu=' + menu_id + ']');
-        }
-        if (!$primary_menu.length) {
-            return;
-        }
-        $primary_menu.addClass('active');
-        this.$secondary_menu.find(
-            'div[data-menu-parent=' + $primary_menu.data('menu') + ']').addClass('active').toggle(!this.folded);
-    },
-    on_menu_click: function(ev, id) {
-        id = id || 0;
-        var $clicked_menu, manual = false;
-
-        if (id) {
-            // We can manually activate a menu with it's id (for hash url mapping)
-            manual = true;
-            $clicked_menu = this.$element.find('a[data-menu=' + id + ']');
-            if (!$clicked_menu.length) {
-                $clicked_menu = this.$secondary_menu.find('a[data-menu=' + id + ']');
-            }
-        } else {
-            $clicked_menu = $(ev.currentTarget);
-            id = $clicked_menu.data('menu');
-        }
-
-        if (this.do_menu_click($clicked_menu, manual) && id) {
-            this.current_menu = id;
-            this.session.active_id = id;
-            this.rpc('/web/menu/action', {'menu_id': id}, this.on_menu_action_loaded);
-        }
-        if (ev) {
-            ev.stopPropagation();
-        }
-        return false;
-    },
-    do_menu_click: function($clicked_menu, manual) {
-        var $sub_menu, $main_menu,
-            active = $clicked_menu.is('.active'),
-            sub_menu_visible = false,
-            has_submenu_items = false;
-
-        if (this.$secondary_menu.has($clicked_menu).length) {
-            $sub_menu = $clicked_menu.parents('.oe_secondary_menu');
-            $main_menu = this.$element.find('a[data-menu=' + $sub_menu.data('menu-parent') + ']');
-        } else {
-            $sub_menu = this.$secondary_menu.find('.oe_secondary_menu[data-menu-parent=' + $clicked_menu.attr('data-menu') + ']');
-            $main_menu = $clicked_menu;
-        }
-
-        sub_menu_visible = $sub_menu.is(':visible');
-        has_submenu_items = !!$sub_menu.children().length;
-        this.$secondary_menu.find('.oe_secondary_menu').hide();
-
-        $('.active', this.$element.add(this.$secondary_menu)).removeClass('active');
-        $main_menu.add($clicked_menu).add($sub_menu).addClass('active');
-
-        if (has_submenu_items) {
-            if (!(this.folded && manual)) {
-                this.do_show_secondary($sub_menu, $main_menu);
-            } else {
-                this.do_show_secondary();
-            }
-        }
-
-        if ($main_menu != $clicked_menu) {
-            if ($clicked_menu.is('.submenu')) {
-                $sub_menu.find('.submenu.opened').each(function() {
-                    if (!$(this).next().has($clicked_menu).length && !$(this).is($clicked_menu)) {
-                        $(this).removeClass('opened').next().hide();
-                    }
-                });
-                $clicked_menu.toggleClass('opened').next().toggle();
-            } else if ($clicked_menu.is('.leaf')) {
-                $sub_menu.toggle(!this.folded);
-                return true;
-            }
-        } else if (this.folded) {
-            if ((active && sub_menu_visible) || !has_submenu_items) {
-                $sub_menu.hide();
-                return true;
-            }
-            return manual;
-        } else {
-            return true;
-        }
-        return false;
-    },
-    do_hide_secondary: function() {
-        this.$secondary_menu.hide();
-    },
-    do_show_secondary: function($sub_menu, $main_menu) {
+instance.web.WebClient = instance.web.Widget.extend({
+    init: function(parent) {
         var self = this;
-        this.$secondary_menu.show();
-        if (!arguments.length) {
-            return;
-        }
-        if (this.folded) {
-            var css = $main_menu.position(),
-                fold_width = this.$secondary_menu.width() + 2,
-                window_width = $(window).width();
-            css.top += 33;
-            css.left -= Math.round(($sub_menu.width() - $main_menu.width()) / 2);
-            css.left = css.left < fold_width ? fold_width : css.left;
-            if ((css.left + $sub_menu.width()) > window_width) {
-                delete(css.left);
-                css.right = 1;
-            }
-            $sub_menu.css(css);
-            $sub_menu.mouseenter(function() {
-                clearTimeout($sub_menu.data('timeoutId'));
-                $sub_menu.data('timeoutId', null);
-                return false;
-            }).mouseleave(function(evt) {
-                var timeoutId = setTimeout(function() {
-                    if (self.folded && $sub_menu.data('timeoutId')) {
-                        $sub_menu.hide().unbind('mouseenter').unbind('mouseleave');
-                    }
-                }, self.float_timeout);
-                $sub_menu.data('timeoutId', timeoutId);
-                return false;
-            });
-        }
-        $sub_menu.show();
+        this._super(parent);
+        instance.webclient = this;
+        this.querystring = '?' + jQuery.param.querystring();
+        this._current_state = null;
     },
-    on_menu_action_loaded: function(data) {
-        var self = this;
-        if (data.action.length) {
-            var action = data.action[0][2];
-            action.from_menu = true;
-            self.on_action(action);
+    _get_version_label: function() {
+        if (this.session.openerp_entreprise) {
+            return 'OpenERP';
         } else {
-            self.on_action({type: 'null_action'});
+            return _t("OpenERP - Unsupported/Community Version");
         }
     },
-    on_action: function(action) {
-    }
-});
-
-openerp.web.WebClient = openerp.web.OldWidget.extend(/** @lends openerp.web.WebClient */{
-    /**
-     * @constructs openerp.web.WebClient
-     * @extends openerp.web.OldWidget
-     *
-     * @param element_id
-     */
-    init: function(parent) {
-        var self = this;
-        this._super(parent);
-        openerp.webclient = this;
-
-        this._current_state = null;
+    set_title: function(title) {
+        title = _.str.clean(title);
+        var sep = _.isEmpty(title) ? '' : ' - ';
+        document.title = title + sep + 'OpenERP';
     },
     start: function() {
         var self = this;
-        this.$element = $(document.body);
-        if (jQuery.param != undefined && jQuery.deparam(jQuery.param.querystring()).kitten != undefined) {
-            this.$element.addClass("kitten-mode-activated");
-            this.$element.delegate('img.oe-record-edit-link-img', 'hover', function(e) {
-                self.$element.toggleClass('clark-gable');
-            });
+        this.$element.addClass("openerp openerp_webclient_container");
+        if (jQuery.param !== undefined && jQuery.deparam(jQuery.param.querystring()).kitten !== undefined) {
+            $("body").addClass("kitten-mode-activated");
+            if ($.blockUI) {
+                $.blockUI.defaults.message = '<img src="http://www.amigrave.com/kitten.gif">';
+            }
         }
-        this.session.bind().then(function() {
+        this.session.session_bind().then(function() {
+            self.destroy_content();
+            self.show_common();
             if (!self.session.session_is_valid()) {
                 self.show_login();
+            } else {
+                self.show_application();
             }
         });
-        this.session.on_session_valid.add(function() {
-            self.show_application();
-            
-            self.header.do_update();
-            self.menu.do_reload();
-            if(self.action_manager)
-                self.action_manager.stop();
-            self.action_manager = new openerp.web.ActionManager(self);
-            self.action_manager.appendTo($("#oe_app"));
-            self.bind_hashchange();
-            var version_label = _t("OpenERP - Unsupported/Community Version");
-            if (!self.session.openerp_entreprise) {
-                self.$element.find('.oe_footer_powered').append(_.str.sprintf('<span> - <a href="http://www.openerp.com/support-or-publisher-warranty-contract" target="_blank">%s</a></span>', version_label));
-                document.title = version_label;
-            }
+        this.$element.on('mouseenter', '.oe_systray > div:not([data-tipsy=true])', function() {
+            $(this).attr('data-tipsy', 'true').tipsy().trigger('mouseenter');
+        });
+        this.$element.on('click', '.oe_dropdown_toggle', function(ev) {
+            ev.preventDefault();
+            var $menu = $(this).find('.oe_dropdown_menu');
+            var state = $menu.is('.oe_opened');
+            setTimeout(function() {
+                // Do not alter propagation
+                $menu.toggleClass('oe_opened', !state);
+                if (!state) {
+                    // Move $menu if outside window's edge
+                    var doc_width = $(document).width();
+                    var offset = $menu.offset();
+                    var menu_width = $menu.width();
+                    var x = doc_width - offset.left - menu_width - 15;
+                    if (x < 0) {
+                        $menu.offset({ left: offset.left + x }).width(menu_width);
+                    }
+                }
+            }, 0);
+        });
+        instance.web.bus.on('click', this, function() {
+            self.$element.find('.oe_dropdown_menu.oe_opened').removeClass('oe_opened');
         });
     },
+    show_common: function() {
+        var self = this;
+        this.crashmanager =  new instance.web.CrashManager();
+        instance.connection.on_rpc_error.add(this.crashmanager.on_rpc_error);
+        window.onerror = function (message, file, line) {
+            self.crashmanager.on_traceback({
+                type: _t("Client Error"),
+                message: message,
+                data: {debug: file + ':' + line}
+            });
+        };
+        self.notification = new instance.web.Notification(this);
+        self.notification.appendTo(self.$element);
+        self.loading = new instance.web.Loading(self);
+        self.loading.appendTo(self.$element);
+        self.login = new instance.web.Login(self);
+        self.login.on("login",self,self.show_application);
+        self.$table = $(QWeb.render("WebClient", {}));
+        self.action_manager = new instance.web.ActionManager(self);
+        self.action_manager.appendTo(self.$table.find('.oe_application'));
+    },
     show_login: function() {
         var self = this;
-        this.destroy_content();
-        this.show_common();
-        self.login = new openerp.web.Login(self);
         self.login.appendTo(self.$element);
     },
     show_application: function() {
         var self = this;
-        this.destroy_content();
-        this.show_common();
-        self.$table = $(QWeb.render("Interface", {}));
         self.$element.append(self.$table);
-        self.header = new openerp.web.Header(self);
-        self.header.on_logout.add(this.proxy('on_logout'));
-        self.header.on_action.add(this.proxy('on_menu_action'));
-        self.header.appendTo($("#oe_header"));
-        self.menu = new openerp.web.Menu(self, "oe_menu", "oe_secondary_menu");
-        self.menu.on_action.add(this.proxy('on_menu_action'));
-        self.menu.start();
-    },
-    show_common: function() {
-        var self = this;
-        if (!this.crashmanager) {
-            this.crashmanager =  new openerp.web.CrashManager();
-            openerp.connection.on_rpc_error.add(this.crashmanager.on_rpc_error);
-            window.onerror = function (message, file, line) {
-                self.crashmanager.on_traceback({
-                    type: _t("Client Error"),
-                    message: message,
-                    data: {debug: file + ':' + line}
-                });
-            }
+        self.login.$element.hide();
+        self.menu = new instance.web.Menu(self);
+        self.menu.replace(this.$element.find('.oe_menu_placeholder'));
+        self.menu.on('menu_click', this, this.on_menu_action);
+        self.user_menu = new instance.web.UserMenu(self);
+        self.user_menu.replace(this.$element.find('.oe_user_menu_placeholder'));
+        self.user_menu.on_menu_logout.add(this.proxy('on_logout'));
+        self.user_menu.on_action.add(this.proxy('on_menu_action'));
+        self.user_menu.do_update();
+        self.bind_hashchange();
+        if (!self.session.openerp_entreprise) {
+            var version_label = self._get_version_label();
+            self.$element.find('.oe_footer_powered').append(_.str.sprintf('<span> - <a href="http://www.openerp.com/support-or-publisher-warranty-contract" target="_blank">%s</a></span>', version_label));
         }
-        this.notification = new openerp.web.Notification(this);
-        this.notification.appendTo(this.$element);
-        this.loading = new openerp.web.Loading(this);
-        this.loading.appendTo(this.$element);
+        self.set_title();
     },
     destroy_content: function() {
-        _.each(_.clone(this.widget_children), function(el) {
-            el.stop();
+        _.each(_.clone(this.getChildren()), function(el) {
+            el.destroy();
         });
         this.$element.children().remove();
     },
     do_reload: function() {
         var self = this;
         return this.session.session_reload().pipe(function () {
-            openerp.connection.load_modules(true).pipe(
+            instance.connection.load_modules(true).pipe(
                 self.menu.proxy('do_reload')); });
 
     },
@@ -1135,39 +975,37 @@ openerp.web.WebClient = openerp.web.OldWidget.extend(/** @lends openerp.web.WebC
     bind_hashchange: function() {
         var self = this;
         $(window).bind('hashchange', this.on_hashchange);
+
         var state = $.bbq.getState(true);
         if (! _.isEmpty(state)) {
             $(window).trigger('hashchange');
         } else {
-            var ds = new openerp.web.DataSetSearch(this, 'res.users');
-            ds.read_ids([this.session.uid], ['action_id']).then(function (users) {
-                var default_home = {type: 'ir.actions.client', tag: 'default_home'};
-                var home_action = users[0].action_id;
-                if (!home_action) {
-                    self.action_manager.do_action(default_home);
-                } else {
-                    // FIXME Dirty hack to avoid -u board, dont merge in 7
-                    var domain = [['model','=','ir.actions.act_window'],['res_id','=',home_action[0]]];
-                    var imd = new openerp.web.DataSetSearch(this, 'ir.model.data', {}, domain);
-                    imd.read_slice(['name']).then(function (r) {
-                        if(r.length && r[0].name === "board_homepage_action") {
-                            self.action_manager.do_action(default_home);
-                        } else {
-                            self.action_manager.do_action(home_action[0]);
-                        }
-                    })
+            self.menu.has_been_loaded.then(function() {
+                var first_menu_id = self.menu.$element.find("a:first").data("menu");
+                if(first_menu_id) {
+                    self.menu.menu_click(first_menu_id);
                 }
             });
         }
     },
     on_hashchange: function(event) {
+        var self = this;
         var state = event.getState(true);
         if (!_.isEqual(this._current_state, state)) {
-            this.action_manager.do_load_state(state, !!this._current_state);
+            if(state.action_id === undefined && state.menu_id) {
+                self.menu.has_been_loaded.then(function() {
+                    self.menu.do_reload().then(function() {
+                        self.menu.menu_click(state.menu_id)
+                    });
+                });
+            } else {
+                this.action_manager.do_load_state(state, !!this._current_state);
+            }
         }
         this._current_state = state;
     },
     do_push_state: function(state) {
+        this.set_title(state.title);
         var url = '#' + $.param(state);
         this._current_state = _.clone(state);
         $.bbq.pushState(url);
@@ -1177,25 +1015,30 @@ openerp.web.WebClient = openerp.web.OldWidget.extend(/** @lends openerp.web.WebC
     },
     do_action: function(action) {
         var self = this;
-        // TODO replace by client action menuclick 
+        // TODO replace by client action menuclick
         if(action.menu_id) {
             this.do_reload().then(function () {
-                self.menu.on_menu_click(null, action.menu_id);
+                self.menu.menu_click(action.menu_id);
             });
         }
+    },
+    set_content_full_screen: function(fullscreen) {
+        if (fullscreen)
+            $(".oe_webclient", this.$element).addClass("oe_content_full_screen");
+        else
+            $(".oe_webclient", this.$element).removeClass("oe_content_full_screen");
     }
 });
 
-openerp.web.EmbeddedClient = openerp.web.OldWidget.extend({
+instance.web.EmbeddedClient = instance.web.Widget.extend({
     template: 'EmptyComponent',
-    init: function(action_id, options) {
-        this._super();
-        // TODO take the xmlid of a action instead of its id 
+    init: function(parent, action_id, options) {
+        this._super(parent);
+        // TODO take the xmlid of a action instead of its id
         this.action_id = action_id;
         this.options = options || {};
-        this.am = new openerp.web.ActionManager(this);
+        this.am = new instance.web.ActionManager(this);
     },
-
     start: function() {
         var self = this;
         this.am.appendTo(this.$element.addClass('openerp'));
@@ -1212,10 +1055,9 @@ openerp.web.EmbeddedClient = openerp.web.OldWidget.extend({
             self.am.do_action(action);
         });
     }
-
 });
 
-openerp.web.embed = function (origin, dbname, login, key, action, options) {
+instance.web.embed = function (origin, dbname, login, key, action, options) {
     $('head').append($('<link>', {
         'rel': 'stylesheet',
         'type': 'text/css',
@@ -1226,14 +1068,14 @@ openerp.web.embed = function (origin, dbname, login, key, action, options) {
         var sc = document.getElementsByTagName('script');
         currentScript = sc[sc.length-1];
     }
-    openerp.connection.bind(origin).then(function () {
-        openerp.connection.session_authenticate(dbname, login, key, true).then(function () {
-            var client = new openerp.web.EmbeddedClient(action, options);
+    instance.connection.session_bind(origin).then(function () {
+        instance.connection.session_authenticate(dbname, login, key, true).then(function () {
+            var client = new instance.web.EmbeddedClient(null, action, options);
             client.insertAfter(currentScript);
         });
     });
 
-}
+};
 
 };