Merge branch 'f-chart-picker-in-gl'
[kivitendo-erp.git] / js / kivi.js
1 namespace("kivi", function(ns) {
2   "use strict";
3
4   ns._locale = {};
5   ns._date_format   = {
6     sep: '.',
7     y:   2,
8     m:   1,
9     d:   0
10   };
11   ns._number_format = {
12     decimalSep:  ',',
13     thousandSep: '.'
14   };
15
16   ns.setup_formats = function(params) {
17     var res = (params.dates || "").match(/^([ymd]+)([^a-z])([ymd]+)[^a-z]([ymd]+)$/);
18     if (res) {
19       ns._date_format                      = { sep: res[2] };
20       ns._date_format[res[1].substr(0, 1)] = 0;
21       ns._date_format[res[3].substr(0, 1)] = 1;
22       ns._date_format[res[4].substr(0, 1)] = 2;
23     }
24
25     res = (params.numbers || "").match(/^\d*([^\d]?)\d+([^\d])\d+$/);
26     if (res)
27       ns._number_format = {
28         decimalSep:  res[2],
29         thousandSep: res[1]
30       };
31   };
32
33   ns.parse_date = function(date) {
34     var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
35     date     = new Date(
36       ((parts[ ns._date_format.y ] || 0) * 1) || (new Date()).getFullYear(),
37        (parts[ ns._date_format.m ] || 0) * 1 - 1, // Months are 0-based.
38        (parts[ ns._date_format.d ] || 0) * 1
39     );
40
41     return isNaN(date.getTime()) ? undefined : date;
42   };
43
44   ns.format_date = function(date) {
45     if (isNaN(date.getTime()))
46       return undefined;
47
48     var parts = [ "", "", "" ]
49     parts[ ns._date_format.y ] = date.getFullYear();
50     parts[ ns._date_format.m ] = (date.getMonth() <  9 ? "0" : "") + (date.getMonth() + 1); // Months are 0-based, but days are 1-based.
51     parts[ ns._date_format.d ] = (date.getDate()  < 10 ? "0" : "") + date.getDate();
52     return parts.join(ns._date_format.sep);
53   };
54
55   ns.parse_amount = function(amount) {
56     if ((amount === undefined) || (amount === ''))
57       return 0;
58
59     if (ns._number_format.decimalSep == ',')
60       amount = amount.replace(/\./g, "").replace(/,/g, ".");
61
62     amount = amount.replace(/[\',]/g, "")
63
64     /* jshint -W061 */
65     return eval(amount);
66   };
67
68   ns.round_amount = function(amount, places) {
69     var neg  = amount >= 0 ? 1 : -1;
70     var mult = Math.pow(10, places + 1);
71     var temp = Math.abs(amount) * mult;
72     var diff = Math.abs(1 - temp + Math.floor(temp));
73     temp     = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
74     var dec  = temp % 10;
75     temp    += dec >= 5 ? 10 - dec: dec * -1;
76
77     return neg * temp / mult;
78   };
79
80   ns.format_amount = function(amount, places) {
81     amount = amount || 0;
82
83     if ((places !== undefined) && (places >= 0))
84       amount = ns.round_amount(amount, Math.abs(places));
85
86     var parts = ("" + Math.abs(amount)).split(/\./);
87     var intg  = parts[0];
88     var dec   = parts.length > 1 ? parts[1] : "";
89     var sign  = amount  < 0      ? "-"      : "";
90
91     if (places !== undefined) {
92       while (dec.length < Math.abs(places))
93         dec += "0";
94
95       if ((places > 0) && (dec.length > Math.abs(places)))
96         dec = d.substr(0, places);
97     }
98
99     if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
100       var len   = ((intg.length + 2) % 3) + 1,
101           start = len,
102           res   = intg.substr(0, len);
103       while (start < intg.length) {
104         res   += ns._number_format.thousandSep + intg.substr(start, 3);
105         start += 3;
106       }
107
108       intg = res;
109     }
110
111     var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
112
113     return sign + intg + sep + dec;
114   };
115
116   ns.t8 = function(text, params) {
117     text = ns._locale[text] || text;
118     var key, value
119
120     if( Object.prototype.toString.call( params ) === '[object Array]' ) {
121       var len = params.length;
122
123       for(var i=0; i<len; ++i) {
124         key = i + 1;
125         value = params[i];
126         text = text.split("#"+ key).join(value);
127       }
128     }
129     else if( typeof params == 'object' ) {
130       for(key in params) {
131         value = params[key];
132         text = text.split("#{"+ key +"}").join(value);
133       }
134     }
135
136     return text;
137   };
138
139   ns.setupLocale = function(locale) {
140     ns._locale = locale;
141   };
142
143   ns.set_focus = function(element) {
144     var $e = $(element).eq(0);
145     if ($e.data('ckeditorInstance'))
146       ns.focus_ckeditor_when_ready($e);
147     else
148       $e.focus();
149   };
150
151   ns.focus_ckeditor_when_ready = function(element) {
152     $(element).ckeditor(function() { ns.focus_ckeditor(element); });
153   };
154
155   ns.focus_ckeditor = function(element) {
156     var editor   = $(element).ckeditorGet();
157                 var editable = editor.editable();
158
159                 if (editable.is('textarea')) {
160                         var textarea = editable.$;
161
162                         if (CKEDITOR.env.ie)
163                                 textarea.createTextRange().execCommand('SelectAll');
164                         else {
165                                 textarea.selectionStart = 0;
166                                 textarea.selectionEnd   = textarea.value.length;
167                         }
168
169                         textarea.focus();
170
171                 } else {
172                         if (editable.is('body'))
173                                 editor.document.$.execCommand('SelectAll', false, null);
174
175                         else {
176                                 var range = editor.createRange();
177                                 range.selectNodeContents(editable);
178                                 range.select();
179                         }
180
181                         editor.forceNextSelectionCheck();
182                         editor.selectionChange();
183
184       editor.focus();
185                 }
186   };
187
188   ns.init_tabwidget = function(element) {
189     var $element   = $(element);
190     var tabsParams = {};
191     var elementId  = $element.attr('id');
192
193     if (elementId) {
194       var cookieName      = 'jquery_ui_tab_'+ elementId;
195       tabsParams.active   = $.cookie(cookieName);
196       tabsParams.activate = function(event, ui) {
197         var i = ui.newTab.parent().children().index(ui.newTab);
198         $.cookie(cookieName, i);
199       };
200     }
201
202     $element.tabs(tabsParams);
203   };
204
205   ns.init_text_editor = function(element) {
206     var layouts = {
207       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
208       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
209     };
210
211     var $e      = $(element);
212     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
213     var config  = {
214       entities:      false,
215       language:      'de',
216       removePlugins: 'resize',
217       toolbar:       buttons
218     }
219
220     var style = $e.prop('style');
221     $(['width', 'height']).each(function(idx, prop) {
222       var matches = (style[prop] || '').match(/(\d+)px/);
223       if (matches && (matches.length > 1))
224         config[prop] = matches[1];
225     });
226
227     $e.ckeditor(config);
228
229     if ($e.hasClass('texteditor-autofocus'))
230       $e.ckeditor(function() { ns.focus_ckeditor($e); });
231   };
232
233   ns.reinit_widgets = function() {
234     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
235       $(elt).datepicker();
236     });
237
238     if (ns.PartPicker)
239       ns.run_once_for('input.part_autocomplete', 'part_picker', function(elt) {
240         kivi.PartPicker($(elt));
241       });
242
243     if (ns.ProjectPicker)
244       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
245         kivi.ProjectPicker($(elt));
246       });
247
248     if (ns.CustomerVendorPicker)
249       ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
250         kivi.CustomerVendorPicker($(elt));
251       });
252
253     if (ns.ChartPicker)
254       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
255         kivi.ChartPicker($(elt));
256       });
257
258
259     var func = kivi.get_function_by_name('local_reinit_widgets');
260     if (func)
261       func();
262
263     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
264       $(elt).tooltipster({
265         contentAsHTML: false,
266         theme: 'tooltipster-light'
267       })
268     });
269
270     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
271       $(elt).tooltipster({
272         contentAsHTML: true,
273         theme: 'tooltipster-light'
274       })
275     });
276
277     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
278     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
279   };
280
281   ns.submit_ajax_form = function(url, form_selector, additional_data) {
282     $(form_selector).ajaxSubmit({
283       url:     url,
284       data:    additional_data,
285       success: ns.eval_json_result
286     });
287
288     return true;
289   };
290
291   // This function submits an existing form given by "form_selector"
292   // and sets the "action" input to "action_to_call" before submitting
293   // it. Any existing input named "action" will be removed prior to
294   // submitting.
295   ns.submit_form_with_action = function(form_selector, action_to_call) {
296     $('[name=action]').remove();
297
298     var $form   = $(form_selector);
299     var $hidden = $('<input type=hidden>');
300
301     $hidden.attr('name',  'action');
302     $hidden.attr('value', action_to_call);
303     $form.append($hidden);
304
305     $form.submit();
306   };
307
308   // This function exists solely so that it can be found with
309   // kivi.get_functions_by_name() and called later on. Using something
310   // like "var func = history["back"]" works, but calling it later
311   // with "func.apply()" doesn't.
312   ns.history_back = function() {
313     history.back();
314   };
315
316   // Call arbitrary jQuery functions on arbitrary objects with
317   // arbitrary arguments. The use case is to allow eval_json_result
318   // using code to call simple jQuery stuff without having it to wrap
319   // them in their own small functions.
320   // Example usage with ActionBar:
321   //   call => [ 'kivi.call_jquery', '#form', 'resetForm' ],
322   ns.call_jquery = function(this_arg, function_name) {
323     var func = jQuery.fn[function_name];
324     if (!func)
325       return;
326
327     var args = Array.from(arguments);
328     args.splice(0, 2);
329
330     return func.apply($(this_arg), args);
331   };
332
333   // Return a function object by its name (a string). Works both with
334   // global functions (e.g. "check_right_date_format") and those in
335   // namespaces (e.g. "kivi.t8").
336   // Returns null if the object is not found.
337   ns.get_function_by_name = function(name) {
338     var parts = name.match("(.+)\\.([^\\.]+)$");
339     if (!parts)
340       return window[name];
341     return namespace(parts[1])[ parts[2] ];
342   };
343
344   // Open a modal jQuery UI popup dialog. The content can be either
345   // loaded via AJAX (if the parameter 'url' is given) or simply
346   // displayed if it exists in the DOM already (referenced via
347   // 'id') or given via param.html. If an existing DOM div should be used then
348   // the element won't be removed upon closing the dialog which allows
349   // re-opening it later on.
350   //
351   // Parameters:
352   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
353   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
354   // - dialog: an optional object of options passed to the $.dialog() call
355   // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
356   ns.popup_dialog = function(params) {
357     var dialog;
358
359     params            = params        || { };
360     var id            = params.id     || 'jqueryui_popup_dialog';
361     var custom_close  = params.dialog ? params.dialog.close : undefined;
362     var dialog_params = $.extend(
363       { // kivitendo default parameters:
364           width:  800
365         , height: 500
366         , modal:  true
367       },
368         // User supplied options:
369       params.dialog || { },
370       { // Options that must not be changed:
371         close: function(event, ui) {
372           if (custom_close)
373             custom_close();
374
375           if (params.url || params.html)
376             dialog.remove();
377           else
378             dialog.dialog('close');
379         }
380       });
381
382     if (!params.url && !params.html) {
383       // Use existing DOM element and show it. No AJAX call.
384       dialog =
385         $('#' + id)
386         .bind('dialogopen', function() {
387           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
388         })
389         .dialog(dialog_params);
390       return true;
391     }
392
393     $('#' + id).remove();
394
395     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
396     dialog.dialog(dialog_params);
397
398     if (params.html) {
399       dialog.html(params.html);
400     } else {
401       // no html? get it via ajax
402       $.ajax({
403         url:     params.url,
404         data:    params.data,
405         type:    params.type,
406         success: function(new_html) {
407           dialog.html(new_html);
408           dialog.removeClass('loading');
409           if (params.load)
410             params.load();
411         }
412       });
413     }
414
415     return true;
416   };
417
418   // Run code only once for each matched element
419   //
420   // This allows running the function 'code' exactly once for each
421   // element that matches 'selector'. This is achieved by storing the
422   // state with jQuery's 'data' function. The 'identification' is
423   // required for differentiating unambiguously so that different code
424   // functions can still be run on the same elements.
425   //
426   // 'code' can be either a function or the name of one. It must
427   // resolve to a function that receives the jQueryfied element as its
428   // sole argument.
429   //
430   // Returns nothing.
431   ns.run_once_for = function(selector, identification, code) {
432     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
433     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
434     if (!fn) {
435       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
436       return;
437     }
438
439     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
440       var $elt = $(elt);
441       $elt.data(attr_name, true);
442       fn($elt);
443     });
444   };
445
446   // Run a function by its name passing it some arguments
447   //
448   // This is a function useful mainly for the ClientJS functionality.
449   // It finds a function by its name and then executes it on an empty
450   // object passing the elements in 'args' (an array) as the function
451   // parameters retuning its result.
452   //
453   // Logs an error to the console and returns 'undefined' if the
454   // function cannot be found.
455   ns.run = function(function_name, args) {
456     var fn = ns.get_function_by_name(function_name);
457     if (fn)
458       return fn.apply({}, args);
459
460     console.error('kivi.run("' + function_name + '"): No function by that name found');
461     return undefined;
462   };
463
464   ns.detect_duplicate_ids_in_dom = function() {
465     var ids   = {},
466         found = false;
467
468     $('[id]').each(function() {
469       if (this.id && ids[this.id]) {
470         found = true;
471         console.warn('Duplicate ID #' + this.id);
472       }
473       ids[this.id] = 1;
474     });
475
476     if (!found)
477       console.log('No duplicate IDs found :)');
478   };
479 });
480
481 kivi = namespace('kivi');