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