Auftrags-Controller: Einheiten per Select ändern können und sellprice anpassen.
[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     var text = ns._locale[text] || text;
115
116     if( Object.prototype.toString.call( params ) === '[object Array]' ) {
117       var len = params.length;
118
119       for(var i=0; i<len; ++i) {
120         var key = i + 1;
121         var value = params[i];
122         text = text.split("#"+ key).join(value);
123       }
124     }
125     else if( typeof params == 'object' ) {
126       for(var key in params) {
127         var value = params[key];
128         text = text.split("#{"+ key +"}").join(value);
129       }
130     }
131
132     return text;
133   };
134
135   ns.setupLocale = function(locale) {
136     ns._locale = locale;
137   };
138
139   ns.set_focus = function(element) {
140     var $e = $(element).eq(0);
141     if ($e.data('ckeditorInstance'))
142       ns.focus_ckeditor_when_ready($e);
143     else
144       $e.focus();
145   };
146
147   ns.focus_ckeditor_when_ready = function(element) {
148     $(element).ckeditor(function() { ns.focus_ckeditor(element); });
149   };
150
151   ns.focus_ckeditor = function(element) {
152     var editor   = $(element).ckeditorGet();
153                 var editable = editor.editable();
154
155                 if (editable.is('textarea')) {
156                         var textarea = editable.$;
157
158                         if (CKEDITOR.env.ie)
159                                 textarea.createTextRange().execCommand('SelectAll');
160                         else {
161                                 textarea.selectionStart = 0;
162                                 textarea.selectionEnd   = textarea.value.length;
163                         }
164
165                         textarea.focus();
166
167                 } else {
168                         if (editable.is('body'))
169                                 editor.document.$.execCommand('SelectAll', false, null);
170
171                         else {
172                                 var range = editor.createRange();
173                                 range.selectNodeContents(editable);
174                                 range.select();
175                         }
176
177                         editor.forceNextSelectionCheck();
178                         editor.selectionChange();
179
180       editor.focus();
181                 }
182   };
183
184   ns.init_tabwidget = function(element) {
185     var $element   = $(element);
186     var tabsParams = {};
187     var elementId  = $element.attr('id');
188
189     if (elementId) {
190       var cookieName      = 'jquery_ui_tab_'+ elementId;
191       tabsParams.active   = $.cookie(cookieName);
192       tabsParams.activate = function(event, ui) {
193         var i = ui.newTab.parent().children().index(ui.newTab);
194         $.cookie(cookieName, i);
195       };
196     }
197
198     $element.tabs(tabsParams);
199   };
200
201   ns.init_text_editor = function(element) {
202     var layouts = {
203       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
204       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
205     };
206
207     var $e      = $(element);
208     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
209     var config  = {
210       entities:      false,
211       language:      'de',
212       removePlugins: 'resize',
213       toolbar:       buttons
214     }
215
216     var style = $e.prop('style');
217     $(['width', 'height']).each(function(idx, prop) {
218       var matches = (style[prop] || '').match(/(\d+)px/);
219       if (matches && (matches.length > 1))
220         config[prop] = matches[1];
221     });
222
223     $e.ckeditor(config);
224
225     if ($e.hasClass('texteditor-autofocus'))
226       $e.ckeditor(function() { ns.focus_ckeditor($e); });
227   };
228
229   ns.reinit_widgets = function() {
230     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
231       $(elt).datepicker();
232     });
233
234     if (ns.PartPicker)
235       ns.run_once_for('input.part_autocomplete', 'part_picker', function(elt) {
236         kivi.PartPicker($(elt));
237       });
238
239     if (ns.ProjectPicker)
240       ns.run_once_for('input.project_autocomplete', 'project_picker', function(elt) {
241         kivi.ProjectPicker($(elt));
242       });
243
244     if (ns.CustomerVendorPicker)
245       ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
246         kivi.CustomerVendorPicker($(elt));
247       });
248
249     if (ns.ChartPicker)
250       ns.run_once_for('input.chart_autocomplete', 'chart_picker', function(elt) {
251         kivi.ChartPicker($(elt));
252       });
253
254
255     var func = kivi.get_function_by_name('local_reinit_widgets');
256     if (func)
257       func();
258
259     ns.run_once_for('.tooltipster', 'tooltipster', function(elt) {
260       $(elt).tooltipster({
261         contentAsHTML: false,
262         theme: 'tooltipster-light'
263       })
264     });
265
266     ns.run_once_for('.tooltipster-html', 'tooltipster-html', function(elt) {
267       $(elt).tooltipster({
268         contentAsHTML: true,
269         theme: 'tooltipster-light'
270       })
271     });
272
273     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
274     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
275   };
276
277   ns.submit_ajax_form = function(url, form_selector, additional_data) {
278     $(form_selector).ajaxSubmit({
279       url:     url,
280       data:    additional_data,
281       success: ns.eval_json_result
282     });
283
284     return true;
285   };
286
287   // Return a function object by its name (a string). Works both with
288   // global functions (e.g. "check_right_date_format") and those in
289   // namespaces (e.g. "kivi.t8").
290   // Returns null if the object is not found.
291   ns.get_function_by_name = function(name) {
292     var parts = name.match("(.+)\\.([^\\.]+)$");
293     if (!parts)
294       return window[name];
295     return namespace(parts[1])[ parts[2] ];
296   };
297
298   // Open a modal jQuery UI popup dialog. The content can be either
299   // loaded via AJAX (if the parameter 'url' is given) or simply
300   // displayed if it exists in the DOM already (referenced via
301   // 'id') or given via param.html. If an existing DOM div should be used then
302   // the element won't be removed upon closing the dialog which allows
303   // re-opening it later on.
304   //
305   // Parameters:
306   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
307   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
308   // - dialog: an optional object of options passed to the $.dialog() call
309   ns.popup_dialog = function(params) {
310     var dialog;
311
312     params            = params        || { };
313     var id            = params.id     || 'jqueryui_popup_dialog';
314     var dialog_params = $.extend(
315       { // kivitendo default parameters:
316           width:  800
317         , height: 500
318         , modal:  true
319       },
320         // User supplied options:
321       params.dialog || { },
322       { // Options that must not be changed:
323         close: function(event, ui) { if (params.url || params.html) dialog.remove(); else dialog.dialog('close'); }
324       });
325
326     if (!params.url && !params.html) {
327       // Use existing DOM element and show it. No AJAX call.
328       dialog =
329         $('#' + id)
330         .bind('dialogopen', function() {
331           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
332         })
333         .dialog(dialog_params);
334       return true;
335     }
336
337     $('#' + id).remove();
338
339     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
340     dialog.dialog(dialog_params);
341
342     if (params.html) {
343       dialog.html(params.html);
344     } else {
345       // no html? get it via ajax
346       $.ajax({
347         url:     params.url,
348         data:    params.data,
349         type:    params.type,
350         success: function(new_html) {
351           dialog.html(new_html);
352           dialog.removeClass('loading');
353         }
354       });
355     }
356
357     return true;
358   };
359
360   // Run code only once for each matched element
361   //
362   // This allows running the function 'code' exactly once for each
363   // element that matches 'selector'. This is achieved by storing the
364   // state with jQuery's 'data' function. The 'identification' is
365   // required for differentiating unambiguously so that different code
366   // functions can still be run on the same elements.
367   //
368   // 'code' can be either a function or the name of one. It must
369   // resolve to a function that receives the jQueryfied element as its
370   // sole argument.
371   //
372   // Returns nothing.
373   ns.run_once_for = function(selector, identification, code) {
374     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
375     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
376     if (!fn) {
377       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
378       return;
379     }
380
381     $(selector).filter(function() { return $(this).data(attr_name) != true; }).each(function(idx, elt) {
382       var $elt = $(elt);
383       $elt.data(attr_name, true);
384       fn($elt);
385     });
386   };
387
388   // Run a function by its name passing it some arguments
389   //
390   // This is a function useful mainly for the ClientJS functionality.
391   // It finds a function by its name and then executes it on an empty
392   // object passing the elements in 'args' (an array) as the function
393   // parameters retuning its result.
394   //
395   // Logs an error to the console and returns 'undefined' if the
396   // function cannot be found.
397   ns.run = function(function_name, args) {
398     var fn = ns.get_function_by_name(function_name);
399     if (fn)
400       return fn.apply({}, args);
401
402     console.error('kivi.run("' + function_name + '"): No function by that name found');
403     return undefined;
404   };
405 });
406
407 kivi = namespace('kivi');