c6c2b21f9d41edbee04dd5720ef661e0ac8ba111
[odoo/odoo.git] / addons / website / static / src / js / website.js
1 (function() {
2     "use strict";
3
4     var website = {};
5     // The following line can be removed in 2017
6     openerp.website = website;
7
8     website.get_context = function (dict) {
9         var html = document.documentElement;
10         return _.extend({
11             lang: html.getAttribute('lang').replace('-', '_'),
12             website_id: html.getAttribute('data-website-id')|0
13         }, dict);
14     };
15
16     website.parseQS = function (qs) {
17         var match,
18             params = {},
19             pl     = /\+/g,  // Regex for replacing addition symbol with a space
20             search = /([^&=]+)=?([^&]*)/g;
21
22         while ((match = search.exec(qs))) {
23             var name = decodeURIComponent(match[1].replace(pl, " "));
24             var value = decodeURIComponent(match[2].replace(pl, " "));
25             params[name] = value;
26         }
27         return params;
28     };
29
30     var parsedSearch;
31     website.parseSearch = function () {
32         if (!parsedSearch) {
33             parsedSearch = website.parseQS(window.location.search.substring(1));
34         }
35         return parsedSearch;
36     };
37     website.parseHash = function () {
38         return website.parseQS(window.location.hash.substring(1));
39     };
40
41     /* ----- TEMPLATE LOADING ---- */
42     var templates_def = $.Deferred().resolve();
43     website.add_template_file = function(template) {
44         templates_def = templates_def.then(function() {
45             var def = $.Deferred();
46             openerp.qweb.add_template(template, function(err) {
47                 if (err) {
48                     def.reject(err);
49                 } else {
50                     def.resolve();
51                 }
52             });
53             return def;
54         });
55     };
56     website.add_template_file('/website/static/src/xml/website.xml');
57     website.reload = function () {
58         location.hash = "scrollTop=" + window.document.body.scrollTop;
59         if (location.search.indexOf("enable_editor") > -1) {
60             window.location.href = window.location.href.replace(/enable_editor(=[^&]*)?/g, '');
61         } else {
62             window.location.reload();
63         }
64     };
65
66     var all_ready = null;
67     var dom_ready = website.dom_ready = $.Deferred();
68     $(document).ready(function () {
69         website.is_editable = website.is_editable || $('html').data('editable');
70         website.is_editable_button= website.is_editable_button || $('html').data('editable');
71         dom_ready.resolve();
72     });
73
74     website.init_kanban = function ($kanban) {
75         $('.js_kanban_col', $kanban).each(function () {
76             var $col = $(this);
77             var $pagination = $('.pagination', $col);
78             if(!$pagination.size()) {
79                 return;
80             }
81
82             var page_count =  $col.data('page_count');
83             var scope = $pagination.last().find("li").size()-2;
84             var kanban_url_col = $pagination.find("li a:first").attr("href").replace(/[0-9]+$/, '');
85
86             var data = {
87                 'domain': $col.data('domain'),
88                 'model': $col.data('model'),
89                 'template': $col.data('template'),
90                 'step': $col.data('step'),
91                 'orderby': $col.data('orderby')
92             };
93
94             $pagination.on('click', 'a', function (ev) {
95                 ev.preventDefault();
96                 var $a = $(ev.target);
97                 if($a.parent().hasClass('active')) {
98                     return;
99                 }
100
101                 var page = +$a.attr("href").split(",").pop().split('-')[1];
102                 data['page'] = page;
103
104                 $.post('/website/kanban/', data, function (col) {
105                     $col.find("> .thumbnail").remove();
106                     $pagination.last().before(col);
107                 });
108
109                 var page_start = page - parseInt(Math.floor((scope-1)/2), 10);
110                 if (page_start < 1 ) page_start = 1;
111                 var page_end = page_start + (scope-1);
112                 if (page_end > page_count ) page_end = page_count;
113
114                 if (page_end - page_start < scope) {
115                     page_start = page_end - scope > 0 ? page_end - scope : 1;
116                 }
117
118                 $pagination.find('li.prev a').attr("href", kanban_url_col+(page-1 > 0 ? page-1 : 1));
119                 $pagination.find('li.next a').attr("href", kanban_url_col+(page < page_end ? page+1 : page_end));
120                 for(var i=0; i < scope; i++) {
121                     $pagination.find('li:not(.prev):not(.next):eq('+i+') a').attr("href", kanban_url_col+(page_start+i)).html(page_start+i);
122                 }
123                 $pagination.find('li.active').removeClass('active');
124                 $pagination.find('li:has(a[href="'+kanban_url_col+page+'"])').addClass('active');
125
126             });
127
128         });
129     };
130
131     /**
132      * Returns a deferred resolved when the templates are loaded
133      * and the Widgets can be instanciated.
134      */
135     website.ready = function() {
136         if (!all_ready) {
137             all_ready = dom_ready.then(function () {
138                 return templates_def;
139             }).then(function () {
140                 if (website.is_editable) {
141                     website.id = $('html').data('website-id');
142                     website.session = new openerp.Session();
143                     var modules = ['website'];
144                     return openerp._t.database.load_translations(website.session, modules, website.get_context().lang);
145                 }
146             }).promise();
147         }
148         return all_ready;
149     };
150
151     website.error = function(data, url) {
152         var $error = $(openerp.qweb.render('website.error_dialog', {
153             'title': data.data ? data.data.arguments[0] : data.statusText,
154             'message': data.data ? data.data.arguments[1] : "",
155             'backend_url': url
156         }));
157         $error.appendTo("body");
158         $error.modal('show');
159     };
160
161     website.prompt = function (options) {
162         /**
163          * A bootstrapped version of prompt() albeit asynchronous
164          * This was built to quickly prompt the user with a single field.
165          * For anything more complex, please use editor.Dialog class
166          *
167          * Usage Ex:
168          *
169          * website.prompt("What... is your quest ?").then(function (answer) {
170          *     arthur.reply(answer || "To seek the Holy Grail.");
171          * });
172          *
173          * website.prompt({
174          *     select: "Please choose your destiny",
175          *     init: function() {
176          *         return [ [0, "Sub-Zero"], [1, "Robo-Ky"] ];
177          *     }
178          * }).then(function (answer) {
179          *     mame_station.loadCharacter(answer);
180          * });
181          *
182          * @param {Object|String} options A set of options used to configure the prompt or the text field name if string
183          * @param {String} [options.window_title=''] title of the prompt modal
184          * @param {String} [options.input] tell the modal to use an input text field, the given value will be the field title
185          * @param {String} [options.textarea] tell the modal to use a textarea field, the given value will be the field title
186          * @param {String} [options.select] tell the modal to use a select box, the given value will be the field title
187          * @param {Object} [options.default=''] default value of the field
188          * @param {Function} [options.init] optional function that takes the `field` (enhanced with a fillWith() method) and the `dialog` as parameters [can return a deferred]
189          */
190         if (typeof options === 'string') {
191             options = {
192                 text: options
193             };
194         }
195         options = _.extend({
196             window_title: '',
197             field_name: '',
198             default: '',
199             init: function() {}
200         }, options || {});
201
202         var type = _.intersection(Object.keys(options), ['input', 'textarea', 'select']);
203         type = type.length ? type[0] : 'text';
204         options.field_type = type;
205         options.field_name = options.field_name || options[type];
206
207         var def = $.Deferred();
208         var dialog = $(openerp.qweb.render('website.prompt', options)).appendTo("body");
209         var field = dialog.find(options.field_type).first();
210         field.val(options.default);
211         field.fillWith = function (data) {
212             if (field.is('select')) {
213                 var select = field[0];
214                 data.forEach(function (item) {
215                     select.options[select.options.length] = new Option(item[1], item[0]);
216                 });
217             } else {
218                 field.val(data);
219             }
220         };
221         var init = options.init(field, dialog);
222         $.when(init).then(function (fill) {
223             if (fill) {
224                 field.fillWith(fill);
225             }
226             dialog.modal('show');
227             field.focus();
228             dialog.on('click', '.btn-primary', function () {
229                 def.resolve(field.val(), field);
230                 dialog.remove();
231             });
232         });
233         dialog.on('hidden.bs.modal', function () {
234             def.reject();
235             dialog.remove();
236         });
237         if (field.is('input[type="text"], select')) {
238             field.keypress(function (e) {
239                 if (e.which == 13) {
240                     e.preventDefault();
241                     dialog.find('.btn-primary').trigger('click');
242                 }
243             });
244         }
245         return def;
246     };
247
248     website.form = function (url, method, params) {
249         var form = document.createElement('form');
250         form.action = url;
251         form.method = method;
252         _.each(params, function (v, k) {
253             var param = document.createElement('input');
254             param.type = 'hidden';
255             param.name = k;
256             param.value = v;
257             form.appendChild(param);
258         });
259         document.body.appendChild(form);
260         form.submit();
261     };
262
263     dom_ready.then(function () {
264
265         /* ----- BOOTSTRAP  STUFF ---- */
266         // $('.js_tooltip').bstooltip();
267
268         /* ----- PUBLISHING STUFF ---- */
269         $(document).on('click', '.js_publish_management .js_publish_btn', function () {
270             var $data = $(this).parents(".js_publish_management:first");
271             var self=this;
272             openerp.jsonRpc($data.data('controller') || '/website/publish', 'call', {'id': +$data.data('id'), 'object': $data.data('object')})
273                 .then(function (result) {
274                     $data.toggleClass("css_unpublished css_published");
275                     $data.parents("[data-publish]").attr("data-publish", +result ? 'on' : 'off');
276                 }).fail(function (err, data) {
277                     website.error(data, '/web#return_label=Website&model='+$data.data('object')+'&id='+$data.data('id'));
278                 });
279         });
280
281         /* ----- KANBAN WEBSITE ---- */
282         $('.js_kanban').each(function () {
283             website.init_kanban(this);
284         });
285
286         setTimeout(function () {
287             if (window.location.hash.indexOf("scrollTop=") > -1) {
288                 window.document.body.scrollTop = +location.hash.match(/scrollTop=([0-9]+)/)[1];
289             }
290         },0);
291     });
292
293     return website;
294 })();