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