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