]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/xul/staff_client/server/cat/marcedit.js
8359afcef0412a1e433969b0c70c9cc8004f8760
[working/Evergreen.git] / Open-ILS / xul / staff_client / server / cat / marcedit.js
1 /* vim: et:sw=4:ts=4:
2  *
3  * Copyright (C) 2004-2008  Georgia Public Library Service
4  * Copyright (C) 2008-2010  Equinox Software, Inc.
5  * Mike Rylander <miker@esilibrary.com> 
6  *
7  * Copyright (C) 2010 Dan Scott <dan@coffeecode.net>
8  * Copyright (C) 2010 Internationaal Instituut voor Sociale Geschiedenis <info@iisg.nl>
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.  
19  *
20  */
21 // Pretty printing kills whitespace too, so disable it.
22 XML.prettyPrinting = false;
23 var xmlDeclaration = /^<\?xml version[^>]+?>/;
24
25 var serializer = new XMLSerializer();
26 var marcns = new Namespace("http://www.loc.gov/MARC21/slim");
27 var gw = new Namespace("http://opensrf.org/-/namespaces/gateway/v1");
28 var xulns = new Namespace("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
29 default xml namespace = marcns;
30
31 var tooltip_hash = {};
32 var current_focus;
33 var _record;
34 var _record_type;
35 var bib_data;
36
37 var xml_record;
38
39 var context_menus;
40 var tag_menu;
41 var p;
42 var auth_pages = {};
43 var show_auth_menu = false;
44
45 var _fixed_field_values = {}, _fixed_field_context_menus = {};
46 var _fixed_field_anonymous_func_counter = 0;
47
48 function $(id) { return document.getElementById(id); }
49
50 var acs; // AuthorityControlSet
51
52 function get_new_008() {
53     var orig008 = '                                        ';
54     var now = new Date();
55     var y = now.getUTCFullYear().toString().substr(2,2);
56     var m = now.getUTCMonth() + 1;
57     if (m < 10) m = '0' + m;
58     var d = now.getUTCDate();
59     if (d < 10) d = '0' + d;
60
61     if (xml_record.controlfield.(@tag == '008')) {
62         var field = xml_record.controlfield.(@tag == '008')[0];
63         orig008 = field.text();
64     }
65
66     /* lang code from 041a */
67     var lang = orig008.substr(35, 3);
68     if (xml_record.datafield.(@tag == '041')) {
69         var field = xml_record.datafield.(@tag == '041')[0];
70         if (field && field.subfield.(@code == 'a')) {
71             lang = field.subfield.(@code == 'a')[0];
72         }
73     }
74
75     /* country code from 044a */
76     var country = orig008.substr(15, 3);
77     if (xml_record.datafield.(@tag == '044')) {
78         var field = xml_record.datafield.(@tag == '044')[0];
79         if (field && field.subfield.(@code == 'a')) {
80             country = field.subfield.(@code == 'a')[0];
81         }
82     }
83     while (country.length < 3) country = country + ' ';
84     if (country.length > 3) country = country.substr(0,3);
85
86     /* date1 from 260c */
87     var date1 = now.getUTCFullYear().toString();
88     if (xml_record.datafield.(@tag == '260')) {
89         var field = xml_record.datafield.(@tag == '260')[0];
90         if (field && field.subfield.(@code == 'c')) {
91             var tmpd = field.subfield.(@code == 'c')[0].replace(/[^0-9]/g, '');
92             if (tmpd.match(/^\d\d\d\d/)) {
93                 date1 = tmpd.substr(0, 4);
94             }
95         }
96     }
97
98     var date2 = orig008.substr(11, 4);
99     var datetype = orig008.substr(6, 1);
100     var modded = orig008.substr(38, 1);
101     var catsrc = orig008.substr(39, 1);
102
103     return '' + y + m + d + datetype + date1 + date2 + country + '                 ' + lang + modded + catsrc;
104
105 }
106
107 function mangle_005() {
108     var now = new Date();
109     var y = now.getUTCFullYear();
110
111     var m = now.getUTCMonth() + 1;
112     if (m < 10) m = '0' + m;
113     
114     var d = now.getUTCDate();
115     if (d < 10) d = '0' + d;
116     
117     var H = now.getUTCHours();
118     if (H < 10) H = '0' + H;
119     
120     var M = now.getUTCMinutes();
121     if (M < 10) M = '0' + M;
122     
123     var S = now.getUTCSeconds();
124     if (S < 10) S = '0' + S;
125     
126
127     var stamp = '' + y + m + d + H + M + S + '.0';
128     createControlField('005',stamp);
129
130 }
131
132 function createControlField (tag,data) {
133     // first, remove the old field, if any;
134     for (var i in xml_record.controlfield.(@tag == tag)) delete xml_record.controlfield.(@tag == tag)[i];
135
136     var cf = <controlfield tag="" xmlns="http://www.loc.gov/MARC21/slim">{ data }</controlfield>;
137     cf.@tag = tag;
138
139     // then, find the right position and insert it
140     var done = 0;
141     var cfields = xml_record.controlfield;
142     var base = Number(tag.substring(2));
143     for (var i in cfields) {
144         var t = Number(cfields[i].@tag.toString().substring(2));
145         if (t > base) {
146             xml_record.insertChildBefore( cfields[i], cf );
147             done = 1
148             break;
149         }
150     }
151
152     if (!done) xml_record.insertChildBefore( xml_record.datafield[0], cf );
153
154     return cf;
155 }
156
157 function xml_escape_unicode ( str ) {
158     return str.replace(
159         /([\u0080-\ufffe])/g,
160         function (r,s) { return "&#x" + s.charCodeAt(0).toString(16) + ";"; }
161     );
162 }
163
164 function wrap_long_fields (node) {
165     var text_size = dojo.attr(node, 'size');
166     var hard_width = 100; 
167     if (text_size > hard_width) {
168         dojo.attr(node, 'multiline', 'true');
169         dojo.attr(node, 'cols', hard_width);
170         var text_rows = (text_size / hard_width) + 1;
171         dojo.attr(node, 'rows', text_rows);
172     }
173 }
174
175 function set_flat_editor (useFlatText) {
176
177     var xe = $('xul-editor');
178     var te = $('text-editor');
179
180     if (useFlatText) {
181         if (xe.hidden) { return; }
182         te.hidden = false;
183         xe.hidden = true;
184     } else {
185         if (te.hidden) { return; }
186         te.hidden = true;
187         xe.hidden = false;
188     }
189
190     if (te.hidden) {
191         // get the marcxml from the text box
192         var xml_string = new MARC.Record({
193             marcbreaker : $('text-editor-box').value,
194             delimiter : '$'
195         }).toXmlString();
196
197         // reset the xml record and rerender it
198         xml_record = new XML( xml_string );
199         if (xml_record..record[0]) xml_record = xml_record..record[0];
200         loadRecord();
201     } else {
202         var xml_string = xml_record.toXMLString();
203
204         // push the xml record into the textbox
205         var rec = new MARC.Record ({ delimiter : '$', marcxml : xml_string });
206         $('text-editor-box').value = rec.toBreaker();
207     }
208 }
209
210 function my_init() {
211     try {
212
213         if (typeof JSAN == 'undefined') { throw( $("commonStrings").getString('common.jsan.missing') ); }
214         JSAN.errorLevel = "die"; // none, warn, or die
215         JSAN.addRepository('/xul/server/');
216
217         dojo.require('openils.AuthorityControlSet');
218         acs = new openils.AuthorityControlSet ();
219
220         // Fake xulG for standalone...
221         try {
222             window.xulG.record;
223         } catch (e) {
224             window.xulG = {};
225             window.xulG.record = {};
226             window.xulG.save = {};
227             window.xulG.marc_control_number_identifier = 'CONS';
228
229             window.xulG.save.label = $('catStrings').getString('staff.cat.marcedit.save.label');
230             window.xulG.save.func = function (r) { alert(r); }
231
232             var cgi = new CGI();
233             var _rid = cgi.param('record');
234             if (_rid) {
235                 window.xulG.record.id = _rid;
236                 window.xulG.record.url = '/opac/extras/supercat/retrieve/marcxml/record/' + _rid;
237             }
238         }
239
240         // End faking part...
241
242         /* Check for an explicitly passed record type
243          * This is not the same as the fixed-field record type; we can't trust
244          * the fixed fields when making modifications to the attributes for a
245          * given record (in particular, config.bib_source only applies for bib
246          * records, but an auth or MFHD record with the same ID and bad fixed
247          * fields could trample the config.bib_source value for the
248          * corresponding bib record if we're not careful.
249          *
250          * are = authority record
251          * sre = serial record (MFHD)
252          * bre = bibliographic record
253          */
254         if (!window.xulG.record.rtype) {
255             var cgi = new CGI();
256             window.xulG.record.rtype = cgi.param('rtype') || false;
257         }
258
259         document.getElementById('save-button').setAttribute('label', window.xulG.save.label);
260         /* Ugh. Sorry about the spaghetti. */
261         document.getElementById('save-button').setAttribute('oncommand',
262             'var to_save = function() { ' + /* begin to_save() */
263             'if ($("xul-editor").hidden) set_flat_editor(false); ' +
264             'mangle_005(); ' + 
265             'var xml_string = xml_escape_unicode( xml_record.toXMLString() ); ' + 
266             'save_attempt( xml_string ); ' +
267             'loadRecord(); ' +
268             '}; ' + /* end to_save() */
269
270             'if (typeof _owPCW == "object") { ' +
271             ' for (var k in _owPCW) { ' +
272             '  if (_owPCW[k].active) { ' +
273             '    try { _owPCW[k].apply(to_save); to_save.ran = true; } ' +
274             '    catch (E) { alert("_ow_PCW[" + k + "]: " + E); } ' +
275             '    break; ' +
276             '  }' +
277             ' }' +
278             '} ' +
279             'if (!to_save.ran) to_save();'
280         );
281
282         if (window.xulG.record.url) {
283             var req =  new XMLHttpRequest();
284             req.open('POST',window.xulG.record.url,false);
285             req.send(null);
286             window.xulG.record.marc = req.responseText.replace(xmlDeclaration, '');
287         }
288
289         xml_record = new XML( window.xulG.record.marc );
290         if (xml_record..record[0]) xml_record = xml_record..record[0];
291
292         // Get the tooltip xml all async like
293         req =  new XMLHttpRequest();
294
295         // Set a default locale in case preferences fail us
296         var locale = "en-US";
297
298         // Try to get the locale from our preferences
299         try {
300             const Cc = Components.classes;
301             const Ci = Components.interfaces;
302             locale = Cc["@mozilla.org/preferences-service;1"].
303                 getService(Ci.nsIPrefBranch).
304                 getCharPref("general.useragent.locale");
305         }
306         catch (e) { }
307
308         // TODO: We should send a HEAD request to check for the existence of the desired file
309         // then fall back to the default locale if preferred locale is not necessary;
310         // however, for now we have a simplistic check:
311         //
312         // we currently have translations for only three locales; in the absence of a
313         // valid locale, default to the almighty en-US
314         if (locale != 'en-US' && locale != 'fr-CA' && locale != 'fi-FI') {
315             locale = 'en-US';
316         }
317
318         // grab the right tooltip based on MARC type
319         var tooltip_doc = 'marcedit-tooltips.xml';
320         switch (window.xulG.record.rtype) {
321             case 'bre':
322                 tooltip_doc = 'marcedit-tooltips.xml';
323                 break; 
324             case 'are':
325                 tooltip_doc = 'marcedit-tooltips-authority.xml';
326                 locale = 'en-US'; // FIXME - note TODO above; at moment only en-US has this
327                 break; 
328             case 'sre':
329                 tooltip_doc = 'marcedit-tooltips-mfhd.xml';
330                 locale = 'en-US'; // FIXME - note TODO above; at moment only en-US has this
331                 break; 
332             default: 
333                 tooltip_doc = 'marcedit-tooltips.xml';
334         }
335
336         // Get the locale-specific tooltips
337         req.open('GET','/xul/server/locale/' + locale + '/' + tooltip_doc,true);
338
339         context_menus = createComplexXULElement('popupset');
340         document.documentElement.appendChild( context_menus );
341
342         tag_menu = createMenuPopup({position : 'after_start', id : 'tags_popup'});
343         context_menus.appendChild( tag_menu );
344
345         tag_menu.appendChild(
346             createMenuitem(
347                 { label : $('catStrings').getString('staff.cat.marcedit.add_row.label'),
348                   oncommand : 
349                     'var e = document.createEvent("KeyEvents");' +
350                     'e.initKeyEvent("keypress",1,1,null,1,0,0,0,13,0);' +
351                     'current_focus.inputField.dispatchEvent(e);'
352                  }
353             )
354         );
355
356         tag_menu.appendChild(
357             createMenuitem(
358                 { label : $('catStrings').getString('staff.cat.marcedit.insert_row.label'),
359                   oncommand : 
360                     'var e = document.createEvent("KeyEvents");' +
361                     'e.initKeyEvent("keypress",1,1,null,1,0,1,0,13,0);' +
362                     'current_focus.inputField.dispatchEvent(e);'
363                  }
364             )
365         );
366
367         tag_menu.appendChild(
368             createMenuitem(
369                 { label : $('catStrings').getString('staff.cat.marcedit.remove_row.label'),
370                   oncommand : 
371                     'var e = document.createEvent("KeyEvents");' +
372                     'e.initKeyEvent("keypress",1,1,null,1,0,0,0,46,0);' +
373                     'current_focus.inputField.dispatchEvent(e);'
374                 }
375             )
376         );
377
378         tag_menu.appendChild( createComplexXULElement( 'separator' ) );
379
380         tag_menu.appendChild(
381             createMenuitem(
382                 { label : $('catStrings').getString('staff.cat.marcedit.replace_006.label'),
383                   oncommand : 
384                     'var e = document.createEvent("KeyEvents");' +
385                     'e.initKeyEvent("keypress",1,1,null,1,0,0,0,117,0);' +
386                     'current_focus.inputField.dispatchEvent(e);'
387                  }
388             )
389         );
390
391         tag_menu.appendChild(
392             createMenuitem(
393                 { label : $('catStrings').getString('staff.cat.marcedit.replace_007.label'),
394                   oncommand : 
395                     'var e = document.createEvent("KeyEvents");' +
396                     'e.initKeyEvent("keypress",1,1,null,1,0,0,0,118,0);' +
397                     'current_focus.inputField.dispatchEvent(e);'
398                 }
399             )
400         );
401
402         tag_menu.appendChild(
403             createMenuitem(
404                 { label : $('catStrings').getString('staff.cat.marcedit.replace_008.label'),
405                   oncommand : 
406                     'var e = document.createEvent("KeyEvents");' +
407                     'e.initKeyEvent("keypress",1,1,null,1,0,0,0,119,0);' +
408                     'current_focus.inputField.dispatchEvent(e);'
409                 }
410             )
411         );
412
413         tag_menu.appendChild( createComplexXULElement( 'separator' ) );
414
415         p = createComplexXULElement('popupset');
416         document.documentElement.appendChild( p );
417
418         req.onreadystatechange = function () {
419             if (req.readyState == 4) {
420                 bib_data = new XML( req.responseText.replace(xmlDeclaration, '') );
421                 genToolTips();
422             }
423         }
424         req.send(null);
425
426         loadRecord();
427
428
429         if (! xulG.fast_add_item) {
430             document.getElementById('fastItemAdd_checkbox').hidden = true;
431         }
432         document.getElementById('fastItemAdd_textboxes').hidden = document.getElementById('fastItemAdd_checkbox').hidden || !document.getElementById('fastItemAdd_checkbox').checked;
433
434         // Only show bib sources for bib records that already exist in the database
435         if (xulG.record.rtype == 'bre' && xulG.record.id) {
436             dojo.require('openils.PermaCrud');
437             var authtoken = ses();
438             // Retrieve the current record attributes
439             var bib = new openils.PermaCrud({"authtoken": authtoken}).retrieve('bre', xulG.record.id);
440
441             // Remember the current bib source of the record
442             xulG.record.bre = bib;
443
444             buildBibSourceList(authtoken, xulG.record.id);
445         }
446
447         preparePhysCharWizardContext();
448         dojo.require('MARC.FixedFields');
449         dojo.require("openils.widget.PhysCharWizard");
450
451     } catch(E) {
452         alert('FIXME, MARC Editor, my_init: ' + E);
453     }
454 }
455
456
457 function createComplexHTMLElement (e, attrs, objects, text) {
458     var l = document.createElementNS('http://www.w3.org/1999/xhtml',e);
459
460     if (attrs) {
461         for (var i in attrs) l.setAttribute(i,attrs[i]);
462     }
463
464     if (objects) {
465         for ( var i in objects ) l.appendChild( objects[i] );
466     }
467
468     if (text) {
469         l.appendChild( document.createTextNode(text) )
470     }
471
472     return l;
473 }
474
475 function createComplexXULElement (e, attrs, objects) {
476     var l = document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul',e);
477
478     if (attrs) {
479         for (var i in attrs) {
480             if (typeof attrs[i] == 'function') {
481                 l.addEventListener( i, attrs[i], true );
482             } else {
483                 l.setAttribute(i,attrs[i]);
484             }
485         }
486     } 
487
488     if (objects) {
489         for ( var i in objects ) l.appendChild( objects[i] );
490     }
491
492     return l;
493 }
494
495 function createDescription (attrs) {
496     return createComplexXULElement('description', attrs, Array.prototype.slice.apply(arguments, [1]) );
497 }
498
499 function createTooltip (attrs) {
500     return createComplexXULElement('tooltip', attrs, Array.prototype.slice.apply(arguments, [1]) );
501 }
502
503 function createLabel (attrs) {
504     return createComplexXULElement('label', attrs, Array.prototype.slice.apply(arguments, [1]) );
505 }
506
507 function createVbox (attrs) {
508     return createComplexXULElement('vbox', attrs, Array.prototype.slice.apply(arguments, [1]) );
509 }
510
511 function createHbox (attrs) {
512     return createComplexXULElement('hbox', attrs, Array.prototype.slice.apply(arguments, [1]) );
513 }
514
515 function createRow (attrs) {
516     return createComplexXULElement('row', attrs, Array.prototype.slice.apply(arguments, [1]) );
517 }
518
519 function createTextbox (attrs) {
520     return createComplexXULElement('textbox', attrs, Array.prototype.slice.apply(arguments, [1]) );
521 }
522
523 function createMenu (attrs) {
524     return createComplexXULElement('menu', attrs, Array.prototype.slice.apply(arguments, [1]) );
525 }
526
527 function createMenuPopup (attrs) {
528     return createComplexXULElement('menupopup', attrs, Array.prototype.slice.apply(arguments, [1]) );
529 }
530
531 function createPopup (attrs) {
532     return createComplexXULElement('popup', attrs, Array.prototype.slice.apply(arguments, [1]) );
533 }
534
535 function createMenuitem (attrs) {
536     return createComplexXULElement('menuitem', attrs, Array.prototype.slice.apply(arguments, [1]) );
537 }
538
539 function createCheckbox (attrs) {
540     return createComplexXULElement('checkbox', attrs, Array.prototype.slice.apply(arguments, [1]) );
541 }
542
543 // Find the next textbox that we can use for a focus point
544 // For control fields, use the first editable text box
545 // For data fields, focus on the first subfield text box
546 function setFocusToNextTag (row, direction) {
547     var keep_looking = true;
548     while (keep_looking && (direction == 'up' ? row = row.previousSibling : row = row.nextSibling)) {
549         // Is it a datafield?
550         dojo.query('hbox', row).query('hbox').query('textbox').forEach(function(node, index, arr) {
551             node.focus();
552             keep_looking = false;
553         });
554
555         // No, it's a control field; use the first textbox
556         if (keep_looking) {
557             dojo.query('textbox', row).forEach(function(node, index, arr) {
558                 node.focus();
559                 keep_looking = false;
560             });
561         }
562     }
563
564     return true;
565 }
566
567 function set_lock_on_keypress(ev) {
568     try {
569         //dump('keypress: isChar = ' + ev.isChar + ' char = ' + ev.char + ' charCode = ' + ev.charCode + ' key = ' + ev.key + ' keyCode = ' + ev.keyCode + '\n');
570         if (! /* NOT */(
571                 ev.altKey
572                 || ev.ctrlKey
573                 || ev.metaKey
574                 || ev.keyCode == ev.DOM_VK_F1
575                 || ev.keyCode == ev.DOM_VK_F2
576                 || ev.keyCode == ev.DOM_VK_F3
577                 || ev.keyCode == ev.DOM_VK_F4
578                 || ev.keyCode == ev.DOM_VK_F5
579                 || ev.keyCode == ev.DOM_VK_F6
580                 || ev.keyCode == ev.DOM_VK_F7
581                 || ev.keyCode == ev.DOM_VK_F8
582                 || ev.keyCode == ev.DOM_VK_F9
583                 || ev.keyCode == ev.DOM_VK_F10
584                 || ev.keyCode == ev.DOM_VK_F11
585                 || ev.keyCode == ev.DOM_VK_F12
586                 || ev.keyCode == ev.DOM_VK_F13
587                 || ev.keyCode == ev.DOM_VK_F14
588                 || ev.keyCode == ev.DOM_VK_F15
589                 || ev.keyCode == ev.DOM_VK_F16
590                 || ev.keyCode == ev.DOM_VK_F17
591                 || ev.keyCode == ev.DOM_VK_F18
592                 || ev.keyCode == ev.DOM_VK_F19
593                 || ev.keyCode == ev.DOM_VK_F20
594                 || ev.keyCode == ev.DOM_VK_F21
595                 || ev.keyCode == ev.DOM_VK_F22
596                 || ev.keyCode == ev.DOM_VK_F23
597                 || ev.keyCode == ev.DOM_VK_F24
598         )) {
599             oils_lock_page();
600         }
601     } catch(E) {
602         alert(E);
603     }
604 }
605
606 function createMARCTextbox (element,attrs) {
607
608     var box = createComplexXULElement('textbox', attrs, Array.prototype.slice.apply(arguments, [2]) );
609     box.addEventListener(
610         'keypress',
611         set_lock_on_keypress,
612         false
613     );
614     box.onkeypress = function (event) {
615         var root_node;
616         var node = element;
617         while(node = node.parent()) {
618             root_node = node;
619         }
620
621         var row = event.target;
622         while (row.tagName != 'row') row = row.parentNode;
623
624         if (element.nodeKind() == 'attribute') element[0]=box.value;
625         else element.setChildren( box.value );
626
627         if (element.localName() != 'controlfield') {
628             if ((event.charCode == 100 || event.charCode == 105) && event.ctrlKey) { // ctrl+d or ctrl+i
629
630                 var index_sf, target, move_data;
631                 if (element.localName() == 'subfield') {
632                     index_sf = element;
633                     target = event.target.parentNode;
634
635                     var start = event.target.selectionStart;
636                     var end = event.target.selectionEnd - event.target.selectionStart ?
637                             event.target.selectionEnd :
638                             event.target.value.length;
639
640                     move_data = event.target.value.substring(start,end);
641                     event.target.value = event.target.value.substring(0,start) + event.target.value.substring(end);
642                     event.target.setAttribute('size', event.target.value.length + 2);
643     
644                     element.setChildren( event.target.value );
645
646                 } else if (element.localName() == 'code') {
647                     index_sf = element.parent();
648                     target = event.target.parentNode;
649                 } else if (element.localName() == 'tag' || element.localName() == 'ind1' || element.localName() == 'ind2') {
650                     index_sf = element.parent().children()[element.parent().children().length() - 1];
651                     target = event.target.parentNode.lastChild.lastChild;
652                 }
653
654                 var sf = <subfield code="" xmlns="http://www.loc.gov/MARC21/slim">{ move_data }</subfield>;
655
656                 index_sf.parent().insertChildAfter( index_sf, sf );
657
658                 var new_sf = marcSubfield(sf);
659
660                 if (target === target.parentNode.lastChild) {
661                     target.parentNode.appendChild( new_sf );
662                 } else {
663                     target.parentNode.insertBefore( new_sf, target.nextSibling );
664                 }
665
666                 new_sf.firstChild.nextSibling.focus();
667
668                 event.preventDefault();
669                 return false;
670
671             } else if (event.keyCode == 13 || event.keyCode == 77) {
672                 if (event.ctrlKey) { // ctrl+enter
673
674                     var index;
675                     if (element.localName() == 'subfield') index = element.parent();
676                     if (element.localName() == 'code') index = element.parent().parent();
677                     if (element.localName() == 'tag') index = element.parent();
678                     if (element.localName() == 'ind1') index = element.parent();
679                     if (element.localName() == 'ind2') index = element.parent();
680
681                     var df = <datafield tag="" ind1="" ind2="" xmlns="http://www.loc.gov/MARC21/slim"><subfield code="" /></datafield>;
682
683                     if (event.shiftKey) { // ctrl+shift+enter
684                         index.parent().insertChildBefore( index, df );
685                     } else {
686                         index.parent().insertChildAfter( index, df );
687                     }
688
689                     var new_df = marcDatafield(df);
690
691                     if (row.parentNode.lastChild === row) {
692                         row.parentNode.appendChild( new_df );
693                     } else {
694                         if (event.shiftKey) { // ctrl+shift+enter
695                             row.parentNode.insertBefore( new_df, row );
696                         } else {
697                             row.parentNode.insertBefore( new_df, row.nextSibling );
698                         }
699                     }
700
701                     new_df.firstChild.focus();
702
703                     event.preventDefault();
704                     return false;
705
706                 } else if (event.shiftKey) {
707                     if (row.previousSibling.className.match('marcDatafieldRow'))
708                         row.previousSibling.firstChild.focus();
709                 } else {
710                     row.nextSibling.firstChild.focus();
711                 }
712
713             } else if (event.keyCode == 38 || event.keyCode == 40) { // up-arrow or down-arrow
714                 if (event.ctrlKey) { // CTRL key: copy the field
715                     var index;
716                     if (element.localName() == 'subfield') index = element.parent();
717                     if (element.localName() == 'code') index = element.parent().parent();
718                     if (element.localName() == 'tag') index = element.parent();
719                     if (element.localName() == 'ind1') index = element.parent();
720                     if (element.localName() == 'ind2') index = element.parent();
721
722                     var copyField = index.copy();
723
724                     if (event.keyCode == 38) { // ctrl+up-arrow
725                         index.parent().insertChildBefore( index, copyField );
726                     } else {
727                         index.parent().insertChildAfter( index, copyField );
728                     }
729
730                     var new_df = marcDatafield(copyField);
731
732                     if (row.parentNode.lastChild === row) {
733                         row.parentNode.appendChild( new_df );
734                     } else {
735                         if (event.keyCode == 38) { // ctrl+up-arrow
736                             row.parentNode.insertBefore( new_df, row );
737                         } else { // ctrl+down-arrow
738                             row.parentNode.insertBefore( new_df, row.nextSibling );
739                         }
740                     }
741
742                     new_df.firstChild.focus();
743
744                     event.preventDefault();
745
746                     return false;
747                 } else {
748                     if (event.keyCode == 38) {
749                         return setFocusToNextTag(row, 'up');
750                     }
751                     if (event.keyCode == 40) {
752                         return setFocusToNextTag(row, 'down');
753                     }
754                     return false;
755                 }
756
757             } else if (event.keyCode == 46 && event.ctrlKey) { // ctrl+del
758
759                 var index;
760                 if (element.localName() == 'subfield') index = element.parent();
761                 if (element.localName() == 'code') index = element.parent().parent();
762                 if (element.localName() == 'tag') index = element.parent();
763                 if (element.localName() == 'ind1') index = element.parent();
764                 if (element.localName() == 'ind2') index = element.parent();
765
766                 for (var i in index.parent().children()) {
767                     if (index === index.parent().children()[i]) {
768                         delete index.parent().children()[i];
769                         break;
770                     }
771                 }
772
773                 row.previousSibling.firstChild.focus();
774                 row.parentNode.removeChild(row);
775
776                 event.preventDefault();
777                 return false;
778
779             } else if (event.keyCode == 46 && event.shiftKey) { // shift+del
780
781                 var index;
782                 if (element.localName() == 'subfield') index = element;
783                 if (element.localName() == 'code') index = element.parent();
784
785                 if (index) {
786                     for (var i in index.parent().children()) {
787                         if (index === index.parent().children()[i]) {
788                             delete index.parent().children()[i];
789                             break;
790                         }
791                     }
792
793                     if (event.target.parentNode === event.target.parentNode.parentNode.lastChild) {
794                         event.target.parentNode.previousSibling.lastChild.focus();
795                     } else {
796                         event.target.parentNode.nextSibling.firstChild.nextSibling.focus();
797                     }
798
799                     event.target.parentNode.parentNode.removeChild(event.target.parentNode);
800
801                     event.preventDefault();
802                     return false;
803                 }
804             } else if (event.keyCode == 117 && event.ctrlKey) { // ctrl + F6
805                 box = null;
806                 createControlField('006','                                        ');
807                 loadRecord();
808             } else if (event.keyCode == 118 && event.ctrlKey) { // ctrl + F7
809                 box = null;
810                 createControlField('007','                                        ');
811                 loadRecord();
812             } else if (event.keyCode == 119 && event.ctrlKey) { // ctrl + F8
813                 box = null;
814                 createControlField('008', get_new_008());
815                 loadRecord();
816             }
817
818             return true;
819
820         } else { // event on a control field
821             if (event.keyCode == 38) { 
822                 return setFocusToNextTag(row, 'up'); 
823             } else if (event.keyCode == 40) { 
824                 return setFocusToNextTag(row, 'down');
825             }
826         }
827     };
828
829     box.addEventListener(
830         'keypress', 
831         function () {
832             if (element.nodeKind() == 'attribute') element[0]=box.value;
833             else element.setChildren( box.value );
834             return true;
835         },
836         false
837     );
838
839     box.addEventListener(
840         'change', 
841         function () {
842             if (element.nodeKind() == 'attribute') element[0]=box.value;
843             else element.setChildren( box.value );
844             return true;
845         },
846         false
847     );
848
849     box.addEventListener(
850         'keypress', 
851         function () {
852             if (element.nodeKind() == 'attribute') element[0]=box.value;
853             else element.setChildren( box.value );
854             return true;
855         },
856         true
857     );
858
859     // 'input' event catches the box value after the keypress
860     box.addEventListener(
861         'input', 
862         function () {
863             if (element.nodeKind() == 'attribute') element[0]=box.value;
864             else element.setChildren( box.value );
865             return true;
866         },
867         true
868     );
869
870     box.addEventListener(
871         'keyup', 
872         function () {
873             if (element.localName() == 'controlfield')
874                 eval('fillFixedFields();');
875         },
876         true
877     );
878
879     return box;
880 }
881
882 function toggleFFE () {
883     var grid = document.getElementById('leaderGrid');
884     if (grid.hidden) {
885         grid.hidden = false;
886     } else {
887         grid.hidden = true;
888     }
889     return true;
890 }
891
892 function changeFFEditor (type) {
893     var grid = document.getElementById('leaderGrid');
894     grid.setAttribute('type',type);
895     document.getElementById('recordTypeLabel').setAttribute('value',type);
896
897     // Hide FFEditor rows that we don't need for our current type
898     // If all of the labels for a given row do not include our
899     // desired type in their set attribute, we can hide that row
900     dojo.query('rows', grid).query('row').forEach(function(node, index, arr) {
901         if (dojo.query('label[set~=' + type + ']', node).length == 0) {
902             node.hidden = true;
903         }
904     });
905
906     getFFValuesForType(
907         type,
908         function() {
909             updateFFEditorContexts(grid, type);
910         },
911         function() {
912             alert(  /* XXX i18n - the marc editor either isn't tied in to
913                        an overall i18n infrastructure, or it's different
914                        enough from other Evergreen parts that I don't
915                        understand the right way to do i18n here */
916                 "failed to load fixed field values for rec_type '" +
917                 type + "'\n"
918             );
919         }
920     );
921 }
922
923 function getFFValuesForType(type, callback, errback) {
924     if (_fixed_field_values[type]) {
925         callback();
926     } else {
927         dojo.require("openils.Util");
928
929         fieldmapper.standardRequest(
930             ["open-ils.cat",
931                 "open-ils.cat.biblio.fixed_field_values.by_rec_type"], {
932                 "async": true,
933                 "params": [type],
934                 "oncomplete": function(r) {
935                     if (r = openils.Util.readResponse(r)) {
936                         _fixed_field_values[type] = r;
937                         callback();
938                     } else {
939                         errback();
940                     }
941                 },
942                 "onerror": errback
943             }
944         );
945     }
946 }
947
948 function updateFFEditorContexts(grid, type) {
949
950     /* XXX Dojo to navigate a XUL DOM.  Bad form?  We do it elsewhere in this
951      * file, but I think I've heard it scoffed at. */
952
953     var rows_node = dojo.query("rows", grid)[0];
954     dojo.query("row", rows_node).forEach(
955         function(row) {
956             dojo.query("textbox", row).forEach(
957                 function(tb) {
958                     var name = tb.getAttribute("name");
959                     if (_fixed_field_values[type][name]) {
960                         tb.setAttribute(
961                             "context", getFFContextMenu(type, name)
962                         );
963                     } else {
964                         tb.setAttribute("context", "clipboard");
965                     }
966                 }
967             );
968         }
969     );
970 }
971
972 function getFFContextMenu(type, name) {
973     if (!_fixed_field_context_menus[type]) {
974         _fixed_field_context_menus[type] = {};
975     }
976
977     var context_menu_id = "_fixed_field_context_menus_" + type + "_" + name;
978
979     if (!_fixed_field_context_menus[type][name]) {
980         var p = document.getElementsByTagName("popupset")[0];
981         var m = document.createElement("menupopup");
982         m.setAttribute("id", context_menu_id);
983         _fixed_field_values[type][name].forEach(
984             function(v) {
985                 var mi = document.createElement("menuitem");
986                 var funcname = "_ff_anon_" +
987                     String(_fixed_field_anonymous_func_counter++);
988
989                 /* These anon functions linger and take up memory, but due
990                  * to caching there's a limit on how much, and that limit is
991                  * a function of the size of the dataset defined in the
992                  * ccvm/cmfpm tables. */
993                 var code = v[0];
994                 var len = v[2];
995                 var def = v[3];
996                 var el = document.getElementById(name + "_tb");
997                 window[funcname] = function() {
998                     el.value = code;
999                     while (el.value.length < len) {
1000                         el.value += def;
1001                     }
1002                     updateFixedFields(el);
1003                     oils_lock_page();
1004                 };
1005
1006                 /* In XUL land we can't set an element's
1007                  * attribute like oncommand to a code reference. It has to be
1008                  * an actual string to be eval'd. */
1009                 mi.setAttribute("oncommand", funcname + "()");
1010                 mi.setAttribute("label", v[0] + ": " + v[1]); /* XXX i18n ? */
1011                 m.appendChild(mi);
1012             }
1013         );
1014         _fixed_field_context_menus[type][name] = m;
1015         p.appendChild(m);
1016     }
1017
1018     return context_menu_id;
1019 }
1020
1021 /* This just sets up a special context menu for a 007 data field to use, so
1022  * that users can right-click for a menu and get a choice to launch the
1023  * Physical Characteristics Wizard.
1024  */
1025 function preparePhysCharWizardContext() {
1026     var menu = document.getElementById("physCharWizardContext");
1027     menu.appendChild(document.createElement("menuseparator"));
1028
1029     var clipb_children = document.getElementById("clipboard").childNodes;
1030     for (var i = 0; i < clipb_children.length; i++) /* collection not array */ {
1031         var child = clipb_children[i];
1032         if (child.nodeName == 'menuitem')
1033             menu.appendChild(child.cloneNode(true));
1034     }
1035 }
1036
1037 function launchPhysCharWizard(popup_node) {
1038     try {
1039         new openils.widget.PhysCharWizard({
1040             "node": popup_node,
1041             "onapply": function(v) {
1042                 createControlField("007", v);
1043                 oils_lock_page();
1044                 loadRecord();
1045             }
1046         });
1047     } catch (E) {
1048         alert("Exception raised by openils.widget.PhysCharWizard:\n" + E);
1049     }
1050 }
1051
1052 function fillFixedFields () {
1053     try {
1054             var grid = document.getElementById('leaderGrid');
1055             var marc_rec = new MARC.Record ({ delimiter : '$', marcxml : xml_record.toXMLString() });
1056
1057             var list = [];
1058             var pre_list = grid.getElementsByTagName('label');
1059             for (var i in pre_list) {
1060                 if ( pre_list[i].getAttribute && pre_list[i].getAttribute('set').indexOf(grid.getAttribute('type')) > -1 ) {
1061                     list.push( pre_list[i] );
1062                 }
1063             }
1064
1065             for (var i in list) {
1066                 var name = list[i].getAttribute('name');
1067                 var value = marc_rec.extractFixedField(name, true);
1068
1069                 if (value === null) continue;
1070
1071                 list[i].nextSibling.value = value;
1072             }
1073
1074             return true;
1075     } catch(E) {
1076         alert('FIXME, MARC Editor, fillFixedFields: ' + E);
1077     }
1078 }
1079
1080 function updateFixedFields (element) {
1081     var grid = document.getElementById('leaderGrid');
1082     var recGrid = document.getElementById('recGrid');
1083     var new_value = element.value;
1084     // Don't take focus away/adjust the record on partial changes
1085     var length = element.getAttribute('maxlength');
1086     if(new_value.length < length) return true;
1087
1088     var marc_rec = new MARC.Record ({ delimiter : '$', marcxml : xml_record.toXMLString() });
1089     marc_rec.setFixedField(element.getAttribute('name'), new_value);
1090
1091     var xml_string = marc_rec.toXmlString();
1092     xml_record = new XML( xml_string );
1093     if (xml_record..record[0]) xml_record = xml_record..record[0];
1094     loadRecord();
1095     // Put the cursor back to the current fixed field
1096     element.select();
1097
1098     return true;
1099 }
1100
1101 function marcLeader (leader) {
1102     var row = createRow(
1103         { class : 'marcLeaderRow',
1104           tag : 'ldr' },
1105         createLabel(
1106             { value : 'LDR',
1107               class : 'marcTag',
1108               tooltiptext : $('catStrings').getString('staff.cat.marcedit.marcTag.LDR.label') } ),
1109         createLabel(
1110             { value : '',
1111               class : 'marcInd1' } ),
1112         createLabel(
1113             { value : '',
1114               class : 'marcInd2' } ),
1115         createLabel(
1116             { value : leader.text(),
1117               class : 'marcLeader' } )
1118     );
1119
1120     return row;
1121 }
1122
1123 function marcControlfield (field) {
1124     tagname = field.@tag.toString().substr(2);
1125     var row;
1126     if (tagname == '1' || tagname == '3' || tagname == '6' || tagname == '7' || tagname == '8') {
1127         row = createRow(
1128             { class : 'marcControlfieldRow',
1129               tag : '_' + tagname },
1130             createLabel(
1131                 { value : field.@tag,
1132                   class : 'marcTag',
1133                   context : 'tags_popup',
1134                   onmouseover : 'getTooltip(this, "tag");',
1135                   tooltipid : 'tag' + field.@tag } ),
1136             createLabel(
1137                 { value : field.@ind1,
1138                   class : 'marcInd1',
1139                   onmouseover : 'getTooltip(this, "ind1");',
1140                   tooltipid : 'tag' + field.@tag + 'ind1val' + field.@ind1 } ),
1141             createLabel(
1142                 { value : field.@ind2,
1143                   class : 'marcInd2',
1144                   onmouseover : 'getTooltip(this, "ind2");',
1145                   tooltipid : 'tag' + field.@tag + 'ind2val' + field.@ind2 } ),
1146             createMARCTextbox(
1147                 field,
1148                 { value : field.text(),
1149                   class : 'plain marcEditableControlfield',
1150                   name : 'CONTROL' + tagname,
1151                   context : tagname == 7 ? 'physCharWizardContext': 'clipboard',
1152                   size : 50,
1153                   maxlength : 50 } )
1154             );
1155     } else {
1156         row = createRow(
1157             { class : 'marcControlfieldRow',
1158               tag : '_' + tagname },
1159             createLabel(
1160                 { value : field.@tag,
1161                   class : 'marcTag',
1162                   onmouseover : 'getTooltip(this, "tag");',
1163                   tooltipid : 'tag' + field.@tag } ),
1164             createLabel(
1165                 { value : field.@ind1,
1166                   class : 'marcInd1',
1167                   onmouseover : 'getTooltip(this, "ind1");',
1168                   tooltipid : 'tag' + field.@tag + 'ind1val' + field.@ind1 } ),
1169             createLabel(
1170                 { value : field.@ind2,
1171                   class : 'marcInd2',
1172                   onmouseover : 'getTooltip(this, "ind2");',
1173                   tooltipid : 'tag' + field.@tag + 'ind2val' + field.@ind2 } ),
1174             createLabel(
1175                 { value : field.text(),
1176                   class : 'marcControlfield' } )
1177         );
1178     }
1179
1180     return row;
1181 }
1182
1183 function stackSubfields(checkbox) {
1184     var list = document.getElementsByAttribute('name','sf_box');
1185
1186     var o = 'vertical';
1187     if (!checkbox.checked) o = 'horizontal';
1188     
1189     for (var i = 0; i < list.length; i++) {
1190         if (list[i]) list[i].setAttribute('orient',o);
1191     }
1192 }
1193
1194 function fastItemAdd_toggle(checkbox) {
1195     var x = document.getElementById('fastItemAdd_textboxes');
1196     if (checkbox.checked) {
1197         x.hidden = false;
1198         document.getElementById('fastItemAdd_callnumber').focus();
1199         document.getElementById('fastItemAdd_callnumber').select();
1200     } else {
1201         x.hidden = true;
1202     }
1203 }
1204
1205 function fastItemAdd_attempt(doc_id) {
1206     try {
1207         if (typeof window.xulG.fast_add_item != 'function') { return; }
1208         if (!document.getElementById('fastItemAdd_checkbox').checked) { return; }
1209         if (!document.getElementById('fastItemAdd_callnumber').value) { return; }
1210         if (!document.getElementById('fastItemAdd_barcode').value) { return; }
1211         window.xulG.fast_add_item( doc_id, document.getElementById('fastItemAdd_callnumber').value, document.getElementById('fastItemAdd_barcode').value );
1212         document.getElementById('fastItemAdd_barcode').value = '';
1213         return true;
1214     } catch(E) {
1215         alert('fastItemAdd_attempt: ' + E);
1216     }
1217 }
1218
1219 function save_attempt(xml_string) {
1220     try {
1221         var result = window.xulG.save.func( xml_string );
1222         // I'd prefer to pass on_complete on through to fast_item_add,
1223         // but with the way these window scopes get destroyed with
1224         // tab replacement, maybe not a good idea
1225         var replace_on_complete = false;
1226         if (result) {
1227             oils_unlock_page();
1228             if (result.id) {
1229                 replace_on_complete = fastItemAdd_attempt(result.id);
1230             }
1231             if (!replace_on_complete && typeof result.on_complete == 'function') {
1232                 result.on_complete();
1233             }
1234         }
1235     } catch(E) {
1236         alert('save_attempt: ' + E);
1237     }
1238 }
1239
1240 function marcDatafield (field) {
1241     var row = createRow(
1242         { class : 'marcDatafieldRow' },
1243         createMARCTextbox(
1244             field.@tag,
1245             { value : field.@tag,
1246               class : 'plain marcTag',
1247               name : 'marcTag',
1248               context : 'tags_popup',
1249               oninput : 'if (this.value.length == 3) { this.nextSibling.focus(); }',
1250               size : 3,
1251               maxlength : 3,
1252               onmouseover : 'current_focus = this; getTooltip(this, "tag");' } ),
1253         createMARCTextbox(
1254             field.@ind1,
1255             { value : field.@ind1,
1256               class : 'plain marcInd1',
1257               name : 'marcInd1',
1258               oninput : 'if (this.value.length == 1) { this.nextSibling.focus(); }',
1259               size : 1,
1260               maxlength : 1,
1261               onmouseover : 'current_focus = this; getContextMenu(this, "ind1"); getTooltip(this, "ind1");',
1262               oncontextmenu : 'getContextMenu(this, "ind1");' } ),
1263         createMARCTextbox(
1264             field.@ind2,
1265             { value : field.@ind2,
1266               class : 'plain marcInd2',
1267               name : 'marcInd2',
1268               oninput : 'if (this.value.length == 1) { this.nextSibling.firstChild.firstChild.focus(); }',
1269               size : 1,
1270               maxlength : 1,
1271               onmouseover : 'current_focus = this; getContextMenu(this, "ind2"); getTooltip(this, "ind2");',
1272               oncontextmenu : 'getContextMenu(this, "ind2");' } ),
1273         createHbox({ name : 'sf_box' })
1274     );
1275
1276     if (!current_focus && field.@tag == '') current_focus = row.childNodes[0];
1277     if (!current_focus && field.@ind1 == '') current_focus = row.childNodes[1];
1278     if (!current_focus && field.@ind2 == '') current_focus = row.childNodes[2];
1279
1280     var sf_box = row.lastChild;
1281     if (document.getElementById('stackSubfields').checked)
1282         sf_box.setAttribute('orient','vertical');
1283
1284     sf_box.addEventListener(
1285         'click',
1286         function (e) {
1287             if (sf_box === e.target) {
1288                 sf_box.lastChild.lastChild.focus();
1289             } else if (e.target.parentNode === sf_box) {
1290                 e.target.lastChild.focus();
1291             }
1292         },
1293         false
1294     );
1295
1296
1297     for (var i in field.subfield) {
1298         var sf = field.subfield[i];
1299         sf_box.appendChild(
1300             marcSubfield(sf)
1301         );
1302
1303         dojo.query('.marcSubfield', sf_box).forEach(wrap_long_fields);
1304
1305         if (sf.@code == '' && (!current_focus || current_focus.className.match(/Ind/)))
1306             current_focus = sf_box.lastChild.childNodes[1];
1307     }
1308
1309     return row;
1310 }
1311
1312 function marcSubfield (sf) {            
1313     return createHbox(
1314         { class : 'marcSubfieldBox' },
1315         createLabel(
1316             { value : "\u2021",
1317               class : 'plain marcSubfieldDelimiter',
1318               onmouseover : 'getTooltip(this.nextSibling, "subfield");',
1319               oncontextmenu : 'getContextMenu(this.nextSibling, "subfield");',
1320                 //onclick : 'this.nextSibling.focus();',
1321                 onfocus : 'this.nextSibling.focus();',
1322               size : 2 } ),
1323         createMARCTextbox(
1324             sf.@code,
1325             { value : sf.@code,
1326               class : 'plain marcSubfieldCode',
1327               align: 'start',
1328               name : 'marcSubfieldCode',
1329               onmouseover : 'current_focus = this; getContextMenu(this, "subfield"); getTooltip(this, "subfield");',
1330               oncontextmenu : 'getContextMenu(this, "subfield");',
1331               oninput : 'if (this.value.length == 1) { this.nextSibling.focus(); }',
1332               size : 2,
1333               maxlength : 1 } ),
1334         createMARCTextbox(
1335             sf,
1336             { value : sf.text(),
1337               name : sf.parent().@tag + ':' + sf.@code,
1338               class : 'plain marcSubfield', 
1339               align: 'start',
1340               onmouseover : 'getTooltip(this, "subfield");',
1341               contextmenu : function (event) { getAuthorityContextMenu(event.target, sf) },
1342               size : new String(sf.text()).length + 2,
1343               oninput : "this.setAttribute('size', this.value.length + 2);"
1344             } )
1345     );
1346 }
1347
1348 function loadRecord() {
1349     try {
1350             var grid_rows = document.getElementById('recGrid').lastChild;
1351
1352             while (grid_rows.firstChild) grid_rows.removeChild(grid_rows.firstChild);
1353
1354             grid_rows.appendChild( marcLeader( xml_record.leader ) );
1355
1356             for (var i in xml_record.controlfield) {
1357                 grid_rows.appendChild( marcControlfield( xml_record.controlfield[i] ) );
1358             }
1359
1360             for (var i in xml_record.datafield) {
1361                 grid_rows.appendChild( marcDatafield( xml_record.datafield[i] ) );
1362             }
1363
1364             grid_rows.getElementsByAttribute('class','marcDatafieldRow')[0].firstChild.focus();
1365
1366             var marc_rec = new MARC.Record ({ delimiter : '$', marcxml : xml_record.toXMLString() });
1367             changeFFEditor(marc_rec.recordType());
1368             fillFixedFields();
1369     } catch(E) {
1370         alert('FIXME, MARC Editor, loadRecord: ' + E);
1371     }
1372 }
1373
1374
1375 function genToolTips () {
1376     for (var i in bib_data.field) {
1377         var f = bib_data.field[i];
1378     
1379         tag_menu.appendChild(
1380             createMenuitem(
1381                 { label : f.@tag,
1382                   oncommand : 
1383                       'current_focus.value = "' + f.@tag + '";' +
1384                     'var e = document.createEvent("MutationEvents");' +
1385                     'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1386                     'current_focus.inputField.dispatchEvent(e);',
1387                   disabled : f.@tag < '010' ? "true" : "false",
1388                   tooltiptext : f.description }
1389             )
1390         );
1391     
1392         var i1_popup = createMenuPopup({position : 'after_start', id : 't' + f.@tag + 'i1' });
1393         context_menus.appendChild( i1_popup );
1394     
1395         var i2_popup = createMenuPopup({position : 'after_start', id : 't' + f.@tag + 'i2' });
1396         context_menus.appendChild( i2_popup );
1397     
1398         var sf_popup = createMenuPopup({position : 'after_start', id : 't' + f.@tag + 'sf' });
1399         context_menus.appendChild( sf_popup );
1400     
1401         tooltip_hash['tag' + f.@tag] = f.description;
1402         for (var j in f.indicator) {
1403             var ind = f.indicator[j];
1404             tooltip_hash['tag' + f.@tag + 'ind' + ind.@position + 'val' + ind.@value] = ind.description;
1405     
1406             if (ind.@position == 1) {
1407                 i1_popup.appendChild(
1408                     createMenuitem(
1409                         { label : ind.@value,
1410                           oncommand : 
1411                               'current_focus.value = "' + ind.@value + '";' +
1412                             'var e = document.createEvent("MutationEvents");' +
1413                             'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1414                             'current_focus.inputField.dispatchEvent(e);',
1415                           tooltiptext : ind.description }
1416                     )
1417                 );
1418             }
1419     
1420             if (ind.@position == 2) {
1421                 i2_popup.appendChild(
1422                     createMenuitem(
1423                         { label : ind.@value,
1424                           oncommand : 
1425                               'current_focus.value = "' + ind.@value + '";' +
1426                             'var e = document.createEvent("MutationEvents");' +
1427                             'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1428                             'current_focus.inputField.dispatchEvent(e);',
1429                           tooltiptext : ind.description }
1430                     )
1431                 );
1432             }
1433         }
1434     
1435         for (var j in f.subfield) {
1436             var sf = f.subfield[j];
1437             tooltip_hash['tag' + f.@tag + 'sf' + sf.@code] = sf.description;
1438     
1439             sf_popup.appendChild(
1440                 createMenuitem(
1441                     { label : sf.@code,
1442                       oncommand : 
1443                           'current_focus.value = "' + sf.@code + '";' +
1444                         'var e = document.createEvent("MutationEvents");' +
1445                         'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1446                         'current_focus.inputField.dispatchEvent(e);',
1447                       tooltiptext : sf.description
1448                     }
1449                 )
1450             );
1451         }
1452     }
1453 }
1454
1455 function getTooltip (target, type) {
1456
1457     var tt = '';
1458     if (type == 'subfield')
1459         tt = 'tag' + target.parentNode.parentNode.parentNode.firstChild.value + 'sf' + target.parentNode.childNodes[1].value;
1460
1461     if (type == 'ind1')
1462         tt = 'tag' + target.parentNode.firstChild.value + 'ind1val' + target.value;
1463
1464     if (type == 'ind2')
1465         tt = 'tag' + target.parentNode.firstChild.value + 'ind2val' + target.value;
1466
1467     if (type == 'tag')
1468         tt = 'tag' + target.parentNode.firstChild.value;
1469
1470     if (!document.getElementById( tt )) {
1471         p.appendChild(
1472             createTooltip(
1473                 { id : tt,
1474                   flex : "1",
1475                   orient : 'vertical',
1476                   onpopupshown : 'this.width = this.firstChild.boxObject.width + 10; this.height = this.firstChild.boxObject.height + 10;',
1477                   class : 'tooltip' },
1478                 createDescription({}, document.createTextNode( tooltip_hash[tt] ) )
1479             )
1480         );
1481     }
1482
1483     target.tooltip = tt;
1484     return true;
1485 }
1486
1487 function getContextMenu (target, type) {
1488
1489     var tt = '';
1490     if (type == 'subfield')
1491         tt = 't' + target.parentNode.parentNode.parentNode.firstChild.value + 'sf';
1492
1493     if (type == 'ind1')
1494         tt = 't' + target.parentNode.firstChild.value + 'i1';
1495
1496     if (type == 'ind2')
1497         tt = 't' + target.parentNode.firstChild.value + 'i2';
1498
1499     target.setAttribute('context', tt);
1500     return true;
1501 }
1502
1503 var control_map = {
1504     100 : {
1505         'a' : { 100 : 'a' },
1506         'd' : { 100 : 'd' },
1507         'e' : { 100 : 'e' },
1508         'q' : { 100 : 'q' }
1509     },
1510     110 : {
1511         'a' : { 110 : 'a' },
1512         'd' : { 110 : 'd' }
1513     },
1514     111 : {
1515         'a' : { 111 : 'a' },
1516         'd' : { 111 : 'd' }
1517     },
1518     130 : {
1519         'a' : { 130 : 'a' },
1520         'd' : { 130 : 'd' }
1521     },
1522     240 : {
1523         'a' : { 130 : 'a' },
1524         'd' : { 130 : 'd' }
1525     },
1526     400 : {
1527         'a' : { 100 : 'a' },
1528         'd' : { 100 : 'd' }
1529     },
1530     410 : {
1531         'a' : { 110 : 'a' },
1532         'd' : { 110 : 'd' }
1533     },
1534     411 : {
1535         'a' : { 111 : 'a' },
1536         'd' : { 111 : 'd' }
1537     },
1538     440 : {
1539         'a' : { 130 : 'a' },
1540         'n' : { 130 : 'n' },
1541         'p' : { 130 : 'p' }
1542     },
1543     700 : {
1544         'a' : { 100 : 'a' },
1545         'd' : { 100 : 'd' },
1546         'q' : { 100 : 'q' },
1547         't' : { 100 : 't' }
1548     },
1549     710 : {
1550         'a' : { 110 : 'a' },
1551         'd' : { 110 : 'd' }
1552     },
1553     711 : {
1554         'a' : { 111 : 'a' },
1555         'c' : { 111 : 'c' },
1556         'd' : { 111 : 'd' }
1557     },
1558     730 : {
1559         'a' : { 130 : 'a' },
1560         'd' : { 130 : 'd' }
1561     },
1562     800 : {
1563         'a' : { 100 : 'a' },
1564         'd' : { 100 : 'd' }
1565     },
1566     810 : {
1567         'a' : { 110 : 'a' },
1568         'd' : { 110 : 'd' }
1569     },
1570     811 : {
1571         'a' : { 111 : 'a' },
1572         'd' : { 111 : 'd' }
1573     },
1574     830 : {
1575         'a' : { 130 : 'a' },
1576         'd' : { 130 : 'd' }
1577     },
1578     600 : {
1579         'a' : { 100 : 'a' },
1580         'd' : { 100 : 'd' },
1581         'q' : { 100 : 'q' },
1582         't' : { 100 : 't' },
1583         'v' : { 180 : 'v',
1584             100 : 'v',
1585             181 : 'v',
1586             182 : 'v',
1587             185 : 'v'
1588         },
1589         'x' : { 180 : 'x',
1590             100 : 'x',
1591             181 : 'x',
1592             182 : 'x',
1593             185 : 'x'
1594         },
1595         'y' : { 180 : 'y',
1596             100 : 'y',
1597             181 : 'y',
1598             182 : 'y',
1599             185 : 'y'
1600         },
1601         'z' : { 180 : 'z',
1602             100 : 'z',
1603             181 : 'z',
1604             182 : 'z',
1605             185 : 'z'
1606         }
1607     },
1608     610 : {
1609         'a' : { 110 : 'a' },
1610         'd' : { 110 : 'd' },
1611         't' : { 110 : 't' },
1612         'v' : { 180 : 'v',
1613             110 : 'v',
1614             181 : 'v',
1615             182 : 'v',
1616             185 : 'v'
1617         },
1618         'x' : { 180 : 'x',
1619             110 : 'x',
1620             181 : 'x',
1621             182 : 'x',
1622             185 : 'x'
1623         },
1624         'y' : { 180 : 'y',
1625             110 : 'y',
1626             181 : 'y',
1627             182 : 'y',
1628             185 : 'y'
1629         },
1630         'z' : { 180 : 'z',
1631             110 : 'z',
1632             181 : 'z',
1633             182 : 'z',
1634             185 : 'z'
1635         }
1636     },
1637     611 : {
1638         'a' : { 111 : 'a' },
1639         'd' : { 111 : 'd' },
1640         't' : { 111 : 't' },
1641         'v' : { 180 : 'v',
1642             111 : 'v',
1643             181 : 'v',
1644             182 : 'v',
1645             185 : 'v'
1646         },
1647         'x' : { 180 : 'x',
1648             111 : 'x',
1649             181 : 'x',
1650             182 : 'x',
1651             185 : 'x'
1652         },
1653         'y' : { 180 : 'y',
1654             111 : 'y',
1655             181 : 'y',
1656             182 : 'y',
1657             185 : 'y'
1658         },
1659         'z' : { 180 : 'z',
1660             111 : 'z',
1661             181 : 'z',
1662             182 : 'z',
1663             185 : 'z'
1664         }
1665     },
1666     630 : {
1667         'a' : { 130 : 'a' },
1668         'd' : { 130 : 'd' }
1669     },
1670     648 : {
1671         'a' : { 148 : 'a' },
1672         'v' : { 148 : 'v' },
1673         'x' : { 148 : 'x' },
1674         'y' : { 148 : 'y' },
1675         'z' : { 148 : 'z' }
1676     },
1677     650 : {
1678         'a' : { 150 : 'a' },
1679         'b' : { 150 : 'b' },
1680         'v' : { 180 : 'v',
1681             150 : 'v',
1682             181 : 'v',
1683             182 : 'v',
1684             185 : 'v'
1685         },
1686         'x' : { 180 : 'x',
1687             150 : 'x',
1688             181 : 'x',
1689             182 : 'x',
1690             185 : 'x'
1691         },
1692         'y' : { 180 : 'y',
1693             150 : 'y',
1694             181 : 'y',
1695             182 : 'y',
1696             185 : 'y'
1697         },
1698         'z' : { 180 : 'z',
1699             150 : 'z',
1700             181 : 'z',
1701             182 : 'z',
1702             185 : 'z'
1703         }
1704     },
1705     651 : {
1706         'a' : { 151 : 'a' },
1707         'v' : { 180 : 'v',
1708             151 : 'v',
1709             181 : 'v',
1710             182 : 'v',
1711             185 : 'v'
1712         },
1713         'x' : { 180 : 'x',
1714             151 : 'x',
1715             181 : 'x',
1716             182 : 'x',
1717             185 : 'x'
1718         },
1719         'y' : { 180 : 'y',
1720             151 : 'y',
1721             181 : 'y',
1722             182 : 'y',
1723             185 : 'y'
1724         },
1725         'z' : { 180 : 'z',
1726             151 : 'z',
1727             181 : 'z',
1728             182 : 'z',
1729             185 : 'z'
1730         }
1731     },
1732     655 : {
1733         'a' : { 155 : 'a' },
1734         'v' : { 180 : 'v',
1735             155 : 'v',
1736             181 : 'v',
1737             182 : 'v',
1738             185 : 'v'
1739         },
1740         'x' : { 180 : 'x',
1741             155 : 'x',
1742             181 : 'x',
1743             182 : 'x',
1744             185 : 'x'
1745         },
1746         'y' : { 180 : 'y',
1747             155 : 'y',
1748             181 : 'y',
1749             182 : 'y',
1750             185 : 'y'
1751         },
1752         'z' : { 180 : 'z',
1753             155 : 'z',
1754             181 : 'z',
1755             182 : 'z',
1756             185 : 'z'
1757         }
1758     }
1759 };
1760
1761 function getAuthorityContextMenu (target, sf) {
1762     var menu_id = sf.parent().@tag + ':' + sf.@code + '-authority-context-' + sf;
1763
1764     var page = 0;
1765     var old = dojo.byId( menu_id );
1766     if (old) {
1767         page = auth_pages[menu_id];
1768         old.parentNode.removeChild(old);
1769     } else {
1770         auth_pages[menu_id] = 0;
1771     }
1772
1773     var sf_popup = createMenuPopup({ id : menu_id, flex : 1 });
1774
1775     sf_popup.addEventListener("popuphiding", function(event) {
1776         if (show_auth_menu) {
1777             show_auth_menu = false;
1778             getAuthorityContextMenu(target, sf);
1779             dojo.byId(menu_id).openPopup();
1780         }  
1781     }, false);
1782
1783     context_menus.appendChild( sf_popup );
1784
1785     var found_acs = [];
1786     dojo.forEach( acs.controlSetList(), function (acs_id) {
1787         if (acs.controlSet(acs_id).control_map[sf.parent().@tag]) found_acs.push(acs_id);
1788     });
1789
1790     if (!found_acs.length) {
1791         sf_popup.appendChild(createLabel( { value : $('catStrings').getString('staff.cat.marcedit.not_authority_field.label') } ) );
1792         target.setAttribute('context', 'clipboard');
1793         return false;
1794     }
1795
1796     if (sf.toString().replace(/\s*/, '')) {
1797         return browseAuthority(sf_popup, menu_id, target, sf, 20, page);
1798     }
1799
1800     return true;
1801 }
1802
1803 /* Apply the complete 1xx */
1804 function applyFullAuthority ( target, ui_sf, e4x_sf ) {
1805     var new_vals = dojo.query('*[tag^="1"]', target);
1806     return applyAuthority( target, ui_sf, e4x_sf, new_vals );
1807 }
1808
1809 function applySelectedAuthority ( target, ui_sf, e4x_sf ) {
1810     var new_vals = target.getElementsByAttribute('checked','true');
1811     return applyAuthority( target, ui_sf, e4x_sf, new_vals );
1812 }
1813
1814 function applyAuthority ( target, ui_sf, e4x_sf, new_vals ) {
1815     var field = e4x_sf.parent();
1816
1817     for (var i = 0; i < new_vals.length; i++) {
1818
1819         var sf_list = field.subfield;
1820         for (var j in sf_list) {
1821
1822             if (sf_list[j].@code == new_vals[i].getAttribute('subfield')) {
1823                 sf_list[j] = new_vals[i].getAttribute('value');
1824                 new_vals[i].setAttribute('subfield','');
1825                 break;
1826             }
1827         }
1828     }
1829
1830     for (var i = 0; i < new_vals.length; i++) {
1831
1832         /* indicators for the authority datafield are carried over in the main entry linking subfield */
1833         if (new_vals[i].getAttribute('subfield') == '0') {
1834             field.@ind1 = new_vals[i].getAttribute('ind1');
1835             field.@ind2 = new_vals[i].getAttribute('ind2');
1836         }
1837
1838         if (!new_vals[i].getAttribute('subfield')) continue;
1839
1840         var val = new_vals[i].getAttribute('value');
1841
1842         var sf = <subfield code="" xmlns="http://www.loc.gov/MARC21/slim">{val}</subfield>;
1843         sf.@code = new_vals[i].getAttribute('subfield');
1844
1845         field.insertChildAfter(field.subfield[field.subfield.length() - 1], sf);
1846     }
1847
1848     var row = marcDatafield( field );
1849
1850     var node = ui_sf;
1851     while (node.nodeName != 'row') {
1852         node = node.parentNode;
1853     }
1854
1855     node.parentNode.replaceChild( row, node );
1856     return true;
1857 }
1858
1859 function validateAuthority (button) {
1860     var grid = document.getElementById('recGrid');
1861     var label = button.getAttribute('label');
1862
1863     //loop over rows
1864     var rows = grid.lastChild.childNodes;
1865     for (var i = 0; i < rows.length; i++) {
1866         var row = rows[i];
1867         var tag = row.firstChild;
1868
1869         var done = false;
1870         dojo.forEach(acs.controlSetList(), function (acs_id) {
1871             if (done) return;
1872             var control_map = acs.controlSet(acs_id).control_map;
1873     
1874             if (!control_map[tag.value]) return;
1875             button.setAttribute('label', label + ' - ' + tag.value);
1876     
1877             var ind1 = tag.nextSibling;
1878             var ind2 = ind1.nextSibling;
1879             var subfields = ind2.nextSibling.childNodes;
1880     
1881             var sf_list = [];
1882             for (var j = 0; j < subfields.length; j++) {
1883                 var sf = subfields[j];
1884                 sf_list.push( [ sf.childNodes[1].value, sf.childNodes[2].value ] );
1885             }
1886
1887             var matches = acs.findMatchingAuthorities(
1888                 new MARC.Field({
1889                     'tag'       : tag.value,
1890                     'subfields' : sf_list
1891                 })
1892             );
1893
1894             // matches = [ { "$csetId" : [ ... ] } ]
1895
1896             var found = false;
1897             if (matches[0]) { // probably set
1898                 for (var cset in matches[0]) {
1899                     var arr = matches[0][cset];
1900                     if (arr.length) {
1901                         // protect against errant empty string values
1902                         if (arr.length == 1 && arr[0] == '')
1903                             continue;
1904                         found = true;
1905                         break;
1906                     }
1907                 }
1908             }
1909
1910     
1911             // XXX If adt, etc should be validated separately from vxz, etc then move this up into the above for loop
1912             for (var j = 0; j < subfields.length; j++) {
1913                 var sf = subfields[j];
1914                 if (!found) {
1915                     dojo.removeClass(sf.childNodes[2], 'marcValidated');
1916                     dojo.addClass(sf.childNodes[2], 'marcUnvalidated');
1917                 } else {
1918                     dojo.removeClass(sf.childNodes[2], 'marcUnvalidated');
1919                     dojo.addClass(sf.childNodes[2], 'marcValidated');
1920                 }
1921             }
1922
1923             if (found) done = true;
1924         });
1925     }
1926
1927     button.setAttribute('label', label);
1928
1929     return true;
1930 }
1931
1932
1933 /*
1934 function validateBibField (tags, searches) {
1935     var url = "/gateway?input_format=json&format=xml&service=open-ils.search&method=open-ils.search.authority.validate.tag";
1936     url += '&param="tags"&param=' + js2JSON(tags);
1937     url += '&param="searches"&param=' + js2JSON(searches);
1938
1939
1940     var req = new XMLHttpRequest();
1941     req.open('GET',url,false);
1942     req.send(null);
1943
1944     return req;
1945
1946 }
1947 */
1948
1949 function searchAuthority (term, tag, sf, limit) {
1950     var url = "/gateway?input_format=json&format=xml&service=open-ils.search&method=open-ils.search.authority.fts";
1951     url += '&param="term"&param="' + term + '"';
1952     url += '&param="limit"&param=' + limit;
1953     url += '&param="tag"&param=' + tag;
1954     url += '&param="subfield"&param="' + sf + '"';
1955
1956
1957     var req = new XMLHttpRequest();
1958     req.open('GET',url,false);
1959     req.send(null);
1960
1961     return req;
1962
1963 }
1964
1965 /* TODO new authority browse support for context sets, and use that here */
1966 function browseAuthority (sf_popup, menu_id, target, sf, limit, page) {
1967     dojo.require('dojox.xml.parser');
1968
1969     // map tag + subfield to the appropriate authority browse axis:
1970     // currently authority.author, authority.subject, authority.title, authority.topic
1971     // based on mappings in OpenILS::Application::SuperCat, though Authority Control
1972     // Sets will change that
1973
1974     var axis_list = acs.bibFieldBrowseAxes( sf.parent().@tag.toString() );
1975
1976     // No matching tag means no authorities to search - shortcut
1977     if (axis_list.length == 0) {
1978         target.setAttribute('context', 'clipboard');
1979         return false;
1980     }
1981
1982     var type = 'authority.' + axis_list[0]; // Just take the first for now
1983                                             // TODO support multiple axes ... loop?
1984     if (!limit) {
1985         limit = 10;
1986     }
1987
1988     if (!page) {
1989         page = 0;
1990     }
1991
1992     var sf_string = '';
1993     var sf_list = sf.parent().subfield;
1994     for ( var i in sf_list) {
1995         sf_string += sf_list[i].toString() + ' ';
1996         if (sf_list[i] === sf) break;
1997     }
1998
1999     var url = '/opac/extras/browse/marcxml/'
2000         + type + '.refs'
2001         + '/1' // OU - currently unscoped
2002         + '/' + sf_string
2003         + '/' + page
2004         + '/' + limit
2005     ;
2006
2007     // would be good to carve this out into a separate function
2008     dojo.xhrGet({"url":url, "sync": true, "preventCache": true, "handleAs":"xml", "load": function(records) {
2009         var create_menu = createMenu({ label: $('catStrings').getString('staff.cat.marcedit.create_authority.label')});
2010
2011         var cm_popup = create_menu.appendChild(
2012             createMenuPopup()
2013         );
2014
2015         cm_popup.appendChild(
2016             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.create_authority_now.label'),
2017                 command : function() { 
2018                     // Call middle-layer function to create and save the new authority
2019                     var source_f = summarizeField(sf);
2020                     var new_auth = fieldmapper.standardRequest(
2021                         ["open-ils.cat", "open-ils.cat.authority.record.create_from_bib"],
2022                         [source_f, xulG.marc_control_number_identifier, ses()]
2023                     );
2024                     if (new_auth && new_auth.id()) {
2025                         addNewAuthorityID(new_auth, sf, target);
2026                     }
2027                 }
2028             })
2029         );
2030
2031         cm_popup.appendChild(
2032             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.create_authority_edit.label'),
2033                 command : function() { 
2034                     // Generate the new authority by calling the new middle-layer
2035                     // function (a non-saving variant), then display in another
2036                     // MARC editor
2037                     var source_f = summarizeField(sf);
2038                     var authtoken = ses();
2039                     dojo.require('openils.PermaCrud');
2040                     var pcrud = new openils.PermaCrud({"authtoken": authtoken});
2041                     var rec = fieldmapper.standardRequest(
2042                         ["open-ils.cat", "open-ils.cat.authority.record.create_from_bib.readonly"],
2043                         { "params": [source_f, xulG.marc_control_number_identifier] }
2044                     );
2045                     loadMarcEditor(pcrud, rec, target, sf);
2046                 }
2047             })
2048         );
2049
2050         sf_popup.appendChild(create_menu);
2051         sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
2052
2053         // append "Previous page" results browser
2054         sf_popup.appendChild(
2055             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.previous_page.label'),
2056                 command : function(event) { 
2057                     auth_pages[menu_id] -= 1;
2058                     show_auth_menu = true;
2059                 }
2060             })
2061         );
2062         sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
2063
2064         dojo.query('record', records).forEach(function(record) {
2065             var main_text = '';
2066             var see_from = [];
2067             var see_also = [];
2068             var auth_id = dojox.xml.parser.textContent(dojo.query('datafield[tag="901"]', record).query('subfield[code="c"]')[0]);
2069             var auth_org = '';
2070             if (dojo.query('controlfield[tag="003"]', record).length > 0) {
2071                 auth_org = dojox.xml.parser.textContent(dojo.query('controlfield[tag="003"]', record)[0]);
2072             }
2073
2074             // Grab the fields with tags beginning with 1 (main entries) and iterate through the subfields
2075             dojo.query('datafield[tag^="1"]', record).forEach(function(field) {
2076                 dojo.query('subfield', field).forEach(function(subfield) {
2077                     if (main_text) {
2078                         main_text += ' / ';
2079                     }
2080                     main_text += dojox.xml.parser.textContent(subfield);
2081                 });
2082             });
2083
2084             // Grab the fields with tags beginning with 4 (see from entries) and iterate through the subfields
2085             dojo.query('datafield[tag^="4"]', record).forEach(function(field) {
2086                 var see_text = '';
2087                 dojo.query('subfield', field).forEach(function(subfield) {
2088                     if (see_text) {
2089                         see_text += ' / ';
2090                     }
2091                     see_text += dojox.xml.parser.textContent(subfield);
2092                 });
2093                 see_from.push($('catStrings').getFormattedString('staff.cat.marcedit.authority_see_from', [see_text]));
2094             });
2095
2096             // Grab the fields with tags beginning with 5 (see also entries) and iterate through the subfields
2097             dojo.query('datafield[tag^="5"]', record).forEach(function(field) {
2098                 var see_text = '';
2099                 dojo.query('subfield', field).forEach(function(subfield) {
2100                     if (see_text) {
2101                         see_text += ' / ';
2102                     }
2103                     see_text += dojox.xml.parser.textContent(subfield);
2104                 });
2105                 see_also.push($('catStrings').getFormattedString('staff.cat.marcedit.authority_see_also', [see_text]));
2106             });
2107
2108             buildAuthorityPopup(main_text, record, auth_org, auth_id, sf_popup, target, sf);
2109
2110             dojo.forEach(see_from, function(entry_text) {
2111                 buildAuthorityPopup(entry_text, record, auth_org, auth_id, sf_popup, target, sf, "font-style: italic; margin-left: 2em;");
2112             });
2113
2114             // To-do: instead of launching the standard selector menu, invoke
2115             // a new authority search using the 5XX entry text
2116             dojo.forEach(see_also, function(entry_text) {
2117                 buildAuthorityPopup(entry_text, record, auth_org, auth_id, sf_popup, target, sf, "font-style: italic; margin-left: 2em;");
2118             });
2119
2120         });
2121
2122         if (sf_popup.childNodes.length == 0) {
2123             sf_popup.appendChild(createLabel( { value : $('catStrings').getString('staff.cat.marcedit.no_authority_match.label') } ) );
2124         } else {
2125             // append "Next page" results browser
2126             sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
2127             sf_popup.appendChild(
2128                 createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.next_page.label'),
2129                     command : function(event) { 
2130                         auth_pages[menu_id] += 1;
2131                         show_auth_menu = true;
2132                     }
2133                 })
2134             );
2135         }
2136
2137         target.setAttribute('context', menu_id);
2138         return true;
2139     }});
2140
2141 }
2142
2143 function buildAuthorityPopup (entry_text, record, auth_org, auth_id, sf_popup, target, sf, style) {
2144     var grid = dojo.query('[name="authority-marc-template"]')[0].cloneNode(true);
2145     grid.setAttribute('name','-none-');
2146     grid.setAttribute('style','overflow:scroll');
2147
2148     var submenu = createMenu( { "label": entry_text } );
2149
2150     var popup = createMenuPopup({ "flex": "1" });
2151     if (style) {
2152         submenu.setAttribute('style', style);
2153         popup.setAttribute('style', 'font-style: normal; margin-left: 0em;');
2154     }
2155     submenu.appendChild(popup);
2156
2157     dojo.query('datafield[tag^="1"]', record).forEach(function(field) {
2158         buildAuthorityPopupSelector(field, grid, auth_org, auth_id);
2159     });
2160     dojo.query('datafield[tag^="4"]', record).forEach(function(field) {
2161         buildAuthorityPopupSelector(field, grid, auth_org, auth_id);
2162     });
2163     dojo.query('datafield[tag^="5"]', record).forEach(function(field) {
2164         buildAuthorityPopupSelector(field, grid, auth_org, auth_id);
2165     });
2166
2167     grid.hidden = false;
2168     popup.appendChild( grid );
2169
2170     popup.appendChild(
2171         createMenuitem(
2172             { label : $('catStrings').getString('staff.cat.marcedit.apply_selected.label'),
2173               command : function (event) {
2174                     applySelectedAuthority(event.target.previousSibling, target, sf);
2175                     return true;
2176               }
2177             }
2178         )
2179     );
2180
2181     popup.appendChild( createComplexXULElement( 'menuseparator' ) );
2182
2183     popup.appendChild(
2184         createMenuitem(
2185             { label : $('catStrings').getString('staff.cat.marcedit.apply_full.label'),
2186               command : function (event) {
2187                     applyFullAuthority(event.target.previousSibling.previousSibling.previousSibling, target, sf);
2188                     return true;
2189               }
2190             }
2191         )
2192     );
2193
2194     sf_popup.appendChild( submenu );
2195 }
2196
2197 function buildAuthorityPopupSelector (field, grid, auth_org, auth_id) {
2198     var row = createRow(
2199         { },
2200         createLabel( { "value" : dojo.attr(field, 'tag') } ),
2201         createLabel( { "value" : dojo.attr(field, 'ind1') } ),
2202         createLabel( { "value" : dojo.attr(field, 'ind2') } )
2203     );
2204
2205     var sf_box = createHbox();
2206     dojo.query('subfield', field).forEach(function(subfield) {
2207         sf_box.appendChild(
2208             createCheckbox(
2209                 { "label"    : '\u2021' + dojo.attr(subfield, 'code') + ' ' + dojox.xml.parser.textContent(subfield),
2210                   "subfield" : dojo.attr(subfield, 'code'),
2211                   "tag"      : dojo.attr(field, 'tag'),
2212                   "value"    : dojox.xml.parser.textContent(subfield)
2213                 }
2214             )
2215         );
2216         row.appendChild(sf_box);
2217     });
2218
2219     // Append the authority linking subfield only for main entries
2220     if (dojo.attr(field, 'tag').charAt(0) == '1') {
2221         sf_box.appendChild(
2222             createCheckbox(
2223                 { "label"    : '\u2021' + '0' + ' (' + auth_org + ')' + auth_id,
2224                   "subfield" : '0',
2225                   "tag"      : dojo.attr(field, 'tag'),
2226                   "ind1"     : dojo.attr(field, 'ind1'),
2227                   "ind2"     : dojo.attr(field, 'ind2'),
2228                   "value"    : '(' + auth_org + ')' + auth_id
2229                 }
2230             )
2231         );
2232     }
2233     row.appendChild(sf_box);
2234
2235     grid.lastChild.appendChild(row);
2236 }
2237
2238 function summarizeField(sf) {
2239     var source_f= {
2240         "tag": '',
2241         "ind1": '',
2242         "ind2": '',
2243         "subfields": []
2244     };
2245
2246     source_f.tag = sf.parent().@tag.toString();
2247     source_f.ind1 = sf.parent().@ind1.toString();
2248     source_f.ind2 = sf.parent().@ind2.toString();
2249
2250     var found_acs = [];
2251     dojo.forEach( acs.controlSetList(), function (acs_id) {
2252         if (acs.controlSet(acs_id).control_map[sf.parent().@tag]) found_acs.push(acs_id);
2253     });
2254
2255     var cmap;
2256     if (!found_acs.length) {
2257         return false;
2258     } else {
2259         cmap = acs.controlSet(found_acs[0]).control_map;
2260     }
2261
2262     for (var i = 0; i < sf.parent().subfield.length(); i++) {
2263         var sf_iter = sf.parent().subfield[i];
2264
2265         /* Filter out subfields that are not controlled for this tag */
2266         if (!cmap[source_f.tag][sf_iter.@code.toString()]) {
2267             continue;
2268         }
2269
2270         source_f.subfields.push([sf_iter.@code.toString(), sf_iter.toString()]);
2271     }
2272
2273     return source_f;
2274 }
2275
2276 function buildBibSourceList (authtoken, recId) {
2277     /* TODO: Work out how to set the bib source of the bre that does not yet
2278      * exist - this is specifically in the case of Z39.50 imports. Right now
2279      * we just avoid populating and showing the config.bib_source list
2280      */
2281     if (!recId) {
2282         return false;
2283     }
2284
2285     var bib = xulG.record.bre;
2286
2287     dojo.require('openils.PermaCrud');
2288
2289     // cbsList = the XUL menulist that contains the available bib sources 
2290     var cbsList = dojo.byId('bib-source-list');
2291
2292     // bibSources = an array containing all of the bib source objects
2293     var bibSources = new openils.PermaCrud({"authtoken": authtoken}).retrieveAll('cbs');
2294
2295     // A tad ugly, but gives us the index of the bib source ID in cbsList
2296     var x = 0;
2297     var cbsListArr = [];
2298     dojo.forEach(bibSources, function (item) {
2299         cbsList.appendItem(item.source(), item.id());
2300         cbsListArr[item.id()] = x;
2301         x++;
2302     });
2303
2304     // Show the current value of the bib source for this record
2305     cbsList.selectedIndex = cbsListArr[bib.source()];
2306
2307     // Display the bib source selection widget
2308     dojo.byId('bib-source-list-caption').hidden = false;
2309     dojo.byId('bib-source-list').hidden = false;
2310     dojo.byId('bib-source-list-button').disabled = true;
2311     dojo.byId('bib-source-list-button').hidden = false;
2312 }
2313
2314 // Fired when the "Update Source" button is clicked
2315 // Updates the value of the bib source for the current record
2316 function updateBibSource() {
2317     var authtoken = ses();
2318     var cbs = dojo.byId('bib-source-list').selectedItem.value;
2319     var recId = xulG.record.id;
2320     var pcrud = new openils.PermaCrud({"authtoken": authtoken});
2321     var bib = pcrud.retrieve('bre', recId);
2322     if (bib.source() != cbs) {
2323         bib.source(cbs);
2324         bib.ischanged = true;
2325         pcrud.update(bib);
2326     }
2327 }
2328
2329 function onBibSourceSelect() {
2330     var cbs = dojo.byId('bib-source-list').selectedItem.value;
2331     var bib = xulG.record.bre;
2332     if (bib.source() != cbs) {
2333         dojo.byId('bib-source-list-button').disabled = false;   
2334     } else {
2335         dojo.byId('bib-source-list-button').disabled = true;   
2336     }
2337 }
2338
2339 function addNewAuthorityID(authority, sf, target) {
2340     var id_sf = <subfield code="0" xmlns="http://www.loc.gov/MARC21/slim">({xulG.marc_control_number_identifier}){authority.id()}</subfield>;
2341     sf.parent().appendChild(id_sf);
2342     var new_sf = marcSubfield(id_sf);
2343
2344     var node = target;
2345     while (dojo.attr(node, 'name') != 'sf_box') {
2346         node = node.parentNode;
2347     }
2348     node.appendChild( new_sf );
2349
2350     alert($('catStrings').getString('staff.cat.marcedit.create_authority_success.label'));
2351 }
2352
2353 function loadMarcEditor(pcrud, marcxml, target, sf) {
2354     /*
2355        To run in Firefox directly, must set signed.applets.codebase_principal_support
2356        to true in about:config
2357      */
2358     win = window.open('/xul/server/cat/marcedit.xul', '_blank', 'chrome'); // XXX version?
2359
2360     // Match marc2are.pl last_xact_id format, roughly
2361     var now = new Date;
2362     var xact_id = 'IMPORT-' + Date.parse(now);
2363     
2364     win.xulG = {
2365         "record": {"marc": marcxml, "rtype": "are"},
2366         "save": {
2367             "label": $('catStrings').getString('staff.cat.marcedit.save.label'),
2368             "func": function(xmlString) {
2369                 var rec = new are();
2370                 rec.marc(xmlString);
2371                 rec.last_xact_id(xact_id);
2372                 rec.isnew(true);
2373                 pcrud.create(rec, {
2374                     "oncomplete": function (r, objs) {
2375                         var new_rec = objs[0];
2376                         if (!new_rec) {
2377                             return '';
2378                         }
2379
2380                         addNewAuthorityID(new_rec, sf, target);
2381
2382                         win.close();
2383                     }
2384                 });
2385             }
2386         }
2387     };
2388 }
2389
2390