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