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