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