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