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