[FIX] completely destroy the current openerp session on logout (but leave the webclie...
[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     _t = openerp.web._t;
7
8 openerp.web.Notification =  openerp.web.OldWidget.extend(/** @lends openerp.web.Notification# */{
9     template: 'Notification',
10
11     init: function() {
12         this._super.apply(this, arguments);
13         openerp.notification = this;
14     },
15
16     start: function() {
17         this._super.apply(this, arguments);
18         this.$element.notify({
19             speed: 500,
20             expires: 2500
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
38 openerp.web.Dialog = openerp.web.OldWidget.extend(/** @lends openerp.web.Dialog# */{
39     dialog_title: "",
40     /**
41      * @constructs openerp.web.Dialog
42      * @extends openerp.web.OldWidget
43      *
44      * @param parent
45      * @param options
46      */
47     init: function (parent, options, content) {
48         var self = this;
49         this._super(parent);
50         if (content) {
51             this.$element = content instanceof $ ? content : $(content);
52         }
53         this.dialog_options = {
54             modal: true,
55             destroy_on_close: true,
56             width: $(window).width() * (($(window).width() > 1024) ? 0.5 : 0.75),
57             min_width: 0,
58             max_width: '95%',
59             height: 'auto',
60             min_height: 0,
61             max_height: this.get_height('100%') - 140,
62             autoOpen: false,
63             position: [false, 50],
64             buttons: {},
65             beforeClose: function () { self.on_close(); },
66             resizeStop: this.on_resized
67         };
68         for (var f in this) {
69             if (f.substr(0, 10) == 'on_button_') {
70                 this.dialog_options.buttons[f.substr(10)] = this[f];
71             }
72         }
73         if (options) {
74             _.extend(this.dialog_options, options);
75         }
76         if (this.dialog_options.autoOpen) {
77             this.open();
78         } else {
79             this.$element.dialog(this.get_options());
80         }
81     },
82     get_options: function(options) {
83         var self = this,
84             o = _.extend({}, this.dialog_options, options || {});
85         _.each(['width', 'height'], function(unit) {
86             o[unit] = self['get_' + unit](o[unit]);
87             o['min_' + unit] = self['get_' + unit](o['min_' + unit] || 0);
88             o['max_' + unit] = self['get_' + unit](o['max_' + unit] || 0);
89             if (o[unit] !== 'auto' && o['min_' + unit] && o[unit] < o['min_' + unit]) o[unit] = o['min_' + unit];
90             if (o[unit] !== 'auto' && o['max_' + unit] && o[unit] > o['max_' + unit]) o[unit] = o['max_' + unit];
91         });
92         if (!o.title && this.dialog_title) {
93             o.title = this.dialog_title;
94         }
95         return o;
96     },
97     get_width: function(val) {
98         return this.get_size(val.toString(), $(window.top).width());
99     },
100     get_height: function(val) {
101         return this.get_size(val.toString(), $(window.top).height());
102     },
103     get_size: function(val, available_size) {
104         if (val === 'auto') {
105             return val;
106         } else if (val.slice(-1) == "%") {
107             return Math.round(available_size / 100 * parseInt(val.slice(0, -1), 10));
108         } else {
109             return parseInt(val, 10);
110         }
111     },
112     open: function(options) {
113         // TODO fme: bind window on resize
114         if (this.template) {
115             this.$element.html(this.render());
116         }
117         var o = this.get_options(options);
118         this.$element.dialog(o).dialog('open');
119         if (o.height === 'auto' && o.max_height) {
120             this.$element.css({ 'max-height': o.max_height, 'overflow-y': 'auto' });
121         }
122         return this;
123     },
124     close: function() {
125         this.$element.dialog('close');
126     },
127     on_close: function() {
128         if (this.dialog_options.destroy_on_close) {
129             this.$element.dialog('destroy');
130         }
131     },
132     on_resized: function() {
133         //openerp.log("Dialog resized to %d x %d", this.$element.width(), this.$element.height());
134     },
135     stop: function () {
136         // Destroy widget
137         this.close();
138         this.$element.dialog('destroy');
139         this._super();
140     }
141 });
142
143 openerp.web.CrashManager = openerp.web.CallbackEnabled.extend({
144     on_rpc_error: function(error) {
145         if (error.data.fault_code) {
146             var split = ("" + error.data.fault_code).split('\n')[0].split(' -- ');
147             if (split.length > 1) {
148                 error.type = split.shift();
149                 error.data.fault_code = error.data.fault_code.substr(error.type.length + 4);
150             }
151         }
152         if (error.code === 200 && error.type) {
153             this.on_managed_error(error);
154         } else {
155             this.on_traceback(error);
156         }
157     },
158     on_managed_error: function(error) {
159         $('<div>' + QWeb.render('CrashManagerWarning', {error: error}) + '</div>').dialog({
160             title: "OpenERP " + _.str.capitalize(error.type),
161             buttons: [
162                 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
163             ]
164         });
165     },
166     on_traceback: function(error) {
167         var self = this;
168         var buttons = {};
169         if (openerp.connection.openerp_entreprise) {
170             buttons[_t("Send OpenERP Enterprise Report")] = function() {
171                 var $this = $(this);
172                 var issuename = $('#issuename').val();
173                 var explanation = $('#explanation').val();
174                 var remark = $('#remark').val();
175                 // Call the send method from server to send mail with details
176                 new openerp.web.DataSet(self, 'publisher_warranty.contract').call_and_eval('send', [error.data,explanation,remark,issuename]).then(function(result){
177                     if (result === false) {
178                         alert('There was a communication error.')
179                     } else {
180                         $this.dialog('close');
181                     }
182                 });
183             };
184             buttons[_t("Dont send")] = function() {
185                 $(this).dialog("close");
186             };
187         } else {
188             buttons[_t("Ok")] = function() {
189                 $(this).dialog("close");
190             };
191         }
192         var dialog = new openerp.web.Dialog(this, {
193             title: "OpenERP " + _.str.capitalize(error.type),
194             width: '80%',
195             height: '50%',
196             min_width: '800px',
197             min_height: '600px',
198             buttons: buttons
199         }).open();
200         dialog.$element.html(QWeb.render('CrashManagerError', {session: openerp.connection, error: error}));
201     }
202 });
203
204 openerp.web.Loading = openerp.web.OldWidget.extend(/** @lends openerp.web.Loading# */{
205     template: 'Loading',
206     /**
207      * @constructs openerp.web.Loading
208      * @extends openerp.web.OldWidget
209      *
210      * @param parent
211      * @param element_id
212      */
213     init: function(parent) {
214         this._super(parent);
215         this.count = 0;
216         this.blocked_ui = false;
217         var self = this;
218         this.request_call = function() {
219             self.on_rpc_event(1);
220         };
221         this.response_call = function() {
222             self.on_rpc_event(-1);
223         };
224         this.session.on_rpc_request.add_first(this.request_call);
225         this.session.on_rpc_response.add_last(this.response_call);
226     },
227     stop: function() {
228         this.session.on_rpc_request.remove(this.request_call);
229         this.session.on_rpc_response.remove(this.response_call);
230         this.on_rpc_event(-this.count);
231         this._super();
232     },
233     on_rpc_event : function(increment) {
234         var self = this;
235         if (!this.count && increment === 1) {
236             // Block UI after 3s
237             this.long_running_timer = setTimeout(function () {
238                 self.blocked_ui = true;
239                 $.blockUI();
240             }, 3000);
241         }
242
243         this.count += increment;
244         if (this.count > 0) {
245             $(".loading",this.$element).text(_.str.sprintf(
246                 _t("Loading (%d)"), this.count));
247             $(".loading",this.$element).show();
248             this.widget_parent.$element.addClass('loading');
249         } else {
250             this.count = 0;
251             clearTimeout(this.long_running_timer);
252             // Don't unblock if blocked by somebody else
253             if (self.blocked_ui) {
254                 this.blocked_ui = false;
255                 $.unblockUI();
256             }
257             $(".loading",this.$element).fadeOut();
258             this.widget_parent.$element.removeClass('loading');
259         }
260     }
261 });
262
263 openerp.web.Database = openerp.web.OldWidget.extend(/** @lends openerp.web.Database# */{
264     template: "DatabaseManager",
265     /**
266      * @constructs openerp.web.Database
267      * @extends openerp.web.OldWidget
268      *
269      * @param parent
270      * @param element_id
271      * @param option_id
272      */
273     init: function(parent, element_id, option_id) {
274         this._super(parent, element_id);
275         this.unblockUIFunction = $.unblockUI;
276         $.validator.addMethod('matches', function (s, _, re) {
277             return new RegExp(re).test(s);
278         }, _t("Invalid database name"));
279     },
280     start: function() {
281         this.$option_id = $("#oe_db_options");
282
283         var self = this;
284         var fetch_db = this.rpc("/web/database/get_list", {}).pipe(
285             function(result) { self.db_list = result.db_list; },
286             function (_, ev) { ev.preventDefault(); self.db_list = null; });
287         var fetch_langs = this.rpc("/web/session/get_lang_list", {}, function(result) {
288             if (result.error) {
289                 self.display_error(result);
290                 return;
291             }
292             self.lang_list = result.lang_list;
293         });
294         $.when(fetch_db, fetch_langs).then(function () {self.do_create();});
295
296         this.$element.find('#db-create').click(this.do_create);
297         this.$element.find('#db-drop').click(this.do_drop);
298         this.$element.find('#db-backup').click(this.do_backup);
299         this.$element.find('#db-restore').click(this.do_restore);
300         this.$element.find('#db-change-password').click(this.do_change_password);
301         this.$element.find('#back-to-login').click(function() {
302             self.hide();
303         });
304     },
305     stop: function () {
306         this.hide();
307         this.$option_id.empty();
308
309         this.$element
310             .find('#db-create, #db-drop, #db-backup, #db-restore, #db-change-password, #back-to-login')
311                 .unbind('click')
312             .end()
313             .empty();
314         this._super();
315     },
316     show: function () {
317         this.$element.closest(".login")
318                 .addClass("database_block");
319     },
320     hide: function () {
321         this.$element.closest(".login")
322                 .removeClass("database_block")
323     },
324     /**
325      * Converts a .serializeArray() result into a dict. Does not bother folding
326      * multiple identical keys into an array, last key wins.
327      *
328      * @param {Array} array
329      */
330     to_object: function (array) {
331         var result = {};
332         _(array).each(function (record) {
333             result[record.name] = record.value;
334         });
335         return result;
336     },
337     /**
338      * Waits until the new database is done creating, then unblocks the UI and
339      * logs the user in as admin
340      *
341      * @param {Number} db_creation_id identifier for the db-creation operation, used to fetch the current installation progress
342      * @param {Object} info info fields for this database creation
343      * @param {String} info.db name of the database being created
344      * @param {String} info.password super-admin password for the database
345      */
346     wait_for_newdb: function (db_creation_id, info) {
347         var self = this;
348         self.rpc('/web/database/progress', {
349             id: db_creation_id,
350             password: info.password
351         }, function (result) {
352             var progress = result[0];
353             // I'd display a progress bar, but turns out the progress status
354             // the server report kind-of blows goats: it's at 0 for ~75% of
355             // the installation, then jumps to 75%, then jumps down to either
356             // 0 or ~40%, then back up to 75%, then terminates. Let's keep that
357             // mess hidden behind a not-very-useful but not overly weird
358             // message instead.
359             if (progress < 1) {
360                 setTimeout(function () {
361                     self.wait_for_newdb(db_creation_id, info);
362                 }, 500);
363                 return;
364             }
365
366             var admin = result[1][0];
367             setTimeout(function () {
368                 self.widget_parent.do_login(
369                         info.db, admin.login, admin.password);
370                 self.stop();
371                 self.unblockUI();
372             });
373         });
374     },
375     /**
376      * Blocks UI and replaces $.unblockUI by a noop to prevent third parties
377      * from unblocking the UI
378      */
379     blockUI: function () {
380         $.blockUI();
381         $.unblockUI = function () {};
382     },
383     /**
384      * Reinstates $.unblockUI so third parties can play with blockUI, and
385      * unblocks the UI
386      */
387     unblockUI: function () {
388         $.unblockUI = this.unblockUIFunction;
389         $.unblockUI();
390     },
391     /**
392      * Displays an error dialog resulting from the various RPC communications
393      * failing over themselves
394      *
395      * @param {Object} error error description
396      * @param {String} error.title title of the error dialog
397      * @param {String} error.error message of the error dialog
398      */
399     display_error: function (error) {
400         return $('<div>').dialog({
401             modal: true,
402             title: error.title,
403             buttons: [
404                 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
405             ]
406         }).html(error.error);
407     },
408     do_create: function() {
409         var self = this;
410         self.$option_id.html(QWeb.render("Database.CreateDB", self));
411         self.$option_id.find("form[name=create_db_form]").validate({
412             submitHandler: function (form) {
413                 var fields = $(form).serializeArray();
414                 self.blockUI();
415                 self.rpc("/web/database/create", {'fields': fields}, function(result) {
416                     if (result.error) {
417                         self.unblockUI();
418                         self.display_error(result);
419                         return;
420                     }
421                     if (self.db_list) {
422                         self.db_list.push(self.to_object(fields)['db_name']);
423                         self.db_list.sort();
424                         self.widget_parent.set_db_list(self.db_list);
425                     }
426                     var form_obj = self.to_object(fields);
427                     self.wait_for_newdb(result, {
428                         password: form_obj['super_admin_pwd'],
429                         db: form_obj['db_name']
430                     });
431                 });
432             }
433         });
434     },
435     do_drop: function() {
436         var self = this;
437         self.$option_id.html(QWeb.render("DropDB", self));
438         self.$option_id.find("form[name=drop_db_form]").validate({
439             submitHandler: function (form) {
440                 var $form = $(form),
441                     fields = $form.serializeArray(),
442                     $db_list = $form.find('select[name=drop_db]'),
443                     db = $db_list.val();
444
445                 if (!confirm("Do you really want to delete the database: " + db + " ?")) {
446                     return;
447                 }
448                 self.rpc("/web/database/drop", {'fields': fields}, function(result) {
449                     if (result.error) {
450                         self.display_error(result);
451                         return;
452                     }
453                     $db_list.find(':selected').remove();
454                     if (self.db_list) {
455                         self.db_list.splice(_.indexOf(self.db_list, db, true), 1);
456                         self.widget_parent.set_db_list(self.db_list);
457                     }
458                     self.do_notify("Dropping database", "The database '" + db + "' has been dropped");
459                 });
460             }
461         });
462     },
463     do_backup: function() {
464         var self = this;
465         self.$option_id
466             .html(QWeb.render("BackupDB", self))
467             .find("form[name=backup_db_form]").validate({
468             submitHandler: function (form) {
469                 self.blockUI();
470                 self.session.get_file({
471                     form: form,
472                     success: function () {
473                         self.do_notify(_t("Backed"),
474                             _t("Database backed up successfully"));
475                     },
476                     error: openerp.webclient.crashmanager.on_rpc_error,
477                     complete: function() {
478                         self.unblockUI();
479                     }
480                 });
481             }
482         });
483     },
484     do_restore: function() {
485         var self = this;
486         self.$option_id.html(QWeb.render("RestoreDB", self));
487
488         self.$option_id.find("form[name=restore_db_form]").validate({
489             submitHandler: function (form) {
490                 self.blockUI();
491                 $(form).ajaxSubmit({
492                     url: '/web/database/restore',
493                     type: 'POST',
494                     resetForm: true,
495                     success: function (body) {
496                         // TODO: ui manipulations
497                         // note: response objects don't work, but we have the
498                         // HTTP body of the response~~
499
500                         // If empty body, everything went fine
501                         if (!body) { return; }
502
503                         if (body.indexOf('403 Forbidden') !== -1) {
504                             self.display_error({
505                                 title: 'Access Denied',
506                                 error: 'Incorrect super-administrator password'
507                             })
508                         } else {
509                             self.display_error({
510                                 title: 'Restore Database',
511                                 error: 'Could not restore the database'
512                             })
513                         }
514                     },
515                     complete: function() {
516                         self.unblockUI();
517                         self.do_notify(_t("Restored"), _t("Database restored successfully"));
518                     }
519                 });
520             }
521         });
522     },
523     do_change_password: function() {
524         var self = this;
525         self.$option_id.html(QWeb.render("Change_DB_Pwd", self));
526
527         self.$option_id.find("form[name=change_pwd_form]").validate({
528             messages: {
529                 old_pwd: "Please enter your previous password",
530                 new_pwd: "Please enter your new password",
531                 confirm_pwd: {
532                     required: "Please confirm your new password",
533                     equalTo: "The confirmation does not match the password"
534                 }
535             },
536             submitHandler: function (form) {
537                 self.rpc("/web/database/change_password", {
538                     'fields': $(form).serializeArray()
539                 }, function(result) {
540                     if (result.error) {
541                         self.display_error(result);
542                         return;
543                     }
544                     self.do_notify("Changed Password", "Password has been changed successfully");
545                 });
546             }
547         });
548     }
549 });
550
551 openerp.web.Login =  openerp.web.OldWidget.extend(/** @lends openerp.web.Login# */{
552     remember_credentials: true,
553     
554     template: "Login",
555     /**
556      * @constructs openerp.web.Login
557      * @extends openerp.web.OldWidget
558      *
559      * @param parent
560      * @param element_id
561      */
562
563     init: function(parent) {
564         this._super(parent);
565         this.has_local_storage = typeof(localStorage) != 'undefined';
566         this.selected_db = null;
567         this.selected_login = null;
568
569         if (this.has_local_storage && this.remember_credentials) {
570             this.selected_db = localStorage.getItem('last_db_login_success');
571             this.selected_login = localStorage.getItem('last_login_login_success');
572             if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
573                 this.selected_password = localStorage.getItem('last_password_login_success');
574             }
575         }
576     },
577     start: function() {
578         var self = this;
579         this.database = new openerp.web.Database(this);
580         this.database.appendTo(this.$element);
581
582         this.$element.find('#oe-db-config').click(function() {
583             self.database.show();
584         });
585
586         this.$element.find("form").submit(this.on_submit);
587
588         this.rpc("/web/database/get_list", {}, function(result) {
589             self.set_db_list(result.db_list);
590         }, 
591         function(error, event) {
592             if (error.data.fault_code === 'AccessDenied') {
593                 event.preventDefault();
594             }
595         });
596
597     },
598     set_db_list: function (list) {
599         this.$element.find("[name=db]").replaceWith(
600             openerp.web.qweb.render('Login_dblist', {
601                 db_list: list, selected_db: this.selected_db}))
602     },
603     on_submit: function(ev) {
604         if(ev) {
605             ev.preventDefault();
606         }
607         var $e = this.$element;
608         var db = $e.find("form [name=db]").val();
609         var login = $e.find("form input[name=login]").val();
610         var password = $e.find("form input[name=password]").val();
611
612         this.do_login(db, login, password);
613     },
614     /**
615      * Performs actual login operation, and UI-related stuff
616      *
617      * @param {String} db database to log in
618      * @param {String} login user login
619      * @param {String} password user password
620      */
621     do_login: function (db, login, password) {
622         var self = this;
623         this.$element.removeClass('login_invalid');
624         this.session.on_session_invalid.add({
625             callback: function () {
626                 self.$element.addClass("login_invalid");
627             },
628             unique: true
629         });
630         this.session.session_authenticate(db, login, password).then(function() {
631             self.$element.removeClass("login_invalid");
632             if (self.has_local_storage) {
633                 if(self.remember_credentials) {
634                     localStorage.setItem('last_db_login_success', db);
635                     localStorage.setItem('last_login_login_success', login);
636                     if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
637                         localStorage.setItem('last_password_login_success', password);
638                     }
639                 } else {
640                     localStorage.setItem('last_db_login_success', '');
641                     localStorage.setItem('last_login_login_success', '');
642                     localStorage.setItem('last_password_login_success', '');
643                 }
644             }
645         });
646     }
647 });
648
649 openerp.web.Header =  openerp.web.OldWidget.extend(/** @lends openerp.web.Header# */{
650     template: "Header",
651     /**
652      * @constructs openerp.web.Header
653      * @extends openerp.web.OldWidget
654      *
655      * @param parent
656      */
657     init: function(parent) {
658         this._super(parent);
659         this.qs = "?" + jQuery.param.querystring();
660         this.$content = $();
661         this.update_promise = $.Deferred().resolve();
662     },
663     start: function() {
664         this._super();
665     },
666     do_update: function () {
667         var self = this;
668         var fct = function() {
669             self.$content.remove();
670             if (!self.session.uid)
671                 return;
672             var func = new openerp.web.Model("res.users").get_func("read");
673             return func(self.session.uid, ["name", "company_id"]).pipe(function(res) {
674                 self.$content = $(QWeb.render("Header-content", {widget: self, user: res}));
675                 self.$content.appendTo(self.$element);
676                 self.$element.find(".logout").click(self.on_logout);
677                 self.$element.find("a.preferences").click(self.on_preferences);
678                 self.$element.find(".about").click(self.on_about);
679                 return self.shortcut_load();
680             });
681         };
682         this.update_promise = this.update_promise.pipe(fct, fct);
683     },
684     on_about: function() {
685         var self = this;
686         self.rpc("/web/webclient/version_info", {}).then(function(res) {
687             var $help = $(QWeb.render("About-Page", {version_info: res}));
688             $help.find('a.oe_activate_debug_mode').click(function (e) {
689                 e.preventDefault();
690                 window.location = $.param.querystring(
691                         window.location.href, 'debug');
692             });
693             $help.dialog({autoOpen: true,
694                 modal: true, width: 960, title: _t("About")});
695         });
696     },
697     shortcut_load :function(){
698         var self = this,
699             sc = self.session.shortcuts,
700             shortcuts_ds = new openerp.web.DataSet(this, 'ir.ui.view_sc');
701         // TODO: better way to communicate between sections.
702         // sc.bindings, because jquery does not bind/trigger on arrays...
703         if (!sc.binding) {
704             sc.binding = {};
705             $(sc.binding).bind({
706                 'add': function (e, attrs) {
707                     shortcuts_ds.create(attrs, function (out) {
708                         $('<li>', {
709                             'data-shortcut-id':out.result,
710                             'data-id': attrs.res_id
711                         }).text(attrs.name)
712                           .appendTo(self.$element.find('.oe-shortcuts ul'));
713                         attrs.id = out.result;
714                         sc.push(attrs);
715                     });
716                 },
717                 'remove-current': function () {
718                     var menu_id = self.session.active_id;
719                     var $shortcut = self.$element
720                         .find('.oe-shortcuts li[data-id=' + menu_id + ']');
721                     var shortcut_id = $shortcut.data('shortcut-id');
722                     $shortcut.remove();
723                     shortcuts_ds.unlink([shortcut_id]);
724                     var sc_new = _.reject(sc, function(shortcut){ return shortcut_id === shortcut.id});
725                     sc.splice(0, sc.length);
726                     sc.push.apply(sc, sc_new);
727                     }
728             });
729         }
730         return this.rpc('/web/session/sc_list', {}, function(shortcuts) {
731             sc.splice(0, sc.length);
732             sc.push.apply(sc, shortcuts);
733
734             self.$element.find('.oe-shortcuts')
735                 .html(QWeb.render('Shortcuts', {'shortcuts': shortcuts}))
736                 .undelegate('li', 'click')
737
738                 .delegate('li', 'click', function(e) {
739                     e.stopPropagation();
740                     var id = $(this).data('id');
741                     self.session.active_id = id;
742                     self.rpc('/web/menu/action', {'menu_id':id}, function(ir_menu_data) {
743                         if (ir_menu_data.action.length){
744                             self.on_action(ir_menu_data.action[0][2]);
745                         }
746                     });
747                 });
748         });
749     },
750
751     on_action: function(action) {
752     },
753     on_preferences: function(){
754         var self = this;
755         var action_manager = new openerp.web.ActionManager(this);
756         var dataset = new openerp.web.DataSet (this,'res.users',this.context);
757         dataset.call ('action_get','',function (result){
758             self.rpc('/web/action/load', {action_id:result}, function(result){
759                 action_manager.do_action(_.extend(result['result'], {
760                     res_id: self.session.uid,
761                     res_model: 'res.users',
762                     flags: {
763                         action_buttons: false,
764                         search_view: false,
765                         sidebar: false,
766                         views_switcher: false,
767                         pager: false
768                     }
769                 }));
770             });
771         });
772         this.dialog = new openerp.web.Dialog(this,{
773             title: _t("Preferences"),
774             width: '700px',
775             buttons: [
776                 {text: _t("Cancel"), click: function(){ $(this).dialog('destroy'); }},
777                 {text: _t("Change password"), click: function(){ self.change_password(); }},
778                 {text: _t("Save"), click: function(){
779                         var inner_viewmanager = action_manager.inner_viewmanager;
780                         inner_viewmanager.views[inner_viewmanager.active_view].controller.do_save()
781                         .then(function() {
782                             self.dialog.stop();
783                             // needs to refresh interface in case language changed
784                             window.location.reload();
785                         });
786                     }
787                 }
788             ]
789         }).open();
790        action_manager.appendTo(this.dialog);
791        action_manager.render(this.dialog);
792     },
793
794     change_password :function() {
795         var self = this;
796         this.dialog = new openerp.web.Dialog(this, {
797             title: _t("Change Password"),
798             width : 'auto'
799         }).open();
800         this.dialog.$element.html(QWeb.render("Change_Pwd", self));
801         this.dialog.$element.find("form[name=change_password_form]").validate({
802             submitHandler: function (form) {
803                 self.rpc("/web/session/change_password",{
804                     'fields': $(form).serializeArray()
805                 }, function(result) {
806                     if (result.error) {
807                         self.display_error(result);
808                         return;
809                     } else {
810                         openerp.webclient.on_logout();
811                     }
812                 });
813             }
814         });
815     },
816     display_error: function (error) {
817         return $('<div>').dialog({
818             modal: true,
819             title: error.title,
820             buttons: [
821                 {text: _("Ok"), click: function() { $(this).dialog("close"); }}
822             ]
823         }).html(error.error);
824     },
825     on_logout: function() {
826     }
827 });
828
829 openerp.web.Menu =  openerp.web.OldWidget.extend(/** @lends openerp.web.Menu# */{
830     /**
831      * @constructs openerp.web.Menu
832      * @extends openerp.web.OldWidget
833      *
834      * @param parent
835      * @param element_id
836      * @param secondary_menu_id
837      */
838     init: function(parent, element_id, secondary_menu_id) {
839         this._super(parent, element_id);
840         this.secondary_menu_id = secondary_menu_id;
841         this.$secondary_menu = $("#" + secondary_menu_id);
842         this.menu = false;
843         this.folded = false;
844         if (window.localStorage) {
845             this.folded = localStorage.getItem('oe_menu_folded') === 'true';
846         }
847         this.float_timeout = 700;
848     },
849     start: function() {
850         this.$secondary_menu.addClass(this.folded ? 'oe_folded' : 'oe_unfolded');
851     },
852     do_reload: function() {
853         var self = this;
854         return this.rpc("/web/menu/load", {}, this.on_loaded).then(function () {
855             if (self.current_menu) {
856                 self.open_menu(self.current_menu);
857             }
858         });
859     },
860     on_loaded: function(data) {
861         this.data = data;
862         this.$element.html(QWeb.render("Menu", { widget : this }));
863         this.$secondary_menu.html(QWeb.render("Menu.secondary", { widget : this }));
864         this.$element.add(this.$secondary_menu).find("a").click(this.on_menu_click);
865         this.$secondary_menu.find('.oe_toggle_secondary_menu').click(this.on_toggle_fold);
866     },
867     on_toggle_fold: function() {
868         this.$secondary_menu.toggleClass('oe_folded').toggleClass('oe_unfolded');
869         if (this.folded) {
870             this.$secondary_menu.find('.oe_secondary_menu.active').show();
871         } else {
872             this.$secondary_menu.find('.oe_secondary_menu').hide();
873         }
874         this.folded = !this.folded;
875         if (window.localStorage) {
876             localStorage.setItem('oe_menu_folded', this.folded.toString());
877         }
878     },
879     /**
880      * Opens a given menu by id, as if a user had browsed to that menu by hand
881      * except does not trigger any event on the way
882      *
883      * @param {Number} menu_id database id of the terminal menu to select
884      */
885     open_menu: function (menu_id) {
886         this.$element.add(this.$secondary_menu).find('.active')
887                 .removeClass('active');
888         this.$secondary_menu.find('> .oe_secondary_menu').hide();
889
890         var $primary_menu;
891         var $secondary_submenu = this.$secondary_menu.find(
892                 'a[data-menu=' + menu_id +']');
893         if ($secondary_submenu.length) {
894             for(;;) {
895                 if ($secondary_submenu.hasClass('leaf')) {
896                     $secondary_submenu.addClass('active');
897                 } else if ($secondary_submenu.hasClass('submenu')) {
898                     $secondary_submenu.addClass('opened')
899                 }
900                 var $parent = $secondary_submenu.parent().show();
901                 if ($parent.hasClass('oe_secondary_menu')) {
902                     var primary_id = $parent.data('menu-parent');
903                     $primary_menu = this.$element.find(
904                             'a[data-menu=' + primary_id + ']');
905                     break;
906                 }
907                 $secondary_submenu = $parent.prev();
908             }
909         } else {
910             $primary_menu = this.$element.find('a[data-menu=' + menu_id + ']');
911         }
912         if (!$primary_menu.length) {
913             return;
914         }
915         $primary_menu.addClass('active');
916         this.$secondary_menu.find(
917             'div[data-menu-parent=' + $primary_menu.data('menu') + ']').addClass('active').toggle(!this.folded);
918     },
919     on_menu_click: function(ev, id) {
920         id = id || 0;
921         var $clicked_menu, manual = false;
922
923         if (id) {
924             // We can manually activate a menu with it's id (for hash url mapping)
925             manual = true;
926             $clicked_menu = this.$element.find('a[data-menu=' + id + ']');
927             if (!$clicked_menu.length) {
928                 $clicked_menu = this.$secondary_menu.find('a[data-menu=' + id + ']');
929             }
930         } else {
931             $clicked_menu = $(ev.currentTarget);
932             id = $clicked_menu.data('menu');
933         }
934
935         if (this.do_menu_click($clicked_menu, manual) && id) {
936             this.current_menu = id;
937             this.session.active_id = id;
938             this.rpc('/web/menu/action', {'menu_id': id}, this.on_menu_action_loaded);
939         }
940         if (ev) {
941             ev.stopPropagation();
942         }
943         return false;
944     },
945     do_menu_click: function($clicked_menu, manual) {
946         var $sub_menu, $main_menu,
947             active = $clicked_menu.is('.active'),
948             sub_menu_visible = false;
949
950         if (this.$secondary_menu.has($clicked_menu).length) {
951             $sub_menu = $clicked_menu.parents('.oe_secondary_menu');
952             $main_menu = this.$element.find('a[data-menu=' + $sub_menu.data('menu-parent') + ']');
953         } else {
954             $sub_menu = this.$secondary_menu.find('.oe_secondary_menu[data-menu-parent=' + $clicked_menu.attr('data-menu') + ']');
955             $main_menu = $clicked_menu;
956         }
957
958         sub_menu_visible = $sub_menu.is(':visible');
959         this.$secondary_menu.find('.oe_secondary_menu').hide();
960
961         $('.active', this.$element.add(this.$secondary_menu)).removeClass('active');
962         $main_menu.add($clicked_menu).add($sub_menu).addClass('active');
963
964         if (!(this.folded && manual)) {
965             this.do_show_secondary($sub_menu, $main_menu);
966         } else {
967             this.do_show_secondary();
968         }
969
970         if ($main_menu != $clicked_menu) {
971             if ($clicked_menu.is('.submenu')) {
972                 $sub_menu.find('.submenu.opened').each(function() {
973                     if (!$(this).next().has($clicked_menu).length && !$(this).is($clicked_menu)) {
974                         $(this).removeClass('opened').next().hide();
975                     }
976                 });
977                 $clicked_menu.toggleClass('opened').next().toggle();
978             } else if ($clicked_menu.is('.leaf')) {
979                 $sub_menu.toggle(!this.folded);
980                 return true;
981             }
982         } else if (this.folded) {
983             if (active && sub_menu_visible) {
984                 $sub_menu.hide();
985                 return true;
986             }
987             return manual;
988         } else {
989             return true;
990         }
991         return false;
992     },
993     do_hide_secondary: function() {
994         this.$secondary_menu.hide();
995     },
996     do_show_secondary: function($sub_menu, $main_menu) {
997         var self = this;
998         this.$secondary_menu.show();
999         if (!arguments.length) {
1000             return;
1001         }
1002         if (this.folded) {
1003             var css = $main_menu.position(),
1004                 fold_width = this.$secondary_menu.width() + 2,
1005                 window_width = $(window).width();
1006             css.top += 33;
1007             css.left -= Math.round(($sub_menu.width() - $main_menu.width()) / 2);
1008             css.left = css.left < fold_width ? fold_width : css.left;
1009             if ((css.left + $sub_menu.width()) > window_width) {
1010                 delete(css.left);
1011                 css.right = 1;
1012             }
1013             $sub_menu.css(css);
1014             $sub_menu.mouseenter(function() {
1015                 clearTimeout($sub_menu.data('timeoutId'));
1016                 $sub_menu.data('timeoutId', null);
1017                 return false;
1018             }).mouseleave(function(evt) {
1019                 var timeoutId = setTimeout(function() {
1020                     if (self.folded && $sub_menu.data('timeoutId')) {
1021                         $sub_menu.hide().unbind('mouseenter').unbind('mouseleave');
1022                     }
1023                 }, self.float_timeout);
1024                 $sub_menu.data('timeoutId', timeoutId);
1025                 return false;
1026             });
1027         }
1028         $sub_menu.show();
1029     },
1030     on_menu_action_loaded: function(data) {
1031         var self = this;
1032         if (data.action.length) {
1033             var action = data.action[0][2];
1034             action.from_menu = true;
1035             self.on_action(action);
1036         } else {
1037             self.on_action({type: 'null_action'});
1038         }
1039     },
1040     on_action: function(action) {
1041     }
1042 });
1043
1044 openerp.web.WebClient = openerp.web.OldWidget.extend(/** @lends openerp.web.WebClient */{
1045     /**
1046      * @constructs openerp.web.WebClient
1047      * @extends openerp.web.OldWidget
1048      *
1049      * @param element_id
1050      */
1051     init: function(parent) {
1052         var self = this;
1053         this._super(parent);
1054         openerp.webclient = this;
1055
1056         this._current_state = null;
1057     },
1058     start: function() {
1059         var self = this;
1060         this.$element = $(document.body);
1061         if (jQuery.param != undefined && jQuery.deparam(jQuery.param.querystring()).kitten != undefined) {
1062             this.$element.addClass("kitten-mode-activated");
1063             this.$element.delegate('img.oe-record-edit-link-img', 'hover', function(e) {
1064                 self.$element.toggleClass('clark-gable');
1065             });
1066         }
1067         this.session.bind().then(function() {
1068             if (!self.session.session_is_valid()) {
1069                 self.show_login();
1070             }
1071         });
1072         this.session.on_session_valid.add(function() {
1073             self.show_application();
1074             
1075             self.header.do_update();
1076             self.menu.do_reload();
1077             if(self.action_manager)
1078                 self.action_manager.stop();
1079             self.action_manager = new openerp.web.ActionManager(self);
1080             self.action_manager.appendTo($("#oe_app"));
1081             self.bind_hashchange();
1082             var version_label = _t("OpenERP - Unsupported/Community Version");
1083             if (!self.session.openerp_entreprise) {
1084                 self.$element.find('.oe_footer_powered').append(_.str.sprintf('<span> - <a href="http://www.openerp.com/support-or-publisher-warranty-contract" target="_blank">%s</a></span>', version_label));
1085                 document.title = version_label;
1086             }
1087         });
1088     },
1089     show_login: function() {
1090         var self = this;
1091         this.destroy_content();
1092         this.show_common();
1093         self.login = new openerp.web.Login(self);
1094         self.login.appendTo(self.$element);
1095     },
1096     show_application: function() {
1097         var self = this;
1098         this.destroy_content();
1099         this.show_common();
1100         self.$table = $(QWeb.render("Interface", {}));
1101         self.$element.append(self.$table);
1102         self.header = new openerp.web.Header(self);
1103         self.header.on_logout.add(this.proxy('on_logout'));
1104         self.header.on_action.add(this.proxy('on_menu_action'));
1105         self.header.appendTo($("#oe_header"));
1106         self.menu = new openerp.web.Menu(self, "oe_menu", "oe_secondary_menu");
1107         self.menu.on_action.add(this.proxy('on_menu_action'));
1108         self.menu.start();
1109     },
1110     show_common: function() {
1111         var self = this;
1112         if (!this.crashmanager) {
1113             this.crashmanager =  new openerp.web.CrashManager();
1114             openerp.connection.on_rpc_error.add(this.crashmanager.on_rpc_error);
1115             window.onerror = function (message, file, line) {
1116                 self.crashmanager.on_traceback({
1117                     type: _t("Client Error"),
1118                     message: message,
1119                     data: {debug: file + ':' + line}
1120                 });
1121             }
1122         }
1123         this.notification = new openerp.web.Notification(this);
1124         this.notification.appendTo(this.$element);
1125         this.loading = new openerp.web.Loading(this);
1126         this.loading.appendTo(this.$element);
1127     },
1128     destroy_content: function() {
1129         _.each(_.clone(this.widget_children), function(el) {
1130             el.stop();
1131         });
1132         this.$element.children().remove();
1133     },
1134     do_reload: function() {
1135         var self = this;
1136         return this.session.session_reload().pipe(function () {
1137             openerp.connection.load_modules(true).pipe(
1138                 self.menu.proxy('do_reload')); });
1139
1140     },
1141     do_notify: function() {
1142         var n = this.notification;
1143         n.notify.apply(n, arguments);
1144     },
1145     do_warn: function() {
1146         var n = this.notification;
1147         n.warn.apply(n, arguments);
1148     },
1149     on_logout: function() {
1150         var self = this;
1151         this.session.session_logout().then(function () {
1152             $(window).unbind('hashchange', self.on_hashchange);
1153             self.do_push_state({});
1154             //would be cool to be able to do this, but I think it will make addons do strange things
1155             //this.show_login();
1156             window.location.reload();
1157         });
1158     },
1159     bind_hashchange: function() {
1160         $(window).bind('hashchange', this.on_hashchange);
1161
1162         var state = $.bbq.getState(true);
1163         if (! _.isEmpty(state)) {
1164             $(window).trigger('hashchange');
1165         } else {
1166             this.action_manager.do_action({type: 'ir.actions.client', tag: 'default_home'});
1167         }
1168     },
1169     on_hashchange: function(event) {
1170         var state = event.getState(true);
1171         if (!_.isEqual(this._current_state, state)) {
1172             this.action_manager.do_load_state(state, !!this._current_state);
1173         }
1174         this._current_state = state;
1175     },
1176     do_push_state: function(state) {
1177         var url = '#' + $.param(state);
1178         this._current_state = _.clone(state);
1179         $.bbq.pushState(url);
1180     },
1181     on_menu_action: function(action) {
1182         this.action_manager.do_action(action);
1183     },
1184     do_action: function(action) {
1185         var self = this;
1186         // TODO replace by client action menuclick 
1187         if(action.menu_id) {
1188             this.do_reload().then(function () {
1189                 self.menu.on_menu_click(null, action.menu_id);
1190             });
1191         }
1192     }
1193 });
1194
1195 openerp.web.EmbeddedClient = openerp.web.OldWidget.extend({
1196     template: 'EmptyComponent',
1197     init: function(action_id, options) {
1198         this._super();
1199         // TODO take the xmlid of a action instead of its id 
1200         this.action_id = action_id;
1201         this.options = options || {};
1202         this.am = new openerp.web.ActionManager(this);
1203     },
1204
1205     start: function() {
1206         var self = this;
1207         this.am.appendTo(this.$element.addClass('openerp'));
1208         return this.rpc("/web/action/load", { action_id: this.action_id }, function(result) {
1209             var action = result.result;
1210             action.flags = _.extend({
1211                 //views_switcher : false,
1212                 search_view : false,
1213                 action_buttons : false,
1214                 sidebar : false
1215                 //pager : false
1216             }, self.options, action.flags || {});
1217
1218             self.am.do_action(action);
1219         });
1220     }
1221
1222 });
1223
1224 openerp.web.embed = function (origin, dbname, login, key, action, options) {
1225     $('head').append($('<link>', {
1226         'rel': 'stylesheet',
1227         'type': 'text/css',
1228         'href': origin +'/web/webclient/css'
1229     }));
1230     var currentScript = document.currentScript;
1231     if (!currentScript) {
1232         var sc = document.getElementsByTagName('script');
1233         currentScript = sc[sc.length-1];
1234     }
1235     openerp.connection.bind(origin).then(function () {
1236         openerp.connection.session_authenticate(dbname, login, key, true).then(function () {
1237             var client = new openerp.web.EmbeddedClient(action, options);
1238             client.insertAfter(currentScript);
1239         });
1240     });
1241
1242 }
1243
1244 };
1245
1246 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: