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