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