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