41b3762a36feae20ef9630358e3a3e9dce94bca5
[kivitendo-erp.git] / js / kivi.js
1 namespace("kivi", function(ns) {
2   "use strict";
3
4   ns._locale = {};
5   ns._date_format   = {
6     sep: '.',
7     y:   2,
8     m:   1,
9     d:   0
10   };
11   ns._number_format = {
12     decimalSep:  ',',
13     thousandSep: '.'
14   };
15
16   ns.setup_formats = function(params) {
17     var res = (params.dates || "").match(/^([ymd]+)([^a-z])([ymd]+)[^a-z]([ymd]+)$/);
18     if (res) {
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;
23     }
24
25     res = (params.numbers || "").match(/^\d*([^\d]?)\d+([^\d])\d+$/);
26     if (res)
27       ns._number_format = {
28         decimalSep:  res[2],
29         thousandSep: res[1]
30       };
31   };
32
33   ns.parse_date = function(date) {
34     var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
35     date     = new Date(
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
39     );
40
41     return isNaN(date.getTime()) ? undefined : date;
42   };
43
44   ns.format_date = function(date) {
45     if (isNaN(date.getTime()))
46       return undefined;
47
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);
53   };
54
55   ns.parse_amount = function(amount) {
56     if ((amount === undefined) || (amount === ''))
57       return 0;
58
59     if (ns._number_format.decimalSep == ',')
60       amount = amount.replace(/\./g, "").replace(/,/g, ".");
61
62     amount = amount.replace(/[\',]/g, "")
63
64     // Make sure no code wich is not a math expression ends up in eval().
65     if (!amount.match(/^[0-9 ()\-+*/.]*$/))
66       return 0;
67
68     /* jshint -W061 */
69     try {
70       return eval(amount);
71     } catch (err) {
72       return 0;
73     }
74   };
75
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);
82     var dec  = temp % 10;
83     temp    += dec >= 5 ? 10 - dec: dec * -1;
84
85     return neg * temp / mult;
86   };
87
88   ns.format_amount = function(amount, places) {
89     amount = amount || 0;
90
91     if ((places !== undefined) && (places >= 0))
92       amount = ns.round_amount(amount, Math.abs(places));
93
94     var parts = ("" + Math.abs(amount)).split(/\./);
95     var intg  = parts[0];
96     var dec   = parts.length > 1 ? parts[1] : "";
97     var sign  = amount  < 0      ? "-"      : "";
98
99     if (places !== undefined) {
100       while (dec.length < Math.abs(places))
101         dec += "0";
102
103       if ((places > 0) && (dec.length > Math.abs(places)))
104         dec = d.substr(0, places);
105     }
106
107     if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
108       var len   = ((intg.length + 2) % 3) + 1,
109           start = len,
110           res   = intg.substr(0, len);
111       while (start < intg.length) {
112         res   += ns._number_format.thousandSep + intg.substr(start, 3);
113         start += 3;
114       }
115
116       intg = res;
117     }
118
119     var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
120
121     return sign + intg + sep + dec;
122   };
123
124   ns.t8 = function(text, params) {
125     text = ns._locale[text] || text;
126     var key, value
127
128     if( Object.prototype.toString.call( params ) === '[object Array]' ) {
129       var len = params.length;
130
131       for(var i=0; i<len; ++i) {
132         key = i + 1;
133         value = params[i];
134         text = text.split("#"+ key).join(value);
135       }
136     }
137     else if( typeof params == 'object' ) {
138       for(key in params) {
139         value = params[key];
140         text = text.split("#{"+ key +"}").join(value);
141       }
142     }
143
144     return text;
145   };
146
147   ns.setupLocale = function(locale) {
148     ns._locale = locale;
149   };
150
151   ns.set_focus = function(element) {
152     var $e = $(element).eq(0);
153     if ($e.data('ckeditorInstance'))
154       ns.focus_ckeditor_when_ready($e);
155     else
156       $e.focus();
157   };
158
159   ns.focus_ckeditor_when_ready = function(element) {
160     $(element).ckeditor(function() { ns.focus_ckeditor(element); });
161   };
162
163   ns.focus_ckeditor = function(element) {
164     var editor   = $(element).ckeditorGet();
165                 var editable = editor.editable();
166
167                 if (editable.is('textarea')) {
168                         var textarea = editable.$;
169
170                         if (CKEDITOR.env.ie)
171                                 textarea.createTextRange().execCommand('SelectAll');
172                         else {
173                                 textarea.selectionStart = 0;
174                                 textarea.selectionEnd   = textarea.value.length;
175                         }
176
177                         textarea.focus();
178
179                 } else {
180                         if (editable.is('body'))
181                                 editor.document.$.execCommand('SelectAll', false, null);
182
183                         else {
184                                 var range = editor.createRange();
185                                 range.selectNodeContents(editable);
186                                 range.select();
187                         }
188
189                         editor.forceNextSelectionCheck();
190                         editor.selectionChange();
191
192       editor.focus();
193                 }
194   };
195
196   ns.init_tabwidget = function(element) {
197     var $element   = $(element);
198     var tabsParams = {};
199     var elementId  = $element.attr('id');
200
201     if (elementId) {
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);
207       };
208     }
209
210     $element.tabs(tabsParams);
211   };
212
213   ns.init_text_editor = function(element) {
214     var layouts = {
215       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
216       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
217     };
218
219     var $e      = $(element);
220     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
221     var config  = {
222       entities:      false,
223       language:      'de',
224       removePlugins: 'resize',
225       toolbar:       buttons
226     }
227
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];
233     });
234
235     $e.ckeditor(config);
236
237     if ($e.hasClass('texteditor-autofocus'))
238       $e.ckeditor(function() { ns.focus_ckeditor($e); });
239   };
240
241   ns.reinit_widgets = function() {
242     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
243       $(elt).datepicker();
244     });
245
246     if (ns.Part) ns.Part.reinit_widgets();
247
248     if (ns.ProjectPicker)
249       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
250         kivi.ProjectPicker($(elt));
251       });
252
253     if (ns.CustomerVendorPicker)
254       ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
255         kivi.CustomerVendorPicker($(elt));
256       });
257
258     if (ns.ChartPicker)
259       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
260         kivi.ChartPicker($(elt));
261       });
262
263
264     var func = kivi.get_function_by_name('local_reinit_widgets');
265     if (func)
266       func();
267
268     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
269       $(elt).tooltipster({
270         contentAsHTML: false,
271         theme: 'tooltipster-light'
272       })
273     });
274
275     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
276       $(elt).tooltipster({
277         contentAsHTML: true,
278         theme: 'tooltipster-light'
279       })
280     });
281
282     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
283     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
284   };
285
286   ns.submit_ajax_form = function(url, form_selector, additional_data) {
287     $(form_selector).ajaxSubmit({
288       url:     url,
289       data:    additional_data,
290       success: ns.eval_json_result
291     });
292
293     return true;
294   };
295
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
299   // submitting.
300   ns.submit_form_with_action = function(form_selector, action_to_call) {
301     $('[name=action]').remove();
302
303     var $form   = $(form_selector);
304     var $hidden = $('<input type=hidden>');
305
306     $hidden.attr('name',  'action');
307     $hidden.attr('value', action_to_call);
308     $form.append($hidden);
309
310     $form.submit();
311   };
312
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() {
318     history.back();
319   };
320
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("(.+)\\.([^\\.]+)$");
327     if (!parts)
328       return window[name];
329     return namespace(parts[1])[ parts[2] ];
330   };
331
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.
338   //
339   // Parameters:
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) {
345     var dialog;
346
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:
352           width:  800
353         , height: 500
354         , modal:  true
355       },
356         // User supplied options:
357       params.dialog || { },
358       { // Options that must not be changed:
359         close: function(event, ui) {
360           dialog.dialog('close');
361
362           if (custom_close)
363             custom_close();
364
365           if (params.url || params.html)
366             dialog.remove();
367         }
368       });
369
370     if (!params.url && !params.html) {
371       // Use existing DOM element and show it. No AJAX call.
372       dialog =
373         $('#' + id)
374         .bind('dialogopen', function() {
375           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
376         })
377         .dialog(dialog_params);
378       return true;
379     }
380
381     $('#' + id).remove();
382
383     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
384     dialog.dialog(dialog_params);
385
386     if (params.html) {
387       dialog.html(params.html);
388     } else {
389       // no html? get it via ajax
390       $.ajax({
391         url:     params.url,
392         data:    params.data,
393         type:    params.type,
394         success: function(new_html) {
395           dialog.html(new_html);
396           dialog.removeClass('loading');
397           if (params.load)
398             params.load();
399         }
400       });
401     }
402
403     return true;
404   };
405
406   // Run code only once for each matched element
407   //
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.
413   //
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
416   // sole argument.
417   //
418   // Returns nothing.
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);
422     if (!fn) {
423       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
424       return;
425     }
426
427     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
428       var $elt = $(elt);
429       $elt.data(attr_name, true);
430       fn($elt);
431     });
432   };
433
434   // Run a function by its name passing it some arguments
435   //
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.
440   //
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);
445     if (fn)
446       return fn.apply({}, args || []);
447
448     console.error('kivi.run("' + function_name + '"): No function by that name found');
449     return undefined;
450   };
451
452   ns.detect_duplicate_ids_in_dom = function() {
453     var ids   = {},
454         found = false;
455
456     $('[id]').each(function() {
457       if (this.id && ids[this.id]) {
458         found = true;
459         console.warn('Duplicate ID #' + this.id);
460       }
461       ids[this.id] = 1;
462     });
463
464     if (!found)
465       console.log('No duplicate IDs found :)');
466   };
467
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.
472   //
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)
476       return true;
477
478     alert(kivi.t8('No entries have been selected.'));
479
480     return false;
481   };
482
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.
489   //
490   // Supported validation tests are:
491   // - "required": the field must be set (its .val() must not be empty)
492   //
493   // The validation will abort and return "false" as soon as
494   // validation routine fails.
495   //
496   // The function returns "true" if all validations succeed for all
497   // elements.
498   ns.validate_form = function(selector) {
499     var validate_field = function(elt) {
500       var $elt  = $(elt);
501       var tests = $elt.data('validate').split(/ +/);
502       var info  = {
503         title: $elt.data('title'),
504         value: $elt.val(),
505       };
506
507       for (var test_idx in tests) {
508         var test = tests[test_idx];
509
510         if (test === "required") {
511           if ($elt.val() === '') {
512             alert(kivi.t8("The field '#{title}' must be set.", info));
513             return false;
514           }
515
516         } else {
517           var error = "kivi.validate_form: unknown test '" + test + "' for element ID '" + $elt.prop('id') + "'";
518           console.error(error);
519           alert(error);
520
521           return false;
522         }
523       }
524
525       return true;
526     };
527
528     selector = selector || '#form';
529     var ok   = true;
530     var to_check = $(selector + ' [data-validate]').toArray();
531
532     for (var to_check_idx in to_check)
533       if (!validate_field(to_check[to_check_idx]))
534         return false;
535
536     return true;
537   };
538 });
539
540 kivi = namespace('kivi');