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