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