[FIX] Crashmanager only display one error at a time, closing the previous one. (stupi...
[odoo/odoo.git] / addons / web / static / src / js / chrome.js
1 /*---------------------------------------------------------
2  * OpenERP Web chrome
3  *---------------------------------------------------------*/
4 openerp.web.chrome = function(openerp) {
5 var QWeb = openerp.web.qweb;
6
7 openerp.web.Notification =  openerp.web.Widget.extend(/** @lends openerp.web.Notification# */{
8     template: 'Notification',
9     identifier_prefix: 'notification-',
10
11     init: function() {
12         this._super.apply(this, arguments);
13         openerp.notification = this;
14     },
15
16     start: function() {
17         this._super.apply(this, arguments);
18         this.$element.notify({
19             speed: 500,
20             expires: 1500
21         });
22     },
23     notify: function(title, text) {
24         this.$element.notify('create', {
25             title: title,
26             text: text
27         });
28     },
29     warn: function(title, text) {
30         this.$element.notify('create', 'oe_notification_alert', {
31             title: title,
32             text: text,
33         }, {
34             expires: false,
35         });
36     },
37
38 });
39
40 openerp.web.Dialog = openerp.web.OldWidget.extend(/** @lends openerp.web.Dialog# */{
41     dialog_title: "",
42     identifier_prefix: 'dialog',
43     /**
44      * @constructs openerp.web.Dialog
45      * @extends openerp.web.OldWidget
46      *
47      * @param parent
48      * @param dialog_options
49      */
50     init: function (parent, dialog_options) {
51         var self = this;
52         this._super(parent);
53         this.dialog_options = {
54             modal: true,
55             width: 'auto',
56             min_width: 0,
57             max_width: '100%',
58             height: 'auto',
59             min_height: 0,
60             max_height: '100%',
61             autoOpen: false,
62             buttons: {},
63             beforeClose: function () { self.on_close(); }
64         };
65         for (var f in this) {
66             if (f.substr(0, 10) == 'on_button_') {
67                 this.dialog_options.buttons[f.substr(10)] = this[f];
68             }
69         }
70         if (dialog_options) {
71             this.set_options(dialog_options);
72         }
73     },
74     set_options: function(options) {
75         options = options || {};
76         options.width = this.get_width(options.width || this.dialog_options.width);
77         options.min_width = this.get_width(options.min_width || this.dialog_options.min_width);
78         options.max_width = this.get_width(options.max_width || this.dialog_options.max_width);
79         options.height = this.get_height(options.height || this.dialog_options.height);
80         options.min_height = this.get_height(options.min_height || this.dialog_options.min_height);
81         options.max_height = this.get_height(options.max_height || this.dialog_options.max_width);
82
83         if (options.width !== 'auto') {
84             if (options.width > options.max_width) options.width = options.max_width;
85             if (options.width < options.min_width) options.width = options.min_width;
86         }
87         if (options.height !== 'auto') {
88             if (options.height > options.max_height) options.height = options.max_height;
89             if (options.height < options.min_height) options.height = options.min_height;
90         }
91         if (!options.title && this.dialog_title) {
92             options.title = this.dialog_title;
93         }
94         _.extend(this.dialog_options, options);
95     },
96     get_width: function(val) {
97         return this.get_size(val.toString(), $(window.top).width());
98     },
99     get_height: function(val) {
100         return this.get_size(val.toString(), $(window.top).height());
101     },
102     get_size: function(val, available_size) {
103         if (val === 'auto') {
104             return val;
105         } else if (val.slice(-1) == "%") {
106             return Math.round(available_size / 100 * parseInt(val.slice(0, -1), 10));
107         } else {
108             return parseInt(val, 10);
109         }
110     },
111     start: function () {
112         this.$dialog = $('<div id="' + this.element_id + '"></div>').dialog(this.dialog_options);
113         this._super();
114         return this;
115     },
116     open: function(dialog_options) {
117         // TODO fme: bind window on resize
118         if (this.template) {
119             this.$element.html(this.render());
120         }
121         this.set_options(dialog_options);
122         this.$dialog.dialog(this.dialog_options).dialog('open');
123         return this;
124     },
125     close: function() {
126         // Closes the dialog but leave it in a state where it could be opened again.
127         this.$dialog.dialog('close');
128     },
129     on_close: function() {
130     },
131     stop: function () {
132         // Destroy widget
133         this.close();
134         this.$dialog.dialog('destroy');
135         this._super();
136     }
137 });
138
139 openerp.web.CrashManager = openerp.web.SessionAware.extend({
140     init: function(parent) {
141         this._super((parent || {}).session);
142         this.session.on_rpc_error.add(this.on_rpc_error);
143     },
144     on_rpc_error: function(error) {
145         this.error = error;
146         if (error.data.fault_code) {
147             var split = ("" + error.data.fault_code).split('\n')[0].split(' -- ');
148             if (split.length > 1) {
149                 error.type = split.shift();
150                 error.data.fault_code = error.data.fault_code.substr(error.type.length + 4);
151             }
152         }
153         if (error.code === 200 && error.type) {
154             this.on_managed_error(error);
155         } else {
156             this.on_traceback(error);
157         }
158     },
159     on_managed_error: function(error) {
160         $('<div>' + QWeb.render('DialogWarning', {error: error}) + '</div>').dialog({
161             title: "OpenERP " + _.capitalize(error.type),
162             buttons: {
163                 Ok: function() {
164                     $(this).dialog("close");
165                 }
166             }
167         });
168     },
169     on_traceback: function(error) {
170         var dialog = new openerp.web.Dialog(this, {
171             title: "OpenERP " + _.capitalize(error.type),
172             autoOpen: true,
173             width: '90%',
174             height: '90%',
175             min_width: '800px',
176             min_height: '600px',
177             buttons: {
178                 Ok: function() {
179                     $(this).dialog("close");
180                 }
181             }
182         }).start();
183         dialog.$element.html(QWeb.render('DialogTraceback', {error: error}));
184     }
185 });
186
187 openerp.web.Loading =  openerp.web.Widget.extend(/** @lends openerp.web.Loading# */{
188     /**
189      * @constructs openerp.web.Loading
190      * @extends openerp.web.Widget
191      *
192      * @param parent
193      * @param element_id
194      */
195     init: function(parent, element_id) {
196         this._super(parent, element_id);
197         this.count = 0;
198         this.session.on_rpc_request.add_first(this.on_rpc_event, 1);
199         this.session.on_rpc_response.add_last(this.on_rpc_event, -1);
200     },
201     on_rpc_event : function(increment) {
202         this.count += increment;
203         if (this.count) {
204             //this.$element.html(QWeb.render("Loading", {}));
205             this.$element.html("Loading ("+this.count+")");
206             this.$element.show();
207         } else {
208             this.$element.fadeOut();
209         }
210     }
211 });
212
213 openerp.web.Database = openerp.web.Widget.extend(/** @lends openerp.web.Database# */{
214     /**
215      * @constructs openerp.web.Database
216      * @extends openerp.web.Widget
217      *
218      * @param parent
219      * @param element_id
220      * @param option_id
221      */
222     init: function(parent, element_id, option_id) {
223         this._super(parent, element_id);
224         this.$option_id = $('#' + option_id);
225     },
226     start: function() {
227         this.$element.html(QWeb.render("Database", this));
228         this.$element.closest(".openerp")
229                 .removeClass("login-mode")
230                 .addClass("database_block");
231
232         var self = this;
233         var fetch_db = this.rpc("/web/database/get_list", {}, function(result) {
234             self.db_list = result.db_list;
235         });
236         var fetch_langs = this.rpc("/web/session/get_lang_list", {}, function(result) {
237             if (result.error) {
238                 self.display_error(result);
239                 return;
240             }
241             self.lang_list = result.lang_list;
242         });
243         $.when(fetch_db, fetch_langs).then(function () {self.do_create();});
244
245         this.$element.find('#db-create').click(this.do_create);
246         this.$element.find('#db-drop').click(this.do_drop);
247         this.$element.find('#db-backup').click(this.do_backup);
248         this.$element.find('#db-restore').click(this.do_restore);
249         this.$element.find('#db-change-password').click(this.do_change_password);
250         this.$element.find('#back-to-login').click(function() {
251             self.stop();
252         });
253     },
254     stop: function () {
255         this.$option_id.empty();
256
257         this.$element
258             .find('#db-create, #db-drop, #db-backup, #db-restore, #db-change-password, #back-to-login')
259                 .unbind('click')
260             .end()
261             .closest(".openerp")
262                 .addClass("login-mode")
263                 .removeClass("database_block")
264             .end()
265             .empty();
266         this._super();
267     },
268     /**
269      * Converts a .serializeArray() result into a dict. Does not bother folding
270      * multiple identical keys into an array, last key wins.
271      *
272      * @param {Array} array
273      */
274     to_object: function (array) {
275         var result = {};
276         _(array).each(function (record) {
277             result[record.name] = record.value;
278         });
279         return result;
280     },
281     /**
282      * Waits until the new database is done creating, then unblocks the UI and
283      * logs the user in as admin
284      *
285      * @param {Number} db_creation_id identifier for the db-creation operation, used to fetch the current installation progress
286      * @param {Object} info info fields for this database creation
287      * @param {String} info.db name of the database being created
288      * @param {String} info.password super-admin password for the database
289      */
290     wait_for_newdb: function (db_creation_id, info) {
291         var self = this;
292         self.rpc('/web/database/progress', {
293             id: db_creation_id,
294             password: info.password
295         }, function (result) {
296             var progress = result[0];
297             // I'd display a progress bar, but turns out the progress status
298             // the server report kind-of blows goats: it's at 0 for ~75% of
299             // the installation, then jumps to 75%, then jumps down to either
300             // 0 or ~40%, then back up to 75%, then terminates. Let's keep that
301             // mess hidden behind a not-very-useful but not overly weird
302             // message instead.
303             if (progress < 1) {
304                 setTimeout(function () {
305                     self.wait_for_newdb(db_creation_id, info);
306                 }, 500);
307                 return;
308             }
309
310             var admin = result[1][0];
311             setTimeout(function () {
312                 self.widget_parent.do_login(
313                         info.db, admin.login, admin.password);
314                 self.stop();
315                 $.unblockUI();
316             });
317         });
318     },
319     /**
320      * Displays an error dialog resulting from the various RPC communications
321      * failing over themselves
322      *
323      * @param {Object} error error description
324      * @param {String} error.title title of the error dialog
325      * @param {String} error.error message of the error dialog
326      */
327     display_error: function (error) {
328         return $('<div>').dialog({
329             modal: true,
330             title: error.title,
331             buttons: {
332                 Ok: function() {
333                     $(this).dialog("close");
334                 }
335             }
336         }).html(error.error);
337     },
338     do_create: function() {
339         var self = this;
340         self.$option_id.html(QWeb.render("Database.CreateDB", self));
341         self.$option_id.find("form[name=create_db_form]").validate({
342             submitHandler: function (form) {
343                 var fields = $(form).serializeArray();
344                 $.blockUI({message:'<img src="/web/static/src/img/throbber2.gif">'});
345                 self.rpc("/web/database/create", {'fields': fields}, function(result) {
346                     if (result.error) {
347                         $.unblockUI();
348                         self.display_error(result);
349                         return;
350                     }
351                     self.db_list.push(self.to_object(fields)['db_name']);
352                     self.db_list.sort();
353                     var form_obj = self.to_object(fields);
354                     self.wait_for_newdb(result, {
355                         password: form_obj['super_admin_pwd'],
356                         db: form_obj['db_name']
357                     });
358                 });
359             }
360         });
361     },
362     do_drop: function() {
363         var self = this;
364         self.$option_id.html(QWeb.render("DropDB", self));
365         self.$option_id.find("form[name=drop_db_form]").validate({
366             submitHandler: function (form) {
367                 var $form = $(form),
368                     fields = $form.serializeArray(),
369                     $db_list = $form.find('select[name=drop_db]'),
370                     db = $db_list.val();
371
372                 if (!confirm("Do you really want to delete the database: " + db + " ?")) {
373                     return;
374                 }
375                 self.rpc("/web/database/drop", {'fields': fields}, function(result) {
376                     if (result.error) {
377                         self.display_error(result);
378                         return;
379                     }
380                     $db_list.find(':selected').remove();
381                     self.db_list.splice(_.indexOf(self.db_list, db, true), 1);
382                     self.do_notify("Dropping database", "The database '" + db + "' has been dropped");
383                 });
384             }
385         });
386     },
387     do_backup: function() {
388         var self = this;
389         self.$option_id
390             .html(QWeb.render("BackupDB", self))
391             .find("form[name=backup_db_form]").validate({
392             submitHandler: function (form) {
393                 $.blockUI({message:'<img src="/web/static/src/img/throbber2.gif">'});
394                 self.session.get_file({
395                     form: form,
396                     error: function (body) {
397                         var error = body.firstChild.data.split('|');
398                         self.display_error({
399                             title: error[0],
400                             error: error[1]
401                         });
402                     },
403                     complete: $.unblockUI
404                 });
405             }
406         });
407     },
408     do_restore: function() {
409         var self = this;
410         self.$option_id.html(QWeb.render("RestoreDB", self));
411
412         self.$option_id.find("form[name=restore_db_form]").validate({
413             submitHandler: function (form) {
414                 $.blockUI({message:'<img src="/web/static/src/img/throbber2.gif">'});
415                 $(form).ajaxSubmit({
416                     url: '/web/database/restore',
417                     type: 'POST',
418                     resetForm: true,
419                     success: function (body) {
420                         // TODO: ui manipulations
421                         // note: response objects don't work, but we have the
422                         // HTTP body of the response~~
423
424                         // If empty body, everything went fine
425                         if (!body) { return; }
426
427                         if (body.indexOf('403 Forbidden') !== -1) {
428                             self.display_error({
429                                 title: 'Access Denied',
430                                 error: 'Incorrect super-administrator password'
431                             })
432                         } else {
433                             self.display_error({
434                                 title: 'Restore Database',
435                                 error: 'Could not restore the database'
436                             })
437                         }
438                     },
439                     complete: function () {
440                         $.unblockUI();
441                     }
442                 });
443             }
444         });
445     },
446     do_change_password: function() {
447         var self = this;
448         self.$option_id.html(QWeb.render("Change_DB_Pwd", self));
449
450         self.$option_id.find("form[name=change_pwd_form]").validate({
451             messages: {
452                 old_pwd: "Please enter your previous password",
453                 new_pwd: "Please enter your new password",
454                 confirm_pwd: {
455                     required: "Please confirm your new password",
456                     equalTo: "The confirmation does not match the password"
457                 }
458             },
459             submitHandler: function (form) {
460                 self.rpc("/web/database/change_password", {
461                     'fields': $(form).serializeArray()
462                 }, function(result) {
463                     if (result.error) {
464                         self.display_error(result);
465                         return;
466                     }
467                     self.do_notify("Changed Password", "Password has been changed successfully");
468                 });
469             }
470         });
471     }
472 });
473
474 openerp.web.Login =  openerp.web.Widget.extend(/** @lends openerp.web.Login# */{
475     remember_credentials: true,
476     
477     template: "Login",
478     identifier_prefix: 'oe-app-login-',
479     /**
480      * @constructs openerp.web.Login
481      * @extends openerp.web.Widget
482      *
483      * @param parent
484      * @param element_id
485      */
486
487     init: function(parent) {
488         this._super(parent);
489         this.has_local_storage = typeof(localStorage) != 'undefined';
490         this.selected_db = null;
491         this.selected_login = null;
492
493         if (this.has_local_storage && this.remember_credentials) {
494             this.selected_db = localStorage.getItem('last_db_login_success');
495             this.selected_login = localStorage.getItem('last_login_login_success');
496             if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
497                 this.selected_password = localStorage.getItem('last_password_login_success');
498             }
499         }
500         
501         var qs = jQuery.deparam(jQuery.param.querystring());
502         if (qs.db) {
503             this.selected_db = qs.db;
504         }
505         if (qs.login) {
506             this.selected_login = qs.login;
507         }
508
509     },
510     start: function() {
511         var self = this;
512         this.database = new openerp.web.Database(
513                 this, "oe_database", "oe_db_options");
514
515         this.$element.find('#oe-db-config').click(function() {
516             self.database.start();
517         });
518
519         this.$element.find("form").submit(this.on_submit);
520
521         this.rpc("/web/database/get_list", {}, function(result) {
522             var tpl = openerp.web.qweb.render('Login_dblist', {db_list: result.db_list, selected_db: self.selected_db});
523             self.$element.find("input[name=db]").replaceWith(tpl)
524         }, 
525         function(error, event) {
526             if (error.data.fault_code === 'AccessDenied') {
527                 event.preventDefault();
528             }
529         });
530
531     },
532     on_login_invalid: function() {
533         this.$element.closest(".openerp").addClass("login-mode");
534     },
535     on_login_valid: function() {
536         this.$element.closest(".openerp").removeClass("login-mode");
537     },
538     on_submit: function(ev) {
539         ev.preventDefault();
540         var $e = this.$element;
541         var db = $e.find("form [name=db]").val();
542         var login = $e.find("form input[name=login]").val();
543         var password = $e.find("form input[name=password]").val();
544
545         this.do_login(db, login, password);
546     },
547     /**
548      * Performs actual login operation, and UI-related stuff
549      *
550      * @param {String} db database to log in
551      * @param {String} login user login
552      * @param {String} password user password
553      */
554     do_login: function (db, login, password) {
555         var self = this;
556         this.session.session_login(db, login, password, function() {
557             if(self.session.session_is_valid()) {
558                 if (self.has_local_storage) {
559                     if(self.remember_credentials) {
560                         localStorage.setItem('last_db_login_success', db);
561                         localStorage.setItem('last_login_login_success', login);
562                         if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
563                             localStorage.setItem('last_password_login_success', password);
564                         }
565                     } else {
566                         localStorage.setItem('last_db_login_success', '');
567                         localStorage.setItem('last_login_login_success', '');
568                         localStorage.setItem('last_password_login_success', '');
569                     }
570                 }
571                 self.on_login_valid();
572             } else {
573                 self.$element.addClass("login_invalid");
574                 self.on_login_invalid();
575             }
576         });
577     },
578     do_ask_login: function(continuation) {
579         this.on_login_invalid();
580         this.$element
581             .removeClass("login_invalid");
582         this.on_login_valid.add({
583             position: "last",
584             unique: true,
585             callback: continuation || function() {}
586         });
587     },
588     on_logout: function() {
589         this.session.logout();
590     }
591 });
592
593 openerp.web.Header =  openerp.web.Widget.extend(/** @lends openerp.web.Header# */{
594     template: "Header",
595     identifier_prefix: 'oe-app-header-',
596     /**
597      * @constructs openerp.web.Header
598      * @extends openerp.web.Widget
599      *
600      * @param parent
601      */
602     init: function(parent) {
603         this._super(parent);
604         this.qs = "?" + jQuery.param.querystring();
605         this.$content = $();
606         this.update_promise = $.Deferred().resolve();
607     },
608     start: function() {
609         this._super();
610     },
611     do_update: function () {
612         var self = this;
613         var fct = function() {
614             self.$content.remove();
615             if (!self.session.uid)
616                 return;
617             var func = new openerp.web.Model(self.session, "res.users").get_func("read");
618             return func(self.session.uid, ["name", "company_id"]).pipe(function(res) {
619                 self.$content = $(QWeb.render("Header-content", {widget: self, user: res}));
620                 self.$content.appendTo(self.$element);
621                 self.$element.find(".logout").click(self.on_logout);
622                 self.$element.find("a.preferences").click(self.on_preferences);
623                 self.$element.find(".about").click(self.on_about);
624                 return self.shortcut_load();
625             });
626         };
627         this.update_promise = this.update_promise.pipe(fct, fct);
628     },
629     on_about: function() {
630         var self = this;
631         self.rpc("/web/webclient/version_info", {}).then(function(res) {
632             var $help = $(QWeb.render("About-Page", {version_info: res}));
633             $help.dialog({autoOpen: true,
634                 modal: true, width: 960, title: "About"});
635         });
636     },
637     shortcut_load :function(){
638         var self = this,
639             sc = self.session.shortcuts,
640             shortcuts_ds = new openerp.web.DataSet(this, 'ir.ui.view_sc');
641         // TODO: better way to communicate between sections.
642         // sc.bindings, because jquery does not bind/trigger on arrays...
643         if (!sc.binding) {
644             sc.binding = {};
645             $(sc.binding).bind({
646                 'add': function (e, attrs) {
647                     shortcuts_ds.create(attrs, function (out) {
648                         $('<li>', {
649                             'data-shortcut-id':out.result,
650                             'data-id': attrs.res_id
651                         }).text(attrs.name)
652                           .appendTo(self.$element.find('.oe-shortcuts ul'));
653                         attrs.id = out.result;
654                         sc.push(attrs);
655                     });
656                 },
657                 'remove-current': function () {
658                     var menu_id = self.session.active_id;
659                     var $shortcut = self.$element
660                         .find('.oe-shortcuts li[data-id=' + menu_id + ']');
661                     var shortcut_id = $shortcut.data('shortcut-id');
662                     $shortcut.remove();
663                     shortcuts_ds.unlink([shortcut_id]);
664                     var sc_new = _.reject(sc, function(shortcut){ return shortcut_id === shortcut.id});
665                     sc.splice(0, sc.length);
666                     sc.push.apply(sc, sc_new);
667                     }
668             });
669         }
670         return this.rpc('/web/session/sc_list', {}, function(shortcuts) {
671             sc.splice(0, sc.length);
672             sc.push.apply(sc, shortcuts);
673
674             self.$element.find('.oe-shortcuts')
675                 .html(QWeb.render('Shortcuts', {'shortcuts': shortcuts}))
676                 .undelegate('li', 'click')
677
678                 .delegate('li', 'click', function(e) {
679                     e.stopPropagation();
680                     var id = $(this).data('id');
681                     self.session.active_id = id;
682                     self.rpc('/web/menu/action', {'menu_id':id}, function(ir_menu_data) {
683                         if (ir_menu_data.action.length){
684                             self.on_action(ir_menu_data.action[0][2]);
685                         }
686                     });
687                 });
688         });
689     },
690
691     on_action: function(action) {
692     },
693     on_preferences: function(){
694         var self = this;
695         var action_manager = new openerp.web.ActionManager(this);
696         var dataset = new openerp.web.DataSet (this,'res.users',this.context);
697         dataset.call ('action_get','',function (result){
698             self.rpc('/web/action/load', {action_id:result}, function(result){
699                 action_manager.do_action(_.extend(result['result'], {
700                     res_id: self.session.uid,
701                     res_model: 'res.users',
702                     flags: {
703                         action_buttons: false,
704                         search_view: false,
705                         sidebar: false,
706                         views_switcher: false,
707                         pager: false
708                     }
709                 }));
710             });
711         });
712         this.dialog = new openerp.web.Dialog(this,{
713             modal: true,
714             title: 'Preferences',
715             width: 600,
716             height: 500,
717             buttons: {
718                 "Change password": function(){
719                     self.change_password();
720             },
721                 Cancel: function(){
722                      $(this).dialog('destroy');
723             },
724                 Save: function(){
725                     var inner_viewmanager = action_manager.inner_viewmanager;
726                     inner_viewmanager.views[inner_viewmanager.active_view].controller.do_save()
727                     .then(function() {
728                         self.dialog.stop();
729                         window.location.reload();
730                     });
731                 }
732             }
733         });
734        this.dialog.start().open();
735        action_manager.appendTo(this.dialog);
736        action_manager.render(this.dialog);
737     },
738
739     change_password :function() {
740         var self = this;
741         this.dialog = new openerp.web.Dialog(this,{
742             modal : true,
743             title : 'Change Password',
744             width : 'auto',
745             height : 'auto'
746         });
747         this.dialog.start().open();
748         this.dialog.$element.html(QWeb.render("Change_Pwd", self));
749         this.dialog.$element.find("form[name=change_password_form]").validate({
750             submitHandler: function (form) {
751                 self.rpc("/web/session/change_password",{
752                     'fields': $(form).serializeArray()
753                 }, function(result) {
754                     if (result.error) {
755                         self.display_error(result);
756                         return;
757                     } else {
758                         self.session.logout();
759                     }
760                 });
761             }
762         });
763     },
764     display_error: function (error) {
765         return $('<div>').dialog({
766             modal: true,
767             title: error.title,
768             buttons: {
769                 Ok: function() {
770                     $(this).dialog("close");
771                 }
772             }
773         }).html(error.error);
774     },
775     on_logout: function() {
776     }
777 });
778
779 openerp.web.Menu =  openerp.web.Widget.extend(/** @lends openerp.web.Menu# */{
780     /**
781      * @constructs openerp.web.Menu
782      * @extends openerp.web.Widget
783      *
784      * @param parent
785      * @param element_id
786      * @param secondary_menu_id
787      */
788     init: function(parent, element_id, secondary_menu_id) {
789         this._super(parent, element_id);
790         this.secondary_menu_id = secondary_menu_id;
791         this.$secondary_menu = $("#" + secondary_menu_id).hide();
792         this.menu = false;
793         this.folded = false;
794         if (window.localStorage) {
795             this.folded = localStorage.getItem('oe_menu_folded') === 'true';
796         }
797         this.float_timeout = 700;
798     },
799     start: function() {
800         this.$secondary_menu.addClass(this.folded ? 'oe_folded' : 'oe_unfolded');
801     },
802     do_reload: function() {
803         this.rpc("/web/menu/load", {}, this.on_loaded);
804     },
805     on_loaded: function(data) {
806         this.data = data;
807         this.$element.html(QWeb.render("Menu", { widget : this }));
808         this.$secondary_menu.html(QWeb.render("Menu.secondary", { widget : this }));
809         this.$element.add(this.$secondary_menu).find("a").click(this.on_menu_click);
810         this.$secondary_menu.find('.oe_toggle_secondary_menu').click(this.on_toggle_fold);
811     },
812     on_toggle_fold: function() {
813         this.$secondary_menu.toggleClass('oe_folded').toggleClass('oe_unfolded');
814         if (this.folded) {
815             this.$secondary_menu.find('.oe_secondary_menu.active').show();
816         } else {
817             this.$secondary_menu.find('.oe_secondary_menu').hide();
818         }
819         this.folded = !this.folded;
820         if (window.localStorage) {
821             localStorage.setItem('oe_menu_folded', this.folded.toString());
822         }
823     },
824     on_menu_click: function(ev, id) {
825         id = id || 0;
826         var $clicked_menu, manual = false;
827
828         if (id) {
829             // We can manually activate a menu with it's id (for hash url mapping)
830             manual = true;
831             $clicked_menu = this.$element.find('a[data-menu=' + id + ']');
832             if (!$clicked_menu.length) {
833                 $clicked_menu = this.$secondary_menu.find('a[data-menu=' + id + ']');
834             }
835         } else {
836             $clicked_menu = $(ev.currentTarget);
837             id = $clicked_menu.data('menu');
838         }
839
840         if (this.do_menu_click($clicked_menu, manual) && id) {
841             this.session.active_id = id;
842             this.rpc('/web/menu/action', {'menu_id': id}, this.on_menu_action_loaded);
843         }
844         if (ev) {
845             ev.stopPropagation();
846         }
847         return false;
848     },
849     do_menu_click: function($clicked_menu, manual) {
850         var $sub_menu, $main_menu,
851             active = $clicked_menu.is('.active'),
852             sub_menu_visible = false;
853
854         if (this.$secondary_menu.has($clicked_menu).length) {
855             $sub_menu = $clicked_menu.parents('.oe_secondary_menu');
856             $main_menu = this.$element.find('a[data-menu=' + $sub_menu.data('menu-parent') + ']');
857         } else {
858             $sub_menu = this.$secondary_menu.find('.oe_secondary_menu[data-menu-parent=' + $clicked_menu.attr('data-menu') + ']');
859             $main_menu = $clicked_menu;
860         }
861
862         sub_menu_visible = $sub_menu.is(':visible');
863         this.$secondary_menu.find('.oe_secondary_menu').hide();
864
865         $('.active', this.$element.add(this.$secondary_menu.show())).removeClass('active');
866         $main_menu.add($clicked_menu).add($sub_menu).addClass('active');
867
868         if (!(this.folded && manual)) {
869             this.do_show_secondary($sub_menu, $main_menu);
870         }
871
872         if ($main_menu != $clicked_menu) {
873             if ($clicked_menu.is('.submenu')) {
874                 $sub_menu.find('.submenu.opened').each(function() {
875                     if (!$(this).next().has($clicked_menu).length && !$(this).is($clicked_menu)) {
876                         $(this).removeClass('opened').next().hide();
877                     }
878                 });
879                 $clicked_menu.toggleClass('opened').next().toggle();
880             } else if ($clicked_menu.is('.leaf')) {
881                 $sub_menu.toggle(!this.folded);
882                 return true;
883             }
884         } else if (this.folded) {
885             if (active && sub_menu_visible) {
886                 $sub_menu.hide();
887                 return true;
888             }
889             return manual;
890         } else {
891             return true;
892         }
893         return false;
894     },
895     do_show_secondary: function($sub_menu, $main_menu) {
896         var self = this;
897         if (this.folded) {
898             var css = $main_menu.position(),
899                 fold_width = this.$secondary_menu.width() + 2,
900                 window_width = $(window).width();
901             css.top += 33;
902             css.left -= Math.round(($sub_menu.width() - $main_menu.width()) / 2);
903             css.left = css.left < fold_width ? fold_width : css.left;
904             if ((css.left + $sub_menu.width()) > window_width) {
905                 delete(css.left);
906                 css.right = 1;
907             }
908             $sub_menu.css(css);
909             $sub_menu.mouseenter(function() {
910                 clearTimeout($sub_menu.data('timeoutId'));
911             }).mouseleave(function(evt) {
912                 var timeoutId = setTimeout(function() {
913                     if (self.folded) {
914                         $sub_menu.hide();
915                     }
916                 }, self.float_timeout);
917                 $sub_menu.data('timeoutId', timeoutId);
918             });
919         }
920         $sub_menu.show();
921     },
922     on_menu_action_loaded: function(data) {
923         var self = this;
924         if (data.action.length) {
925             var action = data.action[0][2];
926             self.on_action(action);
927         }
928     },
929     on_action: function(action) {
930     }
931 });
932
933 openerp.web.WebClient = openerp.web.Widget.extend(/** @lends openerp.web.WebClient */{
934     /**
935      * @constructs openerp.web.WebClient
936      * @extends openerp.web.Widget
937      *
938      * @param element_id
939      */
940     init: function(element_id) {
941         this._super(null, element_id);
942         openerp.webclient = this;
943
944         QWeb.add_template("/web/static/src/xml/base.xml");
945         var params = {};
946         if(jQuery.param != undefined && jQuery.deparam(jQuery.param.querystring()).kitten != undefined) {
947             this.$element.addClass("kitten-mode-activated");
948         }
949         this.$element.html(QWeb.render("Interface", params));
950
951         this.notification = new openerp.web.Notification();
952         this.session = new openerp.web.Session();
953         this.loading = new openerp.web.Loading(this,"oe_loading");
954         this.crashmanager =  new openerp.web.CrashManager(this);
955
956         this.header = new openerp.web.Header(this);
957         this.login = new openerp.web.Login(this);
958         this.header.on_logout.add(this.login.on_logout);
959         this.header.on_action.add(this.on_menu_action);
960
961         this.session.on_session_invalid.add(this.login.do_ask_login);
962         this.session.on_session_valid.add_last(this.header.do_update);
963         this.session.on_session_invalid.add_last(this.header.do_update);
964         this.session.on_session_valid.add_last(this.on_logged);
965
966         this.menu = new openerp.web.Menu(this, "oe_menu", "oe_secondary_menu");
967         this.menu.on_action.add(this.on_menu_action);
968
969         this.url_internal_hashchange = false;
970         this.url_external_hashchange = false;
971         jQuery(window).bind('hashchange', this.on_url_hashchange);
972
973     },
974     start: function() {
975         this._super.apply(this, arguments);
976         this.notification.prependTo(this.$element);
977         this.header.appendTo($("#oe_header"));
978         this.session.start();
979         this.login.appendTo($('#oe_login'));
980         this.menu.start();
981     },
982     do_reload: function() {
983         this.session.session_restore();
984         this.menu.do_reload();
985     },
986     do_notify: function() {
987         var n = this.notification;
988         n.notify.apply(n, arguments);
989     },
990     do_warn: function() {
991         var n = this.notification;
992         n.warn.apply(n, arguments);
993     },
994     on_logged: function() {
995         this.menu.do_reload();
996         if(this.action_manager)
997             this.action_manager.stop();
998         this.action_manager = new openerp.web.ActionManager(this);
999         this.action_manager.appendTo($("#oe_app"));
1000         this.action_manager.do_url_set_hash.add_last(this.do_url_set_hash);
1001
1002         // if using saved actions, load the action and give it to action manager
1003         var parameters = jQuery.deparam(jQuery.param.querystring());
1004         if (parameters["s_action"] != undefined) {
1005             var key = parseInt(parameters["s_action"], 10);
1006             var self = this;
1007             this.rpc("/web/session/get_session_action", {key:key}, function(action) {
1008                 self.action_manager.do_action(action);
1009             });
1010         } else if (openerp._modules_loaded) { // TODO: find better option than this
1011             this.load_url_state()
1012         } else {
1013             this.session.on_modules_loaded.add({
1014                 callback: $.proxy(this, 'load_url_state'),
1015                 unique: true,
1016                 position: 'last'
1017             })
1018         }
1019     },
1020     /**
1021      * Loads state from URL if any, or checks if there is a home action and
1022      * loads that, assuming we're at the index
1023      */
1024     load_url_state: function () {
1025         var self = this;
1026         // TODO: add actual loading if there is url state to unpack, test on window.location.hash
1027         // not logged in
1028         if (!this.session.uid) { return; }
1029         var ds = new openerp.web.DataSetSearch(this, 'res.users');
1030         ds.read_ids([this.session.uid], ['action_id'], function (users) {
1031             var home_action = users[0].action_id;
1032             if (!home_action) {
1033                 self.default_home();
1034                 return;
1035             }
1036             self.execute_home_action(home_action[0], ds);
1037         })
1038     },
1039     default_home: function () {
1040     },
1041     /**
1042      * Bundles the execution of the home action
1043      *
1044      * @param {Number} action action id
1045      * @param {openerp.web.DataSet} dataset action executor
1046      */
1047     execute_home_action: function (action, dataset) {
1048         var self = this;
1049         this.rpc('/web/action/load', {
1050             action_id: action,
1051             context: dataset.get_context()
1052         }, function (meh) {
1053             var action = meh.result;
1054             action.context = _.extend(action.context || {}, {
1055                 active_id: false,
1056                 active_ids: [false],
1057                 active_model: dataset.model
1058             });
1059             self.action_manager.do_action(action);
1060         });
1061     },
1062     do_url_set_hash: function(url) {
1063         if(!this.url_external_hashchange) {
1064             this.url_internal_hashchange = true;
1065             jQuery.bbq.pushState(url);
1066         }
1067     },
1068     on_url_hashchange: function() {
1069         if(this.url_internal_hashchange) {
1070             this.url_internal_hashchange = false;
1071         } else {
1072             var url = jQuery.deparam.fragment();
1073             this.url_external_hashchange = true;
1074             this.action_manager.on_url_hashchange(url);
1075             this.url_external_hashchange = false;
1076         }
1077     },
1078     on_menu_action: function(action) {
1079         this.action_manager.do_action(action);
1080     },
1081     do_about: function() {
1082     },
1083
1084 });
1085
1086 };
1087
1088 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: