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