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