]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/xul/staff_client/chrome/content/main/main.js
Allow staff to pick search/pref libraries
[working/Evergreen.git] / Open-ILS / xul / staff_client / chrome / content / main / main.js
1 dump('entering main/main.js\n');
2 // vim:noet:sw=4:ts=4:
3
4 var xulG;
5 var offlineStrings;
6 var authStrings;
7 var openTabs = new Array();
8 var tempWindow = null;
9 var tempFocusWindow = null;
10
11 function clear_the_cache() {
12     try {
13         var cacheClass         = Components.classes["@mozilla.org/network/cache-service;1"];
14         var cacheService    = cacheClass.getService(Components.interfaces.nsICacheService);
15         cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
16         cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
17     } catch(E) {
18         dump(E+'\n');alert(E);
19     }
20 }
21
22 function toOpenWindowByType(inType, uri) { /* for Venkman */
23     try {
24         var winopts = "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar";
25         window.open(uri, "_blank", winopts);
26     } catch(E) {
27         alert(E); throw(E);
28     }
29 }
30
31 function start_debugger() {
32     setTimeout(
33         function() {
34             try { start_venkman(); } catch(E) { alert(E); }
35         }, 0
36     );
37 };
38
39 function start_inspector() {
40     setTimeout(
41         function() {
42             try { inspectDOMDocument(); } catch(E) { alert(E); }
43         }, 0
44     );
45 };
46
47 function start_chrome_list() {
48     setTimeout(
49         function() {
50             try { startChromeList(); } catch(E) { alert(E); }
51         }, 0
52     );
53 };
54
55 function start_js_shell() {
56     setTimeout(
57         function() {
58             try { window.open('chrome://open_ils_staff_client/content/util/shell.html','shell','chrome,resizable,scrollbars'); } catch(E) { alert(E); }
59         }, 0
60     );
61 };
62
63 function new_tabs(aTabList, aContinue) {
64     if(aTabList != null) {
65         openTabs = openTabs.concat(aTabList);
66     }
67     if(G.data.session) { // Just add to the list of stuff to open unless we are logged in
68         var targetwindow = null;
69         var focuswindow = null;
70         var focustab = {'focus' : true};
71         if(aContinue == true && tempWindow.closed == false) {
72             if(tempWindow.g == undefined || tempWindow.g.menu == undefined) {
73                 setTimeout(
74                     function() {
75                         new_tabs(null, true);
76                     }, 300);
77                 return null;
78             }
79             targetwindow = tempWindow;
80             tempWindow = null;
81             focuswindow = tempFocusWindow;
82             tempFocusWindow = null;
83             focustab = {'nofocus' : true};
84         }
85         else if(tempWindow != null) { // In theory, we are waiting on a setTimeout
86             if(tempWindow.closed == true) // But someone closed our window?
87             {
88                 tempWindow = null;
89                 tempFocusWindow = null;
90             }
91             else
92             {
93                 return null;
94             }
95         }
96         var newTab;
97         var firstURL;
98         var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].
99             getService(Components.interfaces.nsIWindowMediator);
100             // This may look out of place, but this is so we can continue this loop from down below
101 opentabs:
102             while(openTabs.length > 0) {
103             newTab = openTabs.shift();
104             if(newTab == 'new' || newTab == 'init') {
105                 if(newTab != 'init' && openTabs.length > 0 && openTabs[0] != 'new') {
106                     firstURL = openTabs.shift();
107                     if(firstURL != 'tab') { // 'new' followed by 'tab' should be equal to 'init' in functionality, this should do that
108                         if(urls[firstURL]) {
109                             firstURL = urls[firstURL];
110                         }
111                         firstURL = '&firstURL=' + window.escape(firstURL);
112                     }
113                     else {
114                         firstURL = '';
115                     }
116                 }
117                 else {
118                     firstURL = '';
119                 }
120                 targetwindow = xulG.window.open(urls.XUL_MENU_FRAME
121                     + '?server='+window.escape(G.data.server) + firstURL,
122                     '_blank','chrome,resizable'
123                 );
124                 targetwindow.xulG = xulG;
125                 if (focuswindow == null) {
126                     focuswindow = targetwindow;
127                 }
128                 tempWindow = targetwindow;
129                 tempFocusWindow = focuswindow;
130                 setTimeout(
131                     function() {
132                         new_tabs(null, true);
133                     }, 300);
134                 return null;
135             }
136             else {
137                 if(newTab == 'tab') {
138                     newTab = null;
139                 }
140                 else if(urls[newTab]) {
141                     newTab = urls[newTab];
142                 }
143                 if(targetwindow != null) { // Already have a previous target window? Use it first.
144                     if(targetwindow.g.menu.new_tab(newTab,focustab,null)) {
145                         focustab = {'nofocus' : true};
146                         continue;
147                     }
148                 }
149                 var enumerator = wm.getEnumerator('eg_menu');
150                 while(enumerator.hasMoreElements()) {
151                     targetwindow = enumerator.getNext();
152                     if(targetwindow.g.menu.new_tab(newTab,focustab,null)) {
153                         focustab = {'nofocus' : true};
154                         if (focuswindow == null) {
155                             focuswindow = targetwindow;
156                         }
157                         continue opentabs;
158                     }
159                 }
160                 // No windows found to add the tab to? Make a new one.
161                 if(newTab == null) { // Were we making a "default" tab?
162                     openTabs.unshift('init'); // 'init' does that for us!
163                 }
164                 else {
165                     openTabs.unshift('new',newTab);
166                 }
167             }
168         }
169         if(focuswindow != null) {
170             focuswindow.focus();
171         }
172     }
173 }
174
175 // Returns false if we can't get an actual perm list
176 // Returns an array of perms with boolean has/hasn't flag
177 function get_menu_perms(indocument) {
178     // If we don't have our static perm list, and we have a remote window, go looking.
179     // We never need to look twice unless a dev is manually editing their files.
180     // Shame on them, they can restart the entire client ;)
181     if(typeof(get_menu_perms.perm_list) == 'undefined' && indocument != null)
182     {
183         get_menu_perms.perm_list = [ ];
184         var commands = indocument.getElementById('universal_cmds').getElementsByTagName('command');
185         for (var i = 0; i < commands.length; i++) { 
186             if (commands[i].hasAttribute('perm')) {
187                 get_menu_perms.perm_list = get_menu_perms.perm_list.concat(commands[i].getAttribute('perm').split(' '));
188             }           
189         }
190     }
191     // 
192     if(typeof(get_menu_perms.perm_list) == 'object') {
193         G.data.stash_retrieve();
194         if(!G.data.menu_perms) {
195             JSAN.use('util.network');
196             var network = new util.network();
197             var r = network.simple_request('BATCH_PERM_RETRIEVE_WORK_OU', [ G.data.session.key, get_menu_perms.perm_list ]);
198             for(p in r)
199                 r[p] = (typeof(r[p][0]) == 'number');
200             // Developer-enabled clients override permissions and always allow debugging
201             if(G.data.debug_build) {
202                 r['DEBUG_CLIENT'] = true;
203             }
204             // If we have DEBUG_CLIENT (by force or otherwise) we can use debugging interfaces
205             // Doing this here because this function gets called at least once per login
206             // Including operator change
207             G.data.enable_debug = (r['DEBUG_CLIENT'] == true);
208             G.data.stash('enable_debug');
209             G.data.menu_perms = r;
210             G.data.stash('menu_perms');
211         }
212         return G.data.menu_perms;
213     }
214     return false;
215 }
216
217 // Returns a list (cached or from filesystem) of hotkey sets
218 function load_hotkey_sets() {
219     if(typeof(load_hotkey_sets.set_list) == 'undefined') {
220         load_hotkey_sets.set_list = [];
221         // We can't safely use util.file here because extensions aren't unpacked in Firefox 4+
222         // So instead we will use and parse information from a chrome:// URL
223         var hotkeysBase = 'chrome://open_ils_staff_client/skin/hotkeys/';
224         var ioService=Components.classes["@mozilla.org/network/io-service;1"]
225             .getService(Components.interfaces.nsIIOService);
226         var scriptableStream=Components
227             .classes["@mozilla.org/scriptableinputstream;1"]
228             .getService(Components.interfaces.nsIScriptableInputStream);
229
230         var channel=ioService.newChannel(hotkeysBase,null,null);
231         var input=channel.open();
232         var str = '';
233         scriptableStream.init(input);
234         try {
235             while(input.available()) {
236                 str+=scriptableStream.read(input.available());
237             }
238         } catch (E) {}
239         scriptableStream.close();
240         input.close();
241         // str now, in theory, has a list of files (and metadata) for our base chrome URL.
242         str = str.replace(/^(?!201: ).*$/gm,''); // Remove non-filename result lines
243         str = str.replace(/^(?!.*\.keyset).*$/gm,''); // Remove non-keyset file result lines
244         str = str.replace(/^201: (.*)\.keyset.*$/gm, "$1"); // Reduce keyset matches to just base names
245         // Split into an array
246         var files = str.trim().split(/[\r\n]+/g);
247         for (var i = 0; i < files.length; i++) {
248             if(files[i].length = 0) continue;
249             load_hotkey_sets.set_list.push(files[i]);
250         }
251     }
252     return load_hotkey_sets.set_list;
253 }
254
255 // Returns an array (cached or from filesystem) for a given hotkey set
256 function get_hotkey_array(keyset_name) {
257     if(typeof(get_hotkey_array.keyset_cache) == 'undefined') {
258         get_hotkey_array.keyset_cache = {};
259     }
260     if(get_hotkey_array.keyset_cache[keyset_name])
261         return get_hotkey_array.keyset_cache[keyset_name];
262     // We can't safely use util.file here because extensions aren't unpacked in Firefox 4+
263     // So instead we will use and parse information from a chrome:// URL
264     var hotkeysBase = 'chrome://open_ils_staff_client/skin/hotkeys/' + keyset_name + '.keyset';
265     var ioService=Components.classes["@mozilla.org/network/io-service;1"]
266         .getService(Components.interfaces.nsIIOService);
267     var scriptableStream=Components
268         .classes["@mozilla.org/scriptableinputstream;1"]
269         .getService(Components.interfaces.nsIScriptableInputStream);
270
271     var channel=ioService.newChannel(hotkeysBase,null,null);
272     var input=channel.open();
273     var keyset_raw = '';
274     scriptableStream.init(input);
275     try {
276         while(input.available()) {
277             keyset_raw+=scriptableStream.read(input.available());
278         }
279     } catch (E) {}
280     scriptableStream.close();
281     input.close();
282
283     var tempArray = [];
284
285     var keyset_lines = keyset_raw.trim().split("\n");
286     for(var line = 0; line < keyset_lines.length; line++) {
287         // Grab line, strip comments, strip leading/trailing whitespace
288         var curline = keyset_lines[line].replace(/\s*#.*$/,'').trim();
289         if(curline == "") continue; // Skip empty lines
290         // Split into pieces
291         var split_line = curline.split(',');
292         // We need at least 3 elements. Command, modifiers, keycode.
293         if(split_line.length < 3) continue;
294         // Trim each segment
295         split_line[0] = split_line[0].trim();
296         split_line[1] = split_line[1].trim();
297         split_line[2] = split_line[2].trim();
298         if(split_line.length > 3)
299             split_line[3] = split_line[3].trim();
300         // Skip empty commands
301         if(split_line[0] == "") continue;
302         // Push to array
303         tempArray.push(split_line);
304     }
305     get_hotkey_array.keyset_cache[keyset_name] = tempArray;
306     return tempArray;
307 }
308
309 function main_init() {
310     dump('entering main_init()\n');
311     try {
312         clear_the_cache();
313         if("arguments" in window && window.arguments.length > 0 && window.arguments[0].wrappedJSObject != undefined && window.arguments[0].wrappedJSObject.openTabs != undefined) {
314             openTabs = openTabs.concat(window.arguments[0].wrappedJSObject.openTabs);
315         }
316
317         // Disable commands that we can't do anything with right now
318         if(typeof start_venkman != 'function') {
319             document.getElementById('cmd_debugger').setAttribute('disabled','true');
320         }
321         if(typeof inspectDOMDocument != 'function') {
322             document.getElementById('cmd_inspector').setAttribute('disabled','true');
323         }
324         if(typeof startChromeList != 'function') {
325             document.getElementById('cmd_chrome_list').setAttribute('disabled','true');
326         }
327
328         // Now we can safely load the strings without the cache getting wiped
329         offlineStrings = document.getElementById('offlineStrings');
330         authStrings = document.getElementById('authStrings');
331
332         if (typeof JSAN == 'undefined') {
333             throw(
334                 offlineStrings.getString('common.jsan.missing')
335             );
336         }
337         /////////////////////////////////////////////////////////////////////////////
338
339         JSAN.errorLevel = "die"; // none, warn, or die
340         JSAN.addRepository('..');
341
342         //JSAN.use('test.test'); test.test.hello_world();
343
344         var mw = self;
345         G =  {};
346         
347         G.pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
348         G.pref.QueryInterface(Components.interfaces.nsIPrefBranch2);
349
350         JSAN.use('util.error');
351         G.error = new util.error();
352         G.error.sdump('D_ERROR', offlineStrings.getString('main.testing'));
353
354         JSAN.use('util.window');
355         G.window = new util.window();
356
357         JSAN.use('auth.controller');
358         G.auth = new auth.controller( { 'window' : mw } );
359
360         JSAN.use('OpenILS.data');
361         G.data = new OpenILS.data();
362         G.data.on_error = G.auth.logoff;
363
364         JSAN.use('util.file');
365         G.file = new util.file();
366         try {
367             G.file.get('ws_info');
368             G.ws_info = G.file.get_object(); G.file.close();
369         } catch(E) {
370             G.ws_info = {};
371         }
372         G.data.ws_info = G.ws_info; G.data.stash('ws_info');
373
374         G.auth.on_login = function() {
375
376             var url = G.auth.controller.view.server_prompt.value.match(/^[^\/]*/).toString() || urls.remote;
377
378             G.data.server_unadorned = url; G.data.stash('server_unadorned'); G.data.stash_retrieve();
379             try {
380                 G.data.search_lib = G.pref.getIntPref('open-ils.' + url + '.search_lib');
381                 G.data.pref_lib = G.pref.getIntPref('open-ils.' + url + '.pref_lib');
382             } catch(E) {
383                 G.data.search_lib = null;
384                 G.data.pref_lib = null;
385             }
386             G.data.stash('search_lib');
387             G.data.stash('pref_lib');
388
389             if (! url.match( '^(http|https)://' ) ) { url = 'http://' + url; }
390
391             G.data.server = url; G.data.stash('server'); 
392             G.data.session = { 'key' : G.auth.session.key, 'auth' : G.auth.session.authtime }; G.data.stash('session');
393             G.data.stash_retrieve();
394             try {
395                 var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
396                 var cookieUriSSL = ios.newURI("https://" + G.data.server_unadorned, null, null);
397                 var cookieSvc = Components.classes["@mozilla.org/cookieService;1"].getService(Components.interfaces.nsICookieService);
398
399                 cookieSvc.setCookieString(cookieUriSSL, null, "ses="+G.data.session.key + "; secure;", null);
400
401             } catch(E) {
402                 alert(offlineStrings.getFormattedString(main.session_cookie.error, [E]));
403             }
404
405             xulG = {
406                 'auth' : G.auth,
407                 'url' : url,
408                 'window' : G.window,
409                 'data' : G.data,
410                 'pref' : G.pref
411             };
412
413             if (G.data.ws_info && G.data.ws_info[G.auth.controller.view.server_prompt.value]) {
414                 JSAN.use('util.widgets');
415                 var deck = document.getElementById('progress_space');
416                 util.widgets.remove_children( deck );
417                 var iframe = document.createElement('iframe'); deck.appendChild(iframe);
418                 iframe.setAttribute( 'src', urls.XUL_LOGIN_DATA );
419                 iframe.contentWindow.xulG = xulG;
420                 G.data_xul = iframe.contentWindow;
421             } else {
422                 xulG.file = G.file;
423                 var deck = G.auth.controller.view.ws_deck;
424                 JSAN.use('util.widgets'); util.widgets.remove_children('ws_deck');
425                 var iframe = document.createElement('iframe'); deck.appendChild(iframe);
426                 iframe.setAttribute( 'src', urls.XUL_WORKSTATION_INFO );
427                 iframe.contentWindow.xulG = xulG;
428                 deck.selectedIndex = deck.childNodes.length - 1;
429             }
430         };
431
432         G.auth.on_standalone = function() {
433             try {
434                 G.window.open(urls.XUL_STANDALONE,'Offline','chrome,resizable');
435             } catch(E) {
436                 alert(E);
437             }
438         };
439
440         G.auth.on_standalone_export = function() {
441             try {
442                 JSAN.use('util.file'); var file = new util.file('pending_xacts');
443                 if (file._file.exists()) {
444                     var file2 = new util.file('');
445                     var f = file2.pick_file( { 'mode' : 'save', 'title' : offlineStrings.getString('main.transaction_export.title') } );
446                     if (f) {
447                         if (f.exists()) {
448                             var r = G.error.yns_alert(
449                                 offlineStrings.getFormattedString('main.transaction_export.prompt', [f.leafName]),
450                                 offlineStrings.getString('main.transaction_export.prompt.title'),
451                                 offlineStrings.getString('common.yes'),
452                                 offlineStrings.getString('common.no'),
453                                 null,
454                                 offlineStrings.getString('common.confirm')
455                             );
456                             if (r != 0) { file.close(); return; }
457                         }
458                         var e_file = new util.file(''); e_file._file = f;
459                         e_file.write_content( 'truncate', file.get_content() );
460                         e_file.close();
461                         var r = G.error.yns_alert(
462                             offlineStrings.getFormattedString('main.transaction_export.success.prompt', [f.leafName]),
463                             offlineStrings.getString('main.transaction_export.success.title'),
464                             offlineStrings.getString('common.yes'),
465                             offlineStrings.getString('common.no'),
466                             null,
467                             offlineStrings.getString('common.confirm')
468                         );
469                         if (r == 0) {
470                             var count = 0;
471                             var filename = 'pending_xacts_exported_' + new Date().getTime();
472                             var t_file = new util.file(filename);
473                             while (t_file._file.exists()) {
474                                 filename = 'pending_xacts_' + new Date().getTime() + '.exported';
475                                 t_file = new util.file(filename);
476                                 if (count++ > 100) {
477                                     throw(offlineStrings.getString('main.transaction_export.filename.error'));
478                                 }
479                             }
480                             file.close(); file = new util.file('pending_xacts'); // prevents a bug with .moveTo below
481                             file._file.moveTo(null,filename);
482                         } else {
483                             alert(offlineStrings.getString('main.transaction_export.duplicate.warning'));
484                         }
485                     } else {
486                         alert(offlineStrings.getString('main.transaction_export.no_filename.error'));
487                     }
488                 } else {
489                     alert(offlineStrings.getString('main.transaction_export.no_transactions.error'));
490                 }
491                 file.close();
492             } catch(E) {
493                 alert(E);
494             }
495         };
496
497         G.auth.on_standalone_import = function() {
498             try {
499                 JSAN.use('util.file'); var file = new util.file('pending_xacts');
500                 if (file._file.exists()) {
501                     alert(offlineStrings.getString('main.transaction_import.outstanding.error'));
502                 } else {
503                     var file2 = new util.file('');
504                     var f = file2.pick_file( { 'mode' : 'open', 'title' : offlineStrings.getString('main.transaction_import.title')} );
505                     if (f && f.exists()) {
506                         var i_file = new util.file(''); i_file._file = f;
507                         file.write_content( 'truncate', i_file.get_content() );
508                         i_file.close();
509                         var r = G.error.yns_alert(
510                             offlineStrings.getFormattedString('main.transaction_import.delete.prompt', [f.leafName]),
511                             offlineStrings.getString('main.transaction_import.success'),
512                             offlineStrings.getString('common.yes'),
513                             offlineStrings.getString('common.no'),
514                             null,
515                             offlineStrings.getString('common.confirm')
516                         );
517                         if (r == 0) {
518                             f.remove(false);
519                         }
520                     }
521                 }
522                 file.close();
523             } catch(E) {
524                 alert(E);
525             }
526         };
527
528         G.auth.on_debug = function(action) {
529             switch(action) {
530                 case 'js_console' :
531                     G.window.open(urls.XUL_DEBUG_CONSOLE,'testconsole','chrome,resizable');
532                 break;
533                 case 'clear_cache' :
534                     clear_the_cache();
535                     alert(offlineStrings.getString('main.on_debug.clear_cache'));
536                 break;
537                 default:
538                     alert(offlineStrings.getString('main.on_debug.debug'));
539                 break;
540             }
541         };
542
543         G.auth.init();
544         // XML_HTTP_SERVER will get reset to G.auth.controller.view.server_prompt.value
545
546         /////////////////////////////////////////////////////////////////////////////
547
548         var version = CLIENT_VERSION;
549         if (CLIENT_STAMP.length == 0) {
550             version = 'versionless debug build';
551             document.getElementById('debug_gb').hidden = false;
552         }
553
554         try {
555             if (G.pref && G.pref.getBoolPref('open-ils.debug_options')) {
556                 document.getElementById('debug_gb').hidden = false;
557             }
558         } catch(E) {
559         }
560
561         // If we are showing the debugging frame then we consider this a debug build
562         // This could be a versionless build, a developer-pref enabled build, or otherwise
563         // If set this will enable all debugging commands, even if you normally don't have permission to use them
564         G.data.debug_build = !document.getElementById('debug_gb').hidden;
565         G.data.stash('debug_build');
566
567         var appInfo = Components.classes["@mozilla.org/xre/app-info;1"] 
568             .getService(Components.interfaces.nsIXULAppInfo); 
569
570         if (appInfo.ID == "staff-client@open-ils.org")
571         {
572             try {
573                 if (G.pref && G.pref.getBoolPref('app.update.enabled')) {
574                     document.getElementById('check_upgrade_sep').hidden = false;
575                     var upgrademenu = document.getElementById('check_upgrade');
576                     upgrademenu.hidden = false;
577                     G.upgradeCheck = function () {
578                         var um = Components.classes["@mozilla.org/updates/update-manager;1"]
579                             .getService(Components.interfaces.nsIUpdateManager);
580                         var prompter = Components.classes["@mozilla.org/updates/update-prompt;1"]
581                             .createInstance(Components.interfaces.nsIUpdatePrompt);
582
583                         if (um.activeUpdate && um.activeUpdate.state == "pending")
584                             prompter.showUpdateDownloaded(um.activeUpdate);
585                         else
586                             prompter.checkForUpdates();
587                     }
588                     upgrademenu.addEventListener(
589                         'command',
590                         G.upgradeCheck,
591                         false
592                     );
593                 }
594             } catch(E) {
595             }
596         }
597
598         window.document.title = authStrings.getFormattedString('staff.auth.titlebar.label', CLIENT_VERSION);
599         var x = document.getElementById('about_btn');
600         x.addEventListener(
601             'command',
602             function() {
603                 try { 
604                     G.window.open('about.html','about','chrome,resizable,width=800,height=600');
605                 } catch(E) { alert(E); }
606             }, 
607             false
608         );
609
610         var y = document.getElementById('new_window_btn');
611         y.addEventListener(
612             'command',
613             function() {
614                 if (G.data.session) {
615                     new_tabs(Array('new'), null, null);
616                 } else {
617                     alert ( offlineStrings.getString('main.new_window_btn.login_first_warning') );
618                 }
619             },
620             false
621         );
622
623         JSAN.use('util.mozilla');
624         var z = document.getElementById('locale_menupopup');
625         if (z) {
626             while (z.lastChild) z.removeChild(z.lastChild);
627             var locales = util.mozilla.chromeRegistry().getLocalesForPackage( String( location.href ).split(/\//)[2] );
628             var current_locale = util.mozilla.prefs().getCharPref('general.useragent.locale');
629             while (locales.hasMore()) {
630                 var locale = locales.getNext();
631                 var parts = locale.split(/-/);
632                 var label;
633                 try {
634                     label = locale + ' : ' + util.mozilla.languages().GetStringFromName(parts[0]);
635                     if (parts.length > 1) {
636                         try {
637                             label += ' (' + util.mozilla.regions().GetStringFromName(parts[1].toLowerCase()) + ')';
638                         } catch(E) {
639                             label += ' (' + parts[1] + ')';
640                         }
641                     }
642                 } catch(E) {
643                     label = locale;
644                 }
645                 var mi = document.createElement('menuitem');
646                 mi.setAttribute('label',label);
647                 mi.setAttribute('value',locale);
648                 if (locale == current_locale) {
649                     if (z.parentNode.tagName == 'menulist') {
650                         mi.setAttribute('selected','true');
651                         z.parentNode.setAttribute('label',label);
652                         z.parentNode.setAttribute('value',locale);
653                     }
654                 }
655                 z.appendChild( mi );
656             }
657         }
658         var xx = document.getElementById('apply_locale_btn');
659         xx.addEventListener(
660             'command',
661             function() {
662                 util.mozilla.change_locale(z.parentNode.value);
663             },
664             false
665         );
666
667         if ( found_ws_info_in_Achrome() && G.pref && G.pref.getBoolPref("open-ils.write_in_user_chrome_directory") ) {
668             //var hbox = x.parentNode; var b = document.createElement('button'); 
669             //b.setAttribute('label','Migrate legacy settings'); hbox.appendChild(b);
670             //b.addEventListener(
671             //    'command',
672             //    function() {
673             //        try {
674             //            handle_migration();
675             //        } catch(E) { alert(E); }
676             //    },
677             //    false
678             //);
679             if (window.confirm(offlineStrings.getString('main.settings.migrate'))) {
680                 setTimeout( function() { handle_migration(); }, 0 );
681             }
682         }
683
684         window.addEventListener(
685             'close',
686             function(ev) {
687
688                 G.data.stash_retrieve();
689                 if (typeof G.data.unsaved_data != 'undefined') {
690                     if (G.data.unsaved_data > 0) {
691                         var confirmation = window.confirm(offlineStrings.getString('menu.shutdown.unsaved_data_warning'));
692                         if (!confirmation) {
693                             ev.preventDefault();
694                             return false;
695                         }
696                     }
697                 }
698                 G.data.unsaved_data = 0;
699                 G.data.stash('unsaved_data');
700
701                 return true;
702
703             },
704             false
705         );
706
707         /**
708             @brief Stats for Offline Files / Transactions
709             @launchpad #797408
710         */
711         var px = new util.file('pending_xacts');
712         document.getElementById('offline_message').setAttribute('style','display:none;');
713         if (px._file.exists()) {
714             document.getElementById('offline_message').setAttribute('style','background-color:red;display:block;font-weight:bold;padding:2px;');
715             document.getElementById('offline_import_btn').disabled = true;
716         }
717
718         // Attempt auto-login, if provided
719         if("arguments" in window && window.arguments.length > 0 && window.arguments[0].wrappedJSObject != undefined && window.arguments[0].wrappedJSObject.loginInfo != undefined) {
720             auto_login(window.arguments[0].wrappedJSObject.loginInfo);
721             // Regardless of success, clear that variable now, so we don't possibly have passwords hanging around.
722             window.arguments[0].wrappedJSObject.loginInfo = null;
723         }
724
725     } catch(E) {
726         var error = offlineStrings.getFormattedString('common.exception', [E, '']);
727         try { G.error.sdump('D_ERROR',error); } catch(E) { dump(error); }
728         alert(error);
729     }
730     dump('exiting main_init()\n');
731 }
732
733 function found_ws_info_in_Achrome() {
734     JSAN.use('util.file');
735     var f = new util.file();
736     var f_in_chrome = f.get('ws_info','chrome');
737     var path = f_in_chrome.exists() ? f_in_chrome.path : false;
738     f.close();
739     return path;
740 }
741
742 function found_ws_info_in_Uchrome() {
743     JSAN.use('util.file');
744     var f = new util.file();
745     var f_in_uchrome = f.get('ws_info','uchrome');
746     var path = f_in_uchrome.exists() ? f_in_uchrome.path : false;
747     f.close();
748     return path;
749 }
750
751 function handle_migration() {
752     if ( found_ws_info_in_Uchrome() ) {
753         alert(offlineStrings.getFormattedString('main.settings.migrate.failed', [found_ws_info_in_Uchrome(), found_ws_info_in_Achrome()])
754         );
755     } else {
756         var dirService = Components.classes["@mozilla.org/file/directory_service;1"].getService( Components.interfaces.nsIProperties );
757         var f_new = dirService.get( "UChrm", Components.interfaces.nsIFile );
758         var f_old = dirService.get( "AChrom", Components.interfaces.nsIFile );
759         f_old.append(myPackageDir); f_old.append("content"); f_old.append("conf"); 
760         if (window.confirm(offlineStrings.getFormattedString("main.settings.migrate.confirm", [f_old.path, f_new.path]))) {
761             var files = f_old.directoryEntries;
762             while (files.hasMoreElements()) {
763                 var file = files.getNext();
764                 var file2 = file.QueryInterface( Components.interfaces.nsILocalFile );
765                 try {
766                     file2.moveTo( f_new, '' );
767                 } catch(E) {
768                     alert(offlineStrings.getFormattedString('main.settings.migrate.error', [file2.path, f_new.path]) + '\n');
769                 }
770             }
771             location.href = location.href; // huh?
772         }
773     }
774 }
775
776 function auto_login(loginInfo) {
777     G.data.stash_retrieve();
778     if(G.data.session) return; // We are logged in. No auto-logoff supported.
779     if(loginInfo.host) G.auth.controller.view.server_prompt.value = loginInfo.host;
780     if(loginInfo.user) G.auth.controller.view.name_prompt.value = loginInfo.user;
781     if(loginInfo.passwd) G.auth.controller.view.password_prompt.value = loginInfo.passwd;
782     if(loginInfo.host && loginInfo.user && loginInfo.passwd && G.data.ws_info && G.data.ws_info[loginInfo.host]) {
783         G.auth.login();
784     }
785 }
786
787 dump('exiting main/main.js\n');