kivi.js: alle jshint-Warnungen beseitigt & auf strict umgestellt
[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   // Return a function object by its name (a string). Works both with
292   // global functions (e.g. "check_right_date_format") and those in
293   // namespaces (e.g. "kivi.t8").
294   // Returns null if the object is not found.
295   ns.get_function_by_name = function(name) {
296     var parts = name.match("(.+)\\.([^\\.]+)$");
297     if (!parts)
298       return window[name];
299     return namespace(parts[1])[ parts[2] ];
300   };
301
302   // Open a modal jQuery UI popup dialog. The content can be either
303   // loaded via AJAX (if the parameter 'url' is given) or simply
304   // displayed if it exists in the DOM already (referenced via
305   // 'id') or given via param.html. If an existing DOM div should be used then
306   // the element won't be removed upon closing the dialog which allows
307   // re-opening it later on.
308   //
309   // Parameters:
310   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
311   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
312   // - dialog: an optional object of options passed to the $.dialog() call
313   // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
314   ns.popup_dialog = function(params) {
315     var dialog;
316
317     params            = params        || { };
318     var id            = params.id     || 'jqueryui_popup_dialog';
319     var custom_close  = params.dialog ? params.dialog.close : undefined;
320     var dialog_params = $.extend(
321       { // kivitendo default parameters:
322           width:  800
323         , height: 500
324         , modal:  true
325       },
326         // User supplied options:
327       params.dialog || { },
328       { // Options that must not be changed:
329         close: function(event, ui) {
330           if (custom_close)
331             custom_close();
332
333           if (params.url || params.html)
334             dialog.remove();
335           else
336             dialog.dialog('close');
337         }
338       });
339
340     if (!params.url && !params.html) {
341       // Use existing DOM element and show it. No AJAX call.
342       dialog =
343         $('#' + id)
344         .bind('dialogopen', function() {
345           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
346         })
347         .dialog(dialog_params);
348       return true;
349     }
350
351     $('#' + id).remove();
352
353     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
354     dialog.dialog(dialog_params);
355
356     if (params.html) {
357       dialog.html(params.html);
358     } else {
359       // no html? get it via ajax
360       $.ajax({
361         url:     params.url,
362         data:    params.data,
363         type:    params.type,
364         success: function(new_html) {
365           dialog.html(new_html);
366           dialog.removeClass('loading');
367           if (params.load)
368             params.load();
369         }
370       });
371     }
372
373     return true;
374   };
375
376   // Run code only once for each matched element
377   //
378   // This allows running the function 'code' exactly once for each
379   // element that matches 'selector'. This is achieved by storing the
380   // state with jQuery's 'data' function. The 'identification' is
381   // required for differentiating unambiguously so that different code
382   // functions can still be run on the same elements.
383   //
384   // 'code' can be either a function or the name of one. It must
385   // resolve to a function that receives the jQueryfied element as its
386   // sole argument.
387   //
388   // Returns nothing.
389   ns.run_once_for = function(selector, identification, code) {
390     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
391     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
392     if (!fn) {
393       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
394       return;
395     }
396
397     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
398       var $elt = $(elt);
399       $elt.data(attr_name, true);
400       fn($elt);
401     });
402   };
403
404   // Run a function by its name passing it some arguments
405   //
406   // This is a function useful mainly for the ClientJS functionality.
407   // It finds a function by its name and then executes it on an empty
408   // object passing the elements in 'args' (an array) as the function
409   // parameters retuning its result.
410   //
411   // Logs an error to the console and returns 'undefined' if the
412   // function cannot be found.
413   ns.run = function(function_name, args) {
414     var fn = ns.get_function_by_name(function_name);
415     if (fn)
416       return fn.apply({}, args);
417
418     console.error('kivi.run("' + function_name + '"): No function by that name found');
419     return undefined;
420   };
421
422   ns.detect_duplicate_ids_in_dom = function() {
423     var ids   = {},
424         found = false;
425
426     $('[id]').each(function() {
427       if (this.id && ids[this.id]) {
428         found = true;
429         console.warn('Duplicate ID #' + this.id);
430       }
431       ids[this.id] = 1;
432     });
433
434     if (!found)
435       console.log('No duplicate IDs found :)');
436   };
437 });
438
439 kivi = namespace('kivi');