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