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