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, "")
68 ns.round_amount = function(amount, places) {
69 var neg = amount >= 0 ? 1 : -1;
70 var mult = Math.pow(10, places + 1);
71 var temp = Math.abs(amount) * mult;
72 var diff = Math.abs(1 - temp + Math.floor(temp));
73 temp = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
75 temp += dec >= 5 ? 10 - dec: dec * -1;
77 return neg * temp / mult;
80 ns.format_amount = function(amount, places) {
83 if ((places !== undefined) && (places >= 0))
84 amount = ns.round_amount(amount, Math.abs(places));
86 var parts = ("" + Math.abs(amount)).split(/\./);
88 var dec = parts.length > 1 ? parts[1] : "";
89 var sign = amount < 0 ? "-" : "";
91 if (places !== undefined) {
92 while (dec.length < Math.abs(places))
95 if ((places > 0) && (dec.length > Math.abs(places)))
96 dec = d.substr(0, places);
99 if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
100 var len = ((intg.length + 2) % 3) + 1,
102 res = intg.substr(0, len);
103 while (start < intg.length) {
104 res += ns._number_format.thousandSep + intg.substr(start, 3);
111 var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
113 return sign + intg + sep + dec;
116 ns.t8 = function(text, params) {
117 text = ns._locale[text] || text;
120 if( Object.prototype.toString.call( params ) === '[object Array]' ) {
121 var len = params.length;
123 for(var i=0; i<len; ++i) {
126 text = text.split("#"+ key).join(value);
129 else if( typeof params == 'object' ) {
132 text = text.split("#{"+ key +"}").join(value);
139 ns.setupLocale = function(locale) {
143 ns.set_focus = function(element) {
144 var $e = $(element).eq(0);
145 if ($e.data('ckeditorInstance'))
146 ns.focus_ckeditor_when_ready($e);
151 ns.focus_ckeditor_when_ready = function(element) {
152 $(element).ckeditor(function() { ns.focus_ckeditor(element); });
155 ns.focus_ckeditor = function(element) {
156 var editor = $(element).ckeditorGet();
157 var editable = editor.editable();
159 if (editable.is('textarea')) {
160 var textarea = editable.$;
163 textarea.createTextRange().execCommand('SelectAll');
165 textarea.selectionStart = 0;
166 textarea.selectionEnd = textarea.value.length;
172 if (editable.is('body'))
173 editor.document.$.execCommand('SelectAll', false, null);
176 var range = editor.createRange();
177 range.selectNodeContents(editable);
181 editor.forceNextSelectionCheck();
182 editor.selectionChange();
188 ns.init_tabwidget = function(element) {
189 var $element = $(element);
191 var elementId = $element.attr('id');
194 var cookieName = 'jquery_ui_tab_'+ elementId;
195 tabsParams.active = $.cookie(cookieName);
196 tabsParams.activate = function(event, ui) {
197 var i = ui.newTab.parent().children().index(ui.newTab);
198 $.cookie(cookieName, i);
202 $element.tabs(tabsParams);
205 ns.init_text_editor = function(element) {
207 all: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
208 default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
212 var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
216 removePlugins: 'resize',
220 var style = $e.prop('style');
221 $(['width', 'height']).each(function(idx, prop) {
222 var matches = (style[prop] || '').match(/(\d+)px/);
223 if (matches && (matches.length > 1))
224 config[prop] = matches[1];
229 if ($e.hasClass('texteditor-autofocus'))
230 $e.ckeditor(function() { ns.focus_ckeditor($e); });
233 ns.reinit_widgets = function() {
234 ns.run_once_for('.datepicker', 'datepicker', function(elt) {
239 ns.run_once_for('input.part_autocomplete', 'part_picker', function(elt) {
240 kivi.PartPicker($(elt));
243 if (ns.ProjectPicker)
244 ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
245 kivi.ProjectPicker($(elt));
248 if (ns.CustomerVendorPicker)
249 ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
250 kivi.CustomerVendorPicker($(elt));
254 ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
255 kivi.ChartPicker($(elt));
259 var func = kivi.get_function_by_name('local_reinit_widgets');
263 ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
265 contentAsHTML: false,
266 theme: 'tooltipster-light'
270 ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
273 theme: 'tooltipster-light'
277 ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
278 ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
281 ns.submit_ajax_form = function(url, form_selector, additional_data) {
282 $(form_selector).ajaxSubmit({
284 data: additional_data,
285 success: ns.eval_json_result
291 // Return a function object by its name (a string). Works both with
292 // global functions (e.g. "check_right_date_format") and those in
293 // namespaces (e.g. "kivi.t8").
294 // Returns null if the object is not found.
295 ns.get_function_by_name = function(name) {
296 var parts = name.match("(.+)\\.([^\\.]+)$");
299 return namespace(parts[1])[ parts[2] ];
302 // Open a modal jQuery UI popup dialog. The content can be either
303 // loaded via AJAX (if the parameter 'url' is given) or simply
304 // displayed if it exists in the DOM already (referenced via
305 // 'id') or given via param.html. If an existing DOM div should be used then
306 // the element won't be removed upon closing the dialog which allows
307 // re-opening it later on.
310 // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
311 // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
312 // - dialog: an optional object of options passed to the $.dialog() call
313 // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
314 ns.popup_dialog = function(params) {
317 params = params || { };
318 var id = params.id || 'jqueryui_popup_dialog';
319 var custom_close = params.dialog ? params.dialog.close : undefined;
320 var dialog_params = $.extend(
321 { // kivitendo default parameters:
326 // User supplied options:
327 params.dialog || { },
328 { // Options that must not be changed:
329 close: function(event, ui) {
333 if (params.url || params.html)
336 dialog.dialog('close');
340 if (!params.url && !params.html) {
341 // Use existing DOM element and show it. No AJAX call.
344 .bind('dialogopen', function() {
345 ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
347 .dialog(dialog_params);
351 $('#' + id).remove();
353 dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
354 dialog.dialog(dialog_params);
357 dialog.html(params.html);
359 // no html? get it via ajax
364 success: function(new_html) {
365 dialog.html(new_html);
366 dialog.removeClass('loading');
376 // Run code only once for each matched element
378 // This allows running the function 'code' exactly once for each
379 // element that matches 'selector'. This is achieved by storing the
380 // state with jQuery's 'data' function. The 'identification' is
381 // required for differentiating unambiguously so that different code
382 // functions can still be run on the same elements.
384 // 'code' can be either a function or the name of one. It must
385 // resolve to a function that receives the jQueryfied element as its
389 ns.run_once_for = function(selector, identification, code) {
390 var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
391 var fn = typeof code === 'function' ? code : ns.get_function_by_name(code);
393 console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
397 $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
399 $elt.data(attr_name, true);
404 // Run a function by its name passing it some arguments
406 // This is a function useful mainly for the ClientJS functionality.
407 // It finds a function by its name and then executes it on an empty
408 // object passing the elements in 'args' (an array) as the function
409 // parameters retuning its result.
411 // Logs an error to the console and returns 'undefined' if the
412 // function cannot be found.
413 ns.run = function(function_name, args) {
414 var fn = ns.get_function_by_name(function_name);
416 return fn.apply({}, args);
418 console.error('kivi.run("' + function_name + '"): No function by that name found');
422 ns.detect_duplicate_ids_in_dom = function() {
426 $('[id]').each(function() {
427 if (this.id && ids[this.id]) {
429 console.warn('Duplicate ID #' + this.id);
435 console.log('No duplicate IDs found :)');
439 kivi = namespace('kivi');