1 namespace("kivi", function(ns) {
 
  16   ns.setup_formats = function(params) {
 
  17     var res = (params.dates || "").match(/^([ymd]+)([^a-z])([ymd]+)[^a-z]([ymd]+)$/);
 
  19       ns._date_format                      = { sep: res[2] };
 
  20       ns._date_format[res[1].substr(0, 1)] = 0;
 
  21       ns._date_format[res[3].substr(0, 1)] = 1;
 
  22       ns._date_format[res[4].substr(0, 1)] = 2;
 
  25     res = (params.numbers || "").match(/^\d*([^\d]?)\d+([^\d])\d+$/);
 
  33   ns.parse_date = function(date) {
 
  34     if (date === undefined)
 
  40     if (date === '0' || date === '00')
 
  43     var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
 
  44     var today = new Date();
 
  47     // assume fixed pattern, and extract parts again
 
  48     if (parts.length == 1) {
 
  50       parts = date.match(/../g);
 
  51       if (date.length == 8) {
 
  52         parts[ns._date_format.y] += parts.splice(ns._date_format.y + 1, 1)
 
  55       if (date.length == 6 || date.length == 4) {
 
  58       if (date.length == 1 || date.length == 2) {
 
  60         parts[ ns._date_format.y ] = today.getFullYear();
 
  61         parts[ ns._date_format.m ] = today.getMonth() + 1;
 
  62         parts[ ns._date_format.d ] = date;
 
  69     if (parts.length == 3) {
 
  70       var year = +parts[ ns._date_format.y ] || 0 * 1 || (new Date()).getFullYear();
 
  74         year += year > 70 ? 1900 : 2000;
 
  78         (parts[ ns._date_format.m ] || (today.getMonth() + 1)) * 1 - 1, // Months are 0-based.
 
  79         (parts[ ns._date_format.d ] || today.getDate()) * 1
 
  81     } else if (parts.length == 2) {
 
  83         (new Date()).getFullYear(),
 
  84         (parts[ (ns._date_format.m > ns._date_format.d) * 1 ] || (today.getMonth() + 1)) * 1 - 1, // Months are 0-based.
 
  85         (parts[ (ns._date_format.d > ns._date_format.m) * 1 ] || today.getDate()) * 1
 
  90     return isNaN(date.getTime()) ? undefined : date;
 
  93   ns.format_date = function(date) {
 
  94     if (isNaN(date.getTime()))
 
  97     var parts = [ "", "", "" ]
 
  98     parts[ ns._date_format.y ] = date.getFullYear();
 
  99     parts[ ns._date_format.m ] = (date.getMonth() <  9 ? "0" : "") + (date.getMonth() + 1); // Months are 0-based, but days are 1-based.
 
 100     parts[ ns._date_format.d ] = (date.getDate()  < 10 ? "0" : "") + date.getDate();
 
 101     return parts.join(ns._date_format.sep);
 
 104   ns.parse_amount = function(amount) {
 
 105     if (amount === undefined)
 
 111     if (ns._number_format.decimalSep == ',')
 
 112       amount = amount.replace(/\./g, "").replace(/,/g, ".");
 
 114     amount = amount.replace(/[\',]/g, "");
 
 116     // Make sure no code wich is not a math expression ends up in eval().
 
 117     if (!amount.match(/^[0-9 ()\-+*/.]*$/))
 
 120     amount = amount.replace(/^0+(\d+)/, '$1');
 
 130   ns.round_amount = function(amount, places) {
 
 131     var neg  = amount >= 0 ? 1 : -1;
 
 132     var mult = Math.pow(10, places + 1);
 
 133     var temp = Math.abs(amount) * mult;
 
 134     var diff = Math.abs(1 - temp + Math.floor(temp));
 
 135     temp     = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
 
 137     temp    += dec >= 5 ? 10 - dec: dec * -1;
 
 139     return neg * temp / mult;
 
 142   ns.format_amount = function(amount, places) {
 
 143     amount = amount || 0;
 
 145     if ((places !== undefined) && (places >= 0))
 
 146       amount = ns.round_amount(amount, Math.abs(places));
 
 148     var parts = ("" + Math.abs(amount)).split(/\./);
 
 150     var dec   = parts.length > 1 ? parts[1] : "";
 
 151     var sign  = amount  < 0      ? "-"      : "";
 
 153     if (places !== undefined) {
 
 154       while (dec.length < Math.abs(places))
 
 157       if ((places > 0) && (dec.length > Math.abs(places)))
 
 158         dec = d.substr(0, places);
 
 161     if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
 
 162       var len   = ((intg.length + 2) % 3) + 1,
 
 164           res   = intg.substr(0, len);
 
 165       while (start < intg.length) {
 
 166         res   += ns._number_format.thousandSep + intg.substr(start, 3);
 
 173     var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
 
 175     return sign + intg + sep + dec;
 
 178   ns.t8 = function(text, params) {
 
 179     text = ns._locale[text] || text;
 
 182     if( Object.prototype.toString.call( params ) === '[object Array]' ) {
 
 183       var len = params.length;
 
 185       for(var i=0; i<len; ++i) {
 
 188         text = text.split("#"+ key).join(value);
 
 191     else if( typeof params == 'object' ) {
 
 194         text = text.split("#{"+ key +"}").join(value);
 
 201   ns.setupLocale = function(locale) {
 
 205   ns.set_focus = function(element) {
 
 206     var $e = $(element).eq(0);
 
 207     if ($e.data('ckeditorInstance'))
 
 208       ns.focus_ckeditor_when_ready($e);
 
 213   ns.focus_ckeditor_when_ready = function(element) {
 
 214     $(element).data('ckeditorInstance').on('instanceReady', function() { ns.focus_ckeditor(element); });
 
 217   ns.focus_ckeditor = function(element) {
 
 218     $(element).data('ckeditorInstance').focus();
 
 221   ns.selectall_ckeditor = function(element) {
 
 222     var editor   = $(element).ckeditorGet();
 
 223     var editable = editor.editable();
 
 224     if (editable.is('textarea')) {
 
 225       var textarea = editable.$;
 
 228         textarea.createTextRange().execCommand('SelectAll');
 
 230         textarea.selectionStart = 0;
 
 231         textarea.selectionEnd   = textarea.value.length;
 
 234       if (editable.is('body'))
 
 235         editor.document.$.execCommand('SelectAll', false, null);
 
 238         var range = editor.createRange();
 
 239         range.selectNodeContents(editable);
 
 243       editor.forceNextSelectionCheck();
 
 244       editor.selectionChange();
 
 248   ns.init_tabwidget = function(element) {
 
 249     var $element   = $(element);
 
 251     var elementId  = $element.attr('id');
 
 254       var cookieName      = 'jquery_ui_tab_'+ elementId;
 
 255       tabsParams.active   = $.cookie(cookieName);
 
 256       tabsParams.activate = function(event, ui) {
 
 257         var i = ui.newTab.parent().children().index(ui.newTab);
 
 258         $.cookie(cookieName, i);
 
 262     $element.tabs(tabsParams);
 
 265   ns.init_text_editor = function(element) {
 
 267       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
 
 268       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
 
 272     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
 
 276       removePlugins: 'resize',
 
 277       extraPlugins:  'inline_resize',
 
 279       disableAutoInline: true,
 
 283     config.height = $e.height();
 
 284     config.width  = $e.width();
 
 286     var editor = CKEDITOR.inline($e.get(0), config);
 
 287     $e.data('ckeditorInstance', editor);
 
 289     if ($e.hasClass('texteditor-autofocus'))
 
 290       editor.on('instanceReady', function() { ns.focus_ckeditor($e); });
 
 293   ns.reinit_widgets = function() {
 
 294     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
 
 298     if (ns.Part) ns.Part.reinit_widgets();
 
 299     if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
 
 300     if (ns.Validator) ns.Validator.reinit_widgets();
 
 302     if (ns.ProjectPicker)
 
 303       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
 
 304         kivi.ProjectPicker($(elt));
 
 308       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
 
 309         kivi.ChartPicker($(elt));
 
 313     var func = kivi.get_function_by_name('local_reinit_widgets');
 
 317     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
 
 319         contentAsHTML: false,
 
 320         theme: 'tooltipster-light'
 
 324     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
 
 327         theme: 'tooltipster-light'
 
 331     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
 
 332     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
 
 335   ns.submit_ajax_form = function(url, form_selector, additional_data) {
 
 336     $(form_selector).ajaxSubmit({
 
 338       data:    additional_data,
 
 339       success: ns.eval_json_result
 
 345   // This function submits an existing form given by "form_selector"
 
 346   // and sets the "action" input to "action_to_call" before submitting
 
 347   // it. Any existing input named "action" will be removed prior to
 
 349   ns.submit_form_with_action = function(form_selector, action_to_call) {
 
 350     $('[name=action]').remove();
 
 352     var $form   = $(form_selector);
 
 353     var $hidden = $('<input type=hidden>');
 
 355     $hidden.attr('name',  'action');
 
 356     $hidden.attr('value', action_to_call);
 
 357     $form.append($hidden);
 
 362   // This function exists solely so that it can be found with
 
 363   // kivi.get_functions_by_name() and called later on. Using something
 
 364   // like "var func = history["back"]" works, but calling it later
 
 365   // with "func.apply()" doesn't.
 
 366   ns.history_back = function() {
 
 370   // Return a function object by its name (a string). Works both with
 
 371   // global functions (e.g. "focus_by_name") and those in namespaces (e.g.
 
 373   // Returns null if the object is not found.
 
 374   ns.get_function_by_name = function(name) {
 
 375     var parts = name.match("(.+)\\.([^\\.]+)$");
 
 378     return namespace(parts[1])[ parts[2] ];
 
 381   // Open a modal jQuery UI popup dialog. The content can be either
 
 382   // loaded via AJAX (if the parameter 'url' is given) or simply
 
 383   // displayed if it exists in the DOM already (referenced via
 
 384   // 'id') or given via param.html. If an existing DOM div should be used then
 
 385   // the element won't be removed upon closing the dialog which allows
 
 386   // re-opening it later on.
 
 389   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
 
 390   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
 
 391   // - dialog: an optional object of options passed to the $.dialog() call
 
 392   // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
 
 393   ns.popup_dialog = function(params) {
 
 396     params            = params        || { };
 
 397     var id            = params.id     || 'jqueryui_popup_dialog';
 
 398     var custom_close  = params.dialog ? params.dialog.close : undefined;
 
 399     var dialog_params = $.extend(
 
 400       { // kivitendo default parameters:
 
 405         // User supplied options:
 
 406       params.dialog || { },
 
 407       { // Options that must not be changed:
 
 408         close: function(event, ui) {
 
 409           dialog.dialog('close');
 
 414           if (params.url || params.html)
 
 419     if (!params.url && !params.html) {
 
 420       // Use existing DOM element and show it. No AJAX call.
 
 423         .bind('dialogopen', function() {
 
 424           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
 
 426         .dialog(dialog_params);
 
 430     $('#' + id).remove();
 
 432     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
 
 433     dialog.dialog(dialog_params);
 
 436       dialog.html(params.html);
 
 438       // no html? get it via ajax
 
 443         success: function(new_html) {
 
 444           dialog.html(new_html);
 
 445           dialog.removeClass('loading');
 
 455   // Run code only once for each matched element
 
 457   // This allows running the function 'code' exactly once for each
 
 458   // element that matches 'selector'. This is achieved by storing the
 
 459   // state with jQuery's 'data' function. The 'identification' is
 
 460   // required for differentiating unambiguously so that different code
 
 461   // functions can still be run on the same elements.
 
 463   // 'code' can be either a function or the name of one. It must
 
 464   // resolve to a function that receives the jQueryfied element as its
 
 468   ns.run_once_for = function(selector, identification, code) {
 
 469     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
 
 470     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
 
 472       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
 
 476     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
 
 478       $elt.data(attr_name, true);
 
 483   // Run a function by its name passing it some arguments
 
 485   // This is a function useful mainly for the ClientJS functionality.
 
 486   // It finds a function by its name and then executes it on an empty
 
 487   // object passing the elements in 'args' (an array) as the function
 
 488   // parameters retuning its result.
 
 490   // Logs an error to the console and returns 'undefined' if the
 
 491   // function cannot be found.
 
 492   ns.run = function(function_name, args) {
 
 493     var fn = ns.get_function_by_name(function_name);
 
 495       return fn.apply({}, args || []);
 
 497     console.error('kivi.run("' + function_name + '"): No function by that name found');
 
 501   ns.detect_duplicate_ids_in_dom = function() {
 
 505     $('[id]').each(function() {
 
 506       if (this.id && ids[this.id]) {
 
 508         console.warn('Duplicate ID #' + this.id);
 
 514       console.log('No duplicate IDs found :)');
 
 517   ns.validate_form = function(selector) {
 
 518     if (!kivi.Validator) {
 
 519       console.log('kivi.Validator is not loaded');
 
 521       return kivi.Validator.validate_all(selector);
 
 525   // Verifies that at least one checkbox matching the
 
 526   // "checkbox_selector" is actually checked. If not, an error message
 
 527   // is shown, and false is returned. Otherwise (at least one of them
 
 528   // is checked) nothing is shown and true returned.
 
 530   // Can be used in checks when clicking buttons.
 
 531   ns.check_if_entries_selected = function(checkbox_selector) {
 
 532     if ($(checkbox_selector + ':checked').length > 0)
 
 535     alert(kivi.t8('No entries have been selected.'));
 
 540   ns.switch_areainput_to_textarea = function(id) {
 
 541     var $input = $('#' + id);
 
 545     var $area = $('<textarea></textarea>');
 
 547     $area.prop('rows', 3);
 
 548     $area.prop('cols', $input.prop('size') || 40);
 
 549     $area.prop('name', $input.prop('name'));
 
 550     $area.prop('id',   $input.prop('id'));
 
 551     $area.val($input.val());
 
 553     $input.parent().replaceWith($area);
 
 558 kivi = namespace('kivi');