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