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