kivi.parse_amount: bei ungültigen mathematischen Ausdrücken 0 zurückliefern
[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     // Make sure no code wich is not a math expression ends up in eval().
65     if (!amount.match(/^[0-9 ()\-+*/.]*$/))
66       return 0;
67
68     /* jshint -W061 */
69     try {
70       return eval(amount);
71     } catch (err) {
72       return 0;
73     }
74   };
75
76   ns.round_amount = function(amount, places) {
77     var neg  = amount >= 0 ? 1 : -1;
78     var mult = Math.pow(10, places + 1);
79     var temp = Math.abs(amount) * mult;
80     var diff = Math.abs(1 - temp + Math.floor(temp));
81     temp     = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
82     var dec  = temp % 10;
83     temp    += dec >= 5 ? 10 - dec: dec * -1;
84
85     return neg * temp / mult;
86   };
87
88   ns.format_amount = function(amount, places) {
89     amount = amount || 0;
90
91     if ((places !== undefined) && (places >= 0))
92       amount = ns.round_amount(amount, Math.abs(places));
93
94     var parts = ("" + Math.abs(amount)).split(/\./);
95     var intg  = parts[0];
96     var dec   = parts.length > 1 ? parts[1] : "";
97     var sign  = amount  < 0      ? "-"      : "";
98
99     if (places !== undefined) {
100       while (dec.length < Math.abs(places))
101         dec += "0";
102
103       if ((places > 0) && (dec.length > Math.abs(places)))
104         dec = d.substr(0, places);
105     }
106
107     if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
108       var len   = ((intg.length + 2) % 3) + 1,
109           start = len,
110           res   = intg.substr(0, len);
111       while (start < intg.length) {
112         res   += ns._number_format.thousandSep + intg.substr(start, 3);
113         start += 3;
114       }
115
116       intg = res;
117     }
118
119     var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
120
121     return sign + intg + sep + dec;
122   };
123
124   ns.t8 = function(text, params) {
125     text = ns._locale[text] || text;
126     var key, value
127
128     if( Object.prototype.toString.call( params ) === '[object Array]' ) {
129       var len = params.length;
130
131       for(var i=0; i<len; ++i) {
132         key = i + 1;
133         value = params[i];
134         text = text.split("#"+ key).join(value);
135       }
136     }
137     else if( typeof params == 'object' ) {
138       for(key in params) {
139         value = params[key];
140         text = text.split("#{"+ key +"}").join(value);
141       }
142     }
143
144     return text;
145   };
146
147   ns.setupLocale = function(locale) {
148     ns._locale = locale;
149   };
150
151   ns.set_focus = function(element) {
152     var $e = $(element).eq(0);
153     if ($e.data('ckeditorInstance'))
154       ns.focus_ckeditor_when_ready($e);
155     else
156       $e.focus();
157   };
158
159   ns.focus_ckeditor_when_ready = function(element) {
160     $(element).ckeditor(function() { ns.focus_ckeditor(element); });
161   };
162
163   ns.focus_ckeditor = function(element) {
164     var editor   = $(element).ckeditorGet();
165                 var editable = editor.editable();
166
167                 if (editable.is('textarea')) {
168                         var textarea = editable.$;
169
170                         if (CKEDITOR.env.ie)
171                                 textarea.createTextRange().execCommand('SelectAll');
172                         else {
173                                 textarea.selectionStart = 0;
174                                 textarea.selectionEnd   = textarea.value.length;
175                         }
176
177                         textarea.focus();
178
179                 } else {
180                         if (editable.is('body'))
181                                 editor.document.$.execCommand('SelectAll', false, null);
182
183                         else {
184                                 var range = editor.createRange();
185                                 range.selectNodeContents(editable);
186                                 range.select();
187                         }
188
189                         editor.forceNextSelectionCheck();
190                         editor.selectionChange();
191
192       editor.focus();
193                 }
194   };
195
196   ns.init_tabwidget = function(element) {
197     var $element   = $(element);
198     var tabsParams = {};
199     var elementId  = $element.attr('id');
200
201     if (elementId) {
202       var cookieName      = 'jquery_ui_tab_'+ elementId;
203       tabsParams.active   = $.cookie(cookieName);
204       tabsParams.activate = function(event, ui) {
205         var i = ui.newTab.parent().children().index(ui.newTab);
206         $.cookie(cookieName, i);
207       };
208     }
209
210     $element.tabs(tabsParams);
211   };
212
213   ns.init_text_editor = function(element) {
214     var layouts = {
215       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
216       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
217     };
218
219     var $e      = $(element);
220     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
221     var config  = {
222       entities:      false,
223       language:      'de',
224       removePlugins: 'resize',
225       toolbar:       buttons
226     }
227
228     var style = $e.prop('style');
229     $(['width', 'height']).each(function(idx, prop) {
230       var matches = (style[prop] || '').match(/(\d+)px/);
231       if (matches && (matches.length > 1))
232         config[prop] = matches[1];
233     });
234
235     $e.ckeditor(config);
236
237     if ($e.hasClass('texteditor-autofocus'))
238       $e.ckeditor(function() { ns.focus_ckeditor($e); });
239   };
240
241   ns.reinit_widgets = function() {
242     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
243       $(elt).datepicker();
244     });
245
246     if (ns.PartPicker)
247       ns.run_once_for('input.part_autocomplete', 'part_picker', function(elt) {
248         kivi.PartPicker($(elt));
249       });
250
251     if (ns.ProjectPicker)
252       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
253         kivi.ProjectPicker($(elt));
254       });
255
256     if (ns.CustomerVendorPicker)
257       ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
258         kivi.CustomerVendorPicker($(elt));
259       });
260
261     if (ns.ChartPicker)
262       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
263         kivi.ChartPicker($(elt));
264       });
265
266
267     var func = kivi.get_function_by_name('local_reinit_widgets');
268     if (func)
269       func();
270
271     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
272       $(elt).tooltipster({
273         contentAsHTML: false,
274         theme: 'tooltipster-light'
275       })
276     });
277
278     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
279       $(elt).tooltipster({
280         contentAsHTML: true,
281         theme: 'tooltipster-light'
282       })
283     });
284
285     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
286     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
287   };
288
289   ns.submit_ajax_form = function(url, form_selector, additional_data) {
290     $(form_selector).ajaxSubmit({
291       url:     url,
292       data:    additional_data,
293       success: ns.eval_json_result
294     });
295
296     return true;
297   };
298
299   // This function submits an existing form given by "form_selector"
300   // and sets the "action" input to "action_to_call" before submitting
301   // it. Any existing input named "action" will be removed prior to
302   // submitting.
303   ns.submit_form_with_action = function(form_selector, action_to_call) {
304     $('[name=action]').remove();
305
306     var $form   = $(form_selector);
307     var $hidden = $('<input type=hidden>');
308
309     $hidden.attr('name',  'action');
310     $hidden.attr('value', action_to_call);
311     $form.append($hidden);
312
313     $form.submit();
314   };
315
316   // This function exists solely so that it can be found with
317   // kivi.get_functions_by_name() and called later on. Using something
318   // like "var func = history["back"]" works, but calling it later
319   // with "func.apply()" doesn't.
320   ns.history_back = function() {
321     history.back();
322   };
323
324   // Return a function object by its name (a string). Works both with
325   // global functions (e.g. "check_right_date_format") and those in
326   // namespaces (e.g. "kivi.t8").
327   // Returns null if the object is not found.
328   ns.get_function_by_name = function(name) {
329     var parts = name.match("(.+)\\.([^\\.]+)$");
330     if (!parts)
331       return window[name];
332     return namespace(parts[1])[ parts[2] ];
333   };
334
335   // Open a modal jQuery UI popup dialog. The content can be either
336   // loaded via AJAX (if the parameter 'url' is given) or simply
337   // displayed if it exists in the DOM already (referenced via
338   // 'id') or given via param.html. If an existing DOM div should be used then
339   // the element won't be removed upon closing the dialog which allows
340   // re-opening it later on.
341   //
342   // Parameters:
343   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
344   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
345   // - dialog: an optional object of options passed to the $.dialog() call
346   // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
347   ns.popup_dialog = function(params) {
348     var dialog;
349
350     params            = params        || { };
351     var id            = params.id     || 'jqueryui_popup_dialog';
352     var custom_close  = params.dialog ? params.dialog.close : undefined;
353     var dialog_params = $.extend(
354       { // kivitendo default parameters:
355           width:  800
356         , height: 500
357         , modal:  true
358       },
359         // User supplied options:
360       params.dialog || { },
361       { // Options that must not be changed:
362         close: function(event, ui) {
363           if (custom_close)
364             custom_close();
365
366           if (params.url || params.html)
367             dialog.remove();
368           else
369             dialog.dialog('close');
370         }
371       });
372
373     if (!params.url && !params.html) {
374       // Use existing DOM element and show it. No AJAX call.
375       dialog =
376         $('#' + id)
377         .bind('dialogopen', function() {
378           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
379         })
380         .dialog(dialog_params);
381       return true;
382     }
383
384     $('#' + id).remove();
385
386     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
387     dialog.dialog(dialog_params);
388
389     if (params.html) {
390       dialog.html(params.html);
391     } else {
392       // no html? get it via ajax
393       $.ajax({
394         url:     params.url,
395         data:    params.data,
396         type:    params.type,
397         success: function(new_html) {
398           dialog.html(new_html);
399           dialog.removeClass('loading');
400           if (params.load)
401             params.load();
402         }
403       });
404     }
405
406     return true;
407   };
408
409   // Run code only once for each matched element
410   //
411   // This allows running the function 'code' exactly once for each
412   // element that matches 'selector'. This is achieved by storing the
413   // state with jQuery's 'data' function. The 'identification' is
414   // required for differentiating unambiguously so that different code
415   // functions can still be run on the same elements.
416   //
417   // 'code' can be either a function or the name of one. It must
418   // resolve to a function that receives the jQueryfied element as its
419   // sole argument.
420   //
421   // Returns nothing.
422   ns.run_once_for = function(selector, identification, code) {
423     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
424     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
425     if (!fn) {
426       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
427       return;
428     }
429
430     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
431       var $elt = $(elt);
432       $elt.data(attr_name, true);
433       fn($elt);
434     });
435   };
436
437   // Run a function by its name passing it some arguments
438   //
439   // This is a function useful mainly for the ClientJS functionality.
440   // It finds a function by its name and then executes it on an empty
441   // object passing the elements in 'args' (an array) as the function
442   // parameters retuning its result.
443   //
444   // Logs an error to the console and returns 'undefined' if the
445   // function cannot be found.
446   ns.run = function(function_name, args) {
447     var fn = ns.get_function_by_name(function_name);
448     if (fn)
449       return fn.apply({}, args);
450
451     console.error('kivi.run("' + function_name + '"): No function by that name found');
452     return undefined;
453   };
454
455   ns.detect_duplicate_ids_in_dom = function() {
456     var ids   = {},
457         found = false;
458
459     $('[id]').each(function() {
460       if (this.id && ids[this.id]) {
461         found = true;
462         console.warn('Duplicate ID #' + this.id);
463       }
464       ids[this.id] = 1;
465     });
466
467     if (!found)
468       console.log('No duplicate IDs found :)');
469   };
470
471   // Verifies that at least one checkbox matching the
472   // "checkbox_selector" is actually checked. If not, an error message
473   // is shown, and false is returned. Otherwise (at least one of them
474   // is checked) nothing is shown and true returned.
475   //
476   // Can be used in checks when clicking buttons.
477   ns.check_if_entries_selected = function(checkbox_selector) {
478     if ($(checkbox_selector + ':checked').length > 0)
479       return true;
480
481     alert(kivi.t8('No entries have been selected.'));
482
483     return false;
484   };
485
486   // Performs various validation steps on the descendants of
487   // 'selector'. Elements that should be validated must have an
488   // attribute named "data-validate" which is set to a space-separated
489   // list of tests to perform. Additionally, the attribute
490   // "data-title" must be set to a human-readable name of the field
491   // that can be shown as part of an error message.
492   //
493   // Supported validation tests are:
494   // - "required": the field must be set (its .val() must not be empty)
495   //
496   // The validation will abort and return "false" as soon as
497   // validation routine fails.
498   //
499   // The function returns "true" if all validations succeed for all
500   // elements.
501   ns.validate_form = function(selector) {
502     var validate_field = function(elt) {
503       var $elt  = $(elt);
504       var tests = $elt.data('validate').split(/ +/);
505       var info  = {
506         title: $elt.data('title'),
507         value: $elt.val(),
508       };
509
510       for (var test_idx in tests) {
511         var test = tests[test_idx];
512
513         if (test === "required") {
514           if ($elt.val() === '') {
515             alert(kivi.t8("The field '#{title}' must be set.", info));
516             return false;
517           }
518
519         } else {
520           var error = "kivi.validate_form: unknown test '" + test + "' for element ID '" + $elt.prop('id') + "'";
521           console.error(error);
522           alert(error);
523
524           return false;
525         }
526       }
527
528       return true;
529     };
530
531     selector = selector || '#form';
532     var ok   = true;
533     var to_check = $(selector + ' [data-validate]').toArray();
534
535     for (var to_check_idx in to_check)
536       if (!validate_field(to_check[to_check_idx]))
537         return false;
538
539     return true;
540   };
541 });
542
543 kivi = namespace('kivi');