[MERGE]Merge with trunk upto revision no 1043.
[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         var fetch_db = this.rpc("/web/database/get_list", {}, function(result) {
224             self.db_list = result.db_list;
225         });
226         var fetch_langs = this.rpc("/web/session/get_lang_list", {}, function(result) {
227             if (result.error) {
228                 self.display_error(result);
229                 return;
230             }
231             self.lang_list = result.lang_list;
232         });
233         $.when(fetch_db, fetch_langs).then(function () {self.do_create();});
234
235         this.$element.find('#db-create').click(this.do_create);
236         this.$element.find('#db-drop').click(this.do_drop);
237         this.$element.find('#db-backup').click(this.do_backup);
238         this.$element.find('#db-restore').click(this.do_restore);
239         this.$element.find('#db-change-password').click(this.do_change_password);
240         this.$element.find('#back-to-login').click(function() {
241             self.stop();
242         });
243     },
244     stop: function () {
245         this.$option_id.empty();
246
247         this.$element
248             .find('#db-create, #db-drop, #db-backup, #db-restore, #db-change-password, #back-to-login')
249                 .unbind('click')
250             .end()
251             .closest(".openerp")
252                 .addClass("login-mode")
253                 .removeClass("database_block")
254             .end()
255             .empty();
256
257     },
258     /**
259      * Converts a .serializeArray() result into a dict. Does not bother folding
260      * multiple identical keys into an array, last key wins.
261      *
262      * @param {Array} array
263      */
264     to_object: function (array) {
265         var result = {};
266         _(array).each(function (record) {
267             result[record.name] = record.value;
268         });
269         return result;
270     },
271     /**
272      * Waits until the new database is done creating, then unblocks the UI and
273      * logs the user in as admin
274      *
275      * @param {Number} db_creation_id identifier for the db-creation operation, used to fetch the current installation progress
276      * @param {Object} info info fields for this database creation
277      * @param {String} info.db name of the database being created
278      * @param {String} info.password super-admin password for the database
279      */
280     wait_for_newdb: function (db_creation_id, info) {
281         var self = this;
282         self.rpc('/web/database/progress', {
283             id: db_creation_id,
284             password: info.password
285         }, function (result) {
286             var progress = result[0];
287             // I'd display a progress bar, but turns out the progress status
288             // the server report kind-of blows goats: it's at 0 for ~75% of
289             // the installation, then jumps to 75%, then jumps down to either
290             // 0 or ~40%, then back up to 75%, then terminates. Let's keep that
291             // mess hidden behind a not-very-useful but not overly weird
292             // message instead.
293             if (progress < 1) {
294                 setTimeout(function () {
295                     self.wait_for_newdb(db_creation_id, info);
296                 }, 500);
297                 return;
298             }
299
300             var admin = result[1][0];
301             setTimeout(function () {
302                 self.stop();
303                 self.widget_parent.do_login(
304                         info.db, admin.login, admin.password);
305                 $.unblockUI();
306             });
307         });
308     },
309     /**
310      * Displays an error dialog resulting from the various RPC communications
311      * failing over themselves
312      *
313      * @param {Object} error error description
314      * @param {String} error.title title of the error dialog
315      * @param {String} error.error message of the error dialog
316      */
317     display_error: function (error) {
318         return $('<div>').dialog({
319             modal: true,
320             title: error.title,
321             buttons: {
322                 Ok: function() {
323                     $(this).dialog("close");
324                 }
325             }
326         }).html(error.error);
327     },
328     do_create: function() {
329         var self = this;
330         self.$option_id.html(QWeb.render("Database.CreateDB", self));
331         self.$option_id.find("form[name=create_db_form]").validate({
332             submitHandler: function (form) {
333                 var fields = $(form).serializeArray();
334                 $.blockUI({message:'<img src="/web/static/src/img/throbber2.gif">'});
335                 self.rpc("/web/database/create", {'fields': fields}, function(result) {
336                     if (result.error) {
337                         $.unblockUI();
338                         self.display_error(result);
339                         return;
340                     }
341                     self.db_list.push(self.to_object(fields)['db_name']);
342                     self.db_list.sort();
343                     var form_obj = self.to_object(fields);
344                     self.wait_for_newdb(result, {
345                         password: form_obj['super_admin_pwd'],
346                         db: form_obj['db_name']
347                     });
348                 });
349             }
350         });
351     },
352     do_drop: function() {
353         var self = this;
354         self.$option_id.html(QWeb.render("DropDB", self));
355         self.$option_id.find("form[name=drop_db_form]").validate({
356             submitHandler: function (form) {
357                 var $form = $(form),
358                     fields = $form.serializeArray(),
359                     $db_list = $form.find('select[name=drop_db]'),
360                     db = $db_list.val();
361
362                 if (!confirm("Do you really want to delete the database: " + db + " ?")) {
363                     return;
364                 }
365                 self.rpc("/web/database/drop", {'fields': fields}, function(result) {
366                     if (result.error) {
367                         self.display_error(result);
368                         return;
369                     }
370                     $db_list.find(':selected').remove();
371                     self.db_list.splice(_.indexOf(self.db_list, db, true), 1);
372                     self.notification.notify("Dropping database", "The database '" + db + "' has been dropped");
373                 });
374             }
375         });
376     },
377     do_backup: function() {
378         var self = this;
379         self.$option_id
380             .html(QWeb.render("BackupDB", self))
381             .find("form[name=backup_db_form]").validate({
382             submitHandler: function (form) {
383                 $.blockUI({message:'<img src="/web/static/src/img/throbber2.gif">'});
384                 self.session.get_file({
385                     form: form,
386                     error: function (body) {
387                         var error = body.firstChild.data.split('|');
388                         self.display_error({
389                             title: error[0],
390                             error: error[1]
391                         });
392                     },
393                     complete: $.unblockUI
394                 });
395             }
396         });
397     },
398     do_restore: function() {
399         var self = this;
400         self.$option_id.html(QWeb.render("RestoreDB", self));
401
402         self.$option_id.find("form[name=restore_db_form]").validate({
403             submitHandler: function (form) {
404                 $.blockUI({message:'<img src="/web/static/src/img/throbber2.gif">'});
405                 $(form).ajaxSubmit({
406                     url: '/web/database/restore',
407                     type: 'POST',
408                     resetForm: true,
409                     success: function (body) {
410                         // TODO: ui manipulations
411                         // note: response objects don't work, but we have the
412                         // HTTP body of the response~~
413
414                         // If empty body, everything went fine
415                         if (!body) { return; }
416
417                         if (body.indexOf('403 Forbidden') !== -1) {
418                             self.display_error({
419                                 title: 'Access Denied',
420                                 error: 'Incorrect super-administrator password'
421                             })
422                         } else {
423                             self.display_error({
424                                 title: 'Restore Database',
425                                 error: 'Could not restore the database'
426                             })
427                         }
428                     },
429                     complete: function () {
430                         $.unblockUI();
431                     }
432                 });
433             }
434         });
435     },
436     do_change_password: function() {
437         var self = this;
438         self.$option_id.html(QWeb.render("Change_DB_Pwd", self));
439
440         self.$option_id.find("form[name=change_pwd_form]").validate({
441             messages: {
442                 old_pwd: "Please enter your previous password",
443                 new_pwd: "Please enter your new password",
444                 confirm_pwd: {
445                     required: "Please confirm your new password",
446                     equalTo: "The confirmation does not match the password"
447                 }
448             },
449             submitHandler: function (form) {
450                 self.rpc("/web/database/change_password", {
451                     'fields': $(form).serializeArray()
452                 }, function(result) {
453                     if (result.error) {
454                         self.display_error(result);
455                         return;
456                     }
457                     self.notification.notify("Changed Password", "Password has been changed successfully");
458                 });
459             }
460         });
461     }
462 });
463
464 openerp.web.Login =  openerp.web.Widget.extend(/** @lends openerp.web.Login# */{
465     remember_creditentials: true,
466     /**
467      * @constructs openerp.web.Login
468      * @extends openerp.web.Widget
469      *
470      * @param parent
471      * @param element_id
472      */
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     },
780     start: function() {
781         this.rpc("/web/menu/load", {}, this.on_loaded);
782     },
783     on_loaded: function(data) {
784         this.data = data;
785         this.$element.html(QWeb.render("Menu", this.data));
786         for (var i = 0; i < this.data.data.children.length; i++) {
787             var v = { menu : this.data.data.children[i] };
788             this.$secondary_menu.append(QWeb.render("Menu.secondary", v));
789         }
790         this.$secondary_menu.find("div.menu_accordion").accordion({
791             animated : false,
792             autoHeight : false,
793             icons : false
794         });
795         this.$secondary_menu.find("div.submenu_accordion").accordion({
796             animated : false,
797             autoHeight : false,
798             active: false,
799             collapsible: true,
800             header: 'h4'
801         });
802
803         this.$element.add(this.$secondary_menu).find("a").click(this.on_menu_click);
804     },
805     on_menu_click: function(ev, id) {
806         id = id || 0;
807         var $menu, $parent, $secondary;
808
809         if (id) {
810             // We can manually activate a menu with it's id (for hash url mapping)
811             $menu = this.$element.find('a[data-menu=' + id + ']');
812             if (!$menu.length) {
813                 $menu = this.$secondary_menu.find('a[data-menu=' + id + ']');
814             }
815         } else {
816             $menu = $(ev.currentTarget);
817             id = $menu.data('menu');
818         }
819         if (this.$secondary_menu.has($menu).length) {
820             $secondary = $menu.parents('.menu_accordion');
821             $parent = this.$element.find('a[data-menu=' + $secondary.data('menu-parent') + ']');
822         } else {
823             $parent = $menu;
824             $secondary = this.$secondary_menu.find('.menu_accordion[data-menu-parent=' + $menu.attr('data-menu') + ']');
825         }
826
827         this.$secondary_menu.find('.menu_accordion').hide();
828         // TODO: ui-accordion : collapse submenus and expand the good one
829         $secondary.show();
830
831         if (id) {
832             this.session.active_id = id;
833             this.rpc('/web/menu/action', {'menu_id': id},
834                     this.on_menu_action_loaded);
835         }
836
837         $('.active', this.$element.add(this.$secondary_menu.show())).removeClass('active');
838         $parent.addClass('active');
839         $menu.addClass('active');
840         $menu.parent('h4').addClass('active');
841
842         if (this.$secondary_menu.has($menu).length) {
843             return !$menu.is(".leaf");
844         } else {
845             return false;
846         }
847     },
848     on_menu_action_loaded: function(data) {
849         var self = this;
850         if (data.action.length) {
851             var action = data.action[0][2];
852             self.on_action(action);
853         }
854     },
855     on_action: function(action) {
856     }
857 });
858
859 openerp.web.WebClient = openerp.web.Widget.extend(/** @lends openerp.web.WebClient */{
860     /**
861      * @constructs openerp.web.WebClient
862      * @extends openerp.web.Widget
863      *
864      * @param element_id
865      */
866     init: function(element_id) {
867         this._super(null, element_id);
868         openerp.webclient = this;
869
870         QWeb.add_template("/web/static/src/xml/base.xml");
871         var params = {};
872         if(jQuery.param != undefined && jQuery.deparam(jQuery.param.querystring()).kitten != undefined) {
873             this.$element.addClass("kitten-mode-activated");
874         }
875         this.$element.html(QWeb.render("Interface", params));
876
877         this.session = new openerp.web.Session();
878         this.loading = new openerp.web.Loading(this,"oe_loading");
879         this.crashmanager =  new openerp.web.CrashManager(this);
880         this.crashmanager.start();
881
882         // Do you autorize this ? will be replaced by notify() in controller
883         openerp.web.Widget.prototype.notification = new openerp.web.Notification(this, "oe_notification");
884
885         this.header = new openerp.web.Header(this);
886         this.login = new openerp.web.Login(this, "oe_login");
887         this.header.on_logout.add(this.login.on_logout);
888         this.header.on_action.add(this.on_menu_action);
889
890         this.session.on_session_invalid.add(this.login.do_ask_login);
891         this.session.on_session_valid.add_last(this.header.do_update);
892         this.session.on_session_invalid.add_last(this.header.do_update);
893         this.session.on_session_valid.add_last(this.on_logged);
894
895         this.menu = new openerp.web.Menu(this, "oe_menu", "oe_secondary_menu");
896         this.menu.on_action.add(this.on_menu_action);
897
898         this.url_internal_hashchange = false;
899         this.url_external_hashchange = false;
900         jQuery(window).bind('hashchange', this.on_url_hashchange);
901
902     },
903     start: function() {
904         this.header.appendTo($("#oe_header"));
905         this.session.start();
906         this.login.start();
907         this.menu.start();
908         console.debug("The openerp client has been initialized.");
909     },
910     on_logged: function() {
911         if(this.action_manager)
912             this.action_manager.stop();
913         this.action_manager = new openerp.web.ActionManager(this);
914         this.action_manager.appendTo($("#oe_app"));
915         this.action_manager.do_url_set_hash.add_last(this.do_url_set_hash);
916
917         // if using saved actions, load the action and give it to action manager
918         var parameters = jQuery.deparam(jQuery.param.querystring());
919         if (parameters["s_action"] != undefined) {
920             var key = parseInt(parameters["s_action"], 10);
921             var self = this;
922             this.rpc("/web/session/get_session_action", {key:key}, function(action) {
923                 self.action_manager.do_action(action);
924             });
925         } else if (openerp._modules_loaded) { // TODO: find better option than this
926             this.load_url_state()
927         } else {
928             this.session.on_modules_loaded.add({
929                 callback: $.proxy(this, 'load_url_state'),
930                 unique: true,
931                 position: 'last'
932             })
933         }
934     },
935     /**
936      * Loads state from URL if any, or checks if there is a home action and
937      * loads that, assuming we're at the index
938      */
939     load_url_state: function () {
940         var self = this;
941         // TODO: add actual loading if there is url state to unpack, test on window.location.hash
942         // not logged in
943         if (!this.session.uid) { return; }
944         var ds = new openerp.web.DataSetSearch(this, 'res.users');
945         ds.read_ids([this.session.uid], ['action_id'], function (users) {
946             var home_action = users[0].action_id;
947             if (!home_action) {
948                 self.default_home();
949                 return;
950             }
951             self.execute_home_action(home_action[0], ds);
952         })
953     },
954     default_home: function () {
955     },
956     /**
957      * Bundles the execution of the home action
958      *
959      * @param {Number} action action id
960      * @param {openerp.web.DataSet} dataset action executor
961      */
962     execute_home_action: function (action, dataset) {
963         var self = this;
964         this.rpc('/web/action/load', {
965             action_id: action,
966             context: dataset.get_context()
967         }, function (meh) {
968             var action = meh.result;
969             action.context = _.extend(action.context || {}, {
970                 active_id: false,
971                 active_ids: [false],
972                 active_model: dataset.model
973             });
974             self.action_manager.do_action(action);
975         });
976     },
977     do_url_set_hash: function(url) {
978         if(!this.url_external_hashchange) {
979             console.log("url set #hash to",url);
980             this.url_internal_hashchange = true;
981             jQuery.bbq.pushState(url);
982         }
983     },
984     on_url_hashchange: function() {
985         if(this.url_internal_hashchange) {
986             this.url_internal_hashchange = false;
987             console.log("url jump to FLAG OFF");
988         } else {
989             var url = jQuery.deparam.fragment();
990             console.log("url jump to",url);
991             this.url_external_hashchange = true;
992             this.action_manager.on_url_hashchange(url);
993             this.url_external_hashchange = false;
994         }
995     },
996     on_menu_action: function(action) {
997         this.action_manager.do_action(action);
998     },
999     do_about: function() {
1000     }
1001 });
1002
1003 };
1004
1005 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: