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