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