PriceSource: Spalte vor Preis und Rabatt anzeigen.
[kivitendo-erp.git] / js / kivi.js
1 namespace("kivi", function(ns) {
2   ns._locale = {};
3
4   ns.t8 = function(text, params) {
5     var text = ns._locale[text] || text;
6
7     if( Object.prototype.toString.call( params ) === '[object Array]' ) {
8       var len = params.length;
9
10       for(var i=0; i<len; ++i) {
11         var key = i + 1;
12         var value = params[i];
13         text = text.split("#"+ key).join(value);
14       }
15     }
16     else if( typeof params == 'object' ) {
17       for(var key in params) {
18         var value = params[key];
19         text = text.split("#{"+ key +"}").join(value);
20       }
21     }
22
23     return text;
24   };
25
26   ns.setupLocale = function(locale) {
27     ns._locale = locale;
28   };
29
30   ns.set_focus = function(element) {
31     var $e = $(element).eq(0);
32     if ($e.data('ckeditorInstance'))
33       ns.focus_ckeditor_when_ready($e);
34     else
35       $e.focus();
36   };
37
38   ns.focus_ckeditor_when_ready = function(element) {
39     $(element).ckeditor(function() { ns.focus_ckeditor(element); });
40   };
41
42   ns.focus_ckeditor = function(element) {
43     var editor   = $(element).ckeditorGet();
44                 var editable = editor.editable();
45
46                 if (editable.is('textarea')) {
47                         var textarea = editable.$;
48
49                         if (CKEDITOR.env.ie)
50                                 textarea.createTextRange().execCommand('SelectAll');
51                         else {
52                                 textarea.selectionStart = 0;
53                                 textarea.selectionEnd   = textarea.value.length;
54                         }
55
56                         textarea.focus();
57
58                 } else {
59                         if (editable.is('body'))
60                                 editor.document.$.execCommand('SelectAll', false, null);
61
62                         else {
63                                 var range = editor.createRange();
64                                 range.selectNodeContents(editable);
65                                 range.select();
66                         }
67
68                         editor.forceNextSelectionCheck();
69                         editor.selectionChange();
70
71       editor.focus();
72                 }
73   };
74
75   ns.init_tabwidget = function(element) {
76     var $element   = $(element);
77     var tabsParams = {};
78     var elementId  = $element.attr('id');
79
80     if (elementId) {
81       var cookieName      = 'jquery_ui_tab_'+ elementId;
82       tabsParams.active   = $.cookie(cookieName);
83       tabsParams.activate = function(event, ui) {
84         var i = ui.newTab.parent().children().index(ui.newTab);
85         $.cookie(cookieName, i);
86       };
87     }
88
89     $element.tabs(tabsParams);
90   };
91
92   ns.init_text_editor = function(element) {
93     var layouts = {
94       all:     [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ],
95       default: [ [ 'Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript' ], [ 'BulletedList', 'NumberedList' ], [ 'RemoveFormat' ] ]
96     };
97
98     var $e      = $(element);
99     var buttons = layouts[ $e.data('texteditor-layout') || 'default' ] || layouts['default'];
100     var config  = {
101       entities:      false,
102       language:      'de',
103       removePlugins: 'resize',
104       toolbar:       buttons
105     }
106
107     var style = $e.prop('style');
108     $(['width', 'height']).each(function(idx, prop) {
109       var matches = (style[prop] || '').match(/(\d+)px/);
110       if (matches && (matches.length > 1))
111         config[prop] = matches[1];
112     });
113
114     $e.ckeditor(config);
115
116     if ($e.hasClass('texteditor-autofocus'))
117       $e.ckeditor(function() { ns.focus_ckeditor($e); });
118   };
119
120   ns.reinit_widgets = function() {
121     ns.run_once_for('.datepicker', 'datepicker', function(elt) {
122       $(elt).datepicker();
123     });
124
125     if (ns.PartPicker)
126       ns.run_once_for('input.part_autocomplete', 'part_picker', function(elt) {
127         kivi.PartPicker($(elt));
128       });
129
130     if (ns.CustomerVendorPicker)
131       ns.run_once_for('input.customer_vendor_autocomplete', 'customer_vendor_picker', function(elt) {
132         kivi.CustomerVendorPicker($(elt));
133       });
134
135     var func = kivi.get_function_by_name('local_reinit_widgets');
136     if (func)
137       func();
138
139     ns.run_once_for('.tooltip', 'tooltip', function(elt) {
140       $(elt).tooltip();
141     });
142
143     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
144     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
145   };
146
147   ns.submit_ajax_form = function(url, form_selector, additional_data) {
148     $(form_selector).ajaxSubmit({
149       url:     url,
150       data:    additional_data,
151       success: ns.eval_json_result
152     });
153
154     return true;
155   };
156
157   // Return a function object by its name (a string). Works both with
158   // global functions (e.g. "check_right_date_format") and those in
159   // namespaces (e.g. "kivi.t8").
160   // Returns null if the object is not found.
161   ns.get_function_by_name = function(name) {
162     var parts = name.match("(.+)\\.([^\\.]+)$");
163     if (!parts)
164       return window[name];
165     return namespace(parts[1])[ parts[2] ];
166   };
167
168   // Open a modal jQuery UI popup dialog. The content can be either
169   // loaded via AJAX (if the parameter 'url' is given) or simply
170   // displayed if it exists in the DOM already (referenced via
171   // 'id'). If an existing DOM div should be used then the element
172   // won't be removed upon closing the dialog which allows re-opening
173   // it later on.
174   //
175   // Parameters:
176   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
177   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
178   // - dialog: an optional object of options passed to the $.dialog() call
179   ns.popup_dialog = function(params) {
180     var dialog;
181
182     params            = params        || { };
183     var id            = params.id     || 'jqueryui_popup_dialog';
184     var dialog_params = $.extend(
185       { // kivitendo default parameters:
186           width:  800
187         , height: 500
188         , modal:  true
189       },
190         // User supplied options:
191       params.dialog || { },
192       { // Options that must not be changed:
193         close: function(event, ui) { if (params.url) dialog.remove(); else dialog.dialog('close'); }
194       });
195
196     if (!params.url) {
197       // Use existing DOM element and show it. No AJAX call.
198       dialog =
199         $('#' + id)
200         .bind('dialogopen', function() {
201           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
202         })
203         .dialog(dialog_params);
204       return true;
205     }
206
207     $('#' + id).remove();
208
209     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
210     dialog.dialog(dialog_params);
211
212     $.ajax({
213       url:     params.url,
214       data:    params.data,
215       type:    params.type,
216       success: function(new_html) {
217         dialog.html(new_html);
218         dialog.removeClass('loading');
219       }
220     });
221
222     return true;
223   };
224
225   // Run code only once for each matched element
226   //
227   // This allows running the function 'code' exactly once for each
228   // element that matches 'selector'. This is achieved by storing the
229   // state with jQuery's 'data' function. The 'identification' is
230   // required for differentiating unambiguously so that different code
231   // functions can still be run on the same elements.
232   //
233   // 'code' can be either a function or the name of one. It must
234   // resolve to a function that receives the jQueryfied element as its
235   // sole argument.
236   //
237   // Returns nothing.
238   ns.run_once_for = function(selector, identification, code) {
239     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
240     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
241     if (!fn) {
242       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
243       return;
244     }
245
246     $(selector).filter(function() { return $(this).data(attr_name) != true; }).each(function(idx, elt) {
247       var $elt = $(elt);
248       $elt.data(attr_name, true);
249       fn($elt);
250     });
251   };
252
253   // Run a function by its name passing it some arguments
254   //
255   // This is a function useful mainly for the ClientJS functionality.
256   // It finds a function by its name and then executes it on an empty
257   // object passing the elements in 'args' (an array) as the function
258   // parameters retuning its result.
259   //
260   // Logs an error to the console and returns 'undefined' if the
261   // function cannot be found.
262   ns.run = function(function_name, args) {
263     var fn = ns.get_function_by_name(function_name);
264     if (fn)
265       return fn.apply({}, args);
266
267     console.error('kivi.run("' + function_name + '"): No function by that name found');
268     return undefined;
269   };
270 });
271
272 kivi = namespace('kivi');