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