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