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();
 
 374     if (ns.Materialize) ns.Materialize.reinit_widgets();
 
 376     if (ns.ProjectPicker)
 
 377       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
 
 378         kivi.ProjectPicker($(elt));
 
 382       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
 
 383         kivi.ChartPicker($(elt));
 
 386     ns.run_once_for('div.filtered_select input', 'filtered_select', function(elt) {
 
 387       $(elt).bind('change keyup', ns.filter_select);
 
 390     var func = kivi.get_function_by_name('local_reinit_widgets');
 
 394     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
 
 396         contentAsHTML: false,
 
 397         theme: 'tooltipster-light'
 
 401     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
 
 404         theme: 'tooltipster-light'
 
 408     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
 
 409     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
 
 412   ns.submit_ajax_form = function(url, form_selector, additional_data) {
 
 413     $(form_selector).ajaxSubmit({
 
 415       data:    additional_data,
 
 416       success: ns.eval_json_result
 
 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
 
 426   ns.submit_form_with_action = function(form_selector, action_to_call) {
 
 427     $('[name=action]').remove();
 
 429     var $form   = $(form_selector);
 
 430     var $hidden = $('<input type=hidden>');
 
 432     $hidden.attr('name',  'action');
 
 433     $hidden.attr('value', action_to_call);
 
 434     $form.append($hidden);
 
 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() {
 
 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.
 
 450   // Returns null if the object is not found.
 
 451   ns.get_function_by_name = function(name) {
 
 452     var parts = name.match("(.+)\\.([^\\.]+)$");
 
 455     return namespace(parts[1])[ parts[2] ];
 
 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.
 
 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     if (kivi.Materialize)
 
 472       return kivi.Materialize.popup_dialog(params);
 
 476     params            = params        || { };
 
 477     var id            = params.id     || 'jqueryui_popup_dialog';
 
 478     var custom_close  = params.dialog ? params.dialog.close : undefined;
 
 479     var dialog_params = $.extend(
 
 480       { // kivitendo default parameters:
 
 485         // User supplied options:
 
 486       params.dialog || { },
 
 487       { // Options that must not be changed:
 
 488         close: function(event, ui) {
 
 489           dialog.dialog('close');
 
 494           if (params.url || params.html)
 
 499     if (!params.url && !params.html) {
 
 500       // Use existing DOM element and show it. No AJAX call.
 
 503         .bind('dialogopen', function() {
 
 504           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
 
 506         .dialog(dialog_params);
 
 510     $('#' + id).remove();
 
 512     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
 
 513     dialog.dialog(dialog_params);
 
 516       dialog.html(params.html);
 
 518       // no html? get it via ajax
 
 523         success: function(new_html) {
 
 524           dialog.html(new_html);
 
 525           dialog.removeClass('loading');
 
 535   // Run code only once for each matched element
 
 537   // This allows running the function 'code' exactly once for each
 
 538   // element that matches 'selector'. This is achieved by storing the
 
 539   // state with jQuery's 'data' function. The 'identification' is
 
 540   // required for differentiating unambiguously so that different code
 
 541   // functions can still be run on the same elements.
 
 543   // 'code' can be either a function or the name of one. It must
 
 544   // resolve to a function that receives the jQueryfied element as its
 
 548   ns.run_once_for = function(selector, identification, code) {
 
 549     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
 
 550     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
 
 552       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
 
 556     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
 
 558       $elt.data(attr_name, true);
 
 563   // Run a function by its name passing it some arguments
 
 565   // This is a function useful mainly for the ClientJS functionality.
 
 566   // It finds a function by its name and then executes it on an empty
 
 567   // object passing the elements in 'args' (an array) as the function
 
 568   // parameters retuning its result.
 
 570   // Logs an error to the console and returns 'undefined' if the
 
 571   // function cannot be found.
 
 572   ns.run = function(function_name, args) {
 
 573     var fn = ns.get_function_by_name(function_name);
 
 575       return fn.apply({}, args || []);
 
 577     console.error('kivi.run("' + function_name + '"): No function by that name found');
 
 581   ns.save_file = function(base64_data, content_type, size, attachment_name) {
 
 582     // atob returns a unicode string with one codepoint per octet. revert this
 
 583     const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
 
 584       const byteCharacters = atob(b64Data);
 
 585       const byteArrays = [];
 
 587       for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
 
 588         const slice = byteCharacters.slice(offset, offset + sliceSize);
 
 590         const byteNumbers = new Array(slice.length);
 
 591         for (let i = 0; i < slice.length; i++) {
 
 592           byteNumbers[i] = slice.charCodeAt(i);
 
 595         const byteArray = new Uint8Array(byteNumbers);
 
 596         byteArrays.push(byteArray);
 
 599       const blob = new Blob(byteArrays, {type: contentType});
 
 603     var blob = b64toBlob(base64_data, content_type);
 
 604     var a = $("<a style='display: none;'/>");
 
 605     var url = window.URL.createObjectURL(blob);
 
 607     a.attr("download", attachment_name);
 
 610     window.URL.revokeObjectURL(url);
 
 614   ns.detect_duplicate_ids_in_dom = function() {
 
 618     $('[id]').each(function() {
 
 619       if (this.id && ids[this.id]) {
 
 621         console.warn('Duplicate ID #' + this.id);
 
 627       console.log('No duplicate IDs found :)');
 
 630   ns.validate_form = function(selector) {
 
 631     if (!kivi.Validator) {
 
 632       console.log('kivi.Validator is not loaded');
 
 634       return kivi.Validator.validate_all(selector);
 
 638   // Verifies that at least one checkbox matching the
 
 639   // "checkbox_selector" is actually checked. If not, an error message
 
 640   // is shown, and false is returned. Otherwise (at least one of them
 
 641   // is checked) nothing is shown and true returned.
 
 643   // Can be used in checks when clicking buttons.
 
 644   ns.check_if_entries_selected = function(checkbox_selector) {
 
 645     if ($(checkbox_selector + ':checked').length > 0)
 
 648     alert(kivi.t8('No entries have been selected.'));
 
 653   ns.switch_areainput_to_textarea = function(id) {
 
 654     var $input = $('#' + id);
 
 658     var $area = $('<textarea></textarea>');
 
 660     $area.prop('rows', 3);
 
 661     $area.prop('cols', $input.prop('size') || 40);
 
 662     $area.prop('name', $input.prop('name'));
 
 663     $area.prop('id',   $input.prop('id'));
 
 664     $area.val($input.val());
 
 666     $input.parent().replaceWith($area);
 
 670   ns.set_cursor_position = function(selector, position) {
 
 671     var $input = $(selector);
 
 672     if (position === 'end')
 
 673       position = $input.val().length;
 
 675     $input.prop('selectionStart', position);
 
 676     $input.prop('selectionEnd',   position);
 
 680 kivi = namespace('kivi');