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