]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/xul/staff_client/server/cat/marcedit.js
LP#1398926: Allow symbol popup to trigger on new marc fields
[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         var tabs = window.parent.parent.document.getElementById('main_tabs');
570
571         if (tabs) {
572             var idx = tabs.selectedIndex;
573             var tab = tabs.childNodes[idx];
574         }
575         //dump('keypress: isChar = ' + ev.isChar + ' char = ' + ev.char + ' charCode = ' + ev.charCode + ' key = ' + ev.key + ' keyCode = ' + ev.keyCode + '\n');
576         if (! /* NOT */(
577                 ev.altKey
578                 || ev.ctrlKey
579                 || ev.metaKey
580                 || ev.shiftKey
581                 || ev.keyCode == ev.DOM_VK_F1
582                 || ev.keyCode == ev.DOM_VK_F2
583                 || ev.keyCode == ev.DOM_VK_F3
584                 || ev.keyCode == ev.DOM_VK_F4
585                 || ev.keyCode == ev.DOM_VK_F5
586                 || ev.keyCode == ev.DOM_VK_F6
587                 || ev.keyCode == ev.DOM_VK_F7
588                 || ev.keyCode == ev.DOM_VK_F8
589                 || ev.keyCode == ev.DOM_VK_F9
590                 || ev.keyCode == ev.DOM_VK_F10
591                 || ev.keyCode == ev.DOM_VK_F11
592                 || ev.keyCode == ev.DOM_VK_F12
593                 || ev.keyCode == ev.DOM_VK_F13
594                 || ev.keyCode == ev.DOM_VK_F14
595                 || ev.keyCode == ev.DOM_VK_F15
596                 || ev.keyCode == ev.DOM_VK_F16
597                 || ev.keyCode == ev.DOM_VK_F17
598                 || ev.keyCode == ev.DOM_VK_F18
599                 || ev.keyCode == ev.DOM_VK_F19
600                 || ev.keyCode == ev.DOM_VK_F20
601                 || ev.keyCode == ev.DOM_VK_F21
602                 || ev.keyCode == ev.DOM_VK_F22
603                 || ev.keyCode == ev.DOM_VK_F23
604                 || ev.keyCode == ev.DOM_VK_F24
605         )) {
606             var params = {};
607             params.allow_multiple_locks = tab.marc_edit_allow_multiple_locks;
608             oils_lock_page(params);
609         }
610     } catch(E) {
611         alert(E);
612     }
613 }
614
615 function createMARCTextbox (element,attrs) {
616     var box = createComplexXULElement('textbox', attrs, Array.prototype.slice.apply(arguments, [2]) );
617     box.addEventListener(
618         'keypress',
619         set_lock_on_keypress,
620         false
621     );
622     if ($('symbol-panel')) {
623         addSymbolTrigger(box);
624     }
625     box.onkeypress = function (event) {
626         var root_node;
627         var node = element;
628         while(node = node.parent()) {
629             root_node = node;
630         }
631
632         var row = event.target;
633         while (row.tagName != 'row') row = row.parentNode;
634
635         if (element.nodeKind() == 'attribute') element[0]=box.value;
636         else element.setChildren( box.value );
637
638         if (element.localName() != 'controlfield') {
639             if ((event.charCode == 100 || event.charCode == 105) && event.ctrlKey) { // ctrl+d or ctrl+i
640
641                 var index_sf, target, move_data;
642                 if (element.localName() == 'subfield') {
643                     index_sf = element;
644                     target = event.target.parentNode;
645
646                     var start = event.target.selectionStart;
647                     var end = event.target.selectionEnd - event.target.selectionStart ?
648                             event.target.selectionEnd :
649                             event.target.value.length;
650
651                     move_data = event.target.value.substring(start,end);
652                     event.target.value = event.target.value.substring(0,start) + event.target.value.substring(end);
653                     event.target.setAttribute('size', event.target.value.length + 2);
654     
655                     element.setChildren( event.target.value );
656
657                 } else if (element.localName() == 'code') {
658                     index_sf = element.parent();
659                     target = event.target.parentNode;
660                 } else if (element.localName() == 'tag' || element.localName() == 'ind1' || element.localName() == 'ind2') {
661                     index_sf = element.parent().children()[element.parent().children().length() - 1];
662                     target = event.target.parentNode.lastChild.lastChild;
663                 }
664
665                 var sf = <subfield code="" xmlns="http://www.loc.gov/MARC21/slim">{ move_data }</subfield>;
666
667                 index_sf.parent().insertChildAfter( index_sf, sf );
668
669                 var new_sf = marcSubfield(sf);
670
671                 if (target === target.parentNode.lastChild) {
672                     target.parentNode.appendChild( new_sf );
673                 } else {
674                     target.parentNode.insertBefore( new_sf, target.nextSibling );
675                 }
676
677                 new_sf.firstChild.nextSibling.focus();
678
679                 event.preventDefault();
680                 return false;
681
682             } else if (event.keyCode == 13 || event.keyCode == 77) {
683                 if (event.ctrlKey) { // ctrl+enter
684
685                     var index;
686                     if (element.localName() == 'subfield') index = element.parent();
687                     if (element.localName() == 'code') index = element.parent().parent();
688                     if (element.localName() == 'tag') index = element.parent();
689                     if (element.localName() == 'ind1') index = element.parent();
690                     if (element.localName() == 'ind2') index = element.parent();
691
692                     var df = <datafield tag="" ind1="" ind2="" xmlns="http://www.loc.gov/MARC21/slim"><subfield code="" /></datafield>;
693
694                     if (event.shiftKey) { // ctrl+shift+enter
695                         index.parent().insertChildBefore( index, df );
696                     } else {
697                         index.parent().insertChildAfter( index, df );
698                     }
699
700                     var new_df = marcDatafield(df);
701
702                     if (row.parentNode.lastChild === row) {
703                         row.parentNode.appendChild( new_df );
704                     } else {
705                         if (event.shiftKey) { // ctrl+shift+enter
706                             row.parentNode.insertBefore( new_df, row );
707                         } else {
708                             row.parentNode.insertBefore( new_df, row.nextSibling );
709                         }
710                     }
711
712                     new_df.firstChild.focus();
713
714                     event.preventDefault();
715                     return false;
716
717                 } else if (event.shiftKey) {
718                     if (row.previousSibling.className.match('marcDatafieldRow'))
719                         row.previousSibling.firstChild.focus();
720                 } else {
721                     row.nextSibling.firstChild.focus();
722                 }
723
724             } else if (event.keyCode == 38 || event.keyCode == 40) { // up-arrow or down-arrow
725                 if (event.ctrlKey) { // CTRL key: copy the field
726                     var index;
727                     if (element.localName() == 'subfield') index = element.parent();
728                     if (element.localName() == 'code') index = element.parent().parent();
729                     if (element.localName() == 'tag') index = element.parent();
730                     if (element.localName() == 'ind1') index = element.parent();
731                     if (element.localName() == 'ind2') index = element.parent();
732
733                     var copyField = index.copy();
734
735                     if (event.keyCode == 38) { // ctrl+up-arrow
736                         index.parent().insertChildBefore( index, copyField );
737                     } else {
738                         index.parent().insertChildAfter( index, copyField );
739                     }
740
741                     var new_df = marcDatafield(copyField);
742
743                     if (row.parentNode.lastChild === row) {
744                         row.parentNode.appendChild( new_df );
745                     } else {
746                         if (event.keyCode == 38) { // ctrl+up-arrow
747                             row.parentNode.insertBefore( new_df, row );
748                         } else { // ctrl+down-arrow
749                             row.parentNode.insertBefore( new_df, row.nextSibling );
750                         }
751                     }
752
753                     new_df.firstChild.focus();
754
755                     event.preventDefault();
756
757                     return false;
758                 } else {
759                     if (event.keyCode == 38) {
760                         return setFocusToNextTag(row, 'up');
761                     }
762                     if (event.keyCode == 40) {
763                         return setFocusToNextTag(row, 'down');
764                     }
765                     return false;
766                 }
767
768             } else if (event.keyCode == 46 && event.ctrlKey) { // ctrl+del
769
770                 var index;
771                 if (element.localName() == 'subfield') index = element.parent();
772                 if (element.localName() == 'code') index = element.parent().parent();
773                 if (element.localName() == 'tag') index = element.parent();
774                 if (element.localName() == 'ind1') index = element.parent();
775                 if (element.localName() == 'ind2') index = element.parent();
776
777                 for (var i in index.parent().children()) {
778                     if (index === index.parent().children()[i]) {
779                         delete index.parent().children()[i];
780                         break;
781                     }
782                 }
783
784                 row.previousSibling.firstChild.focus();
785                 row.parentNode.removeChild(row);
786
787                 event.preventDefault();
788                 return false;
789
790             } else if (event.keyCode == 46 && event.shiftKey) { // shift+del
791
792                 var index;
793                 if (element.localName() == 'subfield') index = element;
794                 if (element.localName() == 'code') index = element.parent();
795
796                 if (index) {
797                     for (var i in index.parent().children()) {
798                         if (index === index.parent().children()[i]) {
799                             delete index.parent().children()[i];
800                             break;
801                         }
802                     }
803
804                     if (event.target.parentNode === event.target.parentNode.parentNode.lastChild) {
805                         event.target.parentNode.previousSibling.lastChild.focus();
806                     } else {
807                         event.target.parentNode.nextSibling.firstChild.nextSibling.focus();
808                     }
809
810                     event.target.parentNode.parentNode.removeChild(event.target.parentNode);
811
812                     event.preventDefault();
813                     return false;
814                 }
815             } else if (event.keyCode == 117 && event.ctrlKey) { // ctrl + F6
816                 box = null;
817                 createControlField('006','                                        ');
818                 loadRecord();
819             } else if (event.keyCode == 118 && event.ctrlKey) { // ctrl + F7
820                 box = null;
821                 createControlField('007','                                        ');
822                 loadRecord();
823             } else if (event.keyCode == 119 && event.ctrlKey) { // ctrl + F8
824                 box = null;
825                 createControlField('008', get_new_008());
826                 loadRecord();
827             }
828
829             return true;
830
831         } else { // event on a control field
832             if (event.keyCode == 38) { 
833                 return setFocusToNextTag(row, 'up'); 
834             } else if (event.keyCode == 40) { 
835                 return setFocusToNextTag(row, 'down');
836             }
837         }
838     };
839
840     box.addEventListener(
841         'keypress', 
842         function () {
843             if (element.nodeKind() == 'attribute') element[0]=box.value;
844             else element.setChildren( box.value );
845             return true;
846         },
847         false
848     );
849
850     box.addEventListener(
851         'change', 
852         function () {
853             if (element.nodeKind() == 'attribute') element[0]=box.value;
854             else element.setChildren( box.value );
855             return true;
856         },
857         false
858     );
859
860     box.addEventListener(
861         'keypress', 
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     // 'input' event catches the box value after the keypress
871     box.addEventListener(
872         'input', 
873         function () {
874             if (element.nodeKind() == 'attribute') element[0]=box.value;
875             else element.setChildren( box.value );
876             return true;
877         },
878         true
879     );
880
881     box.addEventListener(
882         'keyup', 
883         function () {
884             if (element.localName() == 'controlfield')
885                 eval('fillFixedFields();');
886         },
887         true
888     );
889
890     return box;
891 }
892
893 function toggleFFE () {
894     var grid = document.getElementById('leaderGrid');
895     if (grid.hidden) {
896         grid.hidden = false;
897     } else {
898         grid.hidden = true;
899     }
900     return true;
901 }
902
903 function changeFFEditor (type) {
904     var grid = document.getElementById('leaderGrid');
905     grid.setAttribute('type',type);
906     document.getElementById('recordTypeLabel').setAttribute('value',type);
907
908     // Hide FFEditor rows that we don't need for our current type
909     // If all of the labels for a given row do not include our
910     // desired type in their set attribute, we can hide that row
911     dojo.query('rows', grid).query('row').forEach(function(node, index, arr) {
912         if (dojo.query('label[set~=' + type + ']', node).length == 0) {
913             node.hidden = true;
914         }
915     });
916
917     getFFValuesForType(
918         type,
919         function() {
920             updateFFEditorContexts(grid, type);
921         },
922         function() {
923             alert(  /* XXX i18n - the marc editor either isn't tied in to
924                        an overall i18n infrastructure, or it's different
925                        enough from other Evergreen parts that I don't
926                        understand the right way to do i18n here */
927                 "failed to load fixed field values for rec_type '" +
928                 type + "'\n"
929             );
930         }
931     );
932 }
933
934 function getFFValuesForType(type, callback, errback) {
935     if (_fixed_field_values[type]) {
936         callback();
937     } else {
938         dojo.require("openils.Util");
939
940         fieldmapper.standardRequest(
941             ["open-ils.cat",
942                 "open-ils.cat.biblio.fixed_field_values.by_rec_type"], {
943                 "async": true,
944                 "params": [type],
945                 "oncomplete": function(r) {
946                     if (r = openils.Util.readResponse(r)) {
947                         _fixed_field_values[type] = r;
948                         callback();
949                     } else {
950                         errback();
951                     }
952                 },
953                 "onerror": errback
954             }
955         );
956     }
957 }
958
959 function updateFFEditorContexts(grid, type) {
960
961     /* XXX Dojo to navigate a XUL DOM.  Bad form?  We do it elsewhere in this
962      * file, but I think I've heard it scoffed at. */
963
964     var rows_node = dojo.query("rows", grid)[0];
965     dojo.query("row", rows_node).forEach(
966         function(row) {
967             dojo.query("textbox", row).forEach(
968                 function(tb) {
969                     var name = tb.getAttribute("name");
970                     if (_fixed_field_values[type][name]) {
971                         tb.setAttribute(
972                             "context", getFFContextMenu(type, name)
973                         );
974                     } else {
975                         tb.setAttribute("context", "clipboard");
976                     }
977                 }
978             );
979         }
980     );
981 }
982
983 function getFFContextMenu(type, name) {
984     if (!_fixed_field_context_menus[type]) {
985         _fixed_field_context_menus[type] = {};
986     }
987
988     var context_menu_id = "_fixed_field_context_menus_" + type + "_" + name;
989
990     if (!_fixed_field_context_menus[type][name]) {
991         var p = document.getElementsByTagName("popupset")[0];
992         var m = document.createElement("menupopup");
993         m.setAttribute("id", context_menu_id);
994         _fixed_field_values[type][name].forEach(
995             function(v) {
996                 var mi = document.createElement("menuitem");
997                 var funcname = "_ff_anon_" +
998                     String(_fixed_field_anonymous_func_counter++);
999
1000                 /* These anon functions linger and take up memory, but due
1001                  * to caching there's a limit on how much, and that limit is
1002                  * a function of the size of the dataset defined in the
1003                  * ccvm/cmfpm tables. */
1004                 var code = v[0];
1005                 var len = v[2];
1006                 var def = v[3];
1007                 var el = document.getElementById(name + "_tb");
1008                 window[funcname] = function() {
1009                     el.value = code;
1010                     while (el.value.length < len) {
1011                         el.value += def;
1012                     }
1013                     updateFixedFields(el);
1014                     oils_lock_page();
1015                 };
1016
1017                 /* In XUL land we can't set an element's
1018                  * attribute like oncommand to a code reference. It has to be
1019                  * an actual string to be eval'd. */
1020                 mi.setAttribute("oncommand", funcname + "()");
1021                 mi.setAttribute("label", v[0] + ": " + v[1]); /* XXX i18n ? */
1022                 m.appendChild(mi);
1023             }
1024         );
1025         _fixed_field_context_menus[type][name] = m;
1026         p.appendChild(m);
1027     }
1028
1029     return context_menu_id;
1030 }
1031
1032 /* This just sets up a special context menu for a 007 data field to use, so
1033  * that users can right-click for a menu and get a choice to launch the
1034  * Physical Characteristics Wizard.
1035  */
1036 function preparePhysCharWizardContext() {
1037     var menu = document.getElementById("physCharWizardContext");
1038     menu.appendChild(document.createElement("menuseparator"));
1039
1040     var clipb_children = document.getElementById("clipboard").childNodes;
1041     for (var i = 0; i < clipb_children.length; i++) /* collection not array */ {
1042         var child = clipb_children[i];
1043         if (child.nodeName == 'menuitem')
1044             menu.appendChild(child.cloneNode(true));
1045     }
1046 }
1047
1048 function launchPhysCharWizard(popup_node) {
1049     try {
1050         new openils.widget.PhysCharWizard({
1051             "node": popup_node,
1052             "onapply": function(v) {
1053                 createControlField("007", v);
1054                 oils_lock_page();
1055                 loadRecord();
1056             }
1057         });
1058     } catch (E) {
1059         alert("Exception raised by openils.widget.PhysCharWizard:\n" + E);
1060     }
1061 }
1062
1063 function fillFixedFields () {
1064     try {
1065             var grid = document.getElementById('leaderGrid');
1066             var marc_rec = new MARC.Record ({ delimiter : '$', marcxml : xml_record.toXMLString() });
1067
1068             var list = [];
1069             var pre_list = grid.getElementsByTagName('label');
1070             for (var i in pre_list) {
1071                 if ( pre_list[i].getAttribute && pre_list[i].getAttribute('set').indexOf(grid.getAttribute('type')) > -1 ) {
1072                     list.push( pre_list[i] );
1073                 }
1074             }
1075
1076             for (var i in list) {
1077                 var name = list[i].getAttribute('name');
1078                 var value = marc_rec.extractFixedField(name, true);
1079
1080                 if (value === null) continue;
1081
1082                 list[i].nextSibling.value = value;
1083             }
1084
1085             return true;
1086     } catch(E) {
1087         alert('FIXME, MARC Editor, fillFixedFields: ' + E);
1088     }
1089 }
1090
1091 function updateFixedFields (element) {
1092     var new_value = element.value;
1093
1094     var marc_rec = new MARC.Record ({ delimiter : '$', marcxml : xml_record.toXMLString() });
1095     marc_rec.setFixedField(element.getAttribute('name'), new_value);
1096
1097     var xml_string = marc_rec.toXmlString();
1098     xml_record = new XML( xml_string );
1099     if (xml_record..record[0]) xml_record = xml_record..record[0];
1100     loadRecord();
1101     // Put the cursor back to the current fixed field
1102     element.select();
1103
1104     return true;
1105 }
1106
1107 function marcLeader (leader) {
1108     var row = createRow(
1109         { class : 'marcLeaderRow',
1110           tag : 'ldr' },
1111         createLabel(
1112             { value : 'LDR',
1113               class : 'marcTag',
1114               tooltiptext : $('catStrings').getString('staff.cat.marcedit.marcTag.LDR.label') } ),
1115         createLabel(
1116             { value : '',
1117               class : 'marcInd1' } ),
1118         createLabel(
1119             { value : '',
1120               class : 'marcInd2' } ),
1121         createLabel(
1122             { value : leader.text(),
1123               class : 'marcLeader' } )
1124     );
1125
1126     return row;
1127 }
1128
1129 function marcControlfield (field) {
1130     tagname = field.@tag.toString().substr(2);
1131     var row;
1132     if (tagname == '1' || tagname == '3' || tagname == '6' || tagname == '7' || tagname == '8') {
1133         row = createRow(
1134             { class : 'marcControlfieldRow',
1135               tag : '_' + tagname },
1136             createLabel(
1137                 { value : field.@tag,
1138                   class : 'marcTag',
1139                   context : 'tags_popup',
1140                   onmouseover : 'getTooltip(this, "tag");',
1141                   tooltipid : 'tag' + field.@tag } ),
1142             createLabel(
1143                 { value : field.@ind1,
1144                   class : 'marcInd1',
1145                   onmouseover : 'getTooltip(this, "ind1");',
1146                   tooltipid : 'tag' + field.@tag + 'ind1val' + field.@ind1 } ),
1147             createLabel(
1148                 { value : field.@ind2,
1149                   class : 'marcInd2',
1150                   onmouseover : 'getTooltip(this, "ind2");',
1151                   tooltipid : 'tag' + field.@tag + 'ind2val' + field.@ind2 } ),
1152             createMARCTextbox(
1153                 field,
1154                 { value : field.text(),
1155                   class : 'plain marcEditableControlfield',
1156                   name : 'CONTROL' + tagname,
1157                   context : tagname == 7 ? 'physCharWizardContext': 'clipboard',
1158                   size : 50,
1159                   maxlength : 50 } )
1160             );
1161     } else {
1162         row = createRow(
1163             { class : 'marcControlfieldRow',
1164               tag : '_' + tagname },
1165             createLabel(
1166                 { value : field.@tag,
1167                   class : 'marcTag',
1168                   onmouseover : 'getTooltip(this, "tag");',
1169                   tooltipid : 'tag' + field.@tag } ),
1170             createLabel(
1171                 { value : field.@ind1,
1172                   class : 'marcInd1',
1173                   onmouseover : 'getTooltip(this, "ind1");',
1174                   tooltipid : 'tag' + field.@tag + 'ind1val' + field.@ind1 } ),
1175             createLabel(
1176                 { value : field.@ind2,
1177                   class : 'marcInd2',
1178                   onmouseover : 'getTooltip(this, "ind2");',
1179                   tooltipid : 'tag' + field.@tag + 'ind2val' + field.@ind2 } ),
1180             createLabel(
1181                 { value : field.text(),
1182                   class : 'marcControlfield' } )
1183         );
1184     }
1185
1186     return row;
1187 }
1188
1189 function stackSubfields(checkbox) {
1190     var list = document.getElementsByAttribute('name','sf_box');
1191
1192     var o = 'vertical';
1193     if (!checkbox.checked) o = 'horizontal';
1194     
1195     for (var i = 0; i < list.length; i++) {
1196         if (list[i]) list[i].setAttribute('orient',o);
1197     }
1198 }
1199
1200 function fastItemAdd_toggle(checkbox) {
1201     var x = document.getElementById('fastItemAdd_textboxes');
1202     if (checkbox.checked) {
1203         x.hidden = false;
1204         document.getElementById('fastItemAdd_callnumber').focus();
1205         document.getElementById('fastItemAdd_callnumber').select();
1206     } else {
1207         x.hidden = true;
1208     }
1209 }
1210
1211 function fastItemAdd_attempt(doc_id) {
1212     try {
1213         if (typeof window.xulG.fast_add_item != 'function') { return; }
1214         if (!document.getElementById('fastItemAdd_checkbox').checked) { return; }
1215         if (!document.getElementById('fastItemAdd_callnumber').value) { return; }
1216         if (!document.getElementById('fastItemAdd_barcode').value) { return; }
1217         window.xulG.fast_add_item( doc_id, document.getElementById('fastItemAdd_callnumber').value, document.getElementById('fastItemAdd_barcode').value );
1218         document.getElementById('fastItemAdd_barcode').value = '';
1219         return true;
1220     } catch(E) {
1221         alert('fastItemAdd_attempt: ' + E);
1222     }
1223 }
1224
1225 function save_attempt(xml_string) {
1226     try {
1227         var tabs = window.parent.parent.document.getElementById('main_tabs');
1228
1229         if (tabs) {
1230             var idx = tabs.selectedIndex;
1231             var tab = tabs.childNodes[idx];
1232         }
1233         var result = window.xulG.save.func( xml_string );
1234         // I'd prefer to pass on_complete on through to fast_item_add,
1235         // but with the way these window scopes get destroyed with
1236         // tab replacement, maybe not a good idea
1237         var replace_on_complete = false;
1238         if (result) {
1239             if (tab) {
1240                 tab.marc_edit_changed = false;
1241             }
1242             oils_unlock_page();
1243             if (result.id) {
1244                 replace_on_complete = fastItemAdd_attempt(result.id);
1245             }
1246         // When fastItemAdd is not used, replace_on_complete is undefined
1247         // When it is used, and successful, replace_on_complete will be set to true 
1248         // then we need it to execute on_complete()
1249             if ((replace_on_complete==undefined || replace_on_complete ) && typeof result.on_complete == 'function') {
1250                 result.on_complete();
1251             }
1252         }
1253     } catch(E) {
1254         alert('save_attempt: ' + E);
1255     }
1256 }
1257
1258 function marcDatafield (field) {
1259     var row = createRow(
1260         { class : 'marcDatafieldRow' },
1261         createMARCTextbox(
1262             field.@tag,
1263             { value : field.@tag,
1264               class : 'plain marcTag',
1265               name : 'marcTag',
1266               context : 'tags_popup',
1267               oninput : 'if (this.value.length == 3) { this.nextSibling.focus(); }',
1268               size : 3,
1269               maxlength : 3,
1270               onmouseover : 'current_focus = this; getTooltip(this, "tag");' } ),
1271         createMARCTextbox(
1272             field.@ind1,
1273             { value : field.@ind1,
1274               class : 'plain marcInd1',
1275               name : 'marcInd1',
1276               oninput : 'if (this.value.length == 1) { this.nextSibling.focus(); }',
1277               size : 1,
1278               maxlength : 1,
1279               onmouseover : 'current_focus = this; getContextMenu(this, "ind1"); getTooltip(this, "ind1");',
1280               oncontextmenu : 'getContextMenu(this, "ind1");' } ),
1281         createMARCTextbox(
1282             field.@ind2,
1283             { value : field.@ind2,
1284               class : 'plain marcInd2',
1285               name : 'marcInd2',
1286               oninput : 'if (this.value.length == 1) { this.nextSibling.firstChild.firstChild.focus(); }',
1287               size : 1,
1288               maxlength : 1,
1289               onmouseover : 'current_focus = this; getContextMenu(this, "ind2"); getTooltip(this, "ind2");',
1290               oncontextmenu : 'getContextMenu(this, "ind2");' } ),
1291         createHbox({ name : 'sf_box' })
1292     );
1293
1294     if (!current_focus && field.@tag == '') current_focus = row.childNodes[0];
1295     if (!current_focus && field.@ind1 == '') current_focus = row.childNodes[1];
1296     if (!current_focus && field.@ind2 == '') current_focus = row.childNodes[2];
1297
1298     var sf_box = row.lastChild;
1299     if (document.getElementById('stackSubfields').checked)
1300         sf_box.setAttribute('orient','vertical');
1301
1302     sf_box.addEventListener(
1303         'click',
1304         function (e) {
1305             if (sf_box === e.target) {
1306                 sf_box.lastChild.lastChild.focus();
1307             } else if (e.target.parentNode === sf_box) {
1308                 e.target.lastChild.focus();
1309             }
1310         },
1311         false
1312     );
1313
1314
1315     for (var i in field.subfield) {
1316         var sf = field.subfield[i];
1317         sf_box.appendChild(
1318             marcSubfield(sf)
1319         );
1320
1321         dojo.query('.marcSubfield', sf_box).forEach(wrap_long_fields);
1322
1323         if (sf.@code == '' && (!current_focus || current_focus.className.match(/Ind/)))
1324             current_focus = sf_box.lastChild.childNodes[1];
1325     }
1326
1327     return row;
1328 }
1329
1330 function marcSubfield (sf) {            
1331     return createHbox(
1332         { class : 'marcSubfieldBox' },
1333         createLabel(
1334             { value : "\u2021",
1335               class : 'plain marcSubfieldDelimiter',
1336               onmouseover : 'getTooltip(this.nextSibling, "subfield");',
1337               oncontextmenu : 'getContextMenu(this.nextSibling, "subfield");',
1338                 //onclick : 'this.nextSibling.focus();',
1339                 onfocus : 'this.nextSibling.focus();',
1340               size : 2 } ),
1341         createMARCTextbox(
1342             sf.@code,
1343             { value : sf.@code,
1344               class : 'plain marcSubfieldCode',
1345               align: 'start',
1346               name : 'marcSubfieldCode',
1347               onmouseover : 'current_focus = this; getContextMenu(this, "subfield"); getTooltip(this, "subfield");',
1348               oncontextmenu : 'getContextMenu(this, "subfield");',
1349               oninput : 'if (this.value.length == 1) { this.nextSibling.focus(); }',
1350               size : 2,
1351               maxlength : 1 } ),
1352         createMARCTextbox(
1353             sf,
1354             { value : sf.text(),
1355               name : sf.parent().@tag + ':' + sf.@code,
1356               class : 'plain marcSubfield', 
1357               align: 'start',
1358               onmouseover : 'getTooltip(this, "subfield");',
1359               contextmenu : function (event) { getAuthorityContextMenu(event.target, sf) },
1360               size : new String(sf.text()).length + 2,
1361               oninput : "this.setAttribute('size', this.value.length + 2);"
1362             } )
1363     );
1364 }
1365
1366 function loadRecord() {
1367     try {
1368             var tabs = window.parent.parent.document.getElementById('main_tabs');
1369
1370             if (tabs) {
1371                 var idx = tabs.selectedIndex;
1372                 var tab = tabs.childNodes[idx];
1373                 tab.marc_edit_changed = false;
1374                 tab.marc_edit_allow_multiple_locks = true;
1375             }
1376
1377             var grid_rows = document.getElementById('recGrid').lastChild;
1378
1379             while (grid_rows.firstChild) grid_rows.removeChild(grid_rows.firstChild);
1380
1381             grid_rows.appendChild( marcLeader( xml_record.leader ) );
1382
1383             for (var i in xml_record.controlfield) {
1384                 grid_rows.appendChild( marcControlfield( xml_record.controlfield[i] ) );
1385             }
1386
1387             for (var i in xml_record.datafield) {
1388                 grid_rows.appendChild( marcDatafield( xml_record.datafield[i] ) );
1389             }
1390
1391             grid_rows.getElementsByAttribute('class','marcDatafieldRow')[0].firstChild.focus();
1392
1393             var marc_rec = new MARC.Record ({ delimiter : '$', marcxml : xml_record.toXMLString() });
1394             changeFFEditor(marc_rec.recordType());
1395             fillFixedFields();
1396     } catch(E) {
1397         alert('FIXME, MARC Editor, loadRecord: ' + E);
1398     }
1399 }
1400
1401
1402 function genToolTips () {
1403     for (var i in bib_data.field) {
1404         var f = bib_data.field[i];
1405     
1406         tag_menu.appendChild(
1407             createMenuitem(
1408                 { label : f.@tag,
1409                   oncommand : 
1410                       'current_focus.value = "' + f.@tag + '";' +
1411                     'var e = document.createEvent("MutationEvents");' +
1412                     'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1413                     'current_focus.inputField.dispatchEvent(e);',
1414                   disabled : f.@tag < '010' ? "true" : "false",
1415                   tooltiptext : f.description }
1416             )
1417         );
1418     
1419         var i1_popup = createMenuPopup({position : 'after_start', id : 't' + f.@tag + 'i1' });
1420         context_menus.appendChild( i1_popup );
1421     
1422         var i2_popup = createMenuPopup({position : 'after_start', id : 't' + f.@tag + 'i2' });
1423         context_menus.appendChild( i2_popup );
1424     
1425         var sf_popup = createMenuPopup({position : 'after_start', id : 't' + f.@tag + 'sf' });
1426         context_menus.appendChild( sf_popup );
1427     
1428         tooltip_hash['tag' + f.@tag] = f.description;
1429         for (var j in f.indicator) {
1430             var ind = f.indicator[j];
1431             tooltip_hash['tag' + f.@tag + 'ind' + ind.@position + 'val' + ind.@value] = ind.description;
1432     
1433             if (ind.@position == 1) {
1434                 i1_popup.appendChild(
1435                     createMenuitem(
1436                         { label : ind.@value,
1437                           oncommand : 
1438                               'current_focus.value = "' + ind.@value + '";' +
1439                             'var e = document.createEvent("MutationEvents");' +
1440                             'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1441                             'current_focus.inputField.dispatchEvent(e);',
1442                           tooltiptext : ind.description }
1443                     )
1444                 );
1445             }
1446     
1447             if (ind.@position == 2) {
1448                 i2_popup.appendChild(
1449                     createMenuitem(
1450                         { label : ind.@value,
1451                           oncommand : 
1452                               'current_focus.value = "' + ind.@value + '";' +
1453                             'var e = document.createEvent("MutationEvents");' +
1454                             'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1455                             'current_focus.inputField.dispatchEvent(e);',
1456                           tooltiptext : ind.description }
1457                     )
1458                 );
1459             }
1460         }
1461     
1462         for (var j in f.subfield) {
1463             var sf = f.subfield[j];
1464             tooltip_hash['tag' + f.@tag + 'sf' + sf.@code] = sf.description;
1465     
1466             sf_popup.appendChild(
1467                 createMenuitem(
1468                     { label : sf.@code,
1469                       oncommand : 
1470                           'current_focus.value = "' + sf.@code + '";' +
1471                         'var e = document.createEvent("MutationEvents");' +
1472                         'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1473                         'current_focus.inputField.dispatchEvent(e);',
1474                       tooltiptext : sf.description
1475                     }
1476                 )
1477             );
1478         }
1479     }
1480 }
1481
1482 function getTooltip (target, type) {
1483
1484     var tt = '';
1485     if (type == 'subfield')
1486         tt = 'tag' + target.parentNode.parentNode.parentNode.firstChild.value + 'sf' + target.parentNode.childNodes[1].value;
1487
1488     if (type == 'ind1')
1489         tt = 'tag' + target.parentNode.firstChild.value + 'ind1val' + target.value;
1490
1491     if (type == 'ind2')
1492         tt = 'tag' + target.parentNode.firstChild.value + 'ind2val' + target.value;
1493
1494     if (type == 'tag')
1495         tt = 'tag' + target.parentNode.firstChild.value;
1496
1497     if (!document.getElementById( tt )) {
1498         p.appendChild(
1499             createTooltip(
1500                 { id : tt,
1501                   flex : "1",
1502                   orient : 'vertical',
1503                   onpopupshown : 'this.width = this.firstChild.boxObject.width + 10; this.height = this.firstChild.boxObject.height + 10;',
1504                   class : 'tooltip' },
1505                 createDescription({}, document.createTextNode( tooltip_hash[tt] ) )
1506             )
1507         );
1508     }
1509
1510     target.tooltip = tt;
1511     return true;
1512 }
1513
1514 function getContextMenu (target, type) {
1515
1516     var tt = '';
1517     if (type == 'subfield')
1518         tt = 't' + target.parentNode.parentNode.parentNode.firstChild.value + 'sf';
1519
1520     if (type == 'ind1')
1521         tt = 't' + target.parentNode.firstChild.value + 'i1';
1522
1523     if (type == 'ind2')
1524         tt = 't' + target.parentNode.firstChild.value + 'i2';
1525
1526     target.setAttribute('context', tt);
1527     return true;
1528 }
1529
1530 var control_map = {
1531     100 : {
1532         'a' : { 100 : 'a' },
1533         'd' : { 100 : 'd' },
1534         'e' : { 100 : 'e' },
1535         'q' : { 100 : 'q' }
1536     },
1537     110 : {
1538         'a' : { 110 : 'a' },
1539         'd' : { 110 : 'd' }
1540     },
1541     111 : {
1542         'a' : { 111 : 'a' },
1543         'd' : { 111 : 'd' }
1544     },
1545     130 : {
1546         'a' : { 130 : 'a' },
1547         'd' : { 130 : 'd' }
1548     },
1549     240 : {
1550         'a' : { 130 : 'a' },
1551         'd' : { 130 : 'd' }
1552     },
1553     400 : {
1554         'a' : { 100 : 'a' },
1555         'd' : { 100 : 'd' }
1556     },
1557     410 : {
1558         'a' : { 110 : 'a' },
1559         'd' : { 110 : 'd' }
1560     },
1561     411 : {
1562         'a' : { 111 : 'a' },
1563         'd' : { 111 : 'd' }
1564     },
1565     440 : {
1566         'a' : { 130 : 'a' },
1567         'n' : { 130 : 'n' },
1568         'p' : { 130 : 'p' }
1569     },
1570     700 : {
1571         'a' : { 100 : 'a' },
1572         'd' : { 100 : 'd' },
1573         'q' : { 100 : 'q' },
1574         't' : { 100 : 't' }
1575     },
1576     710 : {
1577         'a' : { 110 : 'a' },
1578         'd' : { 110 : 'd' }
1579     },
1580     711 : {
1581         'a' : { 111 : 'a' },
1582         'c' : { 111 : 'c' },
1583         'd' : { 111 : 'd' }
1584     },
1585     730 : {
1586         'a' : { 130 : 'a' },
1587         'd' : { 130 : 'd' }
1588     },
1589     800 : {
1590         'a' : { 100 : 'a' },
1591         'd' : { 100 : 'd' }
1592     },
1593     810 : {
1594         'a' : { 110 : 'a' },
1595         'd' : { 110 : 'd' }
1596     },
1597     811 : {
1598         'a' : { 111 : 'a' },
1599         'd' : { 111 : 'd' }
1600     },
1601     830 : {
1602         'a' : { 130 : 'a' },
1603         'd' : { 130 : 'd' }
1604     },
1605     600 : {
1606         'a' : { 100 : 'a' },
1607         'd' : { 100 : 'd' },
1608         'q' : { 100 : 'q' },
1609         't' : { 100 : 't' },
1610         'v' : { 180 : 'v',
1611             100 : 'v',
1612             181 : 'v',
1613             182 : 'v',
1614             185 : 'v'
1615         },
1616         'x' : { 180 : 'x',
1617             100 : 'x',
1618             181 : 'x',
1619             182 : 'x',
1620             185 : 'x'
1621         },
1622         'y' : { 180 : 'y',
1623             100 : 'y',
1624             181 : 'y',
1625             182 : 'y',
1626             185 : 'y'
1627         },
1628         'z' : { 180 : 'z',
1629             100 : 'z',
1630             181 : 'z',
1631             182 : 'z',
1632             185 : 'z'
1633         }
1634     },
1635     610 : {
1636         'a' : { 110 : 'a' },
1637         'd' : { 110 : 'd' },
1638         't' : { 110 : 't' },
1639         'v' : { 180 : 'v',
1640             110 : 'v',
1641             181 : 'v',
1642             182 : 'v',
1643             185 : 'v'
1644         },
1645         'x' : { 180 : 'x',
1646             110 : 'x',
1647             181 : 'x',
1648             182 : 'x',
1649             185 : 'x'
1650         },
1651         'y' : { 180 : 'y',
1652             110 : 'y',
1653             181 : 'y',
1654             182 : 'y',
1655             185 : 'y'
1656         },
1657         'z' : { 180 : 'z',
1658             110 : 'z',
1659             181 : 'z',
1660             182 : 'z',
1661             185 : 'z'
1662         }
1663     },
1664     611 : {
1665         'a' : { 111 : 'a' },
1666         'd' : { 111 : 'd' },
1667         't' : { 111 : 't' },
1668         'v' : { 180 : 'v',
1669             111 : 'v',
1670             181 : 'v',
1671             182 : 'v',
1672             185 : 'v'
1673         },
1674         'x' : { 180 : 'x',
1675             111 : 'x',
1676             181 : 'x',
1677             182 : 'x',
1678             185 : 'x'
1679         },
1680         'y' : { 180 : 'y',
1681             111 : 'y',
1682             181 : 'y',
1683             182 : 'y',
1684             185 : 'y'
1685         },
1686         'z' : { 180 : 'z',
1687             111 : 'z',
1688             181 : 'z',
1689             182 : 'z',
1690             185 : 'z'
1691         }
1692     },
1693     630 : {
1694         'a' : { 130 : 'a' },
1695         'd' : { 130 : 'd' }
1696     },
1697     648 : {
1698         'a' : { 148 : 'a' },
1699         'v' : { 148 : 'v' },
1700         'x' : { 148 : 'x' },
1701         'y' : { 148 : 'y' },
1702         'z' : { 148 : 'z' }
1703     },
1704     650 : {
1705         'a' : { 150 : 'a' },
1706         'b' : { 150 : 'b' },
1707         'v' : { 180 : 'v',
1708             150 : 'v',
1709             181 : 'v',
1710             182 : 'v',
1711             185 : 'v'
1712         },
1713         'x' : { 180 : 'x',
1714             150 : 'x',
1715             181 : 'x',
1716             182 : 'x',
1717             185 : 'x'
1718         },
1719         'y' : { 180 : 'y',
1720             150 : 'y',
1721             181 : 'y',
1722             182 : 'y',
1723             185 : 'y'
1724         },
1725         'z' : { 180 : 'z',
1726             150 : 'z',
1727             181 : 'z',
1728             182 : 'z',
1729             185 : 'z'
1730         }
1731     },
1732     651 : {
1733         'a' : { 151 : 'a' },
1734         'v' : { 180 : 'v',
1735             151 : 'v',
1736             181 : 'v',
1737             182 : 'v',
1738             185 : 'v'
1739         },
1740         'x' : { 180 : 'x',
1741             151 : 'x',
1742             181 : 'x',
1743             182 : 'x',
1744             185 : 'x'
1745         },
1746         'y' : { 180 : 'y',
1747             151 : 'y',
1748             181 : 'y',
1749             182 : 'y',
1750             185 : 'y'
1751         },
1752         'z' : { 180 : 'z',
1753             151 : 'z',
1754             181 : 'z',
1755             182 : 'z',
1756             185 : 'z'
1757         }
1758     },
1759     655 : {
1760         'a' : { 155 : 'a' },
1761         'v' : { 180 : 'v',
1762             155 : 'v',
1763             181 : 'v',
1764             182 : 'v',
1765             185 : 'v'
1766         },
1767         'x' : { 180 : 'x',
1768             155 : 'x',
1769             181 : 'x',
1770             182 : 'x',
1771             185 : 'x'
1772         },
1773         'y' : { 180 : 'y',
1774             155 : 'y',
1775             181 : 'y',
1776             182 : 'y',
1777             185 : 'y'
1778         },
1779         'z' : { 180 : 'z',
1780             155 : 'z',
1781             181 : 'z',
1782             182 : 'z',
1783             185 : 'z'
1784         }
1785     }
1786 };
1787
1788 function getAuthorityContextMenu (target, sf) {
1789     var menu_id = sf.parent().@tag + ':' + sf.@code + '-authority-context-' + sf;
1790
1791     var page = 0;
1792     var old = dojo.byId( menu_id );
1793     if (old) {
1794         page = auth_pages[menu_id];
1795         old.parentNode.removeChild(old);
1796     } else {
1797         auth_pages[menu_id] = 0;
1798     }
1799
1800     var sf_popup = createMenuPopup({ id : menu_id, flex : 1 });
1801
1802     sf_popup.addEventListener("popuphiding", function(event) {
1803         if (show_auth_menu) {
1804             show_auth_menu = false;
1805             getAuthorityContextMenu(target, sf);
1806             dojo.byId(menu_id).openPopup();
1807         }  
1808     }, false);
1809
1810     context_menus.appendChild( sf_popup );
1811
1812     var found_acs = [];
1813     dojo.forEach( acs.controlSetList(), function (acs_id) {
1814         if (acs.controlSet(acs_id).control_map[sf.parent().@tag]) found_acs.push(acs_id);
1815     });
1816
1817     if (!found_acs.length) {
1818         sf_popup.appendChild(createLabel( { value : $('catStrings').getString('staff.cat.marcedit.not_authority_field.label') } ) );
1819         target.setAttribute('context', 'clipboard');
1820         return false;
1821     }
1822
1823     if (sf.toString().replace(/\s*/, '')) {
1824         return browseAuthority(sf_popup, menu_id, target, sf, 20, page);
1825     }
1826
1827     return true;
1828 }
1829
1830 /* Apply the complete 1xx */
1831 function applyFullAuthority ( target, ui_sf, e4x_sf ) {
1832     var new_vals = dojo.query('*[tag^="1"]', target);
1833     return applyAuthority( target, ui_sf, e4x_sf, new_vals );
1834 }
1835
1836 function applySelectedAuthority ( target, ui_sf, e4x_sf ) {
1837     var new_vals = target.getElementsByAttribute('checked','true');
1838     return applyAuthority( target, ui_sf, e4x_sf, new_vals );
1839 }
1840
1841 function applyAuthority ( target, ui_sf, e4x_sf, new_vals ) {
1842     var field = e4x_sf.parent();
1843
1844     for (var i = 0; i < new_vals.length; i++) {
1845
1846         var sf_list = field.subfield;
1847         for (var j in sf_list) {
1848
1849             if (sf_list[j].@code == new_vals[i].getAttribute('subfield')) {
1850                 sf_list[j] = new_vals[i].getAttribute('value');
1851                 new_vals[i].setAttribute('subfield','');
1852                 break;
1853             }
1854         }
1855     }
1856
1857     for (var i = 0; i < new_vals.length; i++) {
1858
1859         /* indicators for the authority datafield are carried over in the main entry linking subfield */
1860         if (new_vals[i].getAttribute('subfield') == '0') {
1861             field.@ind1 = new_vals[i].getAttribute('ind1');
1862             field.@ind2 = new_vals[i].getAttribute('ind2');
1863         }
1864
1865         if (!new_vals[i].getAttribute('subfield')) continue;
1866
1867         var val = new_vals[i].getAttribute('value');
1868
1869         var sf = <subfield code="" xmlns="http://www.loc.gov/MARC21/slim">{val}</subfield>;
1870         sf.@code = new_vals[i].getAttribute('subfield');
1871
1872         field.insertChildAfter(field.subfield[field.subfield.length() - 1], sf);
1873     }
1874
1875     var row = marcDatafield( field );
1876
1877     var node = ui_sf;
1878     while (node.nodeName != 'row') {
1879         node = node.parentNode;
1880     }
1881
1882     node.parentNode.replaceChild( row, node );
1883     return true;
1884 }
1885
1886 function validateAuthority (button) {
1887     var grid = document.getElementById('recGrid');
1888     var label = button.getAttribute('label');
1889
1890     //loop over rows
1891     var rows = grid.lastChild.childNodes;
1892     for (var i = 0; i < rows.length; i++) {
1893         var row = rows[i];
1894         var tag = row.firstChild;
1895
1896         var done = false;
1897         dojo.forEach(acs.controlSetList(), function (acs_id) {
1898             if (done) return;
1899             var control_map = acs.controlSet(acs_id).control_map;
1900     
1901             if (!control_map[tag.value]) return;
1902             button.setAttribute('label', label + ' - ' + tag.value);
1903     
1904             var ind1 = tag.nextSibling;
1905             var ind2 = ind1.nextSibling;
1906             var subfields = ind2.nextSibling.childNodes;
1907     
1908             var sf_list = [];
1909             for (var j = 0; j < subfields.length; j++) {
1910                 var sf = subfields[j];
1911                 sf_list.push( [ sf.childNodes[1].value, sf.childNodes[2].value ] );
1912             }
1913
1914             var matches = acs.findMatchingAuthorities(
1915                 new MARC.Field({
1916                     'tag'       : tag.value,
1917                     'subfields' : sf_list
1918                 })
1919             );
1920
1921             // matches = [ { "$csetId" : [ ... ] } ]
1922
1923             var found = false;
1924             if (matches[0]) { // probably set
1925                 for (var cset in matches[0]) {
1926                     var arr = matches[0][cset];
1927                     if (arr.length) {
1928                         // protect against errant empty string values
1929                         if (arr.length == 1 && arr[0] == '')
1930                             continue;
1931                         found = true;
1932                         break;
1933                     }
1934                 }
1935             }
1936
1937     
1938             // XXX If adt, etc should be validated separately from vxz, etc then move this up into the above for loop
1939             for (var j = 0; j < subfields.length; j++) {
1940                 var sf = subfields[j];
1941                 if (!found) {
1942                     dojo.removeClass(sf.childNodes[2], 'marcValidated');
1943                     dojo.addClass(sf.childNodes[2], 'marcUnvalidated');
1944                 } else {
1945                     dojo.removeClass(sf.childNodes[2], 'marcUnvalidated');
1946                     dojo.addClass(sf.childNodes[2], 'marcValidated');
1947                 }
1948             }
1949
1950             if (found) done = true;
1951         });
1952     }
1953
1954     button.setAttribute('label', label);
1955
1956     return true;
1957 }
1958
1959
1960 /*
1961 function validateBibField (tags, searches) {
1962     var url = "/gateway?input_format=json&format=xml&service=open-ils.search&method=open-ils.search.authority.validate.tag";
1963     url += '&param="tags"&param=' + js2JSON(tags);
1964     url += '&param="searches"&param=' + js2JSON(searches);
1965
1966
1967     var req = new XMLHttpRequest();
1968     req.open('GET',url,false);
1969     req.send(null);
1970
1971     return req;
1972
1973 }
1974 */
1975
1976 function searchAuthority (term, tag, sf, limit) {
1977     var url = "/gateway?input_format=json&format=xml&service=open-ils.search&method=open-ils.search.authority.fts";
1978     url += '&param="term"&param="' + term + '"';
1979     url += '&param="limit"&param=' + limit;
1980     url += '&param="tag"&param=' + tag;
1981     url += '&param="subfield"&param="' + sf + '"';
1982
1983
1984     var req = new XMLHttpRequest();
1985     req.open('GET',url,false);
1986     req.send(null);
1987
1988     return req;
1989
1990 }
1991
1992 /* TODO new authority browse support for context sets, and use that here */
1993 function browseAuthority (sf_popup, menu_id, target, sf, limit, page) {
1994     dojo.require('dojox.xml.parser');
1995
1996     // map tag + subfield to the appropriate authority browse axis:
1997     // currently authority.author, authority.subject, authority.title, authority.topic
1998     // based on mappings in OpenILS::Application::SuperCat, though Authority Control
1999     // Sets will change that
2000
2001     var axis_list = acs.bibFieldBrowseAxes( sf.parent().@tag.toString() );
2002
2003     // No matching tag means no authorities to search - shortcut
2004     if (axis_list.length == 0) {
2005         target.setAttribute('context', 'clipboard');
2006         return false;
2007     }
2008
2009     var type = 'authority.' + axis_list[0]; // Just take the first for now
2010                                             // TODO support multiple axes ... loop?
2011     if (!limit) {
2012         limit = 10;
2013     }
2014
2015     if (!page) {
2016         page = 0;
2017     }
2018
2019     var sf_string = '';
2020     var sf_list = sf.parent().subfield;
2021     for ( var i in sf_list) {
2022         sf_string += sf_list[i].toString() + ' ';
2023         if (sf_list[i] === sf) break;
2024     }
2025
2026     var url = '/opac/extras/browse/marcxml/'
2027         + type + '.refs'
2028         + '/1' // OU - currently unscoped
2029         + '/' + sf_string
2030         + '/' + page
2031         + '/' + limit
2032     ;
2033
2034     // would be good to carve this out into a separate function
2035     dojo.xhrGet({"url":url, "sync": true, "preventCache": true, "handleAs":"xml", "load": function(records) {
2036         var create_menu = createMenu({ label: $('catStrings').getString('staff.cat.marcedit.create_authority.label')});
2037
2038         var cm_popup = create_menu.appendChild(
2039             createMenuPopup()
2040         );
2041
2042         cm_popup.appendChild(
2043             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.create_authority_now.label'),
2044                 command : function() { 
2045                     // Call middle-layer function to create and save the new authority
2046                     var source_f = summarizeField(sf);
2047                     var new_auth = fieldmapper.standardRequest(
2048                         ["open-ils.cat", "open-ils.cat.authority.record.create_from_bib"],
2049                         [source_f, xulG.marc_control_number_identifier, ses()]
2050                     );
2051                     if (new_auth && new_auth.id()) {
2052                         addNewAuthorityID(new_auth, sf, target);
2053                     }
2054                 }
2055             })
2056         );
2057
2058         cm_popup.appendChild(
2059             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.create_authority_edit.label'),
2060                 command : function() { 
2061                     // Generate the new authority by calling the new middle-layer
2062                     // function (a non-saving variant), then display in another
2063                     // MARC editor
2064                     var source_f = summarizeField(sf);
2065                     var authtoken = ses();
2066                     dojo.require('openils.PermaCrud');
2067                     var pcrud = new openils.PermaCrud({"authtoken": authtoken});
2068                     var rec = fieldmapper.standardRequest(
2069                         ["open-ils.cat", "open-ils.cat.authority.record.create_from_bib.readonly"],
2070                         { "params": [source_f, xulG.marc_control_number_identifier] }
2071                     );
2072                     loadMarcEditor(pcrud, rec, target, sf);
2073                 }
2074             })
2075         );
2076
2077         sf_popup.appendChild(create_menu);
2078         sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
2079
2080         // append "Previous page" results browser
2081         sf_popup.appendChild(
2082             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.previous_page.label'),
2083                 command : function(event) { 
2084                     auth_pages[menu_id] -= 1;
2085                     show_auth_menu = true;
2086                 }
2087             })
2088         );
2089         sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
2090
2091         dojo.query('record', records).forEach(function(record) {
2092             var main_text = '';
2093             var see_from = [];
2094             var see_also = [];
2095             var auth_id = dojox.xml.parser.textContent(dojo.query('datafield[tag="901"]', record).query('subfield[code="c"]')[0]);
2096             var auth_org = '';
2097             if (dojo.query('controlfield[tag="003"]', record).length > 0) {
2098                 auth_org = dojox.xml.parser.textContent(dojo.query('controlfield[tag="003"]', record)[0]);
2099             }
2100
2101             // Grab the fields with tags beginning with 1 (main entries) and iterate through the subfields
2102             dojo.query('datafield[tag^="1"]', record).forEach(function(field) {
2103                 dojo.query('subfield', field).forEach(function(subfield) {
2104                     if (main_text) {
2105                         main_text += ' / ';
2106                     }
2107                     main_text += dojox.xml.parser.textContent(subfield);
2108                 });
2109             });
2110
2111             // Grab the fields with tags beginning with 4 (see from entries) and iterate through the subfields
2112             dojo.query('datafield[tag^="4"]', record).forEach(function(field) {
2113                 var see_text = '';
2114                 dojo.query('subfield', field).forEach(function(subfield) {
2115                     if (see_text) {
2116                         see_text += ' / ';
2117                     }
2118                     see_text += dojox.xml.parser.textContent(subfield);
2119                 });
2120                 see_from.push($('catStrings').getFormattedString('staff.cat.marcedit.authority_see_from', [see_text]));
2121             });
2122
2123             // Grab the fields with tags beginning with 5 (see also entries) and iterate through the subfields
2124             dojo.query('datafield[tag^="5"]', record).forEach(function(field) {
2125                 var see_text = '';
2126                 dojo.query('subfield', field).forEach(function(subfield) {
2127                     if (see_text) {
2128                         see_text += ' / ';
2129                     }
2130                     see_text += dojox.xml.parser.textContent(subfield);
2131                 });
2132                 see_also.push($('catStrings').getFormattedString('staff.cat.marcedit.authority_see_also', [see_text]));
2133             });
2134
2135             buildAuthorityPopup(main_text, record, auth_org, auth_id, sf_popup, target, sf);
2136
2137             dojo.forEach(see_from, function(entry_text) {
2138                 buildAuthorityPopup(entry_text, record, auth_org, auth_id, sf_popup, target, sf, "font-style: italic; margin-left: 2em;");
2139             });
2140
2141             // To-do: instead of launching the standard selector menu, invoke
2142             // a new authority search using the 5XX entry text
2143             dojo.forEach(see_also, function(entry_text) {
2144                 buildAuthorityPopup(entry_text, record, auth_org, auth_id, sf_popup, target, sf, "font-style: italic; margin-left: 2em;");
2145             });
2146
2147         });
2148
2149         if (sf_popup.childNodes.length == 0) {
2150             sf_popup.appendChild(createLabel( { value : $('catStrings').getString('staff.cat.marcedit.no_authority_match.label') } ) );
2151         } else {
2152             // append "Next page" results browser
2153             sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
2154             sf_popup.appendChild(
2155                 createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.next_page.label'),
2156                     command : function(event) { 
2157                         auth_pages[menu_id] += 1;
2158                         show_auth_menu = true;
2159                     }
2160                 })
2161             );
2162         }
2163
2164         target.setAttribute('context', menu_id);
2165         return true;
2166     }});
2167
2168 }
2169
2170 function buildAuthorityPopup (entry_text, record, auth_org, auth_id, sf_popup, target, sf, style) {
2171     var grid = dojo.query('[name="authority-marc-template"]')[0].cloneNode(true);
2172     grid.setAttribute('name','-none-');
2173     grid.setAttribute('style','overflow:scroll');
2174
2175     var submenu = createMenu( { "label": entry_text } );
2176
2177     var popup = createMenuPopup({ "flex": "1" });
2178     if (style) {
2179         submenu.setAttribute('style', style);
2180         popup.setAttribute('style', 'font-style: normal; margin-left: 0em;');
2181     }
2182     submenu.appendChild(popup);
2183
2184     dojo.query('datafield[tag^="1"]', record).forEach(function(field) {
2185         buildAuthorityPopupSelector(field, grid, auth_org, auth_id);
2186     });
2187     dojo.query('datafield[tag^="4"]', record).forEach(function(field) {
2188         buildAuthorityPopupSelector(field, grid, auth_org, auth_id);
2189     });
2190     dojo.query('datafield[tag^="5"]', record).forEach(function(field) {
2191         buildAuthorityPopupSelector(field, grid, auth_org, auth_id);
2192     });
2193
2194     grid.hidden = false;
2195     popup.appendChild( grid );
2196
2197     popup.appendChild(
2198         createMenuitem(
2199             { label : $('catStrings').getString('staff.cat.marcedit.apply_selected.label'),
2200               command : function (event) {
2201                     applySelectedAuthority(event.target.previousSibling, target, sf);
2202                     return true;
2203               }
2204             }
2205         )
2206     );
2207
2208     popup.appendChild( createComplexXULElement( 'menuseparator' ) );
2209
2210     popup.appendChild(
2211         createMenuitem(
2212             { label : $('catStrings').getString('staff.cat.marcedit.apply_full.label'),
2213               command : function (event) {
2214                     applyFullAuthority(event.target.previousSibling.previousSibling.previousSibling, target, sf);
2215                     return true;
2216               }
2217             }
2218         )
2219     );
2220
2221     sf_popup.appendChild( submenu );
2222 }
2223
2224 function buildAuthorityPopupSelector (field, grid, auth_org, auth_id) {
2225     var row = createRow(
2226         { },
2227         createLabel( { "value" : dojo.attr(field, 'tag') } ),
2228         createLabel( { "value" : dojo.attr(field, 'ind1') } ),
2229         createLabel( { "value" : dojo.attr(field, 'ind2') } )
2230     );
2231
2232     var sf_box = createHbox();
2233     dojo.query('subfield', field).forEach(function(subfield) {
2234         sf_box.appendChild(
2235             createCheckbox(
2236                 { "label"    : '\u2021' + dojo.attr(subfield, 'code') + ' ' + dojox.xml.parser.textContent(subfield),
2237                   "subfield" : dojo.attr(subfield, 'code'),
2238                   "tag"      : dojo.attr(field, 'tag'),
2239                   "value"    : dojox.xml.parser.textContent(subfield)
2240                 }
2241             )
2242         );
2243         row.appendChild(sf_box);
2244     });
2245
2246     // Append the authority linking subfield only for main entries
2247     if (dojo.attr(field, 'tag').charAt(0) == '1') {
2248         sf_box.appendChild(
2249             createCheckbox(
2250                 { "label"    : '\u2021' + '0' + ' (' + auth_org + ')' + auth_id,
2251                   "subfield" : '0',
2252                   "tag"      : dojo.attr(field, 'tag'),
2253                   "ind1"     : dojo.attr(field, 'ind1'),
2254                   "ind2"     : dojo.attr(field, 'ind2'),
2255                   "value"    : '(' + auth_org + ')' + auth_id
2256                 }
2257             )
2258         );
2259     }
2260     row.appendChild(sf_box);
2261
2262     grid.lastChild.appendChild(row);
2263 }
2264
2265 function summarizeField(sf) {
2266     var source_f= {
2267         "tag": '',
2268         "ind1": '',
2269         "ind2": '',
2270         "subfields": []
2271     };
2272
2273     source_f.tag = sf.parent().@tag.toString();
2274     source_f.ind1 = sf.parent().@ind1.toString();
2275     source_f.ind2 = sf.parent().@ind2.toString();
2276
2277     var found_acs = [];
2278     dojo.forEach( acs.controlSetList(), function (acs_id) {
2279         if (acs.controlSet(acs_id).control_map[sf.parent().@tag]) found_acs.push(acs_id);
2280     });
2281
2282     var cmap;
2283     if (!found_acs.length) {
2284         return false;
2285     } else {
2286         cmap = acs.controlSet(found_acs[0]).control_map;
2287     }
2288
2289     for (var i = 0; i < sf.parent().subfield.length(); i++) {
2290         var sf_iter = sf.parent().subfield[i];
2291
2292         /* Filter out subfields that are not controlled for this tag */
2293         if (!cmap[source_f.tag][sf_iter.@code.toString()]) {
2294             continue;
2295         }
2296
2297         source_f.subfields.push([sf_iter.@code.toString(), sf_iter.toString()]);
2298     }
2299
2300     return source_f;
2301 }
2302
2303 function buildBibSourceList (authtoken, recId) {
2304     /* TODO: Work out how to set the bib source of the bre that does not yet
2305      * exist - this is specifically in the case of Z39.50 imports. Right now
2306      * we just avoid populating and showing the config.bib_source list
2307      */
2308     if (!recId) {
2309         return false;
2310     }
2311
2312     var bib = xulG.record.bre;
2313
2314     dojo.require('openils.PermaCrud');
2315
2316     // cbsList = the XUL menulist that contains the available bib sources 
2317     var cbsList = dojo.byId('bib-source-list');
2318
2319     // bibSources = an array containing all of the bib source objects
2320     var bibSources = new openils.PermaCrud({"authtoken": authtoken}).retrieveAll('cbs');
2321
2322     // A tad ugly, but gives us the index of the bib source ID in cbsList
2323     var x = 0;
2324     var cbsListArr = [];
2325     dojo.forEach(bibSources, function (item) {
2326         cbsList.appendItem(item.source(), item.id());
2327         cbsListArr[item.id()] = x;
2328         x++;
2329     });
2330
2331     // Show the current value of the bib source for this record
2332     cbsList.selectedIndex = cbsListArr[bib.source()];
2333
2334     // Display the bib source selection widget
2335     dojo.byId('bib-source-list-caption').hidden = false;
2336     dojo.byId('bib-source-list').hidden = false;
2337     dojo.byId('bib-source-list-button').disabled = true;
2338     dojo.byId('bib-source-list-button').hidden = false;
2339 }
2340
2341 // Fired when the "Update Source" button is clicked
2342 // Updates the value of the bib source for the current record
2343 function updateBibSource() {
2344     var authtoken = ses();
2345     var cbs = dojo.byId('bib-source-list').selectedItem.value;
2346     var recId = xulG.record.id;
2347     var pcrud = new openils.PermaCrud({"authtoken": authtoken});
2348     var bib = pcrud.retrieve('bre', recId);
2349     if (bib.source() != cbs) {
2350         bib.source(cbs);
2351         bib.ischanged = true;
2352         pcrud.update(bib);
2353     }
2354 }
2355
2356 function onBibSourceSelect() {
2357     var cbs = dojo.byId('bib-source-list').selectedItem.value;
2358     var bib = xulG.record.bre;
2359     if (bib.source() != cbs) {
2360         dojo.byId('bib-source-list-button').disabled = false;   
2361     } else {
2362         dojo.byId('bib-source-list-button').disabled = true;   
2363     }
2364 }
2365
2366 function addNewAuthorityID(authority, sf, target) {
2367     var id_sf = <subfield code="0" xmlns="http://www.loc.gov/MARC21/slim">({xulG.marc_control_number_identifier}){authority.id()}</subfield>;
2368     sf.parent().appendChild(id_sf);
2369     var new_sf = marcSubfield(id_sf);
2370
2371     var node = target;
2372     while (dojo.attr(node, 'name') != 'sf_box') {
2373         node = node.parentNode;
2374     }
2375     node.appendChild( new_sf );
2376
2377     alert($('catStrings').getString('staff.cat.marcedit.create_authority_success.label'));
2378 }
2379
2380 function loadMarcEditor(pcrud, marcxml, target, sf) {
2381     /*
2382        To run in Firefox directly, must set signed.applets.codebase_principal_support
2383        to true in about:config
2384      */
2385     win = window.open('/xul/server/cat/marcedit.xul', '_blank', 'chrome'); // XXX version?
2386
2387     // Match marc2are.pl last_xact_id format, roughly
2388     var now = new Date;
2389     var xact_id = 'IMPORT-' + Date.parse(now);
2390     
2391     win.xulG = {
2392         "record": {"marc": marcxml, "rtype": "are"},
2393         "save": {
2394             "label": $('catStrings').getString('staff.cat.marcedit.save.label'),
2395             "func": function(xmlString) {
2396                 var rec = new are();
2397                 rec.marc(xmlString);
2398                 rec.last_xact_id(xact_id);
2399                 rec.isnew(true);
2400                 pcrud.create(rec, {
2401                     "oncomplete": function (r, objs) {
2402                         var new_rec = objs[0];
2403                         if (!new_rec) {
2404                             return '';
2405                         }
2406
2407                         addNewAuthorityID(new_rec, sf, target);
2408
2409                         win.close();
2410                     }
2411                 });
2412             }
2413         }
2414     };
2415 }
2416
2417