Mobile: js refactored und datepicker übersetzt
[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._time_format = {
12     sep: ':',
13     h: 0,
14     m: 1,
15   };
16   ns._number_format = {
17     decimalSep:  ',',
18     thousandSep: '.'
19   };
20
21   ns.setup_formats = function(params) {
22     var res = (params.dates || "").match(/^([ymd]+)([^a-z])([ymd]+)[^a-z]([ymd]+)$/);
23     if (res) {
24       ns._date_format                      = { sep: res[2] };
25       ns._date_format[res[1].substr(0, 1)] = 0;
26       ns._date_format[res[3].substr(0, 1)] = 1;
27       ns._date_format[res[4].substr(0, 1)] = 2;
28     }
29
30     res = (params.times || "").match(/^([hm]+)([^a-z])([hm]+)$/);
31     if (res) {
32       ns._time_format                      = { sep: res[2] };
33       ns._time_format[res[1].substr(0, 1)] = 0;
34       ns._time_format[res[3].substr(0, 1)] = 1;
35     }
36
37     res = (params.numbers || "").match(/^\d*([^\d]?)\d+([^\d])\d+$/);
38     if (res)
39       ns._number_format = {
40         decimalSep:  res[2],
41         thousandSep: res[1]
42       };
43   };
44
45   ns.parse_date = function(date) {
46     if (date === undefined)
47       return undefined;
48
49     if (date === '')
50       return null;
51
52     if (date === '0' || date === '00')
53       return new Date();
54
55     var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
56     var today = new Date();
57
58     // without separator?
59     // assume fixed pattern, and extract parts again
60     if (parts.length == 1) {
61       date  = parts[0];
62       parts = date.match(/../g);
63       if (date.length == 8) {
64         parts[ns._date_format.y] += parts.splice(ns._date_format.y + 1, 1)
65       }
66       else
67       if (date.length == 6 || date.length == 4) {
68       }
69       else
70       if (date.length == 1 || date.length == 2) {
71         parts = []
72         parts[ ns._date_format.y ] = today.getFullYear();
73         parts[ ns._date_format.m ] = today.getMonth() + 1;
74         parts[ ns._date_format.d ] = date;
75       }
76       else {
77         return undefined;
78       }
79     }
80
81     if (parts.length == 3) {
82       var year = +parts[ ns._date_format.y ] || 0 * 1 || (new Date()).getFullYear();
83       if (year > 9999)
84         return undefined;
85       if (year < 100) {
86         year += year > 70 ? 1900 : 2000;
87       }
88       date = new Date(
89         year,
90         (parts[ ns._date_format.m ] || (today.getMonth() + 1)) * 1 - 1, // Months are 0-based.
91         (parts[ ns._date_format.d ] || today.getDate()) * 1
92       );
93     } else if (parts.length == 2) {
94       date = new Date(
95         (new Date()).getFullYear(),
96         (parts[ (ns._date_format.m > ns._date_format.d) * 1 ] || (today.getMonth() + 1)) * 1 - 1, // Months are 0-based.
97         (parts[ (ns._date_format.d > ns._date_format.m) * 1 ] || today.getDate()) * 1
98       );
99     } else
100       return undefined;
101
102     return isNaN(date.getTime()) ? undefined : date;
103   };
104
105   ns.format_date = function(date) {
106     if (isNaN(date.getTime()))
107       return undefined;
108
109     var parts = [ "", "", "" ]
110     parts[ ns._date_format.y ] = date.getFullYear();
111     parts[ ns._date_format.m ] = (date.getMonth() <  9 ? "0" : "") + (date.getMonth() + 1); // Months are 0-based, but days are 1-based.
112     parts[ ns._date_format.d ] = (date.getDate()  < 10 ? "0" : "") + date.getDate();
113     return parts.join(ns._date_format.sep);
114   };
115
116   ns.parse_time = function(time) {
117     var now = new Date();
118
119     if (time === undefined)
120       return undefined;
121
122     if (time === '')
123       return null;
124
125     if (time === '0')
126       return now;
127
128     // special case 1: military time in fixed "hhmm" format
129     if (time.length == 4) {
130       var res = time.match(/(\d\d)(\d\d)/);
131       if (res) {
132         now.setHours(res[1], res[2]);
133         return now;
134       } else {
135         return undefined;
136       }
137     }
138
139     var parts = time.replace(/\s+/g, "").split(ns._time_format.sep);
140     if (parts.length == 2) {
141       for (var idx in parts) {
142         if (Number.isNaN(Number.parseInt(parts[idx])))
143           return undefined;
144       }
145       now.setHours(parts[ns._time_format.h], parts[ns._time_format.m]);
146       return now;
147     } else
148       return undefined;
149   }
150
151   ns.format_time = function(date) {
152     if (isNaN(date.getTime()))
153       return undefined;
154
155     var parts = [ "", "" ]
156     parts[ ns._time_format.h ] = date.getHours().toString().padStart(2, '0');
157     parts[ ns._time_format.m ] = date.getMinutes().toString().padStart(2, '0');
158     return parts.join(ns._time_format.sep);
159   };
160
161   ns.parse_amount = function(amount) {
162     if (amount === undefined)
163       return undefined;
164
165     if (amount === '')
166       return null;
167
168     if (ns._number_format.decimalSep == ',')
169       amount = amount.replace(/\./g, "").replace(/,/g, ".");
170
171     amount = amount.replace(/[\',]/g, "");
172
173     // Make sure no code wich is not a math expression ends up in eval().
174     if (!amount.match(/^[0-9 ()\-+*/.]*$/))
175       return undefined;
176
177     amount = amount.replace(/^0+(\d+)/, '$1');
178
179     /* jshint -W061 */
180     try {
181       return eval(amount);
182     } catch (err) {
183       return undefined;
184     }
185   };
186
187   ns.round_amount = function(amount, places) {
188     var neg  = amount >= 0 ? 1 : -1;
189     var mult = Math.pow(10, places + 1);
190     var temp = Math.abs(amount) * mult;
191     var diff = Math.abs(1 - temp + Math.floor(temp));
192     temp     = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
193     var dec  = temp % 10;
194     temp    += dec >= 5 ? 10 - dec: dec * -1;
195
196     return neg * temp / mult;
197   };
198
199   ns.format_amount = function(amount, places) {
200     amount = amount || 0;
201
202     if ((places !== undefined) && (places >= 0))
203       amount = ns.round_amount(amount, Math.abs(places));
204
205     var parts = ("" + Math.abs(amount)).split(/\./);
206     var intg  = parts[0];
207     var dec   = parts.length > 1 ? parts[1] : "";
208     var sign  = amount  < 0      ? "-"      : "";
209
210     if (places !== undefined) {
211       while (dec.length < Math.abs(places))
212         dec += "0";
213
214       if ((places > 0) && (dec.length > Math.abs(places)))
215         dec = d.substr(0, places);
216     }
217
218     if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
219       var len   = ((intg.length + 2) % 3) + 1,
220           start = len,
221           res   = intg.substr(0, len);
222       while (start < intg.length) {
223         res   += ns._number_format.thousandSep + intg.substr(start, 3);
224         start += 3;
225       }
226
227       intg = res;
228     }
229
230     var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
231
232     return sign + intg + sep + dec;
233   };
234
235   ns.t8 = function(text, params) {
236     text = ns._locale[text] || text;
237     var key, value
238
239     if( Object.prototype.toString.call( params ) === '[object Array]' ) {
240       var len = params.length;
241
242       for(var i=0; i<len; ++i) {
243         key = i + 1;
244         value = params[i];
245         text = text.split("#"+ key).join(value);
246       }
247     }
248     else if( typeof params == 'object' ) {
249       for(key in params) {
250         value = params[key];
251         text = text.split("#{"+ key +"}").join(value);
252       }
253     }
254
255     return text;
256   };
257
258   ns.setupLocale = function(locale) {
259     ns._locale = locale;
260   };
261
262   ns.set_focus = function(element) {
263     var $e = $(element).eq(0);
264     if ($e.data('ckeditorInstance'))
265       ns.focus_ckeditor_when_ready($e);
266     else
267       $e.focus();
268   };
269
270   ns.focus_ckeditor_when_ready = function(element) {
271     $(element).data('ckeditorInstance').on('instanceReady', function() { ns.focus_ckeditor(element); });
272   };
273
274   ns.focus_ckeditor = function(element) {
275     $(element).data('ckeditorInstance').focus();
276   };
277
278   ns.selectall_ckeditor = function(element) {
279     var editor   = $(element).ckeditorGet();
280     var editable = editor.editable();
281     if (editable.is('textarea')) {
282       var textarea = editable.$;
283
284       if (CKEDITOR.env.ie)
285         textarea.createTextRange().execCommand('SelectAll');
286       else {
287         textarea.selectionStart = 0;
288         textarea.selectionEnd   = textarea.value.length;
289       }
290     } else {
291       if (editable.is('body'))
292         editor.document.$.execCommand('SelectAll', false, null);
293
294       else {
295         var range = editor.createRange();
296         range.selectNodeContents(editable);
297         range.select();
298       }
299
300       editor.forceNextSelectionCheck();
301       editor.selectionChange();
302     }
303   }
304
305   ns.init_tabwidget = function(element) {
306     var $element   = $(element);
307     var tabsParams = {};
308     var elementId  = $element.attr('id');
309
310     if (elementId) {
311       var cookieName      = 'jquery_ui_tab_'+ elementId;
312       if (!window.location.hash) {
313         // only activate if there's no hash to overwrite it
314         tabsParams.active   = $.cookie(cookieName);
315       }
316       tabsParams.activate = function(event, ui) {
317         var i = ui.newTab.parent().children().index(ui.newTab);
318         $.cookie(cookieName, i);
319       };
320     }
321
322     $element.tabs(tabsParams);
323   };
324
325   ns.init_text_editor = function(element) {
326     var layouts = {
327       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
328       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
329     };
330
331     var $e      = $(element);
332     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
333     var config  = {
334       entities:      false,
335       language:      'de',
336       removePlugins: 'resize',
337       extraPlugins:  'inline_resize',
338       toolbar:       buttons,
339       disableAutoInline: true,
340       title:         false
341     };
342
343     config.height = $e.height();
344     config.width  = $e.width();
345
346     var editor = CKEDITOR.inline($e.get(0), config);
347     $e.data('ckeditorInstance', editor);
348
349     if ($e.hasClass('texteditor-autofocus'))
350       editor.on('instanceReady', function() { ns.focus_ckeditor($e); });
351   };
352
353   ns.filter_select = function() {
354     var $input  = $(this);
355     var $select = $('#' + $input.data('select-id'));
356     var filter  = $input.val().toLocaleLowerCase();
357
358     $select.find('option').each(function() {
359       if ($(this).text().toLocaleLowerCase().indexOf(filter) != -1)
360         $(this).show();
361       else
362         $(this).hide();
363     });
364   };
365
366   ns.reinit_widgets = function() {
367     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
368       $(elt).datepicker();
369     });
370
371     if (ns.Part) ns.Part.reinit_widgets();
372     if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
373     if (ns.Validator) ns.Validator.reinit_widgets();
374     if (ns.Materialize) ns.Materialize.reinit_widgets();
375
376     if (ns.ProjectPicker)
377       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
378         kivi.ProjectPicker($(elt));
379       });
380
381     if (ns.ChartPicker)
382       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
383         kivi.ChartPicker($(elt));
384       });
385
386     ns.run_once_for('div.filtered_select input', 'filtered_select', function(elt) {
387       $(elt).bind('change keyup', ns.filter_select);
388     });
389
390     var func = kivi.get_function_by_name('local_reinit_widgets');
391     if (func)
392       func();
393
394     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
395       $(elt).tooltipster({
396         contentAsHTML: false,
397         theme: 'tooltipster-light'
398       })
399     });
400
401     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
402       $(elt).tooltipster({
403         contentAsHTML: true,
404         theme: 'tooltipster-light'
405       })
406     });
407
408     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
409     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
410   };
411
412   ns.submit_ajax_form = function(url, form_selector, additional_data) {
413     $(form_selector).ajaxSubmit({
414       url:     url,
415       data:    additional_data,
416       success: ns.eval_json_result
417     });
418
419     return true;
420   };
421
422   // This function submits an existing form given by "form_selector"
423   // and sets the "action" input to "action_to_call" before submitting
424   // it. Any existing input named "action" will be removed prior to
425   // submitting.
426   ns.submit_form_with_action = function(form_selector, action_to_call) {
427     $('[name=action]').remove();
428
429     var $form   = $(form_selector);
430     var $hidden = $('<input type=hidden>');
431
432     $hidden.attr('name',  'action');
433     $hidden.attr('value', action_to_call);
434     $form.append($hidden);
435
436     $form.submit();
437   };
438
439   // This function exists solely so that it can be found with
440   // kivi.get_functions_by_name() and called later on. Using something
441   // like "var func = history["back"]" works, but calling it later
442   // with "func.apply()" doesn't.
443   ns.history_back = function() {
444     history.back();
445   };
446
447   // Return a function object by its name (a string). Works both with
448   // global functions (e.g. "focus_by_name") and those in namespaces (e.g.
449   // "kivi.t8").
450   // Returns null if the object is not found.
451   ns.get_function_by_name = function(name) {
452     var parts = name.match("(.+)\\.([^\\.]+)$");
453     if (!parts)
454       return window[name];
455     return namespace(parts[1])[ parts[2] ];
456   };
457
458   // Open a modal jQuery UI popup dialog. The content can be either
459   // loaded via AJAX (if the parameter 'url' is given) or simply
460   // displayed if it exists in the DOM already (referenced via
461   // 'id') or given via param.html. If an existing DOM div should be used then
462   // the element won't be removed upon closing the dialog which allows
463   // re-opening it later on.
464   //
465   // Parameters:
466   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
467   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
468   // - dialog: an optional object of options passed to the $.dialog() call
469   // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
470   ns.popup_dialog = function(params) {
471     var dialog;
472
473     params            = params        || { };
474     var id            = params.id     || 'jqueryui_popup_dialog';
475     var custom_close  = params.dialog ? params.dialog.close : undefined;
476     var dialog_params = $.extend(
477       { // kivitendo default parameters:
478           width:  800
479         , height: 500
480         , modal:  true
481       },
482         // User supplied options:
483       params.dialog || { },
484       { // Options that must not be changed:
485         close: function(event, ui) {
486           dialog.dialog('close');
487
488           if (custom_close)
489             custom_close();
490
491           if (params.url || params.html)
492             dialog.remove();
493         }
494       });
495
496     if (!params.url && !params.html) {
497       // Use existing DOM element and show it. No AJAX call.
498       dialog =
499         $('#' + id)
500         .bind('dialogopen', function() {
501           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
502         })
503         .dialog(dialog_params);
504       return true;
505     }
506
507     $('#' + id).remove();
508
509     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
510     dialog.dialog(dialog_params);
511
512     if (params.html) {
513       dialog.html(params.html);
514     } else {
515       // no html? get it via ajax
516       $.ajax({
517         url:     params.url,
518         data:    params.data,
519         type:    params.type,
520         success: function(new_html) {
521           dialog.html(new_html);
522           dialog.removeClass('loading');
523           if (params.load)
524             params.load();
525         }
526       });
527     }
528
529     return true;
530   };
531
532   // Run code only once for each matched element
533   //
534   // This allows running the function 'code' exactly once for each
535   // element that matches 'selector'. This is achieved by storing the
536   // state with jQuery's 'data' function. The 'identification' is
537   // required for differentiating unambiguously so that different code
538   // functions can still be run on the same elements.
539   //
540   // 'code' can be either a function or the name of one. It must
541   // resolve to a function that receives the jQueryfied element as its
542   // sole argument.
543   //
544   // Returns nothing.
545   ns.run_once_for = function(selector, identification, code) {
546     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
547     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
548     if (!fn) {
549       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
550       return;
551     }
552
553     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
554       var $elt = $(elt);
555       $elt.data(attr_name, true);
556       fn($elt);
557     });
558   };
559
560   // Run a function by its name passing it some arguments
561   //
562   // This is a function useful mainly for the ClientJS functionality.
563   // It finds a function by its name and then executes it on an empty
564   // object passing the elements in 'args' (an array) as the function
565   // parameters retuning its result.
566   //
567   // Logs an error to the console and returns 'undefined' if the
568   // function cannot be found.
569   ns.run = function(function_name, args) {
570     var fn = ns.get_function_by_name(function_name);
571     if (fn)
572       return fn.apply({}, args || []);
573
574     console.error('kivi.run("' + function_name + '"): No function by that name found');
575     return undefined;
576   };
577
578   ns.save_file = function(base64_data, content_type, size, attachment_name) {
579     // atob returns a unicode string with one codepoint per octet. revert this
580     const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
581       const byteCharacters = atob(b64Data);
582       const byteArrays = [];
583
584       for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
585         const slice = byteCharacters.slice(offset, offset + sliceSize);
586
587         const byteNumbers = new Array(slice.length);
588         for (let i = 0; i < slice.length; i++) {
589           byteNumbers[i] = slice.charCodeAt(i);
590         }
591
592         const byteArray = new Uint8Array(byteNumbers);
593         byteArrays.push(byteArray);
594       }
595
596       const blob = new Blob(byteArrays, {type: contentType});
597       return blob;
598     }
599
600     var blob = b64toBlob(base64_data, content_type);
601     var a = $("<a style='display: none;'/>");
602     var url = window.URL.createObjectURL(blob);
603     a.attr("href", url);
604     a.attr("download", attachment_name);
605     $("body").append(a);
606     a[0].click();
607     window.URL.revokeObjectURL(url);
608     a.remove();
609   }
610
611   ns.detect_duplicate_ids_in_dom = function() {
612     var ids   = {},
613         found = false;
614
615     $('[id]').each(function() {
616       if (this.id && ids[this.id]) {
617         found = true;
618         console.warn('Duplicate ID #' + this.id);
619       }
620       ids[this.id] = 1;
621     });
622
623     if (!found)
624       console.log('No duplicate IDs found :)');
625   };
626
627   ns.validate_form = function(selector) {
628     if (!kivi.Validator) {
629       console.log('kivi.Validator is not loaded');
630     } else {
631       return kivi.Validator.validate_all(selector);
632     }
633   };
634
635   // Verifies that at least one checkbox matching the
636   // "checkbox_selector" is actually checked. If not, an error message
637   // is shown, and false is returned. Otherwise (at least one of them
638   // is checked) nothing is shown and true returned.
639   //
640   // Can be used in checks when clicking buttons.
641   ns.check_if_entries_selected = function(checkbox_selector) {
642     if ($(checkbox_selector + ':checked').length > 0)
643       return true;
644
645     alert(kivi.t8('No entries have been selected.'));
646
647     return false;
648   };
649
650   ns.switch_areainput_to_textarea = function(id) {
651     var $input = $('#' + id);
652     if (!$input.length)
653       return;
654
655     var $area = $('<textarea></textarea>');
656
657     $area.prop('rows', 3);
658     $area.prop('cols', $input.prop('size') || 40);
659     $area.prop('name', $input.prop('name'));
660     $area.prop('id',   $input.prop('id'));
661     $area.val($input.val());
662
663     $input.parent().replaceWith($area);
664     $area.focus();
665   };
666
667   ns.set_cursor_position = function(selector, position) {
668     var $input = $(selector);
669     if (position === 'end')
670       position = $input.val().length;
671
672     $input.prop('selectionStart', position);
673     $input.prop('selectionEnd',   position);
674   };
675 });
676
677 kivi = namespace('kivi');