]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/xul/staff_client/chrome/content/OpenILS/global_util.js
Some refactoring. Works with <toolbarbutton type="checked"> now, and monitors all...
[Evergreen.git] / Open-ILS / xul / staff_client / chrome / content / OpenILS / global_util.js
1     function $(id) { return document.getElementById(id); }
2
3     function ses(a,params) {
4         try {
5             if (!params) params = {};
6             var data;
7             if (params.data) {
8                 data = params.data; data.stash_retrieve();
9             } else {
10                 // This has been breaking in certain contexts, with an internal instantiation of util.error failing because of util.error being an object instead of the constructor function it should be
11                 JSAN.use('OpenILS.data'); data = new OpenILS.data(); data.stash_retrieve();
12             }
13
14             switch(a) {
15                 case 'staff_id' : return data.list.au[0].id(); break;
16                 case 'staff_usrname' : return data.list.au[0].usrname(); break;
17                 case 'ws_ou' :
18                     return data.list.au[0].ws_ou();
19                 break;
20                 case 'authtime' :
21                     return data.session.authtime;
22                 break;
23                 case 'key':
24                 default:
25                     return data.session.key;
26                 break;
27             }
28         } catch(E) {
29             alert(location.href + '\nError in global_utils.js, ses(): ' + E);
30             throw(E);
31         }
32     }
33
34     function font_helper() {
35         try {
36             JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
37             removeCSSClass(document.documentElement,'ALL_FONTS_LARGER');
38             removeCSSClass(document.documentElement,'ALL_FONTS_SMALLER');
39             removeCSSClass(document.documentElement,'ALL_FONTS_XX_SMALL');
40             removeCSSClass(document.documentElement,'ALL_FONTS_X_SMALL');
41             removeCSSClass(document.documentElement,'ALL_FONTS_SMALL');
42             removeCSSClass(document.documentElement,'ALL_FONTS_MEDIUM');
43             removeCSSClass(document.documentElement,'ALL_FONTS_LARGE');
44             removeCSSClass(document.documentElement,'ALL_FONTS_X_LARGE');
45             removeCSSClass(document.documentElement,'ALL_FONTS_XX_LARGE');
46             addCSSClass(document.documentElement,data.global_font_adjust);
47         } catch(E) {
48             var Strings = $('offlineStrings') || $('commonStrings');
49             alert(Strings.getFormattedString('openils.global_util.font_size.error', [E]));
50         }
51     }
52
53     function oils_persist(e) {
54         try {
55             var evt = document.createEvent("Events");
56             evt.initEvent( 'oils_persist', true, true );
57             e.dispatchEvent(evt);
58         } catch(E) {
59             alert('Error with oils_persist():' + E);
60         }
61     }
62
63     function persist_helper() {
64         try {
65             function gen_event_handler(etype,node) {
66                 return function(ev) {
67                     try {
68                         var evt = document.createEvent("Events");
69                         evt.initEvent( 'oils_persist', true, true );
70                         ev.target.dispatchEvent(evt);
71                     } catch(E) {
72                         alert('Error in persist_helper, firing virtual event oils_persist after ' + etype + ' event on ' + node.nodeName + '.id = ' + node.id + ': ' + E);
73                     }
74                 };
75             };
76
77             function gen_oils_persist_handler(bk,node) {
78                 return function(ev) {
79                     try {
80                         netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
81                         var target;
82                         if (ev.target.nodeName == 'command') {
83                             target = node;
84                             if (ev.explicitOriginalTarget != node) return;
85                         } else {
86                             target = ev.target;
87                         }
88                         var filename = location.pathname.split('/')[ location.pathname.split('/').length - 1 ];
89                         var base_key = 'oils_persist_' + String(location.hostname + '_' + filename + '_' + target.getAttribute('id')).replace('/','_','g') + '_';
90                         var attribute_list = target.getAttribute('oils_persist').split(' ');
91                         dump('persist_helper: <<< ' + target.nodeName + '.id = ' + target.id + '\t' + bk + '\n');
92                         for (var j = 0; j < attribute_list.length; j++) {
93                             var key = base_key + attribute_list[j];
94                             var value = target.getAttribute( attribute_list[j] );
95                             if ( attribute_list[j] == 'checked' && ['checkbox','toolbarbutton'].indexOf( target.nodeName ) > -1 ) {
96                                 value = target.checked;
97                                 dump('\t' + value + ' <== .' + attribute_list[j] + '\n');
98                             } else if ( attribute_list[j] == 'value' && ['textbox'].indexOf( target.nodeName ) > -1 ) {
99                                 value = target.value;
100                                 dump('\t' + value + ' <== .' + attribute_list[j] + '\n');
101                             } else {
102                                 dump('\t' + value + ' <== @' + attribute_list[j] + '\n');
103                             }
104                             prefs.setCharPref( key, value );
105                             // TODO: Need to add logic for window resizing, splitter repositioning, grippy state, etc.
106                         }
107                     } catch(E) {
108                         alert('Error in persist_helper() event listener for ' + bk + ': ' + E);
109                     }
110                 };
111             }
112
113             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
114             var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
115             var nodes = document.getElementsByAttribute('oils_persist','*');
116             for (var i = 0; i < nodes.length; i++) {
117                 var filename = location.pathname.split('/')[ location.pathname.split('/').length - 1 ];
118                 var base_key = 'oils_persist_' + String(location.hostname + '_' + filename + '_' + nodes[i].getAttribute('id')).replace('/','_','g') + '_';
119                 var attribute_list = nodes[i].getAttribute('oils_persist').split(' ');
120                 dump('persist_helper: >>> ' + nodes[i].nodeName + '.id = ' + nodes[i].id + '\t' + base_key + '\n');
121                 for (var j = 0; j < attribute_list.length; j++) {
122                     var key = base_key + attribute_list[j];
123                     var has_key = prefs.prefHasUserValue(key);
124                     var value = has_key ? prefs.getCharPref(key) : null;
125                     if (value == 'true') { value = true; }
126                     if (value == 'false') { value = false; }
127                     if (has_key) {
128                         if ( attribute_list[j] == 'checked' && ['checkbox','toolbarbutton'].indexOf( nodes[i].nodeName ) > -1 ) {
129                             nodes[i].checked = value; 
130                             dump('\t' + value + ' ==> .' + attribute_list[j] + '\n');
131                             if (!value) {
132                                 nodes[i].removeAttribute('checked');
133                                 dump('\tremoving @checked\n');
134                             }
135                         } else if ( attribute_list[j] == 'value' && ['textbox'].indexOf( nodes[i].nodeName ) > -1 ) {
136                             nodes[i].value = value;
137                             dump('\t' + value + ' ==> .' + attribute_list[j] + '\n');
138                         } else {
139                             nodes[i].setAttribute( attribute_list[j], value);
140                             dump('\t' + value + ' ==> @' + attribute_list[j] + '\n');
141                         }
142                     }
143                 }
144                 var cmd = nodes[i].getAttribute('command');
145                 var cmd_el = document.getElementById(cmd);
146                 if (nodes[i].disabled == false && nodes[i].hidden == false) {
147                     var no_poke = nodes[i].getAttribute('oils_persist_no_poke');
148                     if (no_poke && no_poke == 'true') {
149                         // Timing issue for some checkboxes; don't poke them with an event
150                         dump('\tnot poking\n');
151                     } else {
152                         if (cmd_el) {
153                             dump('\tpoking @command\n');
154                             var evt = document.createEvent("Events");
155                             evt.initEvent( 'command', true, true );
156                             cmd_el.dispatchEvent(evt);
157                         } else {
158                             dump('\tpoking\n');
159                             var evt = document.createEvent("Events");
160                             evt.initEvent( 'command', true, true );
161                             nodes[i].dispatchEvent(evt);
162                         }
163                     }
164                 }
165                 if (cmd_el) {
166                     cmd_el.addEventListener(
167                         'command',
168                         gen_event_handler('command',cmd_el),
169                         false
170                     );
171                     cmd_el.addEventListener(
172                         'oils_persist',
173                         gen_oils_persist_handler( base_key, nodes[i] ),
174                         false
175                     );
176                 } else {
177                     var event_types = [];
178                     if (nodes[i].hasAttribute('oils_persist_events')) {
179                         var event_type_list = nodes[i].getAttribute('oils_persist_events').split(' ');
180                         for (var j = 0; j < event_type_list.length; j++) {
181                             event_types.push( event_type_list[j] );
182                         }
183                     } else {
184                         if (nodes[i].nodeName == 'textbox') { 
185                             event_types.push('change'); 
186                         } else {
187                             event_types.push('command'); 
188                         }
189                     }
190                     for (var j = 0; j < event_types.length; j++) {
191                         nodes[i].addEventListener(
192                             event_types[j],
193                             gen_event_handler(event_types[j],nodes[i]),
194                             false
195                         );
196                     }
197                     nodes[i].addEventListener(
198                         'oils_persist',
199                         gen_oils_persist_handler( base_key, nodes[i] ),
200                         false
201                     );
202                 }
203             }
204         } catch(E) {
205             alert('Error in persist_helper(): ' + E);
206         }
207     }
208
209     function getKeys(o) {
210         var keys = [];
211         for (var k in o) keys.push(k);
212         return keys;
213     }
214
215     function get_contentWindow(frame) {
216         try {
217             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
218             if (frame && frame.contentWindow) {
219                 try {
220                     if (typeof frame.contentWindow.wrappedJSObject != 'undefined') {
221                                      return frame.contentWindow.wrappedJSObject;
222                           }
223                 } catch(E) {
224                     var Strings = $('offlineStrings') || $('commonStrings');
225                     alert(Strings.getFormattedString('openils.global_util.content_window_jsobject.error', [frame, E]));
226                 }
227                 return frame.contentWindow;
228             } else {
229                 return null;
230             }
231         } catch(E) {
232             var Strings = $('offlineStrings') || $('commonStrings');
233             alert(Strings.getFormattedString('openils.global_util.content_window.error', [frame, E]));
234         }
235     }
236
237     function update_modal_xulG(v) {
238         try {
239             JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
240             var key = location.pathname + location.search + location.hash;
241             if (typeof data.modal_xulG_stack != 'undefined' && typeof data.modal_xulG_stack[key] != 'undefined') {
242                 data.modal_xulG_stack[key][ data.modal_xulG_stack[key].length - 1 ] = v;
243                 data.stash('modal_xulG_stack');
244             }
245         } catch(E) {
246             alert('FIXME: update_modal_xulG => ' + E);
247         }
248     }
249
250     function xul_param(param_name,_params) {
251         /* By default, this function looks for a CGI-style query param identified by param_name.  If one isn't found, it then looks in xulG.  If one still isn't found, and _params.stash_name is true, it looks in the global xpcom stash for the field identified by stash_name.  If _params.concat is true, then it looks in all these places and concatenates the results.  There are also options for converting JSON to javascript objects, and clearing the xpcom stash_name field after retrieval.  Also added, ability to search a specific spot in the xpcom stash that implements a stack to hold xulG's for modal windows */
252         try {
253             //dump('xul_param('+param_name+','+js2JSON(_params)+')\n');
254             var value = undefined; if (!_params) _params = {};
255             if (typeof _params.no_cgi == 'undefined') {
256                 var cgi = new CGI();
257                 if (cgi.param(param_name)) {
258                     var x = cgi.param(param_name);
259                     //dump('\tfound via location.href = ' + x + '\n');
260                     if (typeof _params.JSON2js_if_cgi != 'undefined') {
261                         x = JSON2js( x );
262                         //dump('\tJSON2js = ' + x + '\n');
263                     }
264                     if (typeof _params.concat == 'undefined') {
265                         //alert(param_name + ' x = ' + x);
266                         return x; // value
267                     } else {
268                         if (value) {
269                             if (value.constructor != Array) value = [ value ];
270                             value = value.concat(x);
271                         } else {
272                             value = x;
273                         }
274                     }
275                 }
276             }
277             if (typeof _params.no_xulG == 'undefined') {
278                 if (typeof _params.modal_xulG != 'undefined') {
279                     JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
280                     var key = location.pathname + location.search + location.hash;
281                     //dump('xul_param, considering modal key = ' + key + '\n');
282                     if (typeof data.modal_xulG_stack != 'undefined' && typeof data.modal_xulG_stack[key] != 'undefined') {
283                         xulG = data.modal_xulG_stack[key][ data.modal_xulG_stack[key].length - 1 ];
284                     }
285                 }
286                 if (typeof xulG == 'object' && typeof xulG[ param_name ] != 'undefined') {
287                     var x = xulG[ param_name ];
288                     //dump('\tfound via xulG = ' + x + '\n');
289                     if (typeof _params.JSON2js_if_xulG != 'undefined') {
290                         x = JSON2js( x );
291                         //dump('\tJSON2js = ' + x + '\n');
292                     }
293                     if (typeof _params.concat == 'undefined') {
294                         //alert(param_name + ' x = ' + x);
295                         return x; // value
296                     } else {
297                         if (value) {
298                             if (value.constructor != Array) value = [ value ];
299                             value = value.concat(x);
300                         } else {
301                             value = x;
302                         }
303                     }
304                 }
305             }
306             if (typeof _params.no_xpcom == 'undefined') {
307                 /* the field names used for temp variables in the global stash tend to be more unique than xuLG or CGI param names, to avoid collisions */
308                 if (typeof _params.stash_name != 'undefined') { 
309                     JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
310                     if (typeof data[ _params.stash_name ] != 'undefined') {
311                         var x = data[ _params.stash_name ];
312                         //dump('\tfound via xpcom = ' + x + '\n');
313                         if (typeof _params.JSON2js_if_xpcom != 'undefined') {
314                             x = JSON2js( x );
315                             //dump('\tJSON2js = ' + x + '\n');
316                         }
317                         if (_params.clear_xpcom) { 
318                             data[ _params.stash_name ] = undefined; data.stash( _params.stash_name ); 
319                         }
320                         if (typeof _params.concat == 'undefined') {
321                             //alert(param_name + ' x = ' + x);
322                             return x; // value
323                         } else {
324                             if (value) {
325                                 if (value.constructor != Array) value = [ value ];
326                                 value = value.concat(x);
327                             } else {
328                                 value = x;
329                             }
330                         }
331                     }
332                 }
333             }
334             //alert(param_name + ' value = ' + value);
335             return value;
336         } catch(E) {
337             dump('xul_param error: ' + E + '\n');
338         }
339     }
340
341     function get_bool(a) {
342         // Normal javascript interpretation except 'f' == false, per postgres, and 'F' == false, and '0' == false (newer JSON is returning '0' instead of 0 in cases)
343         // So false includes 'f', '', '0', 0, null, and undefined
344         if (a == 'f') return false;
345         if (a == 'F') return false;
346         if (a == '0') return false;
347         if (a) return true; else return false;
348     }
349
350     function get_db_true() {
351         return 't';
352     }
353
354     function get_db_false() {
355         return 'f';
356     }
357
358     function copy_to_clipboard(ev) {
359         try {
360             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
361             var text;
362             if (typeof ev == 'object') {
363                 if (typeof ev.target != 'undefined') {
364                     if (typeof ev.target.textContent != 'undefined') if (ev.target.textContent) text = ev.target.textContent;
365                     if (typeof ev.target.value != 'undefined') if (ev.target.value) text = ev.target.value;
366                 }
367             } else if (typeof ev == 'string') {
368                 text = ev;
369             }
370             const gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"]
371                 .getService(Components.interfaces.nsIClipboardHelper);
372             gClipboardHelper.copyString(text);
373             var Strings = $('offlineStrings') || $('commonStrings');
374             alert(Strings.getFormattedString('openils.global_util.clipboard', [text]));
375         } catch(E) {
376             var Strings = $('offlineStrings') || $('commonStrings');
377             alert(Strings.getFormattedString('openils.global_util.clipboard.error', [E]));    
378         }
379     }
380
381     function clear_the_cache() {
382         try {
383             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
384             var cacheClass         = Components.classes["@mozilla.org/network/cache-service;1"];
385             var cacheService    = cacheClass.getService(Components.interfaces.nsICacheService);
386             cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
387             cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
388         } catch(E) {
389             var Strings = $('offlineStrings') || $('commonStrings');
390             alert(Strings.getFormattedString('openils.global_util.clear_cache.error', [E]));
391         }
392     }
393
394     function toOpenWindowByType(inType, uri) {
395         var winopts = "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar";
396         window.open(uri, "_blank", winopts);
397     }
398
399     function url_prefix(url) {
400         if (url.match(/^\//)) url = urls.remote + url;
401         if (! url.match(/^(http|chrome):\/\//) && ! url.match(/^data:/) ) url = 'http://' + url;
402         dump('url_prefix = ' + url + '\n');
403         return url;
404     }
405