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