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 if (date === undefined)
40 var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
41 var today = new Date();
44 // assume fixed pattern, and extract parts again
45 if (parts.length == 1) {
47 parts = date.match(/../g);
48 if (date.length == 8) {
49 parts[ns._date_format.y] += parts.splice(ns._date_format.y + 1, 1)
52 if (date.length == 6 || date.length == 4) {
55 if (date.length == 1 || date.length == 2) {
57 parts[ ns._date_format.y ] = today.getFullYear();
58 parts[ ns._date_format.m ] = today.getMonth() + 1;
59 parts[ ns._date_format.d ] = date;
66 if (parts.length == 3) {
67 var year = +parts[ ns._date_format.y ] || 0 * 1 || (new Date()).getFullYear();
69 year += year > 70 ? 1900 : 2000;
73 (parts[ ns._date_format.m ] || 0) * 1 - 1, // Months are 0-based.
74 (parts[ ns._date_format.d ] || 0) * 1
76 } else if (parts.length == 2) {
78 (new Date()).getFullYear(),
79 (parts[ (ns._date_format.m > ns._date_format.d) * 1 ] || 0) * 1 - 1, // Months are 0-based.
80 (parts[ (ns._date_format.d > ns._date_format.m) * 1 ] || 0) * 1
85 return isNaN(date.getTime()) ? undefined : date;
88 ns.format_date = function(date) {
89 if (isNaN(date.getTime()))
92 var parts = [ "", "", "" ]
93 parts[ ns._date_format.y ] = date.getFullYear();
94 parts[ ns._date_format.m ] = (date.getMonth() < 9 ? "0" : "") + (date.getMonth() + 1); // Months are 0-based, but days are 1-based.
95 parts[ ns._date_format.d ] = (date.getDate() < 10 ? "0" : "") + date.getDate();
96 return parts.join(ns._date_format.sep);
99 ns.parse_amount = function(amount) {
100 if (amount === undefined)
106 if (ns._number_format.decimalSep == ',')
107 amount = amount.replace(/\./g, "").replace(/,/g, ".");
109 amount = amount.replace(/[\',]/g, "");
111 // Make sure no code wich is not a math expression ends up in eval().
112 if (!amount.match(/^[0-9 ()\-+*/.]*$/))
115 amount = amount.replace(/^0+(\d+)/, '$1');
125 ns.round_amount = function(amount, places) {
126 var neg = amount >= 0 ? 1 : -1;
127 var mult = Math.pow(10, places + 1);
128 var temp = Math.abs(amount) * mult;
129 var diff = Math.abs(1 - temp + Math.floor(temp));
130 temp = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
132 temp += dec >= 5 ? 10 - dec: dec * -1;
134 return neg * temp / mult;
137 ns.format_amount = function(amount, places) {
138 amount = amount || 0;
140 if ((places !== undefined) && (places >= 0))
141 amount = ns.round_amount(amount, Math.abs(places));
143 var parts = ("" + Math.abs(amount)).split(/\./);
145 var dec = parts.length > 1 ? parts[1] : "";
146 var sign = amount < 0 ? "-" : "";
148 if (places !== undefined) {
149 while (dec.length < Math.abs(places))
152 if ((places > 0) && (dec.length > Math.abs(places)))
153 dec = d.substr(0, places);
156 if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
157 var len = ((intg.length + 2) % 3) + 1,
159 res = intg.substr(0, len);
160 while (start < intg.length) {
161 res += ns._number_format.thousandSep + intg.substr(start, 3);
168 var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
170 return sign + intg + sep + dec;
173 ns.t8 = function(text, params) {
174 text = ns._locale[text] || text;
177 if( Object.prototype.toString.call( params ) === '[object Array]' ) {
178 var len = params.length;
180 for(var i=0; i<len; ++i) {
183 text = text.split("#"+ key).join(value);
186 else if( typeof params == 'object' ) {
189 text = text.split("#{"+ key +"}").join(value);
196 ns.setupLocale = function(locale) {
200 ns.set_focus = function(element) {
201 var $e = $(element).eq(0);
202 if ($e.data('ckeditorInstance'))
203 ns.focus_ckeditor_when_ready($e);
208 ns.focus_ckeditor_when_ready = function(element) {
209 $(element).data('ckeditorInstance').on('instanceReady', function() { ns.focus_ckeditor(element); });
212 ns.focus_ckeditor = function(element) {
213 $(element).data('ckeditorInstance').focus();
216 ns.selectall_ckeditor = function(element) {
217 var editor = $(element).ckeditorGet();
218 var editable = editor.editable();
219 if (editable.is('textarea')) {
220 var textarea = editable.$;
223 textarea.createTextRange().execCommand('SelectAll');
225 textarea.selectionStart = 0;
226 textarea.selectionEnd = textarea.value.length;
229 if (editable.is('body'))
230 editor.document.$.execCommand('SelectAll', false, null);
233 var range = editor.createRange();
234 range.selectNodeContents(editable);
238 editor.forceNextSelectionCheck();
239 editor.selectionChange();
243 ns.init_tabwidget = function(element) {
244 var $element = $(element);
246 var elementId = $element.attr('id');
249 var cookieName = 'jquery_ui_tab_'+ elementId;
250 tabsParams.active = $.cookie(cookieName);
251 tabsParams.activate = function(event, ui) {
252 var i = ui.newTab.parent().children().index(ui.newTab);
253 $.cookie(cookieName, i);
257 $element.tabs(tabsParams);
260 ns.init_text_editor = function(element) {
262 all: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
263 default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
267 var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
271 removePlugins: 'resize',
272 extraPlugins: 'inline_resize',
274 disableAutoInline: true,
278 config.height = $e.height();
279 config.width = $e.width();
281 var editor = CKEDITOR.inline($e.get(0), config);
282 $e.data('ckeditorInstance', editor);
284 if ($e.hasClass('texteditor-autofocus'))
285 editor.on('instanceReady', function() { ns.focus_ckeditor($e); });
288 ns.reinit_widgets = function() {
289 ns.run_once_for('.datepicker', 'datepicker', function(elt) {
293 if (ns.Part) ns.Part.reinit_widgets();
294 if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
295 if (ns.Validator) ns.Validator.reinit_widgets();
297 if (ns.ProjectPicker)
298 ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
299 kivi.ProjectPicker($(elt));
303 ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
304 kivi.ChartPicker($(elt));
308 var func = kivi.get_function_by_name('local_reinit_widgets');
312 ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
314 contentAsHTML: false,
315 theme: 'tooltipster-light'
319 ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
322 theme: 'tooltipster-light'
326 ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
327 ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
330 ns.submit_ajax_form = function(url, form_selector, additional_data) {
331 $(form_selector).ajaxSubmit({
333 data: additional_data,
334 success: ns.eval_json_result
340 // This function submits an existing form given by "form_selector"
341 // and sets the "action" input to "action_to_call" before submitting
342 // it. Any existing input named "action" will be removed prior to
344 ns.submit_form_with_action = function(form_selector, action_to_call) {
345 $('[name=action]').remove();
347 var $form = $(form_selector);
348 var $hidden = $('<input type=hidden>');
350 $hidden.attr('name', 'action');
351 $hidden.attr('value', action_to_call);
352 $form.append($hidden);
357 // This function exists solely so that it can be found with
358 // kivi.get_functions_by_name() and called later on. Using something
359 // like "var func = history["back"]" works, but calling it later
360 // with "func.apply()" doesn't.
361 ns.history_back = function() {
365 // Return a function object by its name (a string). Works both with
366 // global functions (e.g. "focus_by_name") and those in namespaces (e.g.
368 // Returns null if the object is not found.
369 ns.get_function_by_name = function(name) {
370 var parts = name.match("(.+)\\.([^\\.]+)$");
373 return namespace(parts[1])[ parts[2] ];
376 // Open a modal jQuery UI popup dialog. The content can be either
377 // loaded via AJAX (if the parameter 'url' is given) or simply
378 // displayed if it exists in the DOM already (referenced via
379 // 'id') or given via param.html. If an existing DOM div should be used then
380 // the element won't be removed upon closing the dialog which allows
381 // re-opening it later on.
384 // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
385 // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
386 // - dialog: an optional object of options passed to the $.dialog() call
387 // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
388 ns.popup_dialog = function(params) {
391 params = params || { };
392 var id = params.id || 'jqueryui_popup_dialog';
393 var custom_close = params.dialog ? params.dialog.close : undefined;
394 var dialog_params = $.extend(
395 { // kivitendo default parameters:
400 // User supplied options:
401 params.dialog || { },
402 { // Options that must not be changed:
403 close: function(event, ui) {
404 dialog.dialog('close');
409 if (params.url || params.html)
414 if (!params.url && !params.html) {
415 // Use existing DOM element and show it. No AJAX call.
418 .bind('dialogopen', function() {
419 ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
421 .dialog(dialog_params);
425 $('#' + id).remove();
427 dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
428 dialog.dialog(dialog_params);
431 dialog.html(params.html);
433 // no html? get it via ajax
438 success: function(new_html) {
439 dialog.html(new_html);
440 dialog.removeClass('loading');
450 // Run code only once for each matched element
452 // This allows running the function 'code' exactly once for each
453 // element that matches 'selector'. This is achieved by storing the
454 // state with jQuery's 'data' function. The 'identification' is
455 // required for differentiating unambiguously so that different code
456 // functions can still be run on the same elements.
458 // 'code' can be either a function or the name of one. It must
459 // resolve to a function that receives the jQueryfied element as its
463 ns.run_once_for = function(selector, identification, code) {
464 var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
465 var fn = typeof code === 'function' ? code : ns.get_function_by_name(code);
467 console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
471 $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
473 $elt.data(attr_name, true);
478 // Run a function by its name passing it some arguments
480 // This is a function useful mainly for the ClientJS functionality.
481 // It finds a function by its name and then executes it on an empty
482 // object passing the elements in 'args' (an array) as the function
483 // parameters retuning its result.
485 // Logs an error to the console and returns 'undefined' if the
486 // function cannot be found.
487 ns.run = function(function_name, args) {
488 var fn = ns.get_function_by_name(function_name);
490 return fn.apply({}, args || []);
492 console.error('kivi.run("' + function_name + '"): No function by that name found');
496 ns.detect_duplicate_ids_in_dom = function() {
500 $('[id]').each(function() {
501 if (this.id && ids[this.id]) {
503 console.warn('Duplicate ID #' + this.id);
509 console.log('No duplicate IDs found :)');
512 ns.validate_form = function(selector) {
513 if (!kivi.Validator) {
514 console.log('kivi.Validator is not loaded');
516 return kivi.Validator.validate_all(selector);
520 // Verifies that at least one checkbox matching the
521 // "checkbox_selector" is actually checked. If not, an error message
522 // is shown, and false is returned. Otherwise (at least one of them
523 // is checked) nothing is shown and true returned.
525 // Can be used in checks when clicking buttons.
526 ns.check_if_entries_selected = function(checkbox_selector) {
527 if ($(checkbox_selector + ':checked').length > 0)
530 alert(kivi.t8('No entries have been selected.'));
535 ns.switch_areainput_to_textarea = function(id) {
536 var $input = $('#' + id);
540 var $area = $('<textarea></textarea>');
542 $area.prop('rows', 3);
543 $area.prop('cols', $input.prop('size') || 40);
544 $area.prop('name', $input.prop('name'));
545 $area.prop('id', $input.prop('id'));
546 $area.val($input.val());
548 $input.parent().replaceWith($area);
553 kivi = namespace('kivi');