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