CustomerVendor Picker: auf prototype Picker umgestellt analog zu Part
[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).data('ckeditorInstance').on('instanceReady', function() { ns.focus_ckeditor(element); });
161   };
162
163   ns.focus_ckeditor = function(element) {
164     $(element).data('ckeditorInstance').focus();
165   };
166
167   ns.selectall_ckeditor = function(element) {
168     var editor   = $(element).ckeditorGet();
169     var editable = editor.editable();
170     if (editable.is('textarea')) {
171       var textarea = editable.$;
172
173       if (CKEDITOR.env.ie)
174         textarea.createTextRange().execCommand('SelectAll');
175       else {
176         textarea.selectionStart = 0;
177         textarea.selectionEnd   = textarea.value.length;
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   }
193
194   ns.init_tabwidget = function(element) {
195     var $element   = $(element);
196     var tabsParams = {};
197     var elementId  = $element.attr('id');
198
199     if (elementId) {
200       var cookieName      = 'jquery_ui_tab_'+ elementId;
201       tabsParams.active   = $.cookie(cookieName);
202       tabsParams.activate = function(event, ui) {
203         var i = ui.newTab.parent().children().index(ui.newTab);
204         $.cookie(cookieName, i);
205       };
206     }
207
208     $element.tabs(tabsParams);
209   };
210
211   ns.init_text_editor = function(element) {
212     var layouts = {
213       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
214       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
215     };
216
217     var $e      = $(element);
218     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
219     var config  = {
220       entities:      false,
221       language:      'de',
222       removePlugins: 'resize',
223       extraPlugins:  'inline_resize',
224       toolbar:       buttons,
225       disableAutoInline: true,
226       title:         false
227     };
228
229     config.height = $e.height();
230     config.width  = $e.width();
231
232     var editor = CKEDITOR.inline($e.get(0), config);
233     $e.data('ckeditorInstance', editor);
234
235     if ($e.hasClass('texteditor-autofocus'))
236       editor.on('instanceReady', function() { ns.focus_ckeditor($e); });
237   };
238
239   ns.reinit_widgets = function() {
240     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
241       $(elt).datepicker();
242     });
243
244     if (ns.Part) ns.Part.reinit_widgets();
245     if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
246
247     if (ns.ProjectPicker)
248       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
249         kivi.ProjectPicker($(elt));
250       });
251
252     if (ns.ChartPicker)
253       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
254         kivi.ChartPicker($(elt));
255       });
256
257
258     var func = kivi.get_function_by_name('local_reinit_widgets');
259     if (func)
260       func();
261
262     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
263       $(elt).tooltipster({
264         contentAsHTML: false,
265         theme: 'tooltipster-light'
266       })
267     });
268
269     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
270       $(elt).tooltipster({
271         contentAsHTML: true,
272         theme: 'tooltipster-light'
273       })
274     });
275
276     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
277     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
278   };
279
280   ns.submit_ajax_form = function(url, form_selector, additional_data) {
281     $(form_selector).ajaxSubmit({
282       url:     url,
283       data:    additional_data,
284       success: ns.eval_json_result
285     });
286
287     return true;
288   };
289
290   // This function submits an existing form given by "form_selector"
291   // and sets the "action" input to "action_to_call" before submitting
292   // it. Any existing input named "action" will be removed prior to
293   // submitting.
294   ns.submit_form_with_action = function(form_selector, action_to_call) {
295     $('[name=action]').remove();
296
297     var $form   = $(form_selector);
298     var $hidden = $('<input type=hidden>');
299
300     $hidden.attr('name',  'action');
301     $hidden.attr('value', action_to_call);
302     $form.append($hidden);
303
304     $form.submit();
305   };
306
307   // This function exists solely so that it can be found with
308   // kivi.get_functions_by_name() and called later on. Using something
309   // like "var func = history["back"]" works, but calling it later
310   // with "func.apply()" doesn't.
311   ns.history_back = function() {
312     history.back();
313   };
314
315   // Return a function object by its name (a string). Works both with
316   // global functions (e.g. "check_right_date_format") and those in
317   // namespaces (e.g. "kivi.t8").
318   // Returns null if the object is not found.
319   ns.get_function_by_name = function(name) {
320     var parts = name.match("(.+)\\.([^\\.]+)$");
321     if (!parts)
322       return window[name];
323     return namespace(parts[1])[ parts[2] ];
324   };
325
326   // Open a modal jQuery UI popup dialog. The content can be either
327   // loaded via AJAX (if the parameter 'url' is given) or simply
328   // displayed if it exists in the DOM already (referenced via
329   // 'id') or given via param.html. If an existing DOM div should be used then
330   // the element won't be removed upon closing the dialog which allows
331   // re-opening it later on.
332   //
333   // Parameters:
334   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
335   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
336   // - dialog: an optional object of options passed to the $.dialog() call
337   // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
338   ns.popup_dialog = function(params) {
339     var dialog;
340
341     params            = params        || { };
342     var id            = params.id     || 'jqueryui_popup_dialog';
343     var custom_close  = params.dialog ? params.dialog.close : undefined;
344     var dialog_params = $.extend(
345       { // kivitendo default parameters:
346           width:  800
347         , height: 500
348         , modal:  true
349       },
350         // User supplied options:
351       params.dialog || { },
352       { // Options that must not be changed:
353         close: function(event, ui) {
354           dialog.dialog('close');
355
356           if (custom_close)
357             custom_close();
358
359           if (params.url || params.html)
360             dialog.remove();
361         }
362       });
363
364     if (!params.url && !params.html) {
365       // Use existing DOM element and show it. No AJAX call.
366       dialog =
367         $('#' + id)
368         .bind('dialogopen', function() {
369           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
370         })
371         .dialog(dialog_params);
372       return true;
373     }
374
375     $('#' + id).remove();
376
377     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
378     dialog.dialog(dialog_params);
379
380     if (params.html) {
381       dialog.html(params.html);
382     } else {
383       // no html? get it via ajax
384       $.ajax({
385         url:     params.url,
386         data:    params.data,
387         type:    params.type,
388         success: function(new_html) {
389           dialog.html(new_html);
390           dialog.removeClass('loading');
391           if (params.load)
392             params.load();
393         }
394       });
395     }
396
397     return true;
398   };
399
400   // Run code only once for each matched element
401   //
402   // This allows running the function 'code' exactly once for each
403   // element that matches 'selector'. This is achieved by storing the
404   // state with jQuery's 'data' function. The 'identification' is
405   // required for differentiating unambiguously so that different code
406   // functions can still be run on the same elements.
407   //
408   // 'code' can be either a function or the name of one. It must
409   // resolve to a function that receives the jQueryfied element as its
410   // sole argument.
411   //
412   // Returns nothing.
413   ns.run_once_for = function(selector, identification, code) {
414     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
415     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
416     if (!fn) {
417       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
418       return;
419     }
420
421     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
422       var $elt = $(elt);
423       $elt.data(attr_name, true);
424       fn($elt);
425     });
426   };
427
428   // Run a function by its name passing it some arguments
429   //
430   // This is a function useful mainly for the ClientJS functionality.
431   // It finds a function by its name and then executes it on an empty
432   // object passing the elements in 'args' (an array) as the function
433   // parameters retuning its result.
434   //
435   // Logs an error to the console and returns 'undefined' if the
436   // function cannot be found.
437   ns.run = function(function_name, args) {
438     var fn = ns.get_function_by_name(function_name);
439     if (fn)
440       return fn.apply({}, args || []);
441
442     console.error('kivi.run("' + function_name + '"): No function by that name found');
443     return undefined;
444   };
445
446   ns.detect_duplicate_ids_in_dom = function() {
447     var ids   = {},
448         found = false;
449
450     $('[id]').each(function() {
451       if (this.id && ids[this.id]) {
452         found = true;
453         console.warn('Duplicate ID #' + this.id);
454       }
455       ids[this.id] = 1;
456     });
457
458     if (!found)
459       console.log('No duplicate IDs found :)');
460   };
461
462   // Verifies that at least one checkbox matching the
463   // "checkbox_selector" is actually checked. If not, an error message
464   // is shown, and false is returned. Otherwise (at least one of them
465   // is checked) nothing is shown and true returned.
466   //
467   // Can be used in checks when clicking buttons.
468   ns.check_if_entries_selected = function(checkbox_selector) {
469     if ($(checkbox_selector + ':checked').length > 0)
470       return true;
471
472     alert(kivi.t8('No entries have been selected.'));
473
474     return false;
475   };
476
477   // Performs various validation steps on the descendants of
478   // 'selector'. Elements that should be validated must have an
479   // attribute named "data-validate" which is set to a space-separated
480   // list of tests to perform. Additionally, the attribute
481   // "data-title" must be set to a human-readable name of the field
482   // that can be shown as part of an error message.
483   //
484   // Supported validation tests are:
485   // - "required": the field must be set (its .val() must not be empty)
486   //
487   // The validation will abort and return "false" as soon as
488   // validation routine fails.
489   //
490   // The function returns "true" if all validations succeed for all
491   // elements.
492   ns.validate_form = function(selector) {
493     var validate_field = function(elt) {
494       var $elt  = $(elt);
495       var tests = $elt.data('validate').split(/ +/);
496       var info  = {
497         title: $elt.data('title'),
498         value: $elt.val(),
499       };
500
501       for (var test_idx in tests) {
502         var test = tests[test_idx];
503
504         if (test === "required") {
505           if ($elt.val() === '') {
506             alert(kivi.t8("The field '#{title}' must be set.", info));
507             return false;
508           }
509
510         } else {
511           var error = "kivi.validate_form: unknown test '" + test + "' for element ID '" + $elt.prop('id') + "'";
512           console.error(error);
513           alert(error);
514
515           return false;
516         }
517       }
518
519       return true;
520     };
521
522     selector = selector || '#form';
523     var ok   = true;
524     var to_check = $(selector + ' [data-validate]').toArray();
525
526     for (var to_check_idx in to_check)
527       if (!validate_field(to_check[to_check_idx]))
528         return false;
529
530     return true;
531   };
532
533   ns.switch_areainput_to_textarea = function(id) {
534     var $input = $('#' + id);
535     if (!$input.length)
536       return;
537
538     var $area = $('<textarea></textarea>');
539
540     $area.prop('rows', 3);
541     $area.prop('cols', $input.prop('size') || 40);
542     $area.prop('name', $input.prop('name'));
543     $area.prop('id',   $input.prop('id'));
544     $area.val($input.val());
545
546     $input.parent().replaceWith($area);
547     $area.focus();
548   };
549 });
550
551 kivi = namespace('kivi');