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