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