f4c29617cea792902f47a0b34b0c5a2613bce888
[odoo/odoo.git] / addons / base / static / src / js / core.js
1 /*---------------------------------------------------------
2  * OpenERP Web core
3  *--------------------------------------------------------*/
4
5 openerp.base.core = function(openerp) {
6 /**
7  * John Resig Class with factory improvement
8  */
9 (function() {
10     var initializing = false,
11         fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
12     // The base Class implementation (does nothing)
13     openerp.base.Class = function(){};
14
15     // Create a new Class that inherits from this class
16     openerp.base.Class.extend = function(prop) {
17         var _super = this.prototype;
18
19         // Instantiate a base class (but only create the instance,
20         // don't run the init constructor)
21         initializing = true;
22         var prototype = new this();
23         initializing = false;
24
25         // Copy the properties over onto the new prototype
26         for (var name in prop) {
27             // Check if we're overwriting an existing function
28             prototype[name] = typeof prop[name] == "function" &&
29                               typeof _super[name] == "function" &&
30                               fnTest.test(prop[name]) ?
31                     (function(name, fn) {
32                         return function() {
33                             var tmp = this._super;
34
35                             // Add a new ._super() method that is the same
36                             // method but on the super-class
37                             this._super = _super[name];
38
39                             // The method only need to be bound temporarily, so
40                             // we remove it when we're done executing
41                             var ret = fn.apply(this, arguments);
42                             this._super = tmp;
43
44                             return ret;
45                         };
46                     })(name, prop[name]) :
47                     prop[name];
48         }
49
50         // The dummy class constructor
51         function Class() {
52             // All construction is actually done in the init method
53             if (!initializing && this.init) {
54                 var ret = this.init.apply(this, arguments);
55                 if (ret) { return ret; }
56             }
57             return this;
58         }
59         Class.include = function (properties) {
60             for (var name in properties) {
61                 if (typeof properties[name] !== 'function'
62                         || !fnTest.test(properties[name])) {
63                     prototype[name] = properties[name];
64                 } else if (typeof prototype[name] === 'function'
65                            && prototype.hasOwnProperty(name)) {
66                     prototype[name] = (function (name, fn, previous) {
67                         return function () {
68                             var tmp = this._super;
69                             this._super = previous;
70                             var ret = fn.apply(this, arguments);
71                             this._super = tmp;
72                             return ret;
73                         }
74                     })(name, properties[name], prototype[name]);
75                 } else if (typeof _super[name] === 'function') {
76                     prototype[name] = (function (name, fn) {
77                         return function () {
78                             var tmp = this._super;
79                             this._super = _super[name];
80                             var ret = fn.apply(this, arguments);
81                             this._super = tmp;
82                             return ret;
83                         }
84                     })(name, properties[name]);
85                 }
86             }
87         };
88
89         // Populate our constructed prototype object
90         Class.prototype = prototype;
91
92         // Enforce the constructor to be what we expect
93         Class.constructor = Class;
94
95         // And make this class extendable
96         Class.extend = arguments.callee;
97
98         return Class;
99     };
100 })();
101
102 openerp.base.callback = function(obj, method) {
103     var callback = function() {
104         var args = Array.prototype.slice.call(arguments);
105         var r;
106         for(var i = 0; i < callback.callback_chain.length; i++)  {
107             var c = callback.callback_chain[i];
108             if(c.unique) {
109                 callback.callback_chain.splice(i, 1);
110                 i -= 1;
111             }
112             r = c.callback.apply(c.self, c.args.concat(args));
113             // TODO special value to stop the chain
114             // openerp.base.callback_stop
115         }
116         return r;
117     };
118     callback.callback_chain = [];
119     callback.add = function(f) {
120         if(typeof(f) == 'function') {
121             f = { callback: f, args: Array.prototype.slice.call(arguments, 1) };
122         }
123         f.self = f.self || null;
124         f.args = f.args || [];
125         f.unique = !!f.unique;
126         if(f.position == 'last') {
127             callback.callback_chain.push(f);
128         } else {
129             callback.callback_chain.unshift(f);
130         }
131         return callback;
132     };
133     callback.add_first = function(f) {
134         return callback.add.apply(null,arguments);
135     };
136     callback.add_last = function(f) {
137         return callback.add({
138             callback: f,
139             args: Array.prototype.slice.call(arguments, 1),
140             position: "last"
141         });
142     };
143
144     return callback.add({
145         callback: method,
146         self:obj,
147         args:Array.prototype.slice.call(arguments, 2)
148     });
149 };
150
151 /**
152  * Generates an inherited class that replaces all the methods by null methods (methods
153  * that does nothing and always return undefined).
154  *
155  * @param {Class} claz
156  * @param {dict} add Additional functions to override.
157  * @return {Class}
158  */
159 openerp.base.generate_null_object_class = function(claz, add) {
160     var newer = {};
161     var copy_proto = function(prototype) {
162         for (var name in prototype) {
163             if(typeof prototype[name] == "function") {
164                 newer[name] = function() {};
165             }
166         }
167         if (prototype.prototype)
168             copy_proto(prototype.prototype);
169     };
170     copy_proto(claz.prototype);
171     newer.init = openerp.base.Widget.prototype.init;
172     var tmpclass = claz.extend(newer);
173     return tmpclass.extend(add || {});
174 };
175
176 /**
177  * Base error for lookup failure
178  *
179  * @class
180  */
181 openerp.base.NotFound = openerp.base.Class.extend( /** @lends openerp.base.NotFound# */ {
182 });
183 openerp.base.KeyNotFound = openerp.base.NotFound.extend( /** @lends openerp.base.KeyNotFound# */ {
184     /**
185      * Thrown when a key could not be found in a mapping
186      *
187      * @constructs
188      * @extends openerp.base.NotFound
189      * @param {String} key the key which could not be found
190      */
191     init: function (key) {
192         this.key = key;
193     },
194     toString: function () {
195         return "The key " + this.key + " was not found";
196     }
197 });
198 openerp.base.ObjectNotFound = openerp.base.NotFound.extend( /** @lends openerp.base.ObjectNotFound# */ {
199     /**
200      * Thrown when an object path does not designate a valid class or object
201      * in the openerp hierarchy.
202      *
203      * @constructs
204      * @extends openerp.base.NotFound
205      * @param {String} path the invalid object path
206      */
207     init: function (path) {
208         this.path = path;
209     },
210     toString: function () {
211         return "Could not find any object of path " + this.path;
212     }
213 });
214 openerp.base.Registry = openerp.base.Class.extend( /** @lends openerp.base.Registry# */ {
215     /**
216      * Stores a mapping of arbitrary key (strings) to object paths (as strings
217      * as well).
218      *
219      * Resolves those paths at query time in order to always fetch the correct
220      * object, even if those objects have been overloaded/replaced after the
221      * registry was created.
222      *
223      * An object path is simply a dotted name from the openerp root to the
224      * object pointed to (e.g. ``"openerp.base.Session"`` for an OpenERP
225      * session object).
226      *
227      * @constructs
228      * @param {Object} mapping a mapping of keys to object-paths
229      */
230     init: function (mapping) {
231         this.map = mapping || {};
232     },
233     /**
234      * Retrieves the object matching the provided key string.
235      *
236      * @param {String} key the key to fetch the object for
237      * @returns {Class} the stored class, to initialize
238      *
239      * @throws {openerp.base.KeyNotFound} if the object was not in the mapping
240      * @throws {openerp.base.ObjectNotFound} if the object path was invalid
241      */
242     get_object: function (key) {
243         var path_string = this.map[key];
244         if (path_string === undefined) {
245             throw new openerp.base.KeyNotFound(key);
246         }
247
248         var object_match = openerp;
249         var path = path_string.split('.');
250         // ignore first section
251         for(var i=1; i<path.length; ++i) {
252             object_match = object_match[path[i]];
253
254             if (object_match === undefined) {
255                 throw new openerp.base.ObjectNotFound(path_string);
256             }
257         }
258         return object_match;
259     },
260     /**
261      * Tries a number of keys, and returns the first object matching one of
262      * the keys.
263      *
264      * @param {Array} keys a sequence of keys to fetch the object for
265      * @returns {Class} the first class found matching an object
266      *
267      * @throws {openerp.base.KeyNotFound} if none of the keys was in the mapping
268      * @trows {openerp.base.ObjectNotFound} if a found object path was invalid
269      */
270     get_any: function (keys) {
271         for (var i=0; i<keys.length; ++i) {
272             try {
273                 return this.get_object(keys[i]);
274             } catch (e) {
275                 if (e instanceof openerp.base.KeyNotFound) {
276                     continue;
277                 }
278                 throw e;
279             }
280         }
281         throw new openerp.base.KeyNotFound(keys.join(','));
282     },
283     /**
284      * Adds a new key and value to the registry.
285      *
286      * This method can be chained.
287      *
288      * @param {String} key
289      * @param {String} object_path fully qualified dotted object path
290      * @returns {openerp.base.Registry} itself
291      */
292     add: function (key, object_path) {
293         this.map[key] = object_path;
294         return this;
295     },
296     /**
297      * Creates and returns a copy of the current mapping, with the provided
298      * mapping argument added in (replacing existing keys if needed)
299      *
300      * @param {Object} [mapping={}] a mapping of keys to object-paths
301      */
302     clone: function (mapping) {
303         return new openerp.base.Registry(
304             _.extend({}, this.map, mapping || {}));
305     }
306 });
307
308 openerp.base.CallbackEnabled = openerp.base.Class.extend({
309     init: function() {
310         // Transform on_* method into openerp.base.callbacks
311         for (var name in this) {
312             if(typeof(this[name]) == "function") {
313                 this[name].debug_name = name;
314                 // bind ALL function to this not only on_and _do ?
315                 if((/^on_|^do_/).test(name)) {
316                     this[name] = openerp.base.callback(this, this[name]);
317                 }
318             }
319         }
320     }
321 });
322
323 /**
324  * Utility class that any class is allowed to extend to easy common manipulations.
325  *
326  * It provides rpc calls, callback on all methods preceded by "on_" or "do_" and a
327  * logging facility.
328  */
329 openerp.base.SessionAware = openerp.base.CallbackEnabled.extend({
330     init: function(session) {
331         this._super();
332         this.session = session;
333     },
334     /**
335      * Performs a JSON-RPC call
336      *
337      * @param {String} url endpoint url
338      * @param {Object} data RPC parameters
339      * @param {Function} success RPC call success callback
340      * @param {Function} error RPC call error callback
341      * @returns {jQuery.Deferred} deferred object for the RPC call
342      */
343     rpc: function(url, data, success, error) {
344         return this.session.rpc(url, data, success, error);
345     },
346     log: function() {
347         var args = Array.prototype.slice.call(arguments);
348         var caller = arguments.callee.caller;
349         // TODO add support for line number using
350         // https://github.com/emwendelin/javascript-stacktrace/blob/master/stacktrace.js
351         // args.unshift("" + caller.debug_name);
352         this.on_log.apply(this,args);
353     },
354     on_log: function() {
355         if(window.openerp.debug || (window.location.search.indexOf('?debug') !== -1)) {
356             var notify = false;
357             var body = false;
358             if(window.console) {
359                 console.log(arguments);
360             } else {
361                 body = true;
362             }
363             var a = Array.prototype.slice.call(arguments, 0);
364             for(var i = 0; i < a.length; i++) {
365                 var v = a[i]==null ? "null" : a[i].toString();
366                 if(i==0) {
367                     notify = v.match(/^not/);
368                     body = v.match(/^bod/);
369                 }
370                 if(body) {
371                     $('<pre></pre>').text(v).appendTo($('body'));
372                 }
373                 if(notify && this.notification) {
374                     this.notification.notify("Logging:",v);
375                 }
376             }
377         }
378     }
379 });
380
381 openerp.base.Widget = openerp.base.SessionAware.extend({
382     /**
383      * The name of the QWeb template that will be used for rendering. Must be
384      * redefined in subclasses or the default render() method can not be used.
385      *
386      * @type string
387      */
388     template: null,
389     /**
390      * The prefix used to generate an id automatically. Should be redefined in
391      * subclasses. If it is not defined, a generic identifier will be used.
392      *
393      * @type string
394      */
395     identifier_prefix: 'generic-identifier-',
396     /**
397      * Construct the widget and set its parent if a parent is given.
398      *
399      * @constructs
400      * @param {openerp.base.Widget} parent Binds the current instance to the given Widget instance.
401      * When that widget is destroyed by calling stop(), the current instance will be
402      * destroyed too. Can be null.
403      * @param {String} element_id Deprecated. Sets the element_id. Only useful when you want
404      * to bind the current Widget to an already existing part of the DOM, which is not compatible
405      * with the DOM insertion methods provided by the current implementation of Widget. So
406      * for new components this argument should not be provided any more.
407      */
408     init: function(parent, /** @deprecated */ element_id) {
409         this._super((parent || {}).session);
410         // if given an element_id, try to get the associated DOM element and save
411         // a reference in this.$element. Else just generate a unique identifier.
412         this.element_id = element_id;
413         this.element_id = this.element_id || _.uniqueId(this.identifier_prefix);
414         var tmp = document.getElementById(this.element_id);
415         this.$element = tmp ? $(tmp) : undefined;
416
417         this.widget_parent = parent;
418         this.widget_children = [];
419         if(parent && parent.widget_children) {
420             parent.widget_children.push(this);
421         }
422         // useful to know if the widget was destroyed and should not be used anymore
423         this.widget_is_stopped = false;
424     },
425     /**
426      * Render the current widget and appends it to the given jQuery object or Widget.
427      *
428      * @param target A jQuery object or a Widget instance.
429      */
430     appendTo: function(target) {
431         var self = this;
432         return this._render_and_insert(function(t) {
433             self.$element.appendTo(t);
434         }, target);
435     },
436     /**
437      * Render the current widget and prepends it to the given jQuery object or Widget.
438      *
439      * @param target A jQuery object or a Widget instance.
440      */
441     prependTo: function(target) {
442         var self = this;
443         return this._render_and_insert(function(t) {
444             self.$element.prependTo(t);
445         }, target);
446     },
447     /**
448      * Render the current widget and inserts it after to the given jQuery object or Widget.
449      *
450      * @param target A jQuery object or a Widget instance.
451      */
452     insertAfter: function(target) {
453         var self = this;
454         return this._render_and_insert(function(t) {
455             self.$element.insertAfter(t);
456         }, target);
457     },
458     /**
459      * Render the current widget and inserts it before to the given jQuery object or Widget.
460      *
461      * @param target A jQuery object or a Widget instance.
462      */
463     insertBefore: function(target) {
464         var self = this;
465         return this._render_and_insert(function(t) {
466             self.$element.insertBefore(t);
467         }, target);
468     },
469     _render_and_insert: function(insertion, target) {
470         var rendered = this.render();
471         this.$element = $(rendered);
472         if (target instanceof openerp.base.Widget)
473             target = target.$element;
474         insertion(target);
475         return this.start();
476     },
477     /**
478      * Renders the widget using QWeb, `this.template` must be defined.
479      * The context given to QWeb contains the "widget" key that references `this`.
480      *
481      * @param {Object} additional Additional context arguments to pass to the template.
482      */
483     render: function (additional) {
484         return QWeb.render(this.template, _.extend({widget: this}, additional || {}));
485     },
486     /**
487      * Method called after rendering. Mostly used to bind actions, perform asynchronous
488      * calls, etc...
489      *
490      * By convention, the method should return a promise to inform the caller when
491      * this widget has been initialized.
492      *
493      * @returns {jQuery.Deferred}
494      */
495     start: function() {
496         if (!this.$element) {
497             var tmp = document.getElementById(this.element_id);
498             this.$element = tmp ? $(tmp) : undefined;
499         }
500         return $.Deferred().done().promise();
501     },
502     /**
503      * Destroys the current widget, also destory all its children before destroying itself.
504      */
505     stop: function() {
506         _.each(_.clone(this.widget_children), function(el) {
507             el.stop();
508         });
509         if(this.$element != null) {
510             this.$element.remove();
511         }
512         if (this.widget_parent && this.widget_parent.widget_children) {
513             this.widget_parent.widget_children = _.without(this.widget_parent.widget_children, this);
514         }
515         this.widget_parent = null;
516         this.widget_is_stopped = true;
517     },
518     /**
519      * Inform the action manager to do an action. Of course, this suppose that
520      * the action manager can be found amongst the ancestors of the current widget.
521      * If that's not the case this method will simply return `false`.
522      */
523     do_action: function(action, on_finished) {
524         if (this.widget_parent) {
525             return this.widget_parent.do_action(action, on_finished);
526         }
527         return false;
528     },
529     do_notify: function() {
530         if (this.widget_parent) {
531             return this.widget_parent.do_notify.apply(this,arguments);
532         }
533         return false;
534     },
535     do_warn: function() {
536         if (this.widget_parent) {
537             return this.widget_parent.do_warn.apply(this,arguments);
538         }
539         return false;
540     },
541     rpc: function(url, data, success, error) {
542         var def = $.Deferred().then(success, error);
543         var self = this;
544         this._super(url, data). then(function() {
545             if (!self.widget_is_stopped)
546                 def.resolve.apply(def, arguments);
547         }, function() {
548             if (!self.widget_is_stopped)
549                 def.reject.apply(def, arguments);
550         });
551         return def.promise();
552     }
553 });
554
555 /**
556  * @deprecated
557  * For retro compatibility only, the only difference with is that render() uses
558  * directly `this` instead of context with a "widget" key.
559  */
560 openerp.base.OldWidget = openerp.base.Widget.extend({
561     render: function (additional) {
562         return QWeb.render(this.template, _.extend(_.extend({}, this), additional || {}));
563     }
564 });
565
566 openerp.base.TranslationDataBase = openerp.base.Class.extend({
567     init: function() {
568         this.db = {};
569     },
570     set_bundle: function(translation_bundle) {
571         var self = this;
572         this.db = {};
573         var modules = _.keys(translation_bundle.modules);
574         if (_.include(modules, "base")) {
575             modules = _.without(modules, "base").concat(["base"]);
576         }
577         _.each(modules, function(name) {
578             var mod = translation_bundle.modules[name];
579             _.each(mod.messages, function(message) {
580                 self.db[message.id] = message.string;
581             });
582         });
583     },
584     build_translation_function: function() {
585         var self = this;
586         var fcnt = function(str) {
587             var tmp = self.get(str);
588             return tmp === undefined ? str : tmp;
589         }
590         fcnt.database = this;
591         return fcnt;
592     },
593     get: function(key) {
594         if (this.db[key])
595             return this.db[key];
596         return undefined;
597     }
598 });
599
600 openerp.base._t = new openerp.base.TranslationDataBase().build_translation_function();
601
602 openerp.base.Session = openerp.base.CallbackEnabled.extend( /** @lends openerp.base.Session# */{
603     /**
604      * @constructs
605      * @param element_id to use for exception reporting
606      * @param server
607      * @param port
608      */
609     init: function(server, port) {
610         this._super();
611         this.server = (server == undefined) ? location.hostname : server;
612         this.port = (port == undefined) ? location.port : port;
613         this.rpc_mode = (server == location.hostname) ? "ajax" : "jsonp";
614         this.debug = true;
615         this.db = "";
616         this.login = "";
617         this.password = "";
618         this.uid = false;
619         this.session_id = false;
620         this.module_list = [];
621         this.module_loaded = {"base": true};
622         this.context = {};
623     },
624     start: function() {
625         this.session_restore();
626     },
627     /**
628      * Executes an RPC call, registering the provided callbacks.
629      *
630      * Registers a default error callback if none is provided, and handles
631      * setting the correct session id and session context in the parameter
632      * objects
633      *
634      * @param {String} url RPC endpoint
635      * @param {Object} params call parameters
636      * @param {Function} success_callback function to execute on RPC call success
637      * @param {Function} error_callback function to execute on RPC call failure
638      * @returns {jQuery.Deferred} jquery-provided ajax deferred
639      */
640     rpc: function(url, params, success_callback, error_callback) {
641         var self = this;
642         // Construct a JSON-RPC2 request, method is currently unused
643         params.session_id = this.session_id;
644
645         // Call using the rpc_mode
646         var deferred = $.Deferred();
647         this.rpc_ajax(url, {
648             jsonrpc: "2.0",
649             method: "call",
650             params: params,
651             id:null
652         }).then(function () {deferred.resolve.apply(deferred, arguments);},
653                 function(error) {deferred.reject(error, $.Event());});
654         return deferred.fail(function() {
655             deferred.fail(function(error, event) {
656                 if (!event.isDefaultPrevented()) {
657                     self.on_rpc_error(error, event);
658                 }
659             });
660         }).then(success_callback, error_callback).promise();
661     },
662     /**
663      * Raw JSON-RPC call
664      *
665      * @returns {jQuery.Deferred} ajax-based deferred object
666      */
667     rpc_ajax: function(url, payload) {
668         var self = this;
669         this.on_rpc_request();
670         // url can be an $.ajax option object
671         if (_.isString(url)) {
672             url = {
673                 url: url
674             }
675         }
676         var ajax = _.extend({
677             type: "POST",
678             url: url,
679             dataType: 'json',
680             contentType: 'application/json',
681             data: JSON.stringify(payload),
682             processData: false
683         }, url);
684         var deferred = $.Deferred();
685         $.ajax(ajax).done(function(response, textStatus, jqXHR) {
686             self.on_rpc_response();
687             if (!response.error) {
688                 deferred.resolve(response["result"], textStatus, jqXHR);
689                 return;
690             }
691             if (response.error.data.type !== "session_invalid") {
692                 deferred.reject(response.error);
693                 return;
694             }
695             self.uid = false;
696             self.on_session_invalid(function() {
697                 self.rpc(url, payload.params,
698                     function() {
699                         deferred.resolve.apply(deferred, arguments);
700                     },
701                     function(error, event) {
702                         event.preventDefault();
703                         deferred.reject.apply(deferred, arguments);
704                     });
705             });
706         }).fail(function(jqXHR, textStatus, errorThrown) {
707             self.on_rpc_response();
708             var error = {
709                 code: -32098,
710                 message: "XmlHttpRequestError " + errorThrown,
711                 data: {type: "xhr"+textStatus, debug: jqXHR.responseText, objects: [jqXHR, errorThrown] }
712             };
713             deferred.reject(error);
714         });
715         return deferred.promise();
716     },
717     on_rpc_request: function() {
718     },
719     on_rpc_response: function() {
720     },
721     on_rpc_error: function(error) {
722     },
723     /**
724      * The session is validated either by login or by restoration of a previous session
725      */
726     on_session_valid: function() {
727         if(!openerp._modules_loaded)
728             this.load_modules();
729     },
730     on_session_invalid: function(contination) {
731     },
732     session_is_valid: function() {
733         return this.uid;
734     },
735     session_login: function(db, login, password, success_callback) {
736         var self = this;
737         this.db = db;
738         this.login = login;
739         this.password = password;
740         var params = { db: this.db, login: this.login, password: this.password };
741         this.rpc("/base/session/login", params, function(result) {
742             self.session_id = result.session_id;
743             self.uid = result.uid;
744             self.session_save();
745             self.on_session_valid();
746             if (success_callback)
747                 success_callback();
748         });
749     },
750     session_logout: function() {
751         this.uid = false;
752     },
753     /**
754      * Reloads uid and session_id from local storage, if they exist
755      */
756     session_restore: function () {
757         this.uid = this.get_cookie('uid');
758         this.session_id = this.get_cookie('session_id');
759         this.db = this.get_cookie('db');
760         this.login = this.get_cookie('login');
761         // we should do an rpc to confirm that this session_id is valid and if it is retrieve the information about db and login
762         // then call on_session_valid
763         this.on_session_valid();
764     },
765     /**
766      * Saves the session id and uid locally
767      */
768     session_save: function () {
769         this.set_cookie('uid', this.uid);
770         this.set_cookie('session_id', this.session_id);
771         this.set_cookie('db', this.db);
772         this.set_cookie('login', this.login);
773     },
774     logout: function() {
775         delete this.uid;
776         delete this.session_id;
777         delete this.db;
778         delete this.login;
779         this.set_cookie('uid', '');
780         this.set_cookie('session_id', '');
781         this.set_cookie('db', '');
782         this.set_cookie('login', '');
783         this.on_session_invalid(function() {});
784     },
785     /**
786      * Fetches a cookie stored by an openerp session
787      *
788      * @private
789      * @param name the cookie's name
790      */
791     get_cookie: function (name) {
792         var nameEQ = this.element_id + '|' + name + '=';
793         var cookies = document.cookie.split(';');
794         for(var i=0; i<cookies.length; ++i) {
795             var cookie = cookies[i].replace(/^\s*/, '');
796             if(cookie.indexOf(nameEQ) === 0) {
797                 return JSON.parse(decodeURIComponent(cookie.substring(nameEQ.length)));
798             }
799         }
800         return null;
801     },
802     /**
803      * Create a new cookie with the provided name and value
804      *
805      * @private
806      * @param name the cookie's name
807      * @param value the cookie's value
808      * @param ttl the cookie's time to live, 1 year by default, set to -1 to delete
809      */
810     set_cookie: function (name, value, ttl) {
811         ttl = ttl || 24*60*60*365;
812         document.cookie = [
813             this.element_id + '|' + name + '=' + encodeURIComponent(JSON.stringify(value)),
814             'max-age=' + ttl,
815             'expires=' + new Date(new Date().getTime() + ttl*1000).toGMTString()
816         ].join(';');
817     },
818     /**
819      * Load additional web addons of that instance and init them
820      */
821     load_modules: function() {
822         var self = this;
823         this.rpc('/base/session/modules', {}, function(result) {
824             self.module_list = result;
825             self.rpc('/base/webclient/translations', {mods: ["base"].concat(result), lang: "fr"})
826                 .then(function(transs) {
827                 openerp.base._t.database.set_bundle(transs);
828                 var modules = self.module_list.join(',');
829                 if(self.debug || true) {
830                     self.rpc('/base/webclient/csslist', {"mods": modules}, self.do_load_css);
831                     self.rpc('/base/webclient/jslist', {"mods": modules}, self.do_load_js);
832                 } else {
833                     self.do_load_css(["/base/webclient/css?mods="+modules]);
834                     self.do_load_js(["/base/webclient/js?mods="+modules]);
835                 }
836                 openerp._modules_loaded = true;
837             });
838         });
839     },
840     do_load_css: function (files) {
841         _.each(files, function (file) {
842             $('head').append($('<link>', {
843                 'href': file,
844                 'rel': 'stylesheet',
845                 'type': 'text/css'
846             }));
847         });
848     },
849     do_load_js: function(files) {
850         var self = this;
851         if(files.length != 0) {
852             var file = files.shift();
853             var tag = document.createElement('script');
854             tag.type = 'text/javascript';
855             tag.src = file;
856             tag.onload = tag.onreadystatechange = function() {
857                 if ( (tag.readyState && tag.readyState != "loaded" && tag.readyState != "complete") || tag.onload_done )
858                     return;
859                 tag.onload_done = true;
860                 self.do_load_js(files);
861             };
862             document.head.appendChild(tag);
863         } else {
864             this.on_modules_loaded();
865         }
866     },
867     on_modules_loaded: function() {
868         for(var j=0; j<this.module_list.length; j++) {
869             var mod = this.module_list[j];
870             if(this.module_loaded[mod])
871                 continue;
872             openerp[mod] = {};
873             // init module mod
874             if(openerp._openerp[mod] != undefined) {
875                 openerp._openerp[mod]._T = openerp.base._t.database.build_translation_function();
876                 openerp._openerp[mod](openerp);
877                 this.module_loaded[mod] = true;
878             }
879         }
880     }
881 });
882
883 };
884
885 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: