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 ()\-+*/.]*$/))
72 ns.round_amount = function(amount, places) {
73 var neg = amount >= 0 ? 1 : -1;
74 var mult = Math.pow(10, places + 1);
75 var temp = Math.abs(amount) * mult;
76 var diff = Math.abs(1 - temp + Math.floor(temp));
77 temp = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
79 temp += dec >= 5 ? 10 - dec: dec * -1;
81 return neg * temp / mult;
84 ns.format_amount = function(amount, places) {
87 if ((places !== undefined) && (places >= 0))
88 amount = ns.round_amount(amount, Math.abs(places));
90 var parts = ("" + Math.abs(amount)).split(/\./);
92 var dec = parts.length > 1 ? parts[1] : "";
93 var sign = amount < 0 ? "-" : "";
95 if (places !== undefined) {
96 while (dec.length < Math.abs(places))
99 if ((places > 0) && (dec.length > Math.abs(places)))
100 dec = d.substr(0, places);
103 if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
104 var len = ((intg.length + 2) % 3) + 1,
106 res = intg.substr(0, len);
107 while (start < intg.length) {
108 res += ns._number_format.thousandSep + intg.substr(start, 3);
115 var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
117 return sign + intg + sep + dec;
120 ns.t8 = function(text, params) {
121 text = ns._locale[text] || text;
124 if( Object.prototype.toString.call( params ) === '[object Array]' ) {
125 var len = params.length;
127 for(var i=0; i<len; ++i) {
130 text = text.split("#"+ key).join(value);
133 else if( typeof params == 'object' ) {
136 text = text.split("#{"+ key +"}").join(value);
143 ns.setupLocale = function(locale) {
147 ns.set_focus = function(element) {
148 var $e = $(element).eq(0);
149 if ($e.data('ckeditorInstance'))
150 ns.focus_ckeditor_when_ready($e);
155 ns.focus_ckeditor_when_ready = function(element) {
156 $(element).ckeditor(function() { ns.focus_ckeditor(element); });
159 ns.focus_ckeditor = function(element) {
160 var editor = $(element).ckeditorGet();
161 var editable = editor.editable();
163 if (editable.is('textarea')) {
164 var textarea = editable.$;
167 textarea.createTextRange().execCommand('SelectAll');
169 textarea.selectionStart = 0;
170 textarea.selectionEnd = textarea.value.length;
176 if (editable.is('body'))
177 editor.document.$.execCommand('SelectAll', false, null);
180 var range = editor.createRange();
181 range.selectNodeContents(editable);
185 editor.forceNextSelectionCheck();
186 editor.selectionChange();
192 ns.init_tabwidget = function(element) {
193 var $element = $(element);
195 var elementId = $element.attr('id');
198 var cookieName = 'jquery_ui_tab_'+ elementId;
199 tabsParams.active = $.cookie(cookieName);
200 tabsParams.activate = function(event, ui) {
201 var i = ui.newTab.parent().children().index(ui.newTab);
202 $.cookie(cookieName, i);
206 $element.tabs(tabsParams);
209 ns.init_text_editor = function(element) {
211 all: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
212 default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
216 var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
220 removePlugins: 'resize',
224 var style = $e.prop('style');
225 $(['width', 'height']).each(function(idx, prop) {
226 var matches = (style[prop] || '').match(/(\d+)px/);
227 if (matches && (matches.length > 1))
228 config[prop] = matches[1];
233 if ($e.hasClass('texteditor-autofocus'))
234 $e.ckeditor(function() { ns.focus_ckeditor($e); });
237 ns.reinit_widgets = function() {
238 ns.run_once_for('.datepicker', 'datepicker', function(elt) {
243 ns.run_once_for('input.part_autocomplete', 'part_picker', function(elt) {
244 kivi.PartPicker($(elt));
247 if (ns.ProjectPicker)
248 ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
249 kivi.ProjectPicker($(elt));
252 if (ns.CustomerVendorPicker)
253 ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
254 kivi.CustomerVendorPicker($(elt));
258 ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
259 kivi.ChartPicker($(elt));
263 var func = kivi.get_function_by_name('local_reinit_widgets');
267 ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
269 contentAsHTML: false,
270 theme: 'tooltipster-light'
274 ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
277 theme: 'tooltipster-light'
281 ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
282 ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
285 ns.submit_ajax_form = function(url, form_selector, additional_data) {
286 $(form_selector).ajaxSubmit({
288 data: additional_data,
289 success: ns.eval_json_result
295 // This function submits an existing form given by "form_selector"
296 // and sets the "action" input to "action_to_call" before submitting
297 // it. Any existing input named "action" will be removed prior to
299 ns.submit_form_with_action = function(form_selector, action_to_call) {
300 $('[name=action]').remove();
302 var $form = $(form_selector);
303 var $hidden = $('<input type=hidden>');
305 $hidden.attr('name', 'action');
306 $hidden.attr('value', action_to_call);
307 $form.append($hidden);
312 // This function exists solely so that it can be found with
313 // kivi.get_functions_by_name() and called later on. Using something
314 // like "var func = history["back"]" works, but calling it later
315 // with "func.apply()" doesn't.
316 ns.history_back = function() {
320 // Return a function object by its name (a string). Works both with
321 // global functions (e.g. "check_right_date_format") and those in
322 // namespaces (e.g. "kivi.t8").
323 // Returns null if the object is not found.
324 ns.get_function_by_name = function(name) {
325 var parts = name.match("(.+)\\.([^\\.]+)$");
328 return namespace(parts[1])[ parts[2] ];
331 // Open a modal jQuery UI popup dialog. The content can be either
332 // loaded via AJAX (if the parameter 'url' is given) or simply
333 // displayed if it exists in the DOM already (referenced via
334 // 'id') or given via param.html. If an existing DOM div should be used then
335 // the element won't be removed upon closing the dialog which allows
336 // re-opening it later on.
339 // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
340 // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
341 // - dialog: an optional object of options passed to the $.dialog() call
342 // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
343 ns.popup_dialog = function(params) {
346 params = params || { };
347 var id = params.id || 'jqueryui_popup_dialog';
348 var custom_close = params.dialog ? params.dialog.close : undefined;
349 var dialog_params = $.extend(
350 { // kivitendo default parameters:
355 // User supplied options:
356 params.dialog || { },
357 { // Options that must not be changed:
358 close: function(event, ui) {
362 if (params.url || params.html)
365 dialog.dialog('close');
369 if (!params.url && !params.html) {
370 // Use existing DOM element and show it. No AJAX call.
373 .bind('dialogopen', function() {
374 ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
376 .dialog(dialog_params);
380 $('#' + id).remove();
382 dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
383 dialog.dialog(dialog_params);
386 dialog.html(params.html);
388 // no html? get it via ajax
393 success: function(new_html) {
394 dialog.html(new_html);
395 dialog.removeClass('loading');
405 // Run code only once for each matched element
407 // This allows running the function 'code' exactly once for each
408 // element that matches 'selector'. This is achieved by storing the
409 // state with jQuery's 'data' function. The 'identification' is
410 // required for differentiating unambiguously so that different code
411 // functions can still be run on the same elements.
413 // 'code' can be either a function or the name of one. It must
414 // resolve to a function that receives the jQueryfied element as its
418 ns.run_once_for = function(selector, identification, code) {
419 var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
420 var fn = typeof code === 'function' ? code : ns.get_function_by_name(code);
422 console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
426 $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
428 $elt.data(attr_name, true);
433 // Run a function by its name passing it some arguments
435 // This is a function useful mainly for the ClientJS functionality.
436 // It finds a function by its name and then executes it on an empty
437 // object passing the elements in 'args' (an array) as the function
438 // parameters retuning its result.
440 // Logs an error to the console and returns 'undefined' if the
441 // function cannot be found.
442 ns.run = function(function_name, args) {
443 var fn = ns.get_function_by_name(function_name);
445 return fn.apply({}, args);
447 console.error('kivi.run("' + function_name + '"): No function by that name found');
451 ns.detect_duplicate_ids_in_dom = function() {
455 $('[id]').each(function() {
456 if (this.id && ids[this.id]) {
458 console.warn('Duplicate ID #' + this.id);
464 console.log('No duplicate IDs found :)');
467 // Verifies that at least one checkbox matching the
468 // "checkbox_selector" is actually checked. If not, an error message
469 // is shown, and false is returned. Otherwise (at least one of them
470 // is checked) nothing is shown and true returned.
472 // Can be used in checks when clicking buttons.
473 ns.check_if_entries_selected = function(checkbox_selector) {
474 if ($(checkbox_selector + ':checked').length > 0)
477 alert(kivi.t8('No entries have been selected.'));
482 // Performs various validation steps on the descendants of
483 // 'selector'. Elements that should be validated must have an
484 // attribute named "data-validate" which is set to a space-separated
485 // list of tests to perform. Additionally, the attribute
486 // "data-title" must be set to a human-readable name of the field
487 // that can be shown as part of an error message.
489 // Supported validation tests are:
490 // - "required": the field must be set (its .val() must not be empty)
492 // The validation will abort and return "false" as soon as
493 // validation routine fails.
495 // The function returns "true" if all validations succeed for all
497 ns.validate_form = function(selector) {
498 var validate_field = function(elt) {
500 var tests = $elt.data('validate').split(/ +/);
502 title: $elt.data('title'),
506 for (var test_idx in tests) {
507 var test = tests[test_idx];
509 if (test === "required") {
510 if ($elt.val() === '') {
511 alert(kivi.t8("The field '#{title}' must be set.", info));
516 var error = "kivi.validate_form: unknown test '" + test + "' for element ID '" + $elt.prop('id') + "'";
517 console.error(error);
527 selector = selector || '#form';
529 var to_check = $(selector + ' [data-validate]').toArray();
531 for (var to_check_idx in to_check)
532 if (!validate_field(to_check[to_check_idx]))
539 kivi = namespace('kivi');