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