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) {
247 ns.run_once_for('input.part_autocomplete', 'part_picker', function(elt) {
248 kivi.PartPicker($(elt));
251 if (ns.ProjectPicker)
252 ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
253 kivi.ProjectPicker($(elt));
256 if (ns.CustomerVendorPicker)
257 ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
258 kivi.CustomerVendorPicker($(elt));
262 ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
263 kivi.ChartPicker($(elt));
267 var func = kivi.get_function_by_name('local_reinit_widgets');
271 ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
273 contentAsHTML: false,
274 theme: 'tooltipster-light'
278 ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
281 theme: 'tooltipster-light'
285 ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
286 ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
289 ns.submit_ajax_form = function(url, form_selector, additional_data) {
290 $(form_selector).ajaxSubmit({
292 data: additional_data,
293 success: ns.eval_json_result
299 // This function submits an existing form given by "form_selector"
300 // and sets the "action" input to "action_to_call" before submitting
301 // it. Any existing input named "action" will be removed prior to
303 ns.submit_form_with_action = function(form_selector, action_to_call) {
304 $('[name=action]').remove();
306 var $form = $(form_selector);
307 var $hidden = $('<input type=hidden>');
309 $hidden.attr('name', 'action');
310 $hidden.attr('value', action_to_call);
311 $form.append($hidden);
316 // This function exists solely so that it can be found with
317 // kivi.get_functions_by_name() and called later on. Using something
318 // like "var func = history["back"]" works, but calling it later
319 // with "func.apply()" doesn't.
320 ns.history_back = function() {
324 // Return a function object by its name (a string). Works both with
325 // global functions (e.g. "check_right_date_format") and those in
326 // namespaces (e.g. "kivi.t8").
327 // Returns null if the object is not found.
328 ns.get_function_by_name = function(name) {
329 var parts = name.match("(.+)\\.([^\\.]+)$");
332 return namespace(parts[1])[ parts[2] ];
335 // Open a modal jQuery UI popup dialog. The content can be either
336 // loaded via AJAX (if the parameter 'url' is given) or simply
337 // displayed if it exists in the DOM already (referenced via
338 // 'id') or given via param.html. If an existing DOM div should be used then
339 // the element won't be removed upon closing the dialog which allows
340 // re-opening it later on.
343 // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
344 // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
345 // - dialog: an optional object of options passed to the $.dialog() call
346 // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
347 ns.popup_dialog = function(params) {
350 params = params || { };
351 var id = params.id || 'jqueryui_popup_dialog';
352 var custom_close = params.dialog ? params.dialog.close : undefined;
353 var dialog_params = $.extend(
354 { // kivitendo default parameters:
359 // User supplied options:
360 params.dialog || { },
361 { // Options that must not be changed:
362 close: function(event, ui) {
366 if (params.url || params.html)
369 dialog.dialog('close');
373 if (!params.url && !params.html) {
374 // Use existing DOM element and show it. No AJAX call.
377 .bind('dialogopen', function() {
378 ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
380 .dialog(dialog_params);
384 $('#' + id).remove();
386 dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
387 dialog.dialog(dialog_params);
390 dialog.html(params.html);
392 // no html? get it via ajax
397 success: function(new_html) {
398 dialog.html(new_html);
399 dialog.removeClass('loading');
409 // Run code only once for each matched element
411 // This allows running the function 'code' exactly once for each
412 // element that matches 'selector'. This is achieved by storing the
413 // state with jQuery's 'data' function. The 'identification' is
414 // required for differentiating unambiguously so that different code
415 // functions can still be run on the same elements.
417 // 'code' can be either a function or the name of one. It must
418 // resolve to a function that receives the jQueryfied element as its
422 ns.run_once_for = function(selector, identification, code) {
423 var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
424 var fn = typeof code === 'function' ? code : ns.get_function_by_name(code);
426 console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
430 $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
432 $elt.data(attr_name, true);
437 // Run a function by its name passing it some arguments
439 // This is a function useful mainly for the ClientJS functionality.
440 // It finds a function by its name and then executes it on an empty
441 // object passing the elements in 'args' (an array) as the function
442 // parameters retuning its result.
444 // Logs an error to the console and returns 'undefined' if the
445 // function cannot be found.
446 ns.run = function(function_name, args) {
447 var fn = ns.get_function_by_name(function_name);
449 return fn.apply({}, args);
451 console.error('kivi.run("' + function_name + '"): No function by that name found');
455 ns.detect_duplicate_ids_in_dom = function() {
459 $('[id]').each(function() {
460 if (this.id && ids[this.id]) {
462 console.warn('Duplicate ID #' + this.id);
468 console.log('No duplicate IDs found :)');
471 // Verifies that at least one checkbox matching the
472 // "checkbox_selector" is actually checked. If not, an error message
473 // is shown, and false is returned. Otherwise (at least one of them
474 // is checked) nothing is shown and true returned.
476 // Can be used in checks when clicking buttons.
477 ns.check_if_entries_selected = function(checkbox_selector) {
478 if ($(checkbox_selector + ':checked').length > 0)
481 alert(kivi.t8('No entries have been selected.'));
486 // Performs various validation steps on the descendants of
487 // 'selector'. Elements that should be validated must have an
488 // attribute named "data-validate" which is set to a space-separated
489 // list of tests to perform. Additionally, the attribute
490 // "data-title" must be set to a human-readable name of the field
491 // that can be shown as part of an error message.
493 // Supported validation tests are:
494 // - "required": the field must be set (its .val() must not be empty)
496 // The validation will abort and return "false" as soon as
497 // validation routine fails.
499 // The function returns "true" if all validations succeed for all
501 ns.validate_form = function(selector) {
502 var validate_field = function(elt) {
504 var tests = $elt.data('validate').split(/ +/);
506 title: $elt.data('title'),
510 for (var test_idx in tests) {
511 var test = tests[test_idx];
513 if (test === "required") {
514 if ($elt.val() === '') {
515 alert(kivi.t8("The field '#{title}' must be set.", info));
520 var error = "kivi.validate_form: unknown test '" + test + "' for element ID '" + $elt.prop('id') + "'";
521 console.error(error);
531 selector = selector || '#form';
533 var to_check = $(selector + ' [data-validate]').toArray();
535 for (var to_check_idx in to_check)
536 if (!validate_field(to_check[to_check_idx]))
543 kivi = namespace('kivi');