kivi.js: Und den wirren "00" Sonderfall auch wiederhergestellt
[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     if (date === undefined)
35       return undefined;
36
37     if (date === '')
38       return null;
39
40     if (date === '0' || date === '00')
41       return new Date();
42
43     var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
44     var today = new Date();
45
46     // without separator?
47     // assume fixed pattern, and extract parts again
48     if (parts.length == 1) {
49       date  = parts[0];
50       parts = date.match(/../g);
51       if (date.length == 8) {
52         parts[ns._date_format.y] += parts.splice(ns._date_format.y + 1, 1)
53       }
54       else
55       if (date.length == 6 || date.length == 4) {
56       }
57       else
58       if (date.length == 1 || date.length == 2) {
59         parts = []
60         parts[ ns._date_format.y ] = today.getFullYear();
61         parts[ ns._date_format.m ] = today.getMonth() + 1;
62         parts[ ns._date_format.d ] = date;
63       }
64       else {
65         return undefined;
66       }
67     }
68
69     if (parts.length == 3) {
70       var year = +parts[ ns._date_format.y ] || 0 * 1 || (new Date()).getFullYear();
71       if (year > 9999)
72         return undefined;
73       if (year < 100) {
74         year += year > 70 ? 1900 : 2000;
75       }
76       date = new Date(
77         year,
78         (parts[ ns._date_format.m ] || (today.getMonth() + 1)) * 1 - 1, // Months are 0-based.
79         (parts[ ns._date_format.d ] || today.getDate()) * 1
80       );
81     } else if (parts.length == 2) {
82       date = new Date(
83         (new Date()).getFullYear(),
84         (parts[ (ns._date_format.m > ns._date_format.d) * 1 ] || (today.getMonth() + 1)) * 1 - 1, // Months are 0-based.
85         (parts[ (ns._date_format.d > ns._date_format.m) * 1 ] || today.getDate()) * 1
86       );
87     } else
88       return undefined;
89
90     return isNaN(date.getTime()) ? undefined : date;
91   };
92
93   ns.format_date = function(date) {
94     if (isNaN(date.getTime()))
95       return undefined;
96
97     var parts = [ "", "", "" ]
98     parts[ ns._date_format.y ] = date.getFullYear();
99     parts[ ns._date_format.m ] = (date.getMonth() <  9 ? "0" : "") + (date.getMonth() + 1); // Months are 0-based, but days are 1-based.
100     parts[ ns._date_format.d ] = (date.getDate()  < 10 ? "0" : "") + date.getDate();
101     return parts.join(ns._date_format.sep);
102   };
103
104   ns.parse_amount = function(amount) {
105     if (amount === undefined)
106       return undefined;
107
108     if (amount === '')
109       return null;
110
111     if (ns._number_format.decimalSep == ',')
112       amount = amount.replace(/\./g, "").replace(/,/g, ".");
113
114     amount = amount.replace(/[\',]/g, "");
115
116     // Make sure no code wich is not a math expression ends up in eval().
117     if (!amount.match(/^[0-9 ()\-+*/.]*$/))
118       return undefined;
119
120     amount = amount.replace(/^0+(\d+)/, '$1');
121
122     /* jshint -W061 */
123     try {
124       return eval(amount);
125     } catch (err) {
126       return undefined;
127     }
128   };
129
130   ns.round_amount = function(amount, places) {
131     var neg  = amount >= 0 ? 1 : -1;
132     var mult = Math.pow(10, places + 1);
133     var temp = Math.abs(amount) * mult;
134     var diff = Math.abs(1 - temp + Math.floor(temp));
135     temp     = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
136     var dec  = temp % 10;
137     temp    += dec >= 5 ? 10 - dec: dec * -1;
138
139     return neg * temp / mult;
140   };
141
142   ns.format_amount = function(amount, places) {
143     amount = amount || 0;
144
145     if ((places !== undefined) && (places >= 0))
146       amount = ns.round_amount(amount, Math.abs(places));
147
148     var parts = ("" + Math.abs(amount)).split(/\./);
149     var intg  = parts[0];
150     var dec   = parts.length > 1 ? parts[1] : "";
151     var sign  = amount  < 0      ? "-"      : "";
152
153     if (places !== undefined) {
154       while (dec.length < Math.abs(places))
155         dec += "0";
156
157       if ((places > 0) && (dec.length > Math.abs(places)))
158         dec = d.substr(0, places);
159     }
160
161     if ((ns._number_format.thousandSep !== "") && (intg.length > 3)) {
162       var len   = ((intg.length + 2) % 3) + 1,
163           start = len,
164           res   = intg.substr(0, len);
165       while (start < intg.length) {
166         res   += ns._number_format.thousandSep + intg.substr(start, 3);
167         start += 3;
168       }
169
170       intg = res;
171     }
172
173     var sep = (places !== 0) && (dec !== "") ? ns._number_format.decimalSep : "";
174
175     return sign + intg + sep + dec;
176   };
177
178   ns.t8 = function(text, params) {
179     text = ns._locale[text] || text;
180     var key, value
181
182     if( Object.prototype.toString.call( params ) === '[object Array]' ) {
183       var len = params.length;
184
185       for(var i=0; i<len; ++i) {
186         key = i + 1;
187         value = params[i];
188         text = text.split("#"+ key).join(value);
189       }
190     }
191     else if( typeof params == 'object' ) {
192       for(key in params) {
193         value = params[key];
194         text = text.split("#{"+ key +"}").join(value);
195       }
196     }
197
198     return text;
199   };
200
201   ns.setupLocale = function(locale) {
202     ns._locale = locale;
203   };
204
205   ns.set_focus = function(element) {
206     var $e = $(element).eq(0);
207     if ($e.data('ckeditorInstance'))
208       ns.focus_ckeditor_when_ready($e);
209     else
210       $e.focus();
211   };
212
213   ns.focus_ckeditor_when_ready = function(element) {
214     $(element).data('ckeditorInstance').on('instanceReady', function() { ns.focus_ckeditor(element); });
215   };
216
217   ns.focus_ckeditor = function(element) {
218     $(element).data('ckeditorInstance').focus();
219   };
220
221   ns.selectall_ckeditor = function(element) {
222     var editor   = $(element).ckeditorGet();
223     var editable = editor.editable();
224     if (editable.is('textarea')) {
225       var textarea = editable.$;
226
227       if (CKEDITOR.env.ie)
228         textarea.createTextRange().execCommand('SelectAll');
229       else {
230         textarea.selectionStart = 0;
231         textarea.selectionEnd   = textarea.value.length;
232       }
233     } else {
234       if (editable.is('body'))
235         editor.document.$.execCommand('SelectAll', false, null);
236
237       else {
238         var range = editor.createRange();
239         range.selectNodeContents(editable);
240         range.select();
241       }
242
243       editor.forceNextSelectionCheck();
244       editor.selectionChange();
245     }
246   }
247
248   ns.init_tabwidget = function(element) {
249     var $element   = $(element);
250     var tabsParams = {};
251     var elementId  = $element.attr('id');
252
253     if (elementId) {
254       var cookieName      = 'jquery_ui_tab_'+ elementId;
255       tabsParams.active   = $.cookie(cookieName);
256       tabsParams.activate = function(event, ui) {
257         var i = ui.newTab.parent().children().index(ui.newTab);
258         $.cookie(cookieName, i);
259       };
260     }
261
262     $element.tabs(tabsParams);
263   };
264
265   ns.init_text_editor = function(element) {
266     var layouts = {
267       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
268       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
269     };
270
271     var $e      = $(element);
272     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
273     var config  = {
274       entities:      false,
275       language:      'de',
276       removePlugins: 'resize',
277       extraPlugins:  'inline_resize',
278       toolbar:       buttons,
279       disableAutoInline: true,
280       title:         false
281     };
282
283     config.height = $e.height();
284     config.width  = $e.width();
285
286     var editor = CKEDITOR.inline($e.get(0), config);
287     $e.data('ckeditorInstance', editor);
288
289     if ($e.hasClass('texteditor-autofocus'))
290       editor.on('instanceReady', function() { ns.focus_ckeditor($e); });
291   };
292
293   ns.reinit_widgets = function() {
294     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
295       $(elt).datepicker();
296     });
297
298     if (ns.Part) ns.Part.reinit_widgets();
299     if (ns.CustomerVendor) ns.CustomerVendor.reinit_widgets();
300     if (ns.Validator) ns.Validator.reinit_widgets();
301
302     if (ns.ProjectPicker)
303       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
304         kivi.ProjectPicker($(elt));
305       });
306
307     if (ns.ChartPicker)
308       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
309         kivi.ChartPicker($(elt));
310       });
311
312
313     var func = kivi.get_function_by_name('local_reinit_widgets');
314     if (func)
315       func();
316
317     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
318       $(elt).tooltipster({
319         contentAsHTML: false,
320         theme: 'tooltipster-light'
321       })
322     });
323
324     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
325       $(elt).tooltipster({
326         contentAsHTML: true,
327         theme: 'tooltipster-light'
328       })
329     });
330
331     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
332     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
333   };
334
335   ns.submit_ajax_form = function(url, form_selector, additional_data) {
336     $(form_selector).ajaxSubmit({
337       url:     url,
338       data:    additional_data,
339       success: ns.eval_json_result
340     });
341
342     return true;
343   };
344
345   // This function submits an existing form given by "form_selector"
346   // and sets the "action" input to "action_to_call" before submitting
347   // it. Any existing input named "action" will be removed prior to
348   // submitting.
349   ns.submit_form_with_action = function(form_selector, action_to_call) {
350     $('[name=action]').remove();
351
352     var $form   = $(form_selector);
353     var $hidden = $('<input type=hidden>');
354
355     $hidden.attr('name',  'action');
356     $hidden.attr('value', action_to_call);
357     $form.append($hidden);
358
359     $form.submit();
360   };
361
362   // This function exists solely so that it can be found with
363   // kivi.get_functions_by_name() and called later on. Using something
364   // like "var func = history["back"]" works, but calling it later
365   // with "func.apply()" doesn't.
366   ns.history_back = function() {
367     history.back();
368   };
369
370   // Return a function object by its name (a string). Works both with
371   // global functions (e.g. "focus_by_name") and those in namespaces (e.g.
372   // "kivi.t8").
373   // Returns null if the object is not found.
374   ns.get_function_by_name = function(name) {
375     var parts = name.match("(.+)\\.([^\\.]+)$");
376     if (!parts)
377       return window[name];
378     return namespace(parts[1])[ parts[2] ];
379   };
380
381   // Open a modal jQuery UI popup dialog. The content can be either
382   // loaded via AJAX (if the parameter 'url' is given) or simply
383   // displayed if it exists in the DOM already (referenced via
384   // 'id') or given via param.html. If an existing DOM div should be used then
385   // the element won't be removed upon closing the dialog which allows
386   // re-opening it later on.
387   //
388   // Parameters:
389   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
390   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
391   // - dialog: an optional object of options passed to the $.dialog() call
392   // - load: an optional function that is called after the content has been loaded successfully (only if an AJAX call is made)
393   ns.popup_dialog = function(params) {
394     var dialog;
395
396     params            = params        || { };
397     var id            = params.id     || 'jqueryui_popup_dialog';
398     var custom_close  = params.dialog ? params.dialog.close : undefined;
399     var dialog_params = $.extend(
400       { // kivitendo default parameters:
401           width:  800
402         , height: 500
403         , modal:  true
404       },
405         // User supplied options:
406       params.dialog || { },
407       { // Options that must not be changed:
408         close: function(event, ui) {
409           dialog.dialog('close');
410
411           if (custom_close)
412             custom_close();
413
414           if (params.url || params.html)
415             dialog.remove();
416         }
417       });
418
419     if (!params.url && !params.html) {
420       // Use existing DOM element and show it. No AJAX call.
421       dialog =
422         $('#' + id)
423         .bind('dialogopen', function() {
424           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
425         })
426         .dialog(dialog_params);
427       return true;
428     }
429
430     $('#' + id).remove();
431
432     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
433     dialog.dialog(dialog_params);
434
435     if (params.html) {
436       dialog.html(params.html);
437     } else {
438       // no html? get it via ajax
439       $.ajax({
440         url:     params.url,
441         data:    params.data,
442         type:    params.type,
443         success: function(new_html) {
444           dialog.html(new_html);
445           dialog.removeClass('loading');
446           if (params.load)
447             params.load();
448         }
449       });
450     }
451
452     return true;
453   };
454
455   // Run code only once for each matched element
456   //
457   // This allows running the function 'code' exactly once for each
458   // element that matches 'selector'. This is achieved by storing the
459   // state with jQuery's 'data' function. The 'identification' is
460   // required for differentiating unambiguously so that different code
461   // functions can still be run on the same elements.
462   //
463   // 'code' can be either a function or the name of one. It must
464   // resolve to a function that receives the jQueryfied element as its
465   // sole argument.
466   //
467   // Returns nothing.
468   ns.run_once_for = function(selector, identification, code) {
469     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
470     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
471     if (!fn) {
472       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
473       return;
474     }
475
476     $(selector).filter(function() { return $(this).data(attr_name) !== true; }).each(function(idx, elt) {
477       var $elt = $(elt);
478       $elt.data(attr_name, true);
479       fn($elt);
480     });
481   };
482
483   // Run a function by its name passing it some arguments
484   //
485   // This is a function useful mainly for the ClientJS functionality.
486   // It finds a function by its name and then executes it on an empty
487   // object passing the elements in 'args' (an array) as the function
488   // parameters retuning its result.
489   //
490   // Logs an error to the console and returns 'undefined' if the
491   // function cannot be found.
492   ns.run = function(function_name, args) {
493     var fn = ns.get_function_by_name(function_name);
494     if (fn)
495       return fn.apply({}, args || []);
496
497     console.error('kivi.run("' + function_name + '"): No function by that name found');
498     return undefined;
499   };
500
501   ns.detect_duplicate_ids_in_dom = function() {
502     var ids   = {},
503         found = false;
504
505     $('[id]').each(function() {
506       if (this.id && ids[this.id]) {
507         found = true;
508         console.warn('Duplicate ID #' + this.id);
509       }
510       ids[this.id] = 1;
511     });
512
513     if (!found)
514       console.log('No duplicate IDs found :)');
515   };
516
517   ns.validate_form = function(selector) {
518     if (!kivi.Validator) {
519       console.log('kivi.Validator is not loaded');
520     } else {
521       return kivi.Validator.validate_all(selector);
522     }
523   };
524
525   // Verifies that at least one checkbox matching the
526   // "checkbox_selector" is actually checked. If not, an error message
527   // is shown, and false is returned. Otherwise (at least one of them
528   // is checked) nothing is shown and true returned.
529   //
530   // Can be used in checks when clicking buttons.
531   ns.check_if_entries_selected = function(checkbox_selector) {
532     if ($(checkbox_selector + ':checked').length > 0)
533       return true;
534
535     alert(kivi.t8('No entries have been selected.'));
536
537     return false;
538   };
539
540   ns.switch_areainput_to_textarea = function(id) {
541     var $input = $('#' + id);
542     if (!$input.length)
543       return;
544
545     var $area = $('<textarea></textarea>');
546
547     $area.prop('rows', 3);
548     $area.prop('cols', $input.prop('size') || 40);
549     $area.prop('name', $input.prop('name'));
550     $area.prop('id',   $input.prop('id'));
551     $area.val($input.val());
552
553     $input.parent().replaceWith($area);
554     $area.focus();
555   };
556 });
557
558 kivi = namespace('kivi');