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();
245 if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
247 if (ns.ProjectPicker)
248 ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
249 kivi.ProjectPicker($(elt));
253 ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
254 kivi.ChartPicker($(elt));
258 var func = kivi.get_function_by_name('local_reinit_widgets');
262 ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
264 contentAsHTML: false,
265 theme: 'tooltipster-light'
269 ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
272 theme: 'tooltipster-light'
276 ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
277 ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
280 ns.submit_ajax_form = function(url, form_selector, additional_data) {
281 $(form_selector).ajaxSubmit({
283 data: additional_data,
284 success: ns.eval_json_result
290 // This function submits an existing form given by "form_selector"
291 // and sets the "action" input to "action_to_call" before submitting
292 // it. Any existing input named "action" will be removed prior to
294 ns.submit_form_with_action = function(form_selector, action_to_call) {
295 $('[name=action]').remove();
297 var $form = $(form_selector);
298 var $hidden = $('<input type=hidden>');
300 $hidden.attr('name', 'action');
301 $hidden.attr('value', action_to_call);
302 $form.append($hidden);
307 // This function exists solely so that it can be found with
308 // kivi.get_functions_by_name() and called later on. Using something
309 // like "var func = history["back"]" works, but calling it later
310 // with "func.apply()" doesn't.
311 ns.history_back = function() {
315 // Return a function object by its name (a string). Works both with
316 // global functions (e.g. "check_right_date_format") and those in
317 // namespaces (e.g. "kivi.t8").
318 // Returns null if the object is not found.
319 ns.get_function_by_name = function(name) {
320 var parts = name.match("(.+)\\.([^\\.]+)$");
323 return namespace(parts[1])[ parts[2] ];
326 // Open a modal jQuery UI popup dialog. The content can be either
327 // loaded via AJAX (if the parameter 'url' is given) or simply
328 // displayed if it exists in the DOM already (referenced via
329 // 'id') or given via param.html. If an existing DOM div should be used then
330 // the element won't be removed upon closing the dialog which allows
331 // re-opening it later on.
334 // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
335 // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
336 // - dialog: an optional object of options passed to the $.dialog() call
337 // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
338 ns.popup_dialog = function(params) {
341 params = params || { };
342 var id = params.id || 'jqueryui_popup_dialog';
343 var custom_close = params.dialog ? params.dialog.close : undefined;
344 var dialog_params = $.extend(
345 { // kivitendo default parameters:
350 // User supplied options:
351 params.dialog || { },
352 { // Options that must not be changed:
353 close: function(event, ui) {
354 dialog.dialog('close');
359 if (params.url || params.html)
364 if (!params.url && !params.html) {
365 // Use existing DOM element and show it. No AJAX call.
368 .bind('dialogopen', function() {
369 ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
371 .dialog(dialog_params);
375 $('#' + id).remove();
377 dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
378 dialog.dialog(dialog_params);
381 dialog.html(params.html);
383 // no html? get it via ajax
388 success: function(new_html) {
389 dialog.html(new_html);
390 dialog.removeClass('loading');
400 // Run code only once for each matched element
402 // This allows running the function 'code' exactly once for each
403 // element that matches 'selector'. This is achieved by storing the
404 // state with jQuery's 'data' function. The 'identification' is
405 // required for differentiating unambiguously so that different code
406 // functions can still be run on the same elements.
408 // 'code' can be either a function or the name of one. It must
409 // resolve to a function that receives the jQueryfied element as its
413 ns.run_once_for = function(selector, identification, code) {
414 var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
415 var fn = typeof code === 'function' ? code : ns.get_function_by_name(code);
417 console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
421 $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
423 $elt.data(attr_name, true);
428 // Run a function by its name passing it some arguments
430 // This is a function useful mainly for the ClientJS functionality.
431 // It finds a function by its name and then executes it on an empty
432 // object passing the elements in 'args' (an array) as the function
433 // parameters retuning its result.
435 // Logs an error to the console and returns 'undefined' if the
436 // function cannot be found.
437 ns.run = function(function_name, args) {
438 var fn = ns.get_function_by_name(function_name);
440 return fn.apply({}, args || []);
442 console.error('kivi.run("' + function_name + '"): No function by that name found');
446 ns.detect_duplicate_ids_in_dom = function() {
450 $('[id]').each(function() {
451 if (this.id && ids[this.id]) {
453 console.warn('Duplicate ID #' + this.id);
459 console.log('No duplicate IDs found :)');
462 // Verifies that at least one checkbox matching the
463 // "checkbox_selector" is actually checked. If not, an error message
464 // is shown, and false is returned. Otherwise (at least one of them
465 // is checked) nothing is shown and true returned.
467 // Can be used in checks when clicking buttons.
468 ns.check_if_entries_selected = function(checkbox_selector) {
469 if ($(checkbox_selector + ':checked').length > 0)
472 alert(kivi.t8('No entries have been selected.'));
477 // Performs various validation steps on the descendants of
478 // 'selector'. Elements that should be validated must have an
479 // attribute named "data-validate" which is set to a space-separated
480 // list of tests to perform. Additionally, the attribute
481 // "data-title" must be set to a human-readable name of the field
482 // that can be shown as part of an error message.
484 // Supported validation tests are:
485 // - "required": the field must be set (its .val() must not be empty)
487 // The validation will abort and return "false" as soon as
488 // validation routine fails.
490 // The function returns "true" if all validations succeed for all
492 ns.validate_form = function(selector) {
493 var validate_field = function(elt) {
495 var tests = $elt.data('validate').split(/ +/);
497 title: $elt.data('title'),
501 for (var test_idx in tests) {
502 var test = tests[test_idx];
504 if (test === "required") {
505 if ($elt.val() === '') {
506 alert(kivi.t8("The field '#{title}' must be set.", info));
511 var error = "kivi.validate_form: unknown test '" + test + "' for element ID '" + $elt.prop('id') + "'";
512 console.error(error);
522 selector = selector || '#form';
524 var to_check = $(selector + ' [data-validate]').toArray();
526 for (var to_check_idx in to_check)
527 if (!validate_field(to_check[to_check_idx]))
533 ns.switch_areainput_to_textarea = function(id) {
534 var $input = $('#' + id);
538 var $area = $('<textarea></textarea>');
540 $area.prop('rows', 3);
541 $area.prop('cols', $input.prop('size') || 40);
542 $area.prop('name', $input.prop('name'));
543 $area.prop('id', $input.prop('id'));
544 $area.val($input.val());
546 $input.parent().replaceWith($area);
551 kivi = namespace('kivi');