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