1 namespace("kivi", function(ns) {
 
  14   ns.setup_formats = function(params) {
 
  15     var res = (params.dates || "").match(/^([ymd]+)([^a-z])([ymd]+)[^a-z]([ymd]+)$/);
 
  17       ns._date_format                      = { sep: res[2] };
 
  18       ns._date_format[res[1].substr(0, 1)] = 0;
 
  19       ns._date_format[res[3].substr(0, 1)] = 1;
 
  20       ns._date_format[res[4].substr(0, 1)] = 2;
 
  23     res = (params.numbers || "").match(/^\d*([^\d]?)\d+([^\d])\d+$/);
 
  31   ns.parse_date = function(date) {
 
  32     var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
 
  34       ((parts[ ns._date_format.y ] || 0) * 1) || (new Date).getFullYear(),
 
  35        (parts[ ns._date_format.m ] || 0) * 1 - 1, // Months are 0-based.
 
  36        (parts[ ns._date_format.d ] || 0) * 1
 
  39     return isNaN(date.getTime()) ? undefined : date;
 
  42   ns.format_date = function(date) {
 
  43     if (isNaN(date.getTime()))
 
  46     var parts = [ "", "", "" ]
 
  47     parts[ ns._date_format.y ] = date.getFullYear();
 
  48     parts[ ns._date_format.m ] = (date.getMonth() <  9 ? "0" : "") + (date.getMonth() + 1); // Months are 0-based, but days are 1-based.
 
  49     parts[ ns._date_format.d ] = (date.getDate()  < 10 ? "0" : "") + date.getDate();
 
  50     return parts.join(ns._date_format.sep);
 
  53   ns.parse_amount = function(amount) {
 
  54     if ((amount == undefined) || (amount == ''))
 
  57     if (ns._number_format.decimalSep == ',')
 
  58       amount = amount.replace(/\./g, "").replace(/,/g, ".");
 
  60     amount = amount.replace(/[\',]/g, "")
 
  65   ns.round_amount = function(amount, places) {
 
  66     var neg  = amount >= 0 ? 1 : -1;
 
  67     var mult = Math.pow(10, places + 1);
 
  68     var temp = Math.abs(amount) * mult;
 
  69     var diff = Math.abs(1 - temp + Math.floor(temp));
 
  70     temp     = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
 
  72     temp    += dec >= 5 ? 10 - dec: dec * -1;
 
  74     return neg * temp / mult;
 
  77   ns.format_amount = function(amount, places) {
 
  80     if ((places != undefined) && (places >= 0))
 
  81       amount = ns.round_amount(amount, Math.abs(places));
 
  83     var parts = ("" + Math.abs(amount)).split(/\./);
 
  85     var dec   = parts.length > 1 ? parts[1] : "";
 
  86     var sign  = amount  < 0      ? "-"      : "";
 
  88     if (places != undefined) {
 
  89       while (dec.length < Math.abs(places))
 
  92       if ((places > 0) && (dec.length > Math.abs(places)))
 
  93         dec = d.substr(0, places);
 
  96     if ((ns._number_format.thousandSep != "") && (intg.length > 3)) {
 
  97       var len   = ((intg.length + 2) % 3) + 1,
 
  99           res   = intg.substr(0, len);
 
 100       while (start < intg.length) {
 
 101         res   += ns._number_format.thousandSep + intg.substr(start, 3);
 
 108     var sep = (places != 0) && (dec != "") ? ns._number_format.decimalSep : "";
 
 110     return sign + intg + sep + dec;
 
 113   ns.t8 = function(text, params) {
 
 114     var text = ns._locale[text] || text;
 
 116     if( Object.prototype.toString.call( params ) === '[object Array]' ) {
 
 117       var len = params.length;
 
 119       for(var i=0; i<len; ++i) {
 
 121         var value = params[i];
 
 122         text = text.split("#"+ key).join(value);
 
 125     else if( typeof params == 'object' ) {
 
 126       for(var key in params) {
 
 127         var value = params[key];
 
 128         text = text.split("#{"+ key +"}").join(value);
 
 135   ns.setupLocale = function(locale) {
 
 139   ns.set_focus = function(element) {
 
 140     var $e = $(element).eq(0);
 
 141     if ($e.data('ckeditorInstance'))
 
 142       ns.focus_ckeditor_when_ready($e);
 
 147   ns.focus_ckeditor_when_ready = function(element) {
 
 148     $(element).ckeditor(function() { ns.focus_ckeditor(element); });
 
 151   ns.focus_ckeditor = function(element) {
 
 152     var editor   = $(element).ckeditorGet();
 
 153                 var editable = editor.editable();
 
 155                 if (editable.is('textarea')) {
 
 156                         var textarea = editable.$;
 
 159                                 textarea.createTextRange().execCommand('SelectAll');
 
 161                                 textarea.selectionStart = 0;
 
 162                                 textarea.selectionEnd   = textarea.value.length;
 
 168                         if (editable.is('body'))
 
 169                                 editor.document.$.execCommand('SelectAll', false, null);
 
 172                                 var range = editor.createRange();
 
 173                                 range.selectNodeContents(editable);
 
 177                         editor.forceNextSelectionCheck();
 
 178                         editor.selectionChange();
 
 184   ns.init_tabwidget = function(element) {
 
 185     var $element   = $(element);
 
 187     var elementId  = $element.attr('id');
 
 190       var cookieName      = 'jquery_ui_tab_'+ elementId;
 
 191       tabsParams.active   = $.cookie(cookieName);
 
 192       tabsParams.activate = function(event, ui) {
 
 193         var i = ui.newTab.parent().children().index(ui.newTab);
 
 194         $.cookie(cookieName, i);
 
 198     $element.tabs(tabsParams);
 
 201   ns.init_text_editor = function(element) {
 
 203       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
 
 204       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
 
 208     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
 
 212       removePlugins: 'resize',
 
 216     var style = $e.prop('style');
 
 217     $(['width', 'height']).each(function(idx, prop) {
 
 218       var matches = (style[prop] || '').match(/(\d+)px/);
 
 219       if (matches && (matches.length > 1))
 
 220         config[prop] = matches[1];
 
 225     if ($e.hasClass('texteditor-autofocus'))
 
 226       $e.ckeditor(function() { ns.focus_ckeditor($e); });
 
 229   ns.reinit_widgets = function() {
 
 230     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
 
 235       ns.run_once_for('input.part_autocomplete', 'part_picker', function(elt) {
 
 236         kivi.PartPicker($(elt));
 
 239     if (ns.ProjectPicker)
 
 240       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
 
 241         kivi.ProjectPicker($(elt));
 
 244     if (ns.CustomerVendorPicker)
 
 245       ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
 
 246         kivi.CustomerVendorPicker($(elt));
 
 250       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
 
 251         kivi.ChartPicker($(elt));
 
 255     var func = kivi.get_function_by_name('local_reinit_widgets');
 
 259     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
 
 261         contentAsHTML: false,
 
 262         theme: 'tooltipster-light'
 
 266     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
 
 269         theme: 'tooltipster-light'
 
 273     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
 
 274     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
 
 277   ns.submit_ajax_form = function(url, form_selector, additional_data) {
 
 278     $(form_selector).ajaxSubmit({
 
 280       data:    additional_data,
 
 281       success: ns.eval_json_result
 
 287   // Return a function object by its name (a string). Works both with
 
 288   // global functions (e.g. "check_right_date_format") and those in
 
 289   // namespaces (e.g. "kivi.t8").
 
 290   // Returns null if the object is not found.
 
 291   ns.get_function_by_name = function(name) {
 
 292     var parts = name.match("(.+)\\.([^\\.]+)$");
 
 295     return namespace(parts[1])[ parts[2] ];
 
 298   // Open a modal jQuery UI popup dialog. The content can be either
 
 299   // loaded via AJAX (if the parameter 'url' is given) or simply
 
 300   // displayed if it exists in the DOM already (referenced via
 
 301   // 'id') or given via param.html. If an existing DOM div should be used then
 
 302   // the element won't be removed upon closing the dialog which allows
 
 303   // re-opening it later on.
 
 306   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
 
 307   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
 
 308   // - dialog: an optional object of options passed to the $.dialog() call
 
 309   ns.popup_dialog = function(params) {
 
 312     params            = params        || { };
 
 313     var id            = params.id     || 'jqueryui_popup_dialog';
 
 314     var dialog_params = $.extend(
 
 315       { // kivitendo default parameters:
 
 320         // User supplied options:
 
 321       params.dialog || { },
 
 322       { // Options that must not be changed:
 
 323         close: function(event, ui) { if (params.url || params.html) dialog.remove(); else dialog.dialog('close'); }
 
 326     if (!params.url && !params.html) {
 
 327       // Use existing DOM element and show it. No AJAX call.
 
 330         .bind('dialogopen', function() {
 
 331           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
 
 333         .dialog(dialog_params);
 
 337     $('#' + id).remove();
 
 339     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
 
 340     dialog.dialog(dialog_params);
 
 343       dialog.html(params.html);
 
 345       // no html? get it via ajax
 
 350         success: function(new_html) {
 
 351           dialog.html(new_html);
 
 352           dialog.removeClass('loading');
 
 360   // Run code only once for each matched element
 
 362   // This allows running the function 'code' exactly once for each
 
 363   // element that matches 'selector'. This is achieved by storing the
 
 364   // state with jQuery's 'data' function. The 'identification' is
 
 365   // required for differentiating unambiguously so that different code
 
 366   // functions can still be run on the same elements.
 
 368   // 'code' can be either a function or the name of one. It must
 
 369   // resolve to a function that receives the jQueryfied element as its
 
 373   ns.run_once_for = function(selector, identification, code) {
 
 374     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
 
 375     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
 
 377       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
 
 381     $(selector).filter(function() { return $(this).data(attr_name) != true; }).each(function(idx, elt) {
 
 383       $elt.data(attr_name, true);
 
 388   // Run a function by its name passing it some arguments
 
 390   // This is a function useful mainly for the ClientJS functionality.
 
 391   // It finds a function by its name and then executes it on an empty
 
 392   // object passing the elements in 'args' (an array) as the function
 
 393   // parameters retuning its result.
 
 395   // Logs an error to the console and returns 'undefined' if the
 
 396   // function cannot be found.
 
 397   ns.run = function(function_name, args) {
 
 398     var fn = ns.get_function_by_name(function_name);
 
 400       return fn.apply({}, args);
 
 402     console.error('kivi.run("' + function_name + '"): No function by that name found');
 
 407 kivi = namespace('kivi');