1 namespace("kivi", function(ns) {
21 ns.setup_formats = function(params) {
22 var res = (params.dates || "").match(/^([ymd]+)([^a-z])([ymd]+)[^a-z]([ymd]+)$/);
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;
30 res = (params.times || "").match(/^([hm]+)([^a-z])([hm]+)$/);
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;
37 res = (params.numbers || "").match(/^\d*([^\d]?)\d+([^\d])\d+$/);
45 ns.parse_date = function(date) {
46 if (date === undefined)
52 if (date === '0' || date === '00')
55 var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
56 var today = new Date();
59 // assume fixed pattern, and extract parts again
60 if (parts.length == 1) {
62 parts = date.match(/../g);
63 if (date.length == 8) {
64 parts[ns._date_format.y] += parts.splice(ns._date_format.y + 1, 1)
67 if (date.length == 6 || date.length == 4) {
70 if (date.length == 1 || date.length == 2) {
72 parts[ ns._date_format.y ] = today.getFullYear();
73 parts[ ns._date_format.m ] = today.getMonth() + 1;
74 parts[ ns._date_format.d ] = date;
81 if (parts.length == 3) {
82 var year = +parts[ ns._date_format.y ] || 0 * 1 || (new Date()).getFullYear();
86 year += year > 70 ? 1900 : 2000;
90 (parts[ ns._date_format.m ] || (today.getMonth() + 1)) * 1 - 1, // Months are 0-based.
91 (parts[ ns._date_format.d ] || today.getDate()) * 1
93 } else if (parts.length == 2) {
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
102 return isNaN(date.getTime()) ? undefined : date;
105 ns.format_date = function(date) {
106 if (isNaN(date.getTime()))
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);
116 ns.parse_time = function(time) {
117 var now = new Date();
119 if (time === undefined)
128 // special case 1: military time in fixed "hhmm" format
129 if (time.length == 4) {
130 var res = time.match(/(\d\d)(\d\d)/);
132 now.setHours(res[1], res[2]);
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])))
145 now.setHours(parts[ns._time_format.h], parts[ns._time_format.m]);
151 ns.format_time = function(date) {
152 if (isNaN(date.getTime()))
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);
161 ns.parse_amount = function(amount) {
162 if (amount === undefined)
168 if (ns._number_format.decimalSep == ',')
169 amount = amount.replace(/\./g, "").replace(/,/g, ".");
171 amount = amount.replace(/[\',]/g, "");
173 // Make sure no code wich is not a math expression ends up in eval().
174 if (!amount.match(/^[0-9 ()\-+*/.]*$/))
177 amount = amount.replace(/^0+(\d+)/, '$1');
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);
194 temp += dec >= 5 ? 10 - dec: dec * -1;
196 return neg * temp / mult;
199 ns.format_amount = function(amount, places) {
200 amount = amount || 0;
202 if ((places !== undefined) && (places >= 0))
203 amount = ns.round_amount(amount, Math.abs(places));
205 var parts = ("" + Math.abs(amount)).split(/\./);
207 var dec = parts.length > 1 ? parts[1] : "";
208 var sign = amount < 0 ? "-" : "";
210 if (places !== undefined) {
211 while (dec.length < Math.abs(places))
214 if ((places > 0) && (dec.length > Math.abs(places)))
215 dec = d.substr(0, places);
218 if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
219 var len = ((intg.length + 2) % 3) + 1,
221 res = intg.substr(0, len);
222 while (start < intg.length) {
223 res += ns._number_format.thousandSep + intg.substr(start, 3);
230 var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
232 return sign + intg + sep + dec;
235 ns.t8 = function(text, params) {
236 text = ns._locale[text] || text;
239 if( Object.prototype.toString.call( params ) === '[object Array]' ) {
240 var len = params.length;
242 for(var i=0; i<len; ++i) {
245 text = text.split("#"+ key).join(value);
248 else if( typeof params == 'object' ) {
251 text = text.split("#{"+ key +"}").join(value);
258 ns.setupLocale = function(locale) {
262 ns.set_focus = function(element) {
263 var $e = $(element).eq(0);
264 if ($e.data('ckeditorInstance'))
265 ns.focus_ckeditor_when_ready($e);
270 ns.focus_ckeditor_when_ready = function(element) {
271 $(element).data('ckeditorInstance').on('instanceReady', function() { ns.focus_ckeditor(element); });
274 ns.focus_ckeditor = function(element) {
275 $(element).data('ckeditorInstance').focus();
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.$;
285 textarea.createTextRange().execCommand('SelectAll');
287 textarea.selectionStart = 0;
288 textarea.selectionEnd = textarea.value.length;
291 if (editable.is('body'))
292 editor.document.$.execCommand('SelectAll', false, null);
295 var range = editor.createRange();
296 range.selectNodeContents(editable);
300 editor.forceNextSelectionCheck();
301 editor.selectionChange();
305 ns.init_tabwidget = function(element) {
306 var $element = $(element);
308 var elementId = $element.attr('id');
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);
316 tabsParams.activate = function(event, ui) {
317 var i = ui.newTab.parent().children().index(ui.newTab);
318 $.cookie(cookieName, i);
322 $element.tabs(tabsParams);
325 ns.init_text_editor = function(element) {
327 all: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
328 default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
332 var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
336 removePlugins: 'resize',
337 extraPlugins: 'inline_resize',
339 disableAutoInline: true,
343 config.height = $e.height();
344 config.width = $e.width();
346 var editor = CKEDITOR.inline($e.get(0), config);
347 $e.data('ckeditorInstance', editor);
349 if ($e.hasClass('texteditor-autofocus'))
350 editor.on('instanceReady', function() { ns.focus_ckeditor($e); });
353 ns.reinit_widgets = function() {
354 ns.run_once_for('.datepicker', 'datepicker', function(elt) {
358 if (ns.Part) ns.Part.reinit_widgets();
359 if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
360 if (ns.Validator) ns.Validator.reinit_widgets();
362 if (ns.ProjectPicker)
363 ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
364 kivi.ProjectPicker($(elt));
368 ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
369 kivi.ChartPicker($(elt));
373 var func = kivi.get_function_by_name('local_reinit_widgets');
377 ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
379 contentAsHTML: false,
380 theme: 'tooltipster-light'
384 ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
387 theme: 'tooltipster-light'
391 ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
392 ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
395 ns.submit_ajax_form = function(url, form_selector, additional_data) {
396 $(form_selector).ajaxSubmit({
398 data: additional_data,
399 success: ns.eval_json_result
405 // This function submits an existing form given by "form_selector"
406 // and sets the "action" input to "action_to_call" before submitting
407 // it. Any existing input named "action" will be removed prior to
409 ns.submit_form_with_action = function(form_selector, action_to_call) {
410 $('[name=action]').remove();
412 var $form = $(form_selector);
413 var $hidden = $('<input type=hidden>');
415 $hidden.attr('name', 'action');
416 $hidden.attr('value', action_to_call);
417 $form.append($hidden);
422 // This function exists solely so that it can be found with
423 // kivi.get_functions_by_name() and called later on. Using something
424 // like "var func = history["back"]" works, but calling it later
425 // with "func.apply()" doesn't.
426 ns.history_back = function() {
430 // Return a function object by its name (a string). Works both with
431 // global functions (e.g. "focus_by_name") and those in namespaces (e.g.
433 // Returns null if the object is not found.
434 ns.get_function_by_name = function(name) {
435 var parts = name.match("(.+)\\.([^\\.]+)$");
438 return namespace(parts[1])[ parts[2] ];
441 // Open a modal jQuery UI popup dialog. The content can be either
442 // loaded via AJAX (if the parameter 'url' is given) or simply
443 // displayed if it exists in the DOM already (referenced via
444 // 'id') or given via param.html. If an existing DOM div should be used then
445 // the element won't be removed upon closing the dialog which allows
446 // re-opening it later on.
449 // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
450 // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
451 // - dialog: an optional object of options passed to the $.dialog() call
452 // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
453 ns.popup_dialog = function(params) {
456 params = params || { };
457 var id = params.id || 'jqueryui_popup_dialog';
458 var custom_close = params.dialog ? params.dialog.close : undefined;
459 var dialog_params = $.extend(
460 { // kivitendo default parameters:
465 // User supplied options:
466 params.dialog || { },
467 { // Options that must not be changed:
468 close: function(event, ui) {
469 dialog.dialog('close');
474 if (params.url || params.html)
479 if (!params.url && !params.html) {
480 // Use existing DOM element and show it. No AJAX call.
483 .bind('dialogopen', function() {
484 ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
486 .dialog(dialog_params);
490 $('#' + id).remove();
492 dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
493 dialog.dialog(dialog_params);
496 dialog.html(params.html);
498 // no html? get it via ajax
503 success: function(new_html) {
504 dialog.html(new_html);
505 dialog.removeClass('loading');
515 // Run code only once for each matched element
517 // This allows running the function 'code' exactly once for each
518 // element that matches 'selector'. This is achieved by storing the
519 // state with jQuery's 'data' function. The 'identification' is
520 // required for differentiating unambiguously so that different code
521 // functions can still be run on the same elements.
523 // 'code' can be either a function or the name of one. It must
524 // resolve to a function that receives the jQueryfied element as its
528 ns.run_once_for = function(selector, identification, code) {
529 var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
530 var fn = typeof code === 'function' ? code : ns.get_function_by_name(code);
532 console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
536 $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
538 $elt.data(attr_name, true);
543 // Run a function by its name passing it some arguments
545 // This is a function useful mainly for the ClientJS functionality.
546 // It finds a function by its name and then executes it on an empty
547 // object passing the elements in 'args' (an array) as the function
548 // parameters retuning its result.
550 // Logs an error to the console and returns 'undefined' if the
551 // function cannot be found.
552 ns.run = function(function_name, args) {
553 var fn = ns.get_function_by_name(function_name);
555 return fn.apply({}, args || []);
557 console.error('kivi.run("' + function_name + '"): No function by that name found');
561 ns.save_file = function(base64_data, content_type, size, attachment_name) {
562 // atob returns a unicode string with one codepoint per octet. revert this
563 const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
564 const byteCharacters = atob(b64Data);
565 const byteArrays = [];
567 for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
568 const slice = byteCharacters.slice(offset, offset + sliceSize);
570 const byteNumbers = new Array(slice.length);
571 for (let i = 0; i < slice.length; i++) {
572 byteNumbers[i] = slice.charCodeAt(i);
575 const byteArray = new Uint8Array(byteNumbers);
576 byteArrays.push(byteArray);
579 const blob = new Blob(byteArrays, {type: contentType});
583 var blob = b64toBlob(base64_data, content_type);
584 var a = $("<a style='display: none;'/>");
585 var url = window.URL.createObjectURL(blob);
587 a.attr("download", attachment_name);
590 window.URL.revokeObjectURL(url);
594 ns.detect_duplicate_ids_in_dom = function() {
598 $('[id]').each(function() {
599 if (this.id && ids[this.id]) {
601 console.warn('Duplicate ID #' + this.id);
607 console.log('No duplicate IDs found :)');
610 ns.validate_form = function(selector) {
611 if (!kivi.Validator) {
612 console.log('kivi.Validator is not loaded');
614 return kivi.Validator.validate_all(selector);
618 // Verifies that at least one checkbox matching the
619 // "checkbox_selector" is actually checked. If not, an error message
620 // is shown, and false is returned. Otherwise (at least one of them
621 // is checked) nothing is shown and true returned.
623 // Can be used in checks when clicking buttons.
624 ns.check_if_entries_selected = function(checkbox_selector) {
625 if ($(checkbox_selector + ':checked').length > 0)
628 alert(kivi.t8('No entries have been selected.'));
633 ns.switch_areainput_to_textarea = function(id) {
634 var $input = $('#' + id);
638 var $area = $('<textarea></textarea>');
640 $area.prop('rows', 3);
641 $area.prop('cols', $input.prop('size') || 40);
642 $area.prop('name', $input.prop('name'));
643 $area.prop('id', $input.prop('id'));
644 $area.val($input.val());
646 $input.parent().replaceWith($area);
651 kivi = namespace('kivi');