[fix] problem in database when creating a new database
[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     /**
9      * @constructs openerp.web.Notification
10      * @extends openerp.web.Widget
11      *
12      * @param parent
13      * @param element_id
14      */
15     init: function(parent, element_id) {
16         this._super(parent, element_id);
17         this.$element.notify({
18             speed: 500,
19             expires: 1500
20         });
21     },
22     notify: function(title, text) {
23         this.$element.notify('create', {
24             title: title,
25             text: text
26         });
27     },
28     warn: function(title, text) {
29         this.$element.notify('create', 'oe_notification_alert', {
30             title: title,
31             text: text
32         });
33     }
34 });
35
36 openerp.web.Dialog = openerp.web.OldWidget.extend(/** @lends openerp.web.Dialog# */{
37     dialog_title: "",
38     identifier_prefix: 'dialog',
39     /**
40      * @constructs openerp.web.Dialog
41      * @extends openerp.web.OldWidget
42      *
43      * @param parent
44      * @param dialog_options
45      */
46     init: function (parent, dialog_options) {
47         var self = this;
48         this._super(parent);
49         this.dialog_options = {
50             modal: true,
51             width: 'auto',
52             min_width: 0,
53             max_width: '100%',
54             height: 'auto',
55             min_height: 0,
56             max_height: '100%',
57             autoOpen: false,
58             buttons: {},
59             beforeClose: function () { self.on_close(); }
60         };
61         for (var f in this) {
62             if (f.substr(0, 10) == 'on_button_') {
63                 this.dialog_options.buttons[f.substr(10)] = this[f];
64             }
65         }
66         if (dialog_options) {
67             this.set_options(dialog_options);
68         }
69     },
70     set_options: function(options) {
71         options = options || {};
72         options.width = this.get_width(options.width || this.dialog_options.width);
73         options.min_width = this.get_width(options.min_width || this.dialog_options.min_width);
74         options.max_width = this.get_width(options.max_width || this.dialog_options.max_width);
75         options.height = this.get_height(options.height || this.dialog_options.height);
76         options.min_height = this.get_height(options.min_height || this.dialog_options.min_height);
77         options.max_height = this.get_height(options.max_height || this.dialog_options.max_width);
78
79         if (options.width !== 'auto') {
80             if (options.width > options.max_width) options.width = options.max_width;
81             if (options.width < options.min_width) options.width = options.min_width;
82         }
83         if (options.height !== 'auto') {
84             if (options.height > options.max_height) options.height = options.max_height;
85             if (options.height < options.min_height) options.height = options.min_height;
86         }
87         if (!options.title && this.dialog_title) {
88             options.title = this.dialog_title;
89         }
90         _.extend(this.dialog_options, options);
91     },
92     get_width: function(val) {
93         return this.get_size(val.toString(), $(window.top).width());
94     },
95     get_height: function(val) {
96         return this.get_size(val.toString(), $(window.top).height());
97     },
98     get_size: function(val, available_size) {
99         if (val === 'auto') {
100             return val;
101         } else if (val.slice(-1) == "%") {
102             return Math.round(available_size / 100 * parseInt(val.slice(0, -1), 10));
103         } else {
104             return parseInt(val, 10);
105         }
106     },
107     start: function () {
108         this.$dialog = $('<div id="' + this.element_id + '"></div>').dialog(this.dialog_options);
109         this._super();
110         return this;
111     },
112     open: function(dialog_options) {
113         // TODO fme: bind window on resize
114         if (this.template) {
115             this.$element.html(this.render());
116         }
117         this.set_options(dialog_options);
118         this.$dialog.dialog(this.dialog_options).dialog('open');
119         return this;
120     },
121     close: function() {
122         // Closes the dialog but leave it in a state where it could be opened again.
123         this.$dialog.dialog('close');
124     },
125     on_close: function() {
126     },
127     stop: function () {
128         // Destroy widget
129         this.close();
130         this.$dialog.dialog('destroy');
131         this._super();
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         this._super();
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.widget_parent.do_login(
303                         info.db, admin.login, admin.password);
304                 self.stop();
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     template: "Login",
468     identifier_prefix: 'oe-app-login-',
469     /**
470      * @constructs openerp.web.Login
471      * @extends openerp.web.Widget
472      *
473      * @param parent
474      * @param element_id
475      */
476
477     init: function(parent) {
478         this._super(parent);
479         this.has_local_storage = typeof(localStorage) != 'undefined';
480         this.selected_db = null;
481         this.selected_login = null;
482
483         if (this.has_local_storage && this.remember_creditentials) {
484             this.selected_db = localStorage.getItem('last_db_login_success');
485             this.selected_login = localStorage.getItem('last_login_login_success');
486             if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
487                 this.selected_password = localStorage.getItem('last_password_login_success');
488             }
489         }
490     },
491     start: function() {
492         var self = this;
493         this.database = new openerp.web.Database(
494                 this, "oe_database", "oe_db_options");
495
496         this.$element.find('#oe-db-config').click(function() {
497             self.database.start();
498         });
499
500         this.$element.find("form").submit(this.on_submit);
501
502         this.rpc("/web/database/get_list", {}, function(result) {
503             var tpl = openerp.web.qweb.render('Login_dblist', {db_list: result.db_list, selected_db: self.selected_db});
504             self.$element.find("input[name=db]").replaceWith(tpl)
505         }, 
506         function(error, event) {
507             if (error.data.fault_code === 'AccessDenied') {
508                 event.preventDefault();
509             }
510         });
511
512     },
513     on_login_invalid: function() {
514         this.$element.closest(".openerp").addClass("login-mode");
515     },
516     on_login_valid: function() {
517         this.$element.closest(".openerp").removeClass("login-mode");
518     },
519     on_submit: function(ev) {
520         ev.preventDefault();
521         var $e = this.$element;
522         var db = $e.find("form [name=db]").val();
523         var login = $e.find("form input[name=login]").val();
524         var password = $e.find("form input[name=password]").val();
525
526         this.do_login(db, login, password);
527     },
528     /**
529      * Performs actual login operation, and UI-related stuff
530      *
531      * @param {String} db database to log in
532      * @param {String} login user login
533      * @param {String} password user password
534      */
535     do_login: function (db, login, password) {
536         var self = this;
537         this.session.session_login(db, login, password, function() {
538             if(self.session.session_is_valid()) {
539                 if (self.has_local_storage) {
540                     if(self.remember_creditentials) {
541                         localStorage.setItem('last_db_login_success', db);
542                         localStorage.setItem('last_login_login_success', login);
543                         if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
544                             localStorage.setItem('last_password_login_success', password);
545                         }
546                     } else {
547                         localStorage.setItem('last_db_login_success', '');
548                         localStorage.setItem('last_login_login_success', '');
549                         localStorage.setItem('last_password_login_success', '');
550                     }
551                 }
552                 self.on_login_valid();
553             } else {
554                 self.$element.addClass("login_invalid");
555                 self.on_login_invalid();
556             }
557         });
558     },
559     do_ask_login: function(continuation) {
560         this.on_login_invalid();
561         this.$element
562             .removeClass("login_invalid");
563         this.on_login_valid.add({
564             position: "last",
565             unique: true,
566             callback: continuation || function() {}
567         });
568     },
569     on_logout: function() {
570         this.session.logout();
571     }
572 });
573
574 openerp.web.Header =  openerp.web.Widget.extend(/** @lends openerp.web.Header# */{
575     template: "Header",
576     identifier_prefix: 'oe-app-header-',
577     /**
578      * @constructs openerp.web.Header
579      * @extends openerp.web.Widget
580      *
581      * @param parent
582      */
583     init: function(parent) {
584         this._super(parent);
585         this.qs = "?" + jQuery.param.querystring();
586         this.$content = $();
587         this.update_promise = $.Deferred().resolve();
588     },
589     start: function() {
590         this._super();
591     },
592     do_update: function () {
593         var self = this;
594         var fct = function() {
595             self.$content.remove();
596             if (!self.session.uid)
597                 return;
598             var func = new openerp.web.Model(self.session, "res.users").get_func("read");
599             return func(self.session.uid, ["name", "company_id"]).pipe(function(res) {
600                 self.$content = $(QWeb.render("Header-content", {widget: self, user: res}));
601                 self.$content.appendTo(self.$element);
602                 self.$element.find(".logout").click(self.on_logout);
603                 self.$element.find("a.preferences").click(self.on_preferences);
604                 self.$element.find(".about").click(self.on_about);
605                 return self.shortcut_load();
606             });
607         };
608         this.update_promise = this.update_promise.pipe(fct, fct);
609     },
610     on_about: function() {
611         var self = this;
612         self.rpc("/web/webclient/version_info", {}).then(function(res) {
613             var $help = $(QWeb.render("About-Page", {version_info: res}));
614             $help.dialog({autoOpen: true,
615                 modal: true, width: 960, title: "About"});
616         });
617     },
618     shortcut_load :function(){
619         var self = this,
620             sc = self.session.shortcuts,
621             shortcuts_ds = new openerp.web.DataSet(this, 'ir.ui.view_sc');
622         // TODO: better way to communicate between sections.
623         // sc.bindings, because jquery does not bind/trigger on arrays...
624         if (!sc.binding) {
625             sc.binding = {};
626             $(sc.binding).bind({
627                 'add': function (e, attrs) {
628                     shortcuts_ds.create(attrs, function (out) {
629                         $('<li>', {
630                             'data-shortcut-id':out.result,
631                             'data-id': attrs.res_id
632                         }).text(attrs.name)
633                           .appendTo(self.$element.find('.oe-shortcuts ul'));
634                         attrs.id = out.result;
635                         sc.push(attrs);
636                     });
637                 },
638                 'remove-current': function () {
639                     var menu_id = self.session.active_id;
640                     var $shortcut = self.$element
641                         .find('.oe-shortcuts li[data-id=' + menu_id + ']');
642                     var shortcut_id = $shortcut.data('shortcut-id');
643                     $shortcut.remove();
644                     shortcuts_ds.unlink([shortcut_id]);
645                     var sc_new = _.reject(sc, function(shortcut){ return shortcut_id === shortcut.id});
646                     sc.splice(0, sc.length);
647                     sc.push.apply(sc, sc_new);
648                     }
649             });
650         }
651         return this.rpc('/web/session/sc_list', {}, function(shortcuts) {
652             sc.splice(0, sc.length);
653             sc.push.apply(sc, shortcuts);
654
655             self.$element.find('.oe-shortcuts')
656                 .html(QWeb.render('Shortcuts', {'shortcuts': shortcuts}))
657                 .undelegate('li', 'click')
658
659                 .delegate('li', 'click', function(e) {
660                     e.stopPropagation();
661                     var id = $(this).data('id');
662                     self.session.active_id = id;
663                     self.rpc('/web/menu/action', {'menu_id':id}, function(ir_menu_data) {
664                         if (ir_menu_data.action.length){
665                             self.on_action(ir_menu_data.action[0][2]);
666                         }
667                     });
668                 });
669         });
670     },
671
672     on_action: function(action) {
673     },
674     on_preferences: function(){
675         var self = this;
676         var action_manager = new openerp.web.ActionManager(this);
677         var dataset = new openerp.web.DataSet (this,'res.users',this.context);
678         dataset.call ('action_get','',function (result){
679             self.rpc('/web/action/load', {action_id:result}, function(result){
680                 action_manager.do_action(_.extend(result['result'], {
681                     res_id: self.session.uid,
682                     res_model: 'res.users',
683                     flags: {
684                         action_buttons: false,
685                         search_view: false,
686                         sidebar: false,
687                         views_switcher: false,
688                         pager: false
689                     }
690                 }));
691             });
692         });
693         this.dialog = new openerp.web.Dialog(this,{
694             modal: true,
695             title: 'Preferences',
696             width: 600,
697             height: 500,
698             buttons: {
699                 "Change password": function(){
700                     self.change_password();
701             },
702                 Cancel: function(){
703                      $(this).dialog('destroy');
704             },
705                 Save: function(){
706                     var inner_viewmanager = action_manager.inner_viewmanager;
707                     inner_viewmanager.views[inner_viewmanager.active_view].controller.do_save()
708                     .then(function() {
709                         self.dialog.stop();
710                         window.location.reload();
711                     });
712                 }
713             }
714         });
715        this.dialog.start().open();
716        action_manager.appendTo(this.dialog);
717        action_manager.render(this.dialog);
718     },
719
720     change_password :function() {
721         var self = this;
722         this.dialog = new openerp.web.Dialog(this,{
723             modal : true,
724             title : 'Change Password',
725             width : 'auto',
726             height : 'auto'
727         });
728         this.dialog.start().open();
729         this.dialog.$element.html(QWeb.render("Change_Pwd", self));
730         this.dialog.$element.find("form[name=change_password_form]").validate({
731             submitHandler: function (form) {
732                 self.rpc("/web/session/change_password",{
733                     'fields': $(form).serializeArray()
734                 }, function(result) {
735                     if (result.error) {
736                         self.display_error(result);
737                         return;
738                     } else {
739                         self.session.logout();
740                     }
741                 });
742             }
743         });
744     },
745     display_error: function (error) {
746         return $('<div>').dialog({
747             modal: true,
748             title: error.title,
749             buttons: {
750                 Ok: function() {
751                     $(this).dialog("close");
752                 }
753             }
754         }).html(error.error);
755     },
756     on_logout: function() {
757     }
758 });
759
760 openerp.web.Menu =  openerp.web.Widget.extend(/** @lends openerp.web.Menu# */{
761     /**
762      * @constructs openerp.web.Menu
763      * @extends openerp.web.Widget
764      *
765      * @param parent
766      * @param element_id
767      * @param secondary_menu_id
768      */
769     init: function(parent, element_id, secondary_menu_id) {
770         this._super(parent, element_id);
771         this.secondary_menu_id = secondary_menu_id;
772         this.$secondary_menu = $("#" + secondary_menu_id).hide();
773         this.menu = false;
774         this.folded = false;
775         if (window.localStorage) {
776             this.folded = localStorage.getItem('oe_menu_folded') === 'true';
777         }
778         this.float_timeout = 700;
779     },
780     start: function() {
781         this.$secondary_menu.addClass(this.folded ? 'oe_folded' : 'oe_unfolded');
782         this.reload();
783     },
784     reload: function() {
785         this.rpc("/web/menu/load", {}, this.on_loaded);
786     },
787     on_loaded: function(data) {
788         this.data = data;
789         this.$element.html(QWeb.render("Menu", { widget : this }));
790         this.$secondary_menu.html(QWeb.render("Menu.secondary", { widget : this }));
791         this.$element.add(this.$secondary_menu).find("a").click(this.on_menu_click);
792         this.$secondary_menu.find('.oe_toggle_secondary_menu').click(this.on_toggle_fold);
793     },
794     on_toggle_fold: function() {
795         this.$secondary_menu.toggleClass('oe_folded').toggleClass('oe_unfolded');
796         if (this.folded) {
797             this.$secondary_menu.find('.oe_secondary_menu.active').show();
798         } else {
799             this.$secondary_menu.find('.oe_secondary_menu').hide();
800         }
801         this.folded = !this.folded;
802         if (window.localStorage) {
803             localStorage.setItem('oe_menu_folded', this.folded.toString());
804         }
805     },
806     on_menu_click: function(ev, id) {
807         id = id || 0;
808         var $clicked_menu, manual = false;
809
810         if (id) {
811             // We can manually activate a menu with it's id (for hash url mapping)
812             manual = true;
813             $clicked_menu = this.$element.find('a[data-menu=' + id + ']');
814             if (!$clicked_menu.length) {
815                 $clicked_menu = this.$secondary_menu.find('a[data-menu=' + id + ']');
816             }
817         } else {
818             $clicked_menu = $(ev.currentTarget);
819             id = $clicked_menu.data('menu');
820         }
821
822         if (this.do_menu_click($clicked_menu, manual) && id) {
823             this.session.active_id = id;
824             this.rpc('/web/menu/action', {'menu_id': id}, this.on_menu_action_loaded);
825         }
826         ev.stopPropagation();
827         return false;
828     },
829     do_menu_click: function($clicked_menu, manual) {
830         var $sub_menu, $main_menu,
831             active = $clicked_menu.is('.active'),
832             sub_menu_visible = false;
833
834         if (this.$secondary_menu.has($clicked_menu).length) {
835             $sub_menu = $clicked_menu.parents('.oe_secondary_menu');
836             $main_menu = this.$element.find('a[data-menu=' + $sub_menu.data('menu-parent') + ']');
837         } else {
838             $sub_menu = this.$secondary_menu.find('.oe_secondary_menu[data-menu-parent=' + $clicked_menu.attr('data-menu') + ']');
839             $main_menu = $clicked_menu;
840         }
841
842         sub_menu_visible = $sub_menu.is(':visible');
843         this.$secondary_menu.find('.oe_secondary_menu').hide();
844
845         $('.active', this.$element.add(this.$secondary_menu.show())).removeClass('active');
846         $main_menu.add($clicked_menu).add($sub_menu).addClass('active');
847
848         if (!(this.folded && manual)) {
849             this.do_show_secondary($sub_menu, $main_menu);
850         }
851
852         if ($main_menu != $clicked_menu) {
853             if ($clicked_menu.is('.submenu')) {
854                 $sub_menu.find('.submenu.opened').each(function() {
855                     if (!$(this).next().has($clicked_menu).length && !$(this).is($clicked_menu)) {
856                         $(this).removeClass('opened').next().hide();
857                     }
858                 });
859                 $clicked_menu.toggleClass('opened').next().toggle();
860             } else if ($clicked_menu.is('.leaf')) {
861                 $sub_menu.toggle(!this.folded);
862                 return true;
863             }
864         } else if (this.folded) {
865             if (active && sub_menu_visible) {
866                 $sub_menu.hide();
867                 return true;
868             }
869         } else {
870             return true;
871         }
872         return false;
873     },
874     do_show_secondary: function($sub_menu, $main_menu) {
875         var self = this;
876         if (this.folded) {
877             var css = $main_menu.position(),
878                 fold_width = this.$secondary_menu.width() + 2,
879                 window_width = $(window).width();
880             css.top += 33;
881             css.left -= Math.round(($sub_menu.width() - $main_menu.width()) / 2);
882             css.left = css.left < fold_width ? fold_width : css.left;
883             if ((css.left + $sub_menu.width()) > window_width) {
884                 delete(css.left);
885                 css.right = 1;
886             }
887             $sub_menu.css(css);
888             $sub_menu.mouseenter(function() {
889                 clearTimeout($sub_menu.data('timeoutId'));
890             }).mouseleave(function(evt) {
891                 var timeoutId = setTimeout(function() {
892                     if (self.folded) {
893                         $sub_menu.hide();
894                     }
895                 }, self.float_timeout);
896                 $sub_menu.data('timeoutId', timeoutId);
897             });
898         }
899         $sub_menu.show();
900     },
901     on_menu_action_loaded: function(data) {
902         var self = this;
903         if (data.action.length) {
904             var action = data.action[0][2];
905             self.on_action(action);
906         }
907     },
908     on_action: function(action) {
909     }
910 });
911
912 openerp.web.WebClient = openerp.web.Widget.extend(/** @lends openerp.web.WebClient */{
913     /**
914      * @constructs openerp.web.WebClient
915      * @extends openerp.web.Widget
916      *
917      * @param element_id
918      */
919     init: function(element_id) {
920         this._super(null, element_id);
921         openerp.webclient = this;
922
923         QWeb.add_template("/web/static/src/xml/base.xml");
924         var params = {};
925         if(jQuery.param != undefined && jQuery.deparam(jQuery.param.querystring()).kitten != undefined) {
926             this.$element.addClass("kitten-mode-activated");
927         }
928         this.$element.html(QWeb.render("Interface", params));
929
930         this.session = new openerp.web.Session();
931         this.loading = new openerp.web.Loading(this,"oe_loading");
932         this.crashmanager =  new openerp.web.CrashManager(this);
933         this.crashmanager.start();
934
935         // Do you autorize this ? will be replaced by notify() in controller
936         openerp.web.Widget.prototype.notification = new openerp.web.Notification(this, "oe_notification");
937
938         this.header = new openerp.web.Header(this);
939         this.login = new openerp.web.Login(this);
940         this.header.on_logout.add(this.login.on_logout);
941         this.header.on_action.add(this.on_menu_action);
942
943         this.session.on_session_invalid.add(this.login.do_ask_login);
944         this.session.on_session_valid.add_last(this.header.do_update);
945         this.session.on_session_invalid.add_last(this.header.do_update);
946         this.session.on_session_valid.add_last(this.on_logged);
947
948         this.menu = new openerp.web.Menu(this, "oe_menu", "oe_secondary_menu");
949         this.menu.on_action.add(this.on_menu_action);
950
951         this.url_internal_hashchange = false;
952         this.url_external_hashchange = false;
953         jQuery(window).bind('hashchange', this.on_url_hashchange);
954
955     },
956     start: function() {
957         this.header.appendTo($("#oe_header"));
958         this.session.start();
959         this.login.appendTo($('#oe_login'));
960         this.menu.start();
961     },
962     on_logged: function() {
963         if(this.action_manager)
964             this.action_manager.stop();
965         this.action_manager = new openerp.web.ActionManager(this);
966         this.action_manager.appendTo($("#oe_app"));
967         this.action_manager.do_url_set_hash.add_last(this.do_url_set_hash);
968
969         // if using saved actions, load the action and give it to action manager
970         var parameters = jQuery.deparam(jQuery.param.querystring());
971         if (parameters["s_action"] != undefined) {
972             var key = parseInt(parameters["s_action"], 10);
973             var self = this;
974             this.rpc("/web/session/get_session_action", {key:key}, function(action) {
975                 self.action_manager.do_action(action);
976             });
977         } else if (openerp._modules_loaded) { // TODO: find better option than this
978             this.load_url_state()
979         } else {
980             this.session.on_modules_loaded.add({
981                 callback: $.proxy(this, 'load_url_state'),
982                 unique: true,
983                 position: 'last'
984             })
985         }
986     },
987     /**
988      * Loads state from URL if any, or checks if there is a home action and
989      * loads that, assuming we're at the index
990      */
991     load_url_state: function () {
992         var self = this;
993         // TODO: add actual loading if there is url state to unpack, test on window.location.hash
994         // not logged in
995         if (!this.session.uid) { return; }
996         var ds = new openerp.web.DataSetSearch(this, 'res.users');
997         ds.read_ids([this.session.uid], ['action_id'], function (users) {
998             var home_action = users[0].action_id;
999             if (!home_action) {
1000                 self.default_home();
1001                 return;
1002             }
1003             self.execute_home_action(home_action[0], ds);
1004         })
1005     },
1006     default_home: function () {
1007     },
1008     /**
1009      * Bundles the execution of the home action
1010      *
1011      * @param {Number} action action id
1012      * @param {openerp.web.DataSet} dataset action executor
1013      */
1014     execute_home_action: function (action, dataset) {
1015         var self = this;
1016         this.rpc('/web/action/load', {
1017             action_id: action,
1018             context: dataset.get_context()
1019         }, function (meh) {
1020             var action = meh.result;
1021             action.context = _.extend(action.context || {}, {
1022                 active_id: false,
1023                 active_ids: [false],
1024                 active_model: dataset.model
1025             });
1026             self.action_manager.do_action(action);
1027         });
1028     },
1029     do_url_set_hash: function(url) {
1030         if(!this.url_external_hashchange) {
1031             this.url_internal_hashchange = true;
1032             jQuery.bbq.pushState(url);
1033         }
1034     },
1035     on_url_hashchange: function() {
1036         if(this.url_internal_hashchange) {
1037             this.url_internal_hashchange = false;
1038         } else {
1039             var url = jQuery.deparam.fragment();
1040             this.url_external_hashchange = true;
1041             this.action_manager.on_url_hashchange(url);
1042             this.url_external_hashchange = false;
1043         }
1044     },
1045     on_menu_action: function(action) {
1046         this.action_manager.do_action(action);
1047     },
1048     do_about: function() {
1049     }
1050 });
1051
1052 };
1053
1054 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: