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.filter_select = function() {
354 var $input = $(this);
355 var $select = $('#' + $input.data('select-id'));
356 var filter = $input.val().toLocaleLowerCase();
358 $select.find('option').each(function() {
359 if ($(this).text().toLocaleLowerCase().indexOf(filter) != -1)
366 ns.reinit_widgets = function() {
367 ns.run_once_for('.datepicker', 'datepicker', function(elt) {
371 if (ns.Part) ns.Part.reinit_widgets();
372 if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
373 if (ns.Validator) ns.Validator.reinit_widgets();
375 if (ns.ProjectPicker)
376 ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
377 kivi.ProjectPicker($(elt));
381 ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
382 kivi.ChartPicker($(elt));
385 ns.run_once_for('div.filtered_select input', 'filtered_select', function(elt) {
386 $(elt).bind('change keyup', ns.filter_select);
389 var func = kivi.get_function_by_name('local_reinit_widgets');
393 ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
395 contentAsHTML: false,
396 theme: 'tooltipster-light'
400 ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
403 theme: 'tooltipster-light'
407 ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
408 ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
411 ns.submit_ajax_form = function(url, form_selector, additional_data) {
412 $(form_selector).ajaxSubmit({
414 data: additional_data,
415 success: ns.eval_json_result
421 // This function submits an existing form given by "form_selector"
422 // and sets the "action" input to "action_to_call" before submitting
423 // it. Any existing input named "action" will be removed prior to
425 ns.submit_form_with_action = function(form_selector, action_to_call) {
426 $('[name=action]').remove();
428 var $form = $(form_selector);
429 var $hidden = $('<input type=hidden>');
431 $hidden.attr('name', 'action');
432 $hidden.attr('value', action_to_call);
433 $form.append($hidden);
438 // This function exists solely so that it can be found with
439 // kivi.get_functions_by_name() and called later on. Using something
440 // like "var func = history["back"]" works, but calling it later
441 // with "func.apply()" doesn't.
442 ns.history_back = function() {
446 // Return a function object by its name (a string). Works both with
447 // global functions (e.g. "focus_by_name") and those in namespaces (e.g.
449 // Returns null if the object is not found.
450 ns.get_function_by_name = function(name) {
451 var parts = name.match("(.+)\\.([^\\.]+)$");
454 return namespace(parts[1])[ parts[2] ];
457 // Open a modal jQuery UI popup dialog. The content can be either
458 // loaded via AJAX (if the parameter 'url' is given) or simply
459 // displayed if it exists in the DOM already (referenced via
460 // 'id') or given via param.html. If an existing DOM div should be used then
461 // the element won't be removed upon closing the dialog which allows
462 // re-opening it later on.
465 // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
466 // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
467 // - dialog: an optional object of options passed to the $.dialog() call
468 // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
469 ns.popup_dialog = function(params) {
472 params = params || { };
473 var id = params.id || 'jqueryui_popup_dialog';
474 var custom_close = params.dialog ? params.dialog.close : undefined;
475 var dialog_params = $.extend(
476 { // kivitendo default parameters:
481 // User supplied options:
482 params.dialog || { },
483 { // Options that must not be changed:
484 close: function(event, ui) {
485 dialog.dialog('close');
490 if (params.url || params.html)
495 if (!params.url && !params.html) {
496 // Use existing DOM element and show it. No AJAX call.
499 .bind('dialogopen', function() {
500 ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
502 .dialog(dialog_params);
506 $('#' + id).remove();
508 dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
509 dialog.dialog(dialog_params);
512 dialog.html(params.html);
514 // no html? get it via ajax
519 success: function(new_html) {
520 dialog.html(new_html);
521 dialog.removeClass('loading');
531 // Run code only once for each matched element
533 // This allows running the function 'code' exactly once for each
534 // element that matches 'selector'. This is achieved by storing the
535 // state with jQuery's 'data' function. The 'identification' is
536 // required for differentiating unambiguously so that different code
537 // functions can still be run on the same elements.
539 // 'code' can be either a function or the name of one. It must
540 // resolve to a function that receives the jQueryfied element as its
544 ns.run_once_for = function(selector, identification, code) {
545 var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
546 var fn = typeof code === 'function' ? code : ns.get_function_by_name(code);
548 console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
552 $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
554 $elt.data(attr_name, true);
559 // Run a function by its name passing it some arguments
561 // This is a function useful mainly for the ClientJS functionality.
562 // It finds a function by its name and then executes it on an empty
563 // object passing the elements in 'args' (an array) as the function
564 // parameters retuning its result.
566 // Logs an error to the console and returns 'undefined' if the
567 // function cannot be found.
568 ns.run = function(function_name, args) {
569 var fn = ns.get_function_by_name(function_name);
571 return fn.apply({}, args || []);
573 console.error('kivi.run("' + function_name + '"): No function by that name found');
577 ns.save_file = function(base64_data, content_type, size, attachment_name) {
578 // atob returns a unicode string with one codepoint per octet. revert this
579 const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
580 const byteCharacters = atob(b64Data);
581 const byteArrays = [];
583 for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
584 const slice = byteCharacters.slice(offset, offset + sliceSize);
586 const byteNumbers = new Array(slice.length);
587 for (let i = 0; i < slice.length; i++) {
588 byteNumbers[i] = slice.charCodeAt(i);
591 const byteArray = new Uint8Array(byteNumbers);
592 byteArrays.push(byteArray);
595 const blob = new Blob(byteArrays, {type: contentType});
599 var blob = b64toBlob(base64_data, content_type);
600 var a = $("<a style='display: none;'/>");
601 var url = window.URL.createObjectURL(blob);
603 a.attr("download", attachment_name);
606 window.URL.revokeObjectURL(url);
610 ns.detect_duplicate_ids_in_dom = function() {
614 $('[id]').each(function() {
615 if (this.id && ids[this.id]) {
617 console.warn('Duplicate ID #' + this.id);
623 console.log('No duplicate IDs found :)');
626 ns.validate_form = function(selector) {
627 if (!kivi.Validator) {
628 console.log('kivi.Validator is not loaded');
630 return kivi.Validator.validate_all(selector);
634 // Verifies that at least one checkbox matching the
635 // "checkbox_selector" is actually checked. If not, an error message
636 // is shown, and false is returned. Otherwise (at least one of them
637 // is checked) nothing is shown and true returned.
639 // Can be used in checks when clicking buttons.
640 ns.check_if_entries_selected = function(checkbox_selector) {
641 if ($(checkbox_selector + ':checked').length > 0)
644 alert(kivi.t8('No entries have been selected.'));
649 ns.switch_areainput_to_textarea = function(id) {
650 var $input = $('#' + id);
654 var $area = $('<textarea></textarea>');
656 $area.prop('rows', 3);
657 $area.prop('cols', $input.prop('size') || 40);
658 $area.prop('name', $input.prop('name'));
659 $area.prop('id', $input.prop('id'));
660 $area.val($input.val());
662 $input.parent().replaceWith($area);
666 ns.set_cursor_position = function(selector, position) {
667 var $input = $(selector);
668 if (position === 'end')
669 position = $input.val().length;
671 $input.prop('selectionStart', position);
672 $input.prop('selectionEnd', position);
676 kivi = namespace('kivi');