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