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,
 
 341       disableNativeSpellChecker: false
 
 344     config.height = $e.height();
 
 345     config.width  = $e.width();
 
 347     var editor = CKEDITOR.inline($e.get(0), config);
 
 348     $e.data('ckeditorInstance', editor);
 
 350     if ($e.hasClass('texteditor-space-for-toolbar'))
 
 351       editor.on('instanceReady', function() {
 
 352         var editor   = $e.ckeditorGet();
 
 353         var editable = editor.editable();
 
 354         $(editable.$).css("margin-top", "30px");
 
 358     if ($e.hasClass('texteditor-autofocus'))
 
 359       editor.on('instanceReady', function() { ns.focus_ckeditor($e); });
 
 362   ns.filter_select = function() {
 
 363     var $input  = $(this);
 
 364     var $select = $('#' + $input.data('select-id'));
 
 365     var filter  = $input.val().toLocaleLowerCase();
 
 367     $select.find('option').each(function() {
 
 368       if ($(this).text().toLocaleLowerCase().indexOf(filter) != -1)
 
 375   ns.reinit_widgets = function() {
 
 376     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
 
 380     if (ns.Part) ns.Part.reinit_widgets();
 
 381     if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
 
 382     if (ns.Validator) ns.Validator.reinit_widgets();
 
 383     if (ns.Materialize) ns.Materialize.reinit_widgets();
 
 385     if (ns.ProjectPicker)
 
 386       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
 
 387         kivi.ProjectPicker($(elt));
 
 391       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
 
 392         kivi.ChartPicker($(elt));
 
 395     ns.run_once_for('div.filtered_select input', 'filtered_select', function(elt) {
 
 396       $(elt).bind('change keyup', ns.filter_select);
 
 399     var func = kivi.get_function_by_name('local_reinit_widgets');
 
 403     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
 
 405         contentAsHTML: false,
 
 406         theme: 'tooltipster-light'
 
 410     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
 
 413         theme: 'tooltipster-light'
 
 417     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
 
 418     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
 
 421   ns.submit_ajax_form = function(url, form_selector, additional_data) {
 
 422     $(form_selector).ajaxSubmit({
 
 424       data:    additional_data,
 
 425       success: ns.eval_json_result
 
 431   // This function submits an existing form given by "form_selector"
 
 432   // and sets the "action" input to "action_to_call" before submitting
 
 433   // it. Any existing input named "action" will be removed prior to
 
 435   ns.submit_form_with_action = function(form_selector, action_to_call) {
 
 436     $('[name=action]').remove();
 
 438     var $form   = $(form_selector);
 
 439     var $hidden = $('<input type=hidden>');
 
 441     $hidden.attr('name',  'action');
 
 442     $hidden.attr('value', action_to_call);
 
 443     $form.append($hidden);
 
 448   // This function exists solely so that it can be found with
 
 449   // kivi.get_functions_by_name() and called later on. Using something
 
 450   // like "var func = history["back"]" works, but calling it later
 
 451   // with "func.apply()" doesn't.
 
 452   ns.history_back = function() {
 
 456   // Return a function object by its name (a string). Works both with
 
 457   // global functions (e.g. "focus_by_name") and those in namespaces (e.g.
 
 459   // Returns null if the object is not found.
 
 460   ns.get_function_by_name = function(name) {
 
 461     var parts = name.match("(.+)\\.([^\\.]+)$");
 
 464     return namespace(parts[1])[ parts[2] ];
 
 467   // Open a modal jQuery UI popup dialog. The content can be either
 
 468   // loaded via AJAX (if the parameter 'url' is given) or simply
 
 469   // displayed if it exists in the DOM already (referenced via
 
 470   // 'id') or given via param.html. If an existing DOM div should be used then
 
 471   // the element won't be removed upon closing the dialog which allows
 
 472   // re-opening it later on.
 
 475   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
 
 476   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
 
 477   // - dialog: an optional object of options passed to the $.dialog() call
 
 478   // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
 
 479   ns.popup_dialog = function(params) {
 
 480     if (kivi.Materialize)
 
 481       return kivi.Materialize.popup_dialog(params);
 
 485     params            = params        || { };
 
 486     var id            = params.id     || 'jqueryui_popup_dialog';
 
 487     var custom_close  = params.dialog ? params.dialog.close : undefined;
 
 488     var dialog_params = $.extend(
 
 489       { // kivitendo default parameters:
 
 494         // User supplied options:
 
 495       params.dialog || { },
 
 496       { // Options that must not be changed:
 
 497         close: function(event, ui) {
 
 498           dialog.dialog('close');
 
 503           if (params.url || params.html)
 
 508     if (!params.url && !params.html) {
 
 509       // Use existing DOM element and show it. No AJAX call.
 
 512         .bind('dialogopen', function() {
 
 513           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
 
 515         .dialog(dialog_params);
 
 519     $('#' + id).remove();
 
 521     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
 
 522     dialog.dialog(dialog_params);
 
 525       dialog.html(params.html);
 
 527       // no html? get it via ajax
 
 532         success: function(new_html) {
 
 533           dialog.html(new_html);
 
 534           dialog.removeClass('loading');
 
 544   // Run code only once for each matched element
 
 546   // This allows running the function 'code' exactly once for each
 
 547   // element that matches 'selector'. This is achieved by storing the
 
 548   // state with jQuery's 'data' function. The 'identification' is
 
 549   // required for differentiating unambiguously so that different code
 
 550   // functions can still be run on the same elements.
 
 552   // 'code' can be either a function or the name of one. It must
 
 553   // resolve to a function that receives the jQueryfied element as its
 
 557   ns.run_once_for = function(selector, identification, code) {
 
 558     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
 
 559     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
 
 561       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
 
 565     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
 
 567       $elt.data(attr_name, true);
 
 572   // Run a function by its name passing it some arguments
 
 574   // This is a function useful mainly for the ClientJS functionality.
 
 575   // It finds a function by its name and then executes it on an empty
 
 576   // object passing the elements in 'args' (an array) as the function
 
 577   // parameters retuning its result.
 
 579   // Logs an error to the console and returns 'undefined' if the
 
 580   // function cannot be found.
 
 581   ns.run = function(function_name, args) {
 
 582     var fn = ns.get_function_by_name(function_name);
 
 584       return fn.apply({}, args || []);
 
 586     console.error('kivi.run("' + function_name + '"): No function by that name found');
 
 590   ns.save_file = function(base64_data, content_type, size, attachment_name) {
 
 591     // atob returns a unicode string with one codepoint per octet. revert this
 
 592     const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
 
 593       const byteCharacters = atob(b64Data);
 
 594       const byteArrays = [];
 
 596       for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
 
 597         const slice = byteCharacters.slice(offset, offset + sliceSize);
 
 599         const byteNumbers = new Array(slice.length);
 
 600         for (let i = 0; i < slice.length; i++) {
 
 601           byteNumbers[i] = slice.charCodeAt(i);
 
 604         const byteArray = new Uint8Array(byteNumbers);
 
 605         byteArrays.push(byteArray);
 
 608       const blob = new Blob(byteArrays, {type: contentType});
 
 612     var blob = b64toBlob(base64_data, content_type);
 
 613     var a = $("<a style='display: none;'/>");
 
 614     var url = window.URL.createObjectURL(blob);
 
 616     a.attr("download", attachment_name);
 
 619     window.URL.revokeObjectURL(url);
 
 623   ns.detect_duplicate_ids_in_dom = function() {
 
 627     $('[id]').each(function() {
 
 628       if (this.id && ids[this.id]) {
 
 630         console.warn('Duplicate ID #' + this.id);
 
 636       console.log('No duplicate IDs found :)');
 
 639   ns.validate_form = function(selector) {
 
 640     if (!kivi.Validator) {
 
 641       console.log('kivi.Validator is not loaded');
 
 643       return kivi.Validator.validate_all(selector);
 
 647   // Verifies that at least one checkbox matching the
 
 648   // "checkbox_selector" is actually checked. If not, an error message
 
 649   // is shown, and false is returned. Otherwise (at least one of them
 
 650   // is checked) nothing is shown and true returned.
 
 652   // Can be used in checks when clicking buttons.
 
 653   ns.check_if_entries_selected = function(checkbox_selector) {
 
 654     if ($(checkbox_selector + ':checked').length > 0)
 
 657     alert(kivi.t8('No entries have been selected.'));
 
 662   ns.switch_areainput_to_textarea = function(id) {
 
 663     var $input = $('#' + id);
 
 667     var $area = $('<textarea></textarea>');
 
 669     $area.prop('rows', 3);
 
 670     $area.prop('cols', $input.prop('size') || 40);
 
 671     $area.prop('name', $input.prop('name'));
 
 672     $area.prop('id',   $input.prop('id'));
 
 673     $area.val($input.val());
 
 675     $input.parent().replaceWith($area);
 
 679   ns.set_cursor_position = function(selector, position) {
 
 680     var $input = $(selector);
 
 681     if (position === 'end')
 
 682       position = $input.val().length;
 
 684     $input.prop('selectionStart', position);
 
 685     $input.prop('selectionEnd',   position);
 
 688   ns._shell_escape = function(str) {
 
 689     if (str.match(/^[a-zA-Z0-9.,_=+/-]+$/))
 
 692     return "'" + str.replace(/'/, "'\\''") + "'";
 
 695   ns.call_as_curl = function(params) {
 
 696     params      = params || {};
 
 697     var uri     = document.documentURI.replace(/\?.*/, '');
 
 698     var command = ['curl', '--user', kivi.myconfig.login + ':SECRET', '--request', params.method || 'POST']
 
 700     $(params.data || []).each(function(idx, elt) {
 
 701       command = command.concat([ '--form-string', elt.name + '=' + (elt.value || '') ]);
 
 706     return $.map(command, function(elt, idx) {
 
 707       return kivi._shell_escape(elt);
 
 711   ns.serialize = function(source, target = [], prefix, in_array = false) {
 
 712     let arr_prefix = first => in_array ? (first ? "[+]" : "[]") : "";
 
 714     if (Array.isArray(source) ) {
 
 715       source.forEach(( val, i ) => {
 
 716         ns.serialize(val, target, prefix + arr_prefix(i == 0), true);
 
 718     } else if (typeof source === "object") {
 
 720       for (let key in source) {
 
 721         ns.serialize(source[key], target, (prefix !== undefined ? prefix + arr_prefix(first) + "." : "") + key);
 
 725       target.push({ name: prefix + arr_prefix(false), value: source });
 
 732 kivi = namespace('kivi');