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