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