mebil
[kivitendo-erp.git] / js / kivi.js
1 namespace("kivi", function(ns) {
2   ns._locale = {};
3   ns._date_format   = {
4     sep: '.',
5     y:   2,
6     m:   1,
7     d:   0
8   };
9   ns._number_format = {
10     decimalSep:  ',',
11     thousandSep: '.'
12   };
13
14   ns.setup_formats = function(params) {
15     var res = (params.dates || "").match(/^([ymd]+)([^a-z])([ymd]+)[^a-z]([ymd]+)$/);
16     if (res) {
17       ns._date_format                      = { sep: res[2] };
18       ns._date_format[res[1].substr(0, 1)] = 0;
19       ns._date_format[res[3].substr(0, 1)] = 1;
20       ns._date_format[res[4].substr(0, 1)] = 2;
21     }
22
23     res = (params.numbers || "").match(/^\d*([^\d]?)\d+([^\d])\d+$/);
24     if (res)
25       ns._number_format = {
26         decimalSep:  res[2],
27         thousandSep: res[1]
28       };
29   };
30
31   ns.parse_date = function(date) {
32     var parts = date.replace(/\s+/g, "").split(ns._date_format.sep);
33     date     = new Date(
34       ((parts[ ns._date_format.y ] || 0) * 1) || (new Date()).getFullYear(),
35        (parts[ ns._date_format.m ] || 0) * 1 - 1, // Months are 0-based.
36        (parts[ ns._date_format.d ] || 0) * 1
37     );
38
39     return isNaN(date.getTime()) ? undefined : date;
40   };
41
42   ns.format_date = function(date) {
43     if (isNaN(date.getTime()))
44       return undefined;
45
46     var parts = [ "", "", "" ]
47     parts[ ns._date_format.y ] = date.getFullYear();
48     parts[ ns._date_format.m ] = (date.getMonth() <  9 ? "0" : "") + (date.getMonth() + 1); // Months are 0-based, but days are 1-based.
49     parts[ ns._date_format.d ] = (date.getDate()  < 10 ? "0" : "") + date.getDate();
50     return parts.join(ns._date_format.sep);
51   };
52
53   ns.parse_amount = function(amount) {
54     if ((amount == undefined) || (amount == ''))
55       return 0;
56
57     if (ns._number_format.decimalSep == ',')
58       amount = amount.replace(/\./g, "").replace(/,/g, ".");
59
60     amount = amount.replace(/[\',]/g, "")
61
62     return eval(amount);
63   };
64
65   ns.round_amount = function(amount, places) {
66     var neg  = amount >= 0 ? 1 : -1;
67     var mult = Math.pow(10, places + 1);
68     var temp = Math.abs(amount) * mult;
69     var diff = Math.abs(1 - temp + Math.floor(temp));
70     temp     = Math.floor(temp) + (diff <= 0.00001 ? 1 : 0);
71     var dec  = temp % 10;
72     temp    += dec >= 5 ? 10 - dec: dec * -1;
73
74     return neg * temp / mult;
75   };
76
77   ns.format_amount = function(amount, places) {
78     amount = amount || 0;
79
80     if ((places != undefined) && (places >= 0))
81       amount = ns.round_amount(amount, Math.abs(places));
82
83     var parts = ("" + Math.abs(amount)).split(/\./);
84     var intg  = parts[0];
85     var dec   = parts.length > 1 ? parts[1] : "";
86     var sign  = amount  < 0      ? "-"      : "";
87
88     if (places != undefined) {
89       while (dec.length < Math.abs(places))
90         dec += "0";
91
92       if ((places > 0) && (dec.length > Math.abs(places)))
93         dec = d.substr(0, places);
94     }
95
96     if ((ns._number_format.thousandSep != "") && (intg.length > 3)) {
97       var len   = ((intg.length + 2) % 3) + 1,
98           start = len,
99           res   = intg.substr(0, len);
100       while (start < intg.length) {
101         res   += ns._number_format.thousandSep + intg.substr(start, 3);
102         start += 3;
103       }
104
105       intg = res;
106     }
107
108     var sep = (places != 0) && (dec != "") ? ns._number_format.decimalSep : "";
109
110     return sign + intg + sep + dec;
111   };
112
113   ns.t8 = function(text, params) {
114     text = ns._locale[text] || text;
115     var key, value
116
117     if( Object.prototype.toString.call( params ) === '[object Array]' ) {
118       var len = params.length;
119
120       for(var i=0; i<len; ++i) {
121         key = i + 1;
122         value = params[i];
123         text = text.split("#"+ key).join(value);
124       }
125     }
126     else if( typeof params == 'object' ) {
127       for(key in params) {
128         value = params[key];
129         text = text.split("#{"+ key +"}").join(value);
130       }
131     }
132
133     return text;
134   };
135
136   ns.setupLocale = function(locale) {
137     ns._locale = locale;
138   };
139
140   ns.set_focus = function(element) {
141     var $e = $(element).eq(0);
142     if ($e.data('ckeditorInstance'))
143       ns.focus_ckeditor_when_ready($e);
144     else
145       $e.focus();
146   };
147
148   ns.focus_ckeditor_when_ready = function(element) {
149     $(element).ckeditor(function() { ns.focus_ckeditor(element); });
150   };
151
152   ns.focus_ckeditor = function(element) {
153     var editor   = $(element).ckeditorGet();
154                 var editable = editor.editable();
155
156                 if (editable.is('textarea')) {
157                         var textarea = editable.$;
158
159                         if (CKEDITOR.env.ie)
160                                 textarea.createTextRange().execCommand('SelectAll');
161                         else {
162                                 textarea.selectionStart = 0;
163                                 textarea.selectionEnd   = textarea.value.length;
164                         }
165
166                         textarea.focus();
167
168                 } else {
169                         if (editable.is('body'))
170                                 editor.document.$.execCommand('SelectAll', false, null);
171
172                         else {
173                                 var range = editor.createRange();
174                                 range.selectNodeContents(editable);
175                                 range.select();
176                         }
177
178                         editor.forceNextSelectionCheck();
179                         editor.selectionChange();
180
181       editor.focus();
182                 }
183   };
184
185   ns.init_tabwidget = function(element) {
186     var $element   = $(element);
187     var tabsParams = {};
188     var elementId  = $element.attr('id');
189
190     if (elementId) {
191       var cookieName      = 'jquery_ui_tab_'+ elementId;
192       tabsParams.active   = $.cookie(cookieName);
193       tabsParams.activate = function(event, ui) {
194         var i = ui.newTab.parent().children().index(ui.newTab);
195         $.cookie(cookieName, i);
196       };
197     }
198
199     $element.tabs(tabsParams);
200   };
201
202   ns.init_text_editor = function(element) {
203     var layouts = {
204       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
205       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
206     };
207
208     var $e      = $(element);
209     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
210     var config  = {
211       entities:      false,
212       language:      'de',
213       removePlugins: 'resize',
214       toolbar:       buttons
215     }
216
217     var style = $e.prop('style');
218     $(['width', 'height']).each(function(idx, prop) {
219       var matches = (style[prop] || '').match(/(\d+)px/);
220       if (matches && (matches.length > 1))
221         config[prop] = matches[1];
222     });
223
224     $e.ckeditor(config);
225
226     if ($e.hasClass('texteditor-autofocus'))
227       $e.ckeditor(function() { ns.focus_ckeditor($e); });
228   };
229
230   ns.reinit_widgets = function() {
231     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
232       $(elt).datepicker();
233     });
234
235     if (ns.PartPicker)
236       ns.run_once_for('input.part_autocomplete', 'part_picker', function(elt) {
237         kivi.PartPicker($(elt));
238       });
239
240     if (ns.ProjectPicker)
241       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
242         kivi.ProjectPicker($(elt));
243       });
244
245     if (ns.CustomerVendorPicker)
246       ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
247         kivi.CustomerVendorPicker($(elt));
248       });
249
250     if (ns.ChartPicker)
251       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
252         kivi.ChartPicker($(elt));
253       });
254
255
256     var func = kivi.get_function_by_name('local_reinit_widgets');
257     if (func)
258       func();
259
260     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
261       $(elt).tooltipster({
262         contentAsHTML: false,
263         theme: 'tooltipster-light'
264       })
265     });
266
267     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
268       $(elt).tooltipster({
269         contentAsHTML: true,
270         theme: 'tooltipster-light'
271       })
272     });
273
274     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
275     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
276   };
277
278   ns.submit_ajax_form = function(url, form_selector, additional_data) {
279     $(form_selector).ajaxSubmit({
280       url:     url,
281       data:    additional_data,
282       success: ns.eval_json_result
283     });
284
285     return true;
286   };
287
288   // Return a function object by its name (a string). Works both with
289   // global functions (e.g. "check_right_date_format") and those in
290   // namespaces (e.g. "kivi.t8").
291   // Returns null if the object is not found.
292   ns.get_function_by_name = function(name) {
293     var parts = name.match("(.+)\\.([^\\.]+)$");
294     if (!parts)
295       return window[name];
296     return namespace(parts[1])[ parts[2] ];
297   };
298
299   // Open a modal jQuery UI popup dialog. The content can be either
300   // loaded via AJAX (if the parameter 'url' is given) or simply
301   // displayed if it exists in the DOM already (referenced via
302   // 'id') or given via param.html. If an existing DOM div should be used then
303   // the element won't be removed upon closing the dialog which allows
304   // re-opening it later on.
305   //
306   // Parameters:
307   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
308   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
309   // - dialog: an optional object of options passed to the $.dialog() call
310   ns.popup_dialog = function(params) {
311     var dialog;
312
313     params            = params        || { };
314     var id            = params.id     || 'jqueryui_popup_dialog';
315     var dialog_params = $.extend(
316       { // kivitendo default parameters:
317           width:  800
318         , height: 500
319         , modal:  true
320       },
321         // User supplied options:
322       params.dialog || { },
323       { // Options that must not be changed:
324         close: function(event, ui) { if (params.url || params.html) dialog.remove(); else dialog.dialog('close'); }
325       });
326
327     if (!params.url && !params.html) {
328       // Use existing DOM element and show it. No AJAX call.
329       dialog =
330         $('#' + id)
331         .bind('dialogopen', function() {
332           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
333         })
334         .dialog(dialog_params);
335       return true;
336     }
337
338     $('#' + id).remove();
339
340     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
341     dialog.dialog(dialog_params);
342
343     if (params.html) {
344       dialog.html(params.html);
345     } else {
346       // no html? get it via ajax
347       $.ajax({
348         url:     params.url,
349         data:    params.data,
350         type:    params.type,
351         success: function(new_html) {
352           dialog.html(new_html);
353           dialog.removeClass('loading');
354         }
355       });
356     }
357
358     return true;
359   };
360
361   // Run code only once for each matched element
362   //
363   // This allows running the function 'code' exactly once for each
364   // element that matches 'selector'. This is achieved by storing the
365   // state with jQuery's 'data' function. The 'identification' is
366   // required for differentiating unambiguously so that different code
367   // functions can still be run on the same elements.
368   //
369   // 'code' can be either a function or the name of one. It must
370   // resolve to a function that receives the jQueryfied element as its
371   // sole argument.
372   //
373   // Returns nothing.
374   ns.run_once_for = function(selector, identification, code) {
375     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
376     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
377     if (!fn) {
378       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
379       return;
380     }
381
382     $(selector).filter(function() { return $(this).data(attr_name) != true; }).each(function(idx, elt) {
383       var $elt = $(elt);
384       $elt.data(attr_name, true);
385       fn($elt);
386     });
387   };
388
389   // Run a function by its name passing it some arguments
390   //
391   // This is a function useful mainly for the ClientJS functionality.
392   // It finds a function by its name and then executes it on an empty
393   // object passing the elements in 'args' (an array) as the function
394   // parameters retuning its result.
395   //
396   // Logs an error to the console and returns 'undefined' if the
397   // function cannot be found.
398   ns.run = function(function_name, args) {
399     var fn = ns.get_function_by_name(function_name);
400     if (fn)
401       return fn.apply({}, args);
402
403     console.error('kivi.run("' + function_name + '"): No function by that name found');
404     return undefined;
405   };
406 });
407
408 kivi = namespace('kivi');