]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/xul/staff_client/chrome/content/OpenILS/global_util.js
Wire up the Item Attribute Editor with oils_lock_page. Some tweaks needed to global_...
[working/Evergreen.git] / Open-ILS / xul / staff_client / chrome / content / OpenILS / global_util.js
1     function $(id) { return document.getElementById(id); }
2
3     function oils_lock_page(params) {
4         dump('oils_lock_page\n');
5         if (!params) { params = {}; }
6         if (window.oils_lock) {
7             if (!params.allow_multiple_locks) {
8                 return 'already locked';
9             }
10         }
11         window.oils_lock = true;
12         if (typeof xulG != 'undefined') {
13             if (typeof xulG.unlock_tab == 'function') {
14                 xulG.lock_tab();
15             }
16         }
17         return 'locked';
18     }
19
20     function oils_unlock_page(params) {
21         dump('oils_unlock_page\n');
22         window.oils_lock = false;
23         if (typeof xulG != 'undefined') {
24             if (typeof xulG.unlock_tab == 'function') {
25                 xulG.unlock_tab();
26             }
27         }
28         return 'unlocked';
29     }
30
31     window.addEventListener(
32         'close',
33         function(ev) {
34             try {
35                 dump('oils_lock_page/oils_unlock_page onclose handler\n');
36                 if (window.oils_lock) {
37                     var confirmation = window.confirm($('offlineStrings').getString('menu.close_window.unsaved_data_warning'));
38                     if (!confirmation) {
39                         ev.preventDefault();
40                         return false;
41                     }
42                 }
43
44                 window.oils_lock = false;
45                 if (typeof xulG != 'undefined') {
46                     if (typeof xulG.unlock_tab == 'function') {
47                         xulG.unlock_tab();
48                     }
49                 }
50
51                 // Dispatching the window close event doesn't always close the window, even though the event does happen
52                 setTimeout(
53                     function() {
54                         try {
55                             window.close();
56                         } catch(E) {
57                             dump('Error inside global_util.js, onclose handler, setTimeout window.close KLUDGE: ' + E + '\n');
58                         }
59                     }, 0
60                 );
61
62                 return true;
63             } catch(E) {
64                 dump('Error inside global_util.js, onclose handler: ' + E + '\n');
65                 return true;
66             }
67         },
68         false
69     );
70
71     function ses(a,params) {
72         try {
73             if (!params) params = {};
74             var data;
75             if (params.data) {
76                 data = params.data; data.stash_retrieve();
77             } else {
78                 // 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
79                 JSAN.use('OpenILS.data'); data = new OpenILS.data(); data.stash_retrieve();
80             }
81
82             switch(a) {
83                 case 'staff' : return data.list.au[0]; break;
84                 case 'staff_id' : return data.list.au[0].id(); break;
85                 case 'staff_usrname' : return data.list.au[0].usrname(); break;
86                 case 'ws_ou' :
87                     return data.list.au[0].ws_ou();
88                 break;
89                 case 'ws_ou_shortname' :
90                     return data.hash.aou[ data.list.au[0].ws_ou() ].shortname();
91                 break;
92                 case 'authtime' :
93                     return data.session.authtime;
94                 break;
95                 case 'key':
96                 default:
97                     return data.session.key;
98                 break;
99             }
100         } catch(E) {
101             alert(location.href + '\nError in global_utils.js, ses(): ' + E);
102             throw(E);
103         }
104     }
105
106     function font_helper() {
107         try {
108             JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
109             removeCSSClass(document.documentElement,'ALL_FONTS_LARGER');
110             removeCSSClass(document.documentElement,'ALL_FONTS_SMALLER');
111             removeCSSClass(document.documentElement,'ALL_FONTS_XX_SMALL');
112             removeCSSClass(document.documentElement,'ALL_FONTS_X_SMALL');
113             removeCSSClass(document.documentElement,'ALL_FONTS_SMALL');
114             removeCSSClass(document.documentElement,'ALL_FONTS_MEDIUM');
115             removeCSSClass(document.documentElement,'ALL_FONTS_LARGE');
116             removeCSSClass(document.documentElement,'ALL_FONTS_X_LARGE');
117             removeCSSClass(document.documentElement,'ALL_FONTS_XX_LARGE');
118             addCSSClass(document.documentElement,data.global_font_adjust);
119         } catch(E) {
120             var Strings = $('offlineStrings') || $('commonStrings');
121             alert(Strings.getFormattedString('openils.global_util.font_size.error', [E]));
122         }
123     }
124
125     function oils_persist(e,cancelable) {
126         try {
127             if (!e) { return; }
128             if (typeof cancelable == 'undefined') { cancelable = false; } 
129             var evt = document.createEvent("Events");
130             evt.initEvent( 'oils_persist', false, cancelable ); // event name, bubbles, cancelable
131             e.dispatchEvent(evt);
132         } catch(E) {
133             alert('Error with oils_persist():' + E);
134         }
135     }
136
137     function persist_helper(base_key_suffix) {
138         try {
139             if (base_key_suffix) {
140                 base_key_suffix = base_key_suffix.replace(/[^A-Za-z]/g,'_') + '_';
141             } else {
142                 base_key_suffix = '';
143             }
144
145             function gen_event_handler(etype,node) {
146                 return function(ev) {
147                     try {
148                         oils_persist(ev.target);
149                     } catch(E) {
150                         alert('Error in persist_helper, firing virtual event oils_persist after ' + etype + ' event on ' + node.nodeName + '.id = ' + node.id + ': ' + E);
151                     }
152                 };
153             };
154
155             function gen_oils_persist_handler(bk,node) {
156                 return function(ev) {
157                     try {
158                         netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
159                         var target;
160                         if (ev.target.nodeName == 'command') {
161                             target = node;
162                             if (ev.explicitOriginalTarget != node) return;
163                         } else {
164                             target = ev.target;
165                             if (target == window) {
166                                 target = window.document.documentElement;
167                             }
168                         }
169                         var filename = location.pathname.split('/')[ location.pathname.split('/').length - 1 ];
170                         var base_key = 'oils_persist_' + String(location.hostname + '_' + filename + '_' + target.getAttribute('id')).replace('/','_','g') + '_' + base_key_suffix;
171                         var attribute_list = target.getAttribute('oils_persist').split(' ');
172                         dump('on_oils_persist: <<< ' + target.nodeName + '.id = ' + target.id + '\t' + bk + '\n');
173                         for (var j = 0; j < attribute_list.length; j++) {
174                             var key = base_key + attribute_list[j];
175                             var value = target.getAttribute( attribute_list[j] );
176                             if ( attribute_list[j] == 'checked' && ['checkbox','toolbarbutton'].indexOf( target.nodeName ) > -1 ) {
177                                 value = target.checked;
178                                 dump('\t' + value + ' <== .' + attribute_list[j] + '\n');
179                             } else if ( attribute_list[j] == 'value' && ['textbox'].indexOf( target.nodeName ) > -1 ) {
180                                 value = target.value;
181                                 dump('\t' + value + ' <== .' + attribute_list[j] + '\n');
182                             } else if ( attribute_list[j] == 'sizemode' && ['window'].indexOf( target.nodeName ) > -1 ) {
183                                 value = window.windowState;
184                                 dump('\t' + value + ' <== window.windowState, @' + attribute_list[j] + '\n');
185                             } else if ( attribute_list[j] == 'height' && ['window'].indexOf( target.nodeName ) > -1 ) {
186                                 value = window.outerHeight;
187                                 dump('\t' + value + ' <== window.outerHeight, @' + attribute_list[j] + '\n');
188                             } else if ( attribute_list[j] == 'width' && ['window'].indexOf( target.nodeName ) > -1 ) {
189                                 value = window.outerWidth;
190                                 dump('\t' + value + ' <== window.outerWidth, @' + attribute_list[j] + '\n');
191                             } else {
192                                 dump('\t' + value + ' <== @' + attribute_list[j] + '\n');
193                             }
194                             prefs.setCharPref( key, value );
195                             // TODO: Need to add logic for splitter repositioning, grippy state, etc.
196                             // NOTE: oils_persist_peers and oils_persist="width" on those peers can help with the elements adjacent to a splitter
197                         }
198                         if (target.hasAttribute('oils_persist_peers') && ! ev.cancelable) { // We abuse the .cancelable field on the oils_persist event to prevent looping
199                             var peer_list = target.getAttribute('oils_persist_peers').split(' ');
200                             for (var j = 0; j < peer_list.length; j++) {
201                                 dump('on_oils_persist: dispatching oils_persist to peer ' + peer_list[j] + '\n');
202                                 oils_persist( document.getElementById( peer_list[j] ), true );
203                             } 
204                         }
205                     } catch(E) {
206                         alert('Error in persist_helper() event listener for ' + bk + ': ' + E);
207                     }
208                 };
209             }
210
211             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
212             var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces['nsIPrefBranch']);
213             var nodes = document.getElementsByAttribute('oils_persist','*');
214             for (var i = 0; i < nodes.length; i++) {
215                 var filename = location.pathname.split('/')[ location.pathname.split('/').length - 1 ];
216                 var base_key = 'oils_persist_' + String(location.hostname + '_' + filename + '_' + nodes[i].getAttribute('id')).replace('/','_','g') + '_' + base_key_suffix;
217                 var attribute_list = nodes[i].getAttribute('oils_persist').split(' ');
218                 dump('persist_helper: >>> ' + nodes[i].nodeName + '.id = ' + nodes[i].id + '\t' + base_key + '\n');
219                 for (var j = 0; j < attribute_list.length; j++) {
220                     var key = base_key + attribute_list[j];
221                     var has_key = prefs.prefHasUserValue(key);
222                     var value = has_key ? prefs.getCharPref(key) : null;
223                     if (value == 'true') { value = true; }
224                     if (value == 'false') { value = false; }
225                     if (has_key) {
226                         if ( attribute_list[j] == 'checked' && ['checkbox','toolbarbutton'].indexOf( nodes[i].nodeName ) > -1 ) {
227                             nodes[i].checked = value; 
228                             dump('\t' + value + ' ==> .' + attribute_list[j] + '\n');
229                             if (!value) {
230                                 nodes[i].removeAttribute('checked');
231                                 dump('\tremoving @checked\n');
232                             }
233                         } else if ( attribute_list[j] == 'value' && ['textbox'].indexOf( nodes[i].nodeName ) > -1 ) {
234                             nodes[i].value = value;
235                             dump('\t' + value + ' ==> .' + attribute_list[j] + '\n');
236                         } else if ( attribute_list[j] == 'sizemode' && ['window'].indexOf( nodes[i].nodeName ) > -1 ) {
237                             switch(value) {
238                                 case window.STATE_MAXIMIZED:
239                                     window.maximize();
240                                     break;
241                                 case window.STATE_MINIMIZED:
242                                     window.minimize();
243                                     break;
244                             };
245                             dump('\t' + value + ' ==> window.windowState, @' + attribute_list[j] + '\n');
246                         } else if ( attribute_list[j] == 'height' && ['window'].indexOf( nodes[i].nodeName ) > -1 ) {
247                             window.outerHeight = value;
248                             dump('\t' + value + ' ==> window.outerHeight, @' + attribute_list[j] + '\n');
249                         } else if ( attribute_list[j] == 'width' && ['window'].indexOf( nodes[i].nodeName ) > -1 ) {
250                             window.outerWidth = value;
251                             dump('\t' + value + ' ==> window.outerWidth, @' + attribute_list[j] + '\n');
252                         } else {
253                             nodes[i].setAttribute( attribute_list[j], value);
254                             dump('\t' + value + ' ==> @' + attribute_list[j] + '\n');
255                         }
256                     }
257                 }
258                 var cmd = nodes[i].getAttribute('command');
259                 var cmd_el = document.getElementById(cmd);
260                 if (nodes[i].disabled == false && nodes[i].hidden == false) {
261                     var no_poke = nodes[i].getAttribute('oils_persist_no_poke');
262                     if (no_poke && no_poke == 'true') {
263                         // Timing issue for some checkboxes; don't poke them with an event
264                         dump('\tnot poking\n');
265                     } else {
266                         if (cmd_el) {
267                             dump('\tpoking @command\n');
268                             var evt = document.createEvent("Events");
269                             evt.initEvent( 'command', true, true );
270                             cmd_el.dispatchEvent(evt);
271                         } else {
272                             dump('\tpoking\n');
273                             var evt = document.createEvent("Events");
274                             evt.initEvent( 'command', true, true );
275                             nodes[i].dispatchEvent(evt);
276                         }
277                     }
278                 }
279                 if (cmd_el) {
280                     cmd_el.addEventListener(
281                         'command',
282                         gen_event_handler('command',cmd_el),
283                         false
284                     );
285                     cmd_el.addEventListener(
286                         'oils_persist',
287                         gen_oils_persist_handler( base_key, nodes[i] ),
288                         false
289                     );
290                 } else {
291                     var node = nodes[i];
292                     var event_types = [];
293                     if (node.hasAttribute('oils_persist_events')) {
294                         var event_type_list = node.getAttribute('oils_persist_events').split(' ');
295                         for (var j = 0; j < event_type_list.length; j++) {
296                             event_types.push( event_type_list[j] );
297                         }
298                     } else {
299                         if (node.nodeName == 'textbox') { 
300                             event_types.push('change'); 
301                         } else if (node.nodeName == 'window') {
302                             event_types.push('resize'); 
303                             node = window; // xul window is an element of window.document
304                         } else {
305                             event_types.push('command'); 
306                         }
307                     }
308                     for (var j = 0; j < event_types.length; j++) {
309                         node.addEventListener(
310                             event_types[j],
311                             gen_event_handler(event_types[j],node),
312                             false
313                         );
314                     }
315                     node.addEventListener(
316                         'oils_persist',
317                         gen_oils_persist_handler( base_key, node ),
318                         false
319                     );
320                 }
321             }
322         } catch(E) {
323             alert('Error in persist_helper(): ' + E);
324         }
325     }
326
327     function getKeys(o) {
328         var keys = [];
329         for (var k in o) keys.push(k);
330         return keys;
331     }
332
333     function get_contentWindow(frame) {
334         try {
335             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
336             if (frame && frame.contentWindow) {
337                 try {
338                     if (typeof frame.contentWindow.wrappedJSObject != 'undefined') {
339                                      return frame.contentWindow.wrappedJSObject;
340                           }
341                 } catch(E) {
342                     var Strings = $('offlineStrings') || $('commonStrings');
343                     alert(Strings.getFormattedString('openils.global_util.content_window_jsobject.error', [frame, E]));
344                 }
345                 return frame.contentWindow;
346             } else {
347                 return null;
348             }
349         } catch(E) {
350             var Strings = $('offlineStrings') || $('commonStrings');
351             alert(Strings.getFormattedString('openils.global_util.content_window.error', [frame, E]));
352         }
353     }
354
355     function update_modal_xulG(v) {
356         try {
357             JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
358             var key = location.pathname + location.search + location.hash;
359             if (typeof data.modal_xulG_stack != 'undefined' && typeof data.modal_xulG_stack[key] != 'undefined') {
360                 data.modal_xulG_stack[key][ data.modal_xulG_stack[key].length - 1 ] = v;
361                 data.stash('modal_xulG_stack');
362             }
363         } catch(E) {
364             alert('FIXME: update_modal_xulG => ' + E);
365         }
366     }
367
368     function xul_param(param_name,_params) {
369         /* 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 */
370         try {
371             //dump('xul_param('+param_name+','+js2JSON(_params)+')\n');
372             var value = undefined; if (!_params) _params = {};
373             if (typeof _params.no_cgi == 'undefined') {
374                 var cgi = new CGI();
375                 if (cgi.param(param_name)) {
376                     var x = cgi.param(param_name);
377                     //dump('\tfound via location.href = ' + x + '\n');
378                     if (typeof _params.JSON2js_if_cgi != 'undefined') {
379                         x = JSON2js( x );
380                         //dump('\tJSON2js = ' + x + '\n');
381                     }
382                     if (typeof _params.concat == 'undefined') {
383                         //alert(param_name + ' x = ' + x);
384                         return x; // value
385                     } else {
386                         if (value) {
387                             if (value.constructor != Array) value = [ value ];
388                             value = value.concat(x);
389                         } else {
390                             value = x;
391                         }
392                     }
393                 }
394             }
395             if (typeof _params.no_xulG == 'undefined') {
396                 if (typeof _params.modal_xulG != 'undefined') {
397                     JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
398                     var key = location.pathname + location.search + location.hash;
399                     //dump('xul_param, considering modal key = ' + key + '\n');
400                     if (typeof data.modal_xulG_stack != 'undefined' && typeof data.modal_xulG_stack[key] != 'undefined') {
401                         xulG = data.modal_xulG_stack[key][ data.modal_xulG_stack[key].length - 1 ];
402                     }
403                 }
404                 if (typeof xulG == 'object' && typeof xulG[ param_name ] != 'undefined') {
405                     var x = xulG[ param_name ];
406                     //dump('\tfound via xulG = ' + x + '\n');
407                     if (typeof _params.JSON2js_if_xulG != 'undefined') {
408                         x = JSON2js( x );
409                         //dump('\tJSON2js = ' + x + '\n');
410                     }
411                     if (typeof _params.concat == 'undefined') {
412                         //alert(param_name + ' x = ' + x);
413                         return x; // value
414                     } else {
415                         if (value) {
416                             if (value.constructor != Array) value = [ value ];
417                             value = value.concat(x);
418                         } else {
419                             value = x;
420                         }
421                     }
422                 }
423             }
424             if (typeof _params.no_xpcom == 'undefined') {
425                 /* 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 */
426                 if (typeof _params.stash_name != 'undefined') { 
427                     JSAN.use('OpenILS.data'); var data = new OpenILS.data(); data.init({'via':'stash'});
428                     if (typeof data[ _params.stash_name ] != 'undefined') {
429                         var x = data[ _params.stash_name ];
430                         //dump('\tfound via xpcom = ' + x + '\n');
431                         if (typeof _params.JSON2js_if_xpcom != 'undefined') {
432                             x = JSON2js( x );
433                             //dump('\tJSON2js = ' + x + '\n');
434                         }
435                         if (_params.clear_xpcom) { 
436                             data[ _params.stash_name ] = undefined; data.stash( _params.stash_name ); 
437                         }
438                         if (typeof _params.concat == 'undefined') {
439                             //alert(param_name + ' x = ' + x);
440                             return x; // value
441                         } else {
442                             if (value) {
443                                 if (value.constructor != Array) value = [ value ];
444                                 value = value.concat(x);
445                             } else {
446                                 value = x;
447                             }
448                         }
449                     }
450                 }
451             }
452             //alert(param_name + ' value = ' + value);
453             return value;
454         } catch(E) {
455             dump('xul_param error: ' + E + '\n');
456         }
457     }
458
459     function get_bool(a) {
460         // Normal javascript interpretation except 'f' == false, per postgres, and 'F' == false, and '0' == false (newer JSON is returning '0' instead of 0 in cases)
461         // So false includes 'f', '', '0', 0, null, and undefined
462         if (a == 'f') return false;
463         if (a == 'F') return false;
464         if (a == '0') return false;
465         if (a) return true; else return false;
466     }
467
468     function get_localized_bool(a) {
469         var Strings = $('offlineStrings') || $('commonStrings');
470         return get_bool(a) ? Strings.getString('common.yes') : Strings.getString('common.no');
471     }
472
473     function get_db_true() {
474         return 't';
475     }
476
477     function get_db_false() {
478         return 'f';
479     }
480
481     function copy_to_clipboard(ev) {
482         try {
483             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
484             var text;
485             if (typeof ev == 'object') {
486                 if (typeof ev.target != 'undefined') {
487                     if (typeof ev.target.textContent != 'undefined') if (ev.target.textContent) text = ev.target.textContent;
488                     if (typeof ev.target.value != 'undefined') if (ev.target.value) text = ev.target.value;
489                 }
490             } else if (typeof ev == 'string') {
491                 text = ev;
492             }
493             const gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"]
494                 .getService(Components.interfaces.nsIClipboardHelper);
495             gClipboardHelper.copyString(text);
496             var Strings = $('offlineStrings') || $('commonStrings');
497             alert(Strings.getFormattedString('openils.global_util.clipboard', [text]));
498         } catch(E) {
499             var Strings = $('offlineStrings') || $('commonStrings');
500             alert(Strings.getFormattedString('openils.global_util.clipboard.error', [E]));    
501         }
502     }
503
504     function clear_the_cache() {
505         try {
506             netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
507             var cacheClass         = Components.classes["@mozilla.org/network/cache-service;1"];
508             var cacheService    = cacheClass.getService(Components.interfaces.nsICacheService);
509             cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
510             cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
511         } catch(E) {
512             var Strings = $('offlineStrings') || $('commonStrings');
513             alert(Strings.getFormattedString('openils.global_util.clear_cache.error', [E]));
514         }
515     }
516
517     function toOpenWindowByType(inType, uri) {
518         var winopts = "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar";
519         window.open(uri, "_blank", winopts);
520     }
521
522     function url_prefix(url) {
523         if (url.match(/^\//)) url = urls.remote + url;
524         if (! url.match(/^(http|chrome):\/\//) && ! url.match(/^data:/) ) url = 'http://' + url;
525         dump('url_prefix = ' + url + '\n');
526         return url;
527     }
528