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 // This function submits an existing form given by "form_selector"
292 // and sets the "action" input to "action_to_call" before submitting
293 // it. Any existing input named "action" will be removed prior to
295 ns.submit_form_with_action = function(form_selector, action_to_call) {
296 $('[name=action]').remove();
298 var $form = $(form_selector);
299 var $hidden = $('<input type=hidden>');
301 $hidden.attr('name', 'action');
302 $hidden.attr('value', action_to_call);
303 $form.append($hidden);
308 // This function exists solely so that it can be found with
309 // kivi.get_functions_by_name() and called later on. Using something
310 // like "var func = history["back"]" works, but calling it later
311 // with "func.apply()" doesn't.
312 ns.history_back = function() {
316 // Return a function object by its name (a string). Works both with
317 // global functions (e.g. "check_right_date_format") and those in
318 // namespaces (e.g. "kivi.t8").
319 // Returns null if the object is not found.
320 ns.get_function_by_name = function(name) {
321 var parts = name.match("(.+)\\.([^\\.]+)$");
324 return namespace(parts[1])[ parts[2] ];
327 // Open a modal jQuery UI popup dialog. The content can be either
328 // loaded via AJAX (if the parameter 'url' is given) or simply
329 // displayed if it exists in the DOM already (referenced via
330 // 'id') or given via param.html. If an existing DOM div should be used then
331 // the element won't be removed upon closing the dialog which allows
332 // re-opening it later on.
335 // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
336 // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
337 // - dialog: an optional object of options passed to the $.dialog() call
338 // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
339 ns.popup_dialog = function(params) {
342 params = params || { };
343 var id = params.id || 'jqueryui_popup_dialog';
344 var custom_close = params.dialog ? params.dialog.close : undefined;
345 var dialog_params = $.extend(
346 { // kivitendo default parameters:
351 // User supplied options:
352 params.dialog || { },
353 { // Options that must not be changed:
354 close: function(event, ui) {
358 if (params.url || params.html)
361 dialog.dialog('close');
365 if (!params.url && !params.html) {
366 // Use existing DOM element and show it. No AJAX call.
369 .bind('dialogopen', function() {
370 ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
372 .dialog(dialog_params);
376 $('#' + id).remove();
378 dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
379 dialog.dialog(dialog_params);
382 dialog.html(params.html);
384 // no html? get it via ajax
389 success: function(new_html) {
390 dialog.html(new_html);
391 dialog.removeClass('loading');
401 // Run code only once for each matched element
403 // This allows running the function 'code' exactly once for each
404 // element that matches 'selector'. This is achieved by storing the
405 // state with jQuery's 'data' function. The 'identification' is
406 // required for differentiating unambiguously so that different code
407 // functions can still be run on the same elements.
409 // 'code' can be either a function or the name of one. It must
410 // resolve to a function that receives the jQueryfied element as its
414 ns.run_once_for = function(selector, identification, code) {
415 var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
416 var fn = typeof code === 'function' ? code : ns.get_function_by_name(code);
418 console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
422 $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
424 $elt.data(attr_name, true);
429 // Run a function by its name passing it some arguments
431 // This is a function useful mainly for the ClientJS functionality.
432 // It finds a function by its name and then executes it on an empty
433 // object passing the elements in 'args' (an array) as the function
434 // parameters retuning its result.
436 // Logs an error to the console and returns 'undefined' if the
437 // function cannot be found.
438 ns.run = function(function_name, args) {
439 var fn = ns.get_function_by_name(function_name);
441 return fn.apply({}, args);
443 console.error('kivi.run("' + function_name + '"): No function by that name found');
447 ns.detect_duplicate_ids_in_dom = function() {
451 $('[id]').each(function() {
452 if (this.id && ids[this.id]) {
454 console.warn('Duplicate ID #' + this.id);
460 console.log('No duplicate IDs found :)');
464 kivi = namespace('kivi');