Verkaufs-/Einkaufsmasken: HTML in Langtexten nutzen
[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     var func = kivi.get_function_by_name('local_reinit_widgets');
131     if (func)
132       func();
133
134     ns.run_once_for('.tooltip', 'tooltip', function(elt) {
135       $(elt).tooltip();
136     });
137
138     ns.run_once_for('.tabwidget', 'tabwidget', kivi.init_tabwidget);
139     ns.run_once_for('.texteditor', 'texteditor', kivi.init_text_editor);
140   };
141
142   ns.submit_ajax_form = function(url, form_selector, additional_data) {
143     $(form_selector).ajaxSubmit({
144       url:     url,
145       data:    additional_data,
146       success: ns.eval_json_result
147     });
148
149     return true;
150   };
151
152   // Return a function object by its name (a string). Works both with
153   // global functions (e.g. "check_right_date_format") and those in
154   // namespaces (e.g. "kivi.t8").
155   // Returns null if the object is not found.
156   ns.get_function_by_name = function(name) {
157     var parts = name.match("(.+)\\.([^\\.]+)$");
158     if (!parts)
159       return window[name];
160     return namespace(parts[1])[ parts[2] ];
161   };
162
163   // Open a modal jQuery UI popup dialog. The content can be either
164   // loaded via AJAX (if the parameter 'url' is given) or simply
165   // displayed if it exists in the DOM already (referenced via
166   // 'id'). If an existing DOM div should be used then the element
167   // won't be removed upon closing the dialog which allows re-opening
168   // it later on.
169   //
170   // Parameters:
171   // - id: dialog DIV ID (optional; defaults to 'jqueryui_popup_dialog')
172   // - url, data, type: passed as the first three arguments to the $.ajax() call if an AJAX call is made, otherwise ignored.
173   // - dialog: an optional object of options passed to the $.dialog() call
174   ns.popup_dialog = function(params) {
175     var dialog;
176
177     params            = params        || { };
178     var id            = params.id     || 'jqueryui_popup_dialog';
179     var dialog_params = $.extend(
180       { // kivitendo default parameters:
181           width:  800
182         , height: 500
183         , modal:  true
184       },
185         // User supplied options:
186       params.dialog || { },
187       { // Options that must not be changed:
188         close: function(event, ui) { if (params.url) dialog.remove(); else dialog.dialog('close'); }
189       });
190
191     if (!params.url) {
192       // Use existing DOM element and show it. No AJAX call.
193       dialog =
194         $('#' + id)
195         .bind('dialogopen', function() {
196           ns.run_once_for('.texteditor-in-dialog,.texteditor-dialog', 'texteditor', kivi.init_text_editor);
197         })
198         .dialog(dialog_params);
199       return true;
200     }
201
202     $('#' + id).remove();
203
204     dialog = $('<div style="display:none" class="loading" id="' + id + '"></div>').appendTo('body');
205     dialog.dialog(dialog_params);
206
207     $.ajax({
208       url:     params.url,
209       data:    params.data,
210       type:    params.type,
211       success: function(new_html) {
212         dialog.html(new_html);
213         dialog.removeClass('loading');
214       }
215     });
216
217     return true;
218   };
219
220   // Run code only once for each matched element
221   //
222   // This allows running the function 'code' exactly once for each
223   // element that matches 'selector'. This is achieved by storing the
224   // state with jQuery's 'data' function. The 'identification' is
225   // required for differentiating unambiguously so that different code
226   // functions can still be run on the same elements.
227   //
228   // 'code' can be either a function or the name of one. It must
229   // resolve to a function that receives the jQueryfied element as its
230   // sole argument.
231   //
232   // Returns nothing.
233   ns.run_once_for = function(selector, identification, code) {
234     var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-');
235     var fn        = typeof code === 'function' ? code : ns.get_function_by_name(code);
236     if (!fn) {
237       console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found');
238       return;
239     }
240
241     $(selector).filter(function() { return $(this).data(attr_name) != true; }).each(function(idx, elt) {
242       var $elt = $(elt);
243       $elt.data(attr_name, true);
244       fn($elt);
245     });
246   };
247
248   // Run a function by its name passing it some arguments
249   //
250   // This is a function useful mainly for the ClientJS functionality.
251   // It finds a function by its name and then executes it on an empty
252   // object passing the elements in 'args' (an array) as the function
253   // parameters retuning its result.
254   //
255   // Logs an error to the console and returns 'undefined' if the
256   // function cannot be found.
257   ns.run = function(function_name, args) {
258     var fn = ns.get_function_by_name(function_name);
259     if (fn)
260       return fn.apply({}, args);
261
262     console.error('kivi.run("' + function_name + '"): No function by that name found');
263     return undefined;
264   };
265 });
266
267 kivi = namespace('kivi');