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).ckeditor(function() { ns.focus_ckeditor(element); });
163 ns.focus_ckeditor = function(element) {
164 var editor = $(element).ckeditorGet();
165 var editable = editor.editable();
167 if (editable.is('textarea')) {
168 var textarea = editable.$;
171 textarea.createTextRange().execCommand('SelectAll');
173 textarea.selectionStart = 0;
174 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();
196 ns.init_tabwidget = function(element) {
197 var $element = $(element);
199 var elementId = $element.attr('id');
202 var cookieName = 'jquery_ui_tab_'+ elementId;
203 tabsParams.active = $.cookie(cookieName);
204 tabsParams.activate = function(event, ui) {
205 var i = ui.newTab.parent().children().index(ui.newTab);
206 $.cookie(cookieName, i);
210 $element.tabs(tabsParams);
213 ns.init_text_editor = function(element) {
215 all: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
216 default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
220 var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
224 removePlugins: 'resize',
228 var style = $e.prop('style');
229 $(['width', 'height']).each(function(idx, prop) {
230 var matches = (style[prop] || '').match(/(\d+)px/);
231 if (matches && (matches.length > 1))
232 config[prop] = matches[1];
237 if ($e.hasClass('texteditor-autofocus'))
238 $e.ckeditor(function() { ns.focus_ckeditor($e); });
241 ns.reinit_widgets = function() {
242 ns.run_once_for('.datepicker', 'datepicker', function(elt) {
246 if (ns.Part) ns.Part.reinit_widgets();
248 if (ns.ProjectPicker)
249 ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
250 kivi.ProjectPicker($(elt));
253 if (ns.CustomerVendorPicker)
254 ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
255 kivi.CustomerVendorPicker($(elt));
259 ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
260 kivi.ChartPicker($(elt));
264 var func = kivi.get_function_by_name('local_reinit_widgets');
268 ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
270 contentAsHTML: false,
271 theme: 'tooltipster-light'
275 ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
278 theme: 'tooltipster-light'
282 ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
283 ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
286 ns.submit_ajax_form = function(url, form_selector, additional_data) {
287 $(form_selector).ajaxSubmit({
289 data: additional_data,
290 success: ns.eval_json_result
296 // This function submits an existing form given by "form_selector"
297 // and sets the "action" input to "action_to_call" before submitting
298 // it. Any existing input named "action" will be removed prior to
300 ns.submit_form_with_action = function(form_selector, action_to_call) {
301 $('[name=action]').remove();
303 var $form = $(form_selector);
304 var $hidden = $('<input type=hidden>');
306 $hidden.attr('name', 'action');
307 $hidden.attr('value', action_to_call);
308 $form.append($hidden);
313 // This function exists solely so that it can be found with
314 // kivi.get_functions_by_name() and called later on. Using something
315 // like "var func = history["back"]" works, but calling it later
316 // with "func.apply()" doesn't.
317 ns.history_back = function() {
321 // Return a function object by its name (a string). Works both with
322 // global functions (e.g. "check_right_date_format") and those in
323 // namespaces (e.g. "kivi.t8").
324 // Returns null if the object is not found.
325 ns.get_function_by_name = function(name) {
326 var parts = name.match("(.+)\\.([^\\.]+)$");
329 return namespace(parts[1])[ parts[2] ];
332 // Open a modal jQuery UI popup dialog. The content can be either
333 // loaded via AJAX (if the parameter 'url' is given) or simply
334 // displayed if it exists in the DOM already (referenced via
335 // 'id') or given via param.html. If an existing DOM div should be used then
336 // the element won't be removed upon closing the dialog which allows
337 // re-opening it later on.
340 // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
341 // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
342 // - dialog: an optional object of options passed to the $.dialog() call
343 // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
344 ns.popup_dialog = function(params) {
347 params = params || { };
348 var id = params.id || 'jqueryui_popup_dialog';
349 var custom_close = params.dialog ? params.dialog.close : undefined;
350 var dialog_params = $.extend(
351 { // kivitendo default parameters:
356 // User supplied options:
357 params.dialog || { },
358 { // Options that must not be changed:
359 close: function(event, ui) {
363 if (params.url || params.html)
366 dialog.dialog('close');
370 if (!params.url && !params.html) {
371 // Use existing DOM element and show it. No AJAX call.
374 .bind('dialogopen', function() {
375 ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
377 .dialog(dialog_params);
381 $('#' + id).remove();
383 dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
384 dialog.dialog(dialog_params);
387 dialog.html(params.html);
389 // no html? get it via ajax
394 success: function(new_html) {
395 dialog.html(new_html);
396 dialog.removeClass('loading');
406 // Run code only once for each matched element
408 // This allows running the function 'code' exactly once for each
409 // element that matches 'selector'. This is achieved by storing the
410 // state with jQuery's 'data' function. The 'identification' is
411 // required for differentiating unambiguously so that different code
412 // functions can still be run on the same elements.
414 // 'code' can be either a function or the name of one. It must
415 // resolve to a function that receives the jQueryfied element as its
419 ns.run_once_for = function(selector, identification, code) {
420 var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
421 var fn = typeof code === 'function' ? code : ns.get_function_by_name(code);
423 console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
427 $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
429 $elt.data(attr_name, true);
434 // Run a function by its name passing it some arguments
436 // This is a function useful mainly for the ClientJS functionality.
437 // It finds a function by its name and then executes it on an empty
438 // object passing the elements in 'args' (an array) as the function
439 // parameters retuning its result.
441 // Logs an error to the console and returns 'undefined' if the
442 // function cannot be found.
443 ns.run = function(function_name, args) {
444 var fn = ns.get_function_by_name(function_name);
446 return fn.apply({}, args);
448 console.error('kivi.run("' + function_name + '"): No function by that name found');
452 ns.detect_duplicate_ids_in_dom = function() {
456 $('[id]').each(function() {
457 if (this.id && ids[this.id]) {
459 console.warn('Duplicate ID #' + this.id);
465 console.log('No duplicate IDs found :)');
468 // Verifies that at least one checkbox matching the
469 // "checkbox_selector" is actually checked. If not, an error message
470 // is shown, and false is returned. Otherwise (at least one of them
471 // is checked) nothing is shown and true returned.
473 // Can be used in checks when clicking buttons.
474 ns.check_if_entries_selected = function(checkbox_selector) {
475 if ($(checkbox_selector + ':checked').length > 0)
478 alert(kivi.t8('No entries have been selected.'));
483 // Performs various validation steps on the descendants of
484 // 'selector'. Elements that should be validated must have an
485 // attribute named "data-validate" which is set to a space-separated
486 // list of tests to perform. Additionally, the attribute
487 // "data-title" must be set to a human-readable name of the field
488 // that can be shown as part of an error message.
490 // Supported validation tests are:
491 // - "required": the field must be set (its .val() must not be empty)
493 // The validation will abort and return "false" as soon as
494 // validation routine fails.
496 // The function returns "true" if all validations succeed for all
498 ns.validate_form = function(selector) {
499 var validate_field = function(elt) {
501 var tests = $elt.data('validate').split(/ +/);
503 title: $elt.data('title'),
507 for (var test_idx in tests) {
508 var test = tests[test_idx];
510 if (test === "required") {
511 if ($elt.val() === '') {
512 alert(kivi.t8("The field '#{title}' must be set.", info));
517 var error = "kivi.validate_form: unknown test '" + test + "' for element ID '" + $elt.prop('id') + "'";
518 console.error(error);
528 selector = selector || '#form';
530 var to_check = $(selector + ' [data-validate]').toArray();
532 for (var to_check_idx in to_check)
533 if (!validate_field(to_check[to_check_idx]))
540 kivi = namespace('kivi');