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 var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
36 ((parts[ ns._date_format.y ] || 0) * 1) || (new Date()).getFullYear(),
37 (parts[ ns._date_format.m ] || 0) * 1 - 1, // Months are 0-based.
38 (parts[ ns._date_format.d ] || 0) * 1
41 return isNaN(date.getTime()) ? undefined : date;
44 ns.format_date = function(date) {
45 if (isNaN(date.getTime()))
48 var parts = [ "", "", "" ]
49 parts[ ns._date_format.y ] = date.getFullYear();
50 parts[ ns._date_format.m ] = (date.getMonth() < 9 ? "0" : "") + (date.getMonth() + 1); // Months are 0-based, but days are 1-based.
51 parts[ ns._date_format.d ] = (date.getDate() < 10 ? "0" : "") + date.getDate();
52 return parts.join(ns._date_format.sep);
55 ns.parse_amount = function(amount) {
56 if ((amount === undefined) || (amount === ''))
59 if (ns._number_format.decimalSep == ',')
60 amount = amount.replace(/\./g, "").replace(/,/g, ".");
62 amount = amount.replace(/[\',]/g, "")
64 // Make sure no code wich is not a math expression ends up in eval().
65 if (!amount.match(/^[0-9 ()\-+*/.]*$/))
76 ns.round_amount = function(amount, places) {
77 var neg = amount >= 0 ? 1 : -1;
78 var mult = Math.pow(10, places + 1);
79 var temp = Math.abs(amount) * mult;
80 var diff = Math.abs(1 - temp + Math.floor(temp));
81 temp = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
83 temp += dec >= 5 ? 10 - dec: dec * -1;
85 return neg * temp / mult;
88 ns.format_amount = function(amount, places) {
91 if ((places !== undefined) && (places >= 0))
92 amount = ns.round_amount(amount, Math.abs(places));
94 var parts = ("" + Math.abs(amount)).split(/\./);
96 var dec = parts.length > 1 ? parts[1] : "";
97 var sign = amount < 0 ? "-" : "";
99 if (places !== undefined) {
100 while (dec.length < Math.abs(places))
103 if ((places > 0) && (dec.length > Math.abs(places)))
104 dec = d.substr(0, places);
107 if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
108 var len = ((intg.length + 2) % 3) + 1,
110 res = intg.substr(0, len);
111 while (start < intg.length) {
112 res += ns._number_format.thousandSep + intg.substr(start, 3);
119 var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
121 return sign + intg + sep + dec;
124 ns.t8 = function(text, params) {
125 text = ns._locale[text] || text;
128 if( Object.prototype.toString.call( params ) === '[object Array]' ) {
129 var len = params.length;
131 for(var i=0; i<len; ++i) {
134 text = text.split("#"+ key).join(value);
137 else if( typeof params == 'object' ) {
140 text = text.split("#{"+ key +"}").join(value);
147 ns.setupLocale = function(locale) {
151 ns.set_focus = function(element) {
152 var $e = $(element).eq(0);
153 if ($e.data('ckeditorInstance'))
154 ns.focus_ckeditor_when_ready($e);
159 ns.focus_ckeditor_when_ready = function(element) {
160 $(element).data('ckeditorInstance').on('instanceReady', function() { ns.focus_ckeditor(element); });
163 ns.focus_ckeditor = function(element) {
164 $(element).data('ckeditorInstance').focus();
167 ns.selectall_ckeditor = function(element) {
168 var editor = $(element).ckeditorGet();
169 var editable = editor.editable();
170 if (editable.is('textarea')) {
171 var textarea = editable.$;
174 textarea.createTextRange().execCommand('SelectAll');
176 textarea.selectionStart = 0;
177 textarea.selectionEnd = textarea.value.length;
180 if (editable.is('body'))
181 editor.document.$.execCommand('SelectAll', false, null);
184 var range = editor.createRange();
185 range.selectNodeContents(editable);
189 editor.forceNextSelectionCheck();
190 editor.selectionChange();
194 ns.init_tabwidget = function(element) {
195 var $element = $(element);
197 var elementId = $element.attr('id');
200 var cookieName = 'jquery_ui_tab_'+ elementId;
201 tabsParams.active = $.cookie(cookieName);
202 tabsParams.activate = function(event, ui) {
203 var i = ui.newTab.parent().children().index(ui.newTab);
204 $.cookie(cookieName, i);
208 $element.tabs(tabsParams);
211 ns.init_text_editor = function(element) {
213 all: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
214 default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
218 var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
222 removePlugins: 'resize',
223 extraPlugins: 'inline_resize',
225 disableAutoInline: true,
229 config.height = $e.height();
230 config.width = $e.width();
232 var editor = CKEDITOR.inline($e.get(0), config);
233 $e.data('ckeditorInstance', editor);
235 if ($e.hasClass('texteditor-autofocus'))
236 editor.on('instanceReady', function() { ns.focus_ckeditor($e); });
239 ns.reinit_widgets = function() {
240 ns.run_once_for('.datepicker', 'datepicker', function(elt) {
244 if (ns.Part) ns.Part.reinit_widgets();
246 if (ns.ProjectPicker)
247 ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
248 kivi.ProjectPicker($(elt));
251 if (ns.CustomerVendorPicker)
252 ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
253 kivi.CustomerVendorPicker($(elt));
257 ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
258 kivi.ChartPicker($(elt));
262 var func = kivi.get_function_by_name('local_reinit_widgets');
266 ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
268 contentAsHTML: false,
269 theme: 'tooltipster-light'
273 ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
276 theme: 'tooltipster-light'
280 ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
281 ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
284 ns.submit_ajax_form = function(url, form_selector, additional_data) {
285 $(form_selector).ajaxSubmit({
287 data: additional_data,
288 success: ns.eval_json_result
294 // This function submits an existing form given by "form_selector"
295 // and sets the "action" input to "action_to_call" before submitting
296 // it. Any existing input named "action" will be removed prior to
298 ns.submit_form_with_action = function(form_selector, action_to_call) {
299 $('[name=action]').remove();
301 var $form = $(form_selector);
302 var $hidden = $('<input type=hidden>');
304 $hidden.attr('name', 'action');
305 $hidden.attr('value', action_to_call);
306 $form.append($hidden);
311 // This function exists solely so that it can be found with
312 // kivi.get_functions_by_name() and called later on. Using something
313 // like "var func = history["back"]" works, but calling it later
314 // with "func.apply()" doesn't.
315 ns.history_back = function() {
319 // Return a function object by its name (a string). Works both with
320 // global functions (e.g. "check_right_date_format") and those in
321 // namespaces (e.g. "kivi.t8").
322 // Returns null if the object is not found.
323 ns.get_function_by_name = function(name) {
324 var parts = name.match("(.+)\\.([^\\.]+)$");
327 return namespace(parts[1])[ parts[2] ];
330 // Open a modal jQuery UI popup dialog. The content can be either
331 // loaded via AJAX (if the parameter 'url' is given) or simply
332 // displayed if it exists in the DOM already (referenced via
333 // 'id') or given via param.html. If an existing DOM div should be used then
334 // the element won't be removed upon closing the dialog which allows
335 // re-opening it later on.
338 // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
339 // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
340 // - dialog: an optional object of options passed to the $.dialog() call
341 // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
342 ns.popup_dialog = function(params) {
345 params = params || { };
346 var id = params.id || 'jqueryui_popup_dialog';
347 var custom_close = params.dialog ? params.dialog.close : undefined;
348 var dialog_params = $.extend(
349 { // kivitendo default parameters:
354 // User supplied options:
355 params.dialog || { },
356 { // Options that must not be changed:
357 close: function(event, ui) {
358 dialog.dialog('close');
363 if (params.url || params.html)
368 if (!params.url && !params.html) {
369 // Use existing DOM element and show it. No AJAX call.
372 .bind('dialogopen', function() {
373 ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
375 .dialog(dialog_params);
379 $('#' + id).remove();
381 dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
382 dialog.dialog(dialog_params);
385 dialog.html(params.html);
387 // no html? get it via ajax
392 success: function(new_html) {
393 dialog.html(new_html);
394 dialog.removeClass('loading');
404 // Run code only once for each matched element
406 // This allows running the function 'code' exactly once for each
407 // element that matches 'selector'. This is achieved by storing the
408 // state with jQuery's 'data' function. The 'identification' is
409 // required for differentiating unambiguously so that different code
410 // functions can still be run on the same elements.
412 // 'code' can be either a function or the name of one. It must
413 // resolve to a function that receives the jQueryfied element as its
417 ns.run_once_for = function(selector, identification, code) {
418 var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
419 var fn = typeof code === 'function' ? code : ns.get_function_by_name(code);
421 console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
425 $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
427 $elt.data(attr_name, true);
432 // Run a function by its name passing it some arguments
434 // This is a function useful mainly for the ClientJS functionality.
435 // It finds a function by its name and then executes it on an empty
436 // object passing the elements in 'args' (an array) as the function
437 // parameters retuning its result.
439 // Logs an error to the console and returns 'undefined' if the
440 // function cannot be found.
441 ns.run = function(function_name, args) {
442 var fn = ns.get_function_by_name(function_name);
444 return fn.apply({}, args || []);
446 console.error('kivi.run("' + function_name + '"): No function by that name found');
450 ns.detect_duplicate_ids_in_dom = function() {
454 $('[id]').each(function() {
455 if (this.id && ids[this.id]) {
457 console.warn('Duplicate ID #' + this.id);
463 console.log('No duplicate IDs found :)');
466 // Verifies that at least one checkbox matching the
467 // "checkbox_selector" is actually checked. If not, an error message
468 // is shown, and false is returned. Otherwise (at least one of them
469 // is checked) nothing is shown and true returned.
471 // Can be used in checks when clicking buttons.
472 ns.check_if_entries_selected = function(checkbox_selector) {
473 if ($(checkbox_selector + ':checked').length > 0)
476 alert(kivi.t8('No entries have been selected.'));
481 // Performs various validation steps on the descendants of
482 // 'selector'. Elements that should be validated must have an
483 // attribute named "data-validate" which is set to a space-separated
484 // list of tests to perform. Additionally, the attribute
485 // "data-title" must be set to a human-readable name of the field
486 // that can be shown as part of an error message.
488 // Supported validation tests are:
489 // - "required": the field must be set (its .val() must not be empty)
491 // The validation will abort and return "false" as soon as
492 // validation routine fails.
494 // The function returns "true" if all validations succeed for all
496 ns.validate_form = function(selector) {
497 var validate_field = function(elt) {
499 var tests = $elt.data('validate').split(/ +/);
501 title: $elt.data('title'),
505 for (var test_idx in tests) {
506 var test = tests[test_idx];
508 if (test === "required") {
509 if ($elt.val() === '') {
510 alert(kivi.t8("The field '#{title}' must be set.", info));
515 var error = "kivi.validate_form: unknown test '" + test + "' for element ID '" + $elt.prop('id') + "'";
516 console.error(error);
526 selector = selector || '#form';
528 var to_check = $(selector + ' [data-validate]').toArray();
530 for (var to_check_idx in to_check)
531 if (!validate_field(to_check[to_check_idx]))
537 ns.switch_areainput_to_textarea = function(id) {
538 var $input = $('#' + id);
542 var $area = $('<textarea></textarea>');
544 $area.prop('rows', 3);
545 $area.prop('cols', $input.prop('size') || 40);
546 $area.prop('name', $input.prop('name'));
547 $area.prop('id', $input.prop('id'));
548 $area.val($input.val());
550 $input.parent().replaceWith($area);
555 kivi = namespace('kivi');