]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/xul/staff_client/server/cat/marcedit.js
Merge branch 'master' of git://git.evergreen-ils.org/Evergreen into ttopac
[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
820     var marc_rec = new MARC.Record ({ delimiter : '$', marcxml : xml_record.toXMLString() });
821     marc_rec.setFixedField(element.getAttribute('name'), new_value);
822
823     var xml_string = marc_rec.toXmlString();
824     xml_record = new XML( xml_string );
825     if (xml_record..record[0]) xml_record = xml_record..record[0];
826     loadRecord();
827
828     return true;
829 }
830
831 function marcLeader (leader) {
832     var row = createRow(
833         { class : 'marcLeaderRow',
834           tag : 'ldr' },
835         createLabel(
836             { value : 'LDR',
837               class : 'marcTag',
838               tooltiptext : $('catStrings').getString('staff.cat.marcedit.marcTag.LDR.label') } ),
839         createLabel(
840             { value : '',
841               class : 'marcInd1' } ),
842         createLabel(
843             { value : '',
844               class : 'marcInd2' } ),
845         createLabel(
846             { value : leader.text(),
847               class : 'marcLeader' } )
848     );
849
850     return row;
851 }
852
853 function marcControlfield (field) {
854     tagname = field.@tag.toString().substr(2);
855     var row;
856     if (tagname == '1' || tagname == '3' || tagname == '6' || tagname == '7' || tagname == '8') {
857         row = createRow(
858             { class : 'marcControlfieldRow',
859               tag : '_' + tagname },
860             createLabel(
861                 { value : field.@tag,
862                   class : 'marcTag',
863                   context : 'tags_popup',
864                   onmouseover : 'getTooltip(this, "tag");',
865                   tooltipid : 'tag' + field.@tag } ),
866             createLabel(
867                 { value : field.@ind1,
868                   class : 'marcInd1',
869                   onmouseover : 'getTooltip(this, "ind1");',
870                   tooltipid : 'tag' + field.@tag + 'ind1val' + field.@ind1 } ),
871             createLabel(
872                 { value : field.@ind2,
873                   class : 'marcInd2',
874                   onmouseover : 'getTooltip(this, "ind2");',
875                   tooltipid : 'tag' + field.@tag + 'ind2val' + field.@ind2 } ),
876             createMARCTextbox(
877                 field,
878                 { value : field.text(),
879                   class : 'plain marcEditableControlfield',
880                   name : 'CONTROL' + tagname,
881                   context : 'clipboard',
882                   size : 50,
883                   maxlength : 50 } )
884             );
885     } else {
886         row = createRow(
887             { class : 'marcControlfieldRow',
888               tag : '_' + tagname },
889             createLabel(
890                 { value : field.@tag,
891                   class : 'marcTag',
892                   onmouseover : 'getTooltip(this, "tag");',
893                   tooltipid : 'tag' + field.@tag } ),
894             createLabel(
895                 { value : field.@ind1,
896                   class : 'marcInd1',
897                   onmouseover : 'getTooltip(this, "ind1");',
898                   tooltipid : 'tag' + field.@tag + 'ind1val' + field.@ind1 } ),
899             createLabel(
900                 { value : field.@ind2,
901                   class : 'marcInd2',
902                   onmouseover : 'getTooltip(this, "ind2");',
903                   tooltipid : 'tag' + field.@tag + 'ind2val' + field.@ind2 } ),
904             createLabel(
905                 { value : field.text(),
906                   class : 'marcControlfield' } )
907         );
908     }
909
910     return row;
911 }
912
913 function stackSubfields(checkbox) {
914     var list = document.getElementsByAttribute('name','sf_box');
915
916     var o = 'vertical';
917     if (!checkbox.checked) o = 'horizontal';
918     
919     for (var i = 0; i < list.length; i++) {
920         if (list[i]) list[i].setAttribute('orient',o);
921     }
922 }
923
924 function fastItemAdd_toggle(checkbox) {
925     var x = document.getElementById('fastItemAdd_textboxes');
926     if (checkbox.checked) {
927         x.hidden = false;
928         document.getElementById('fastItemAdd_callnumber').focus();
929         document.getElementById('fastItemAdd_callnumber').select();
930     } else {
931         x.hidden = true;
932     }
933 }
934
935 function fastItemAdd_attempt(doc_id) {
936     try {
937         if (typeof window.xulG.fast_add_item != 'function') { return; }
938         if (!document.getElementById('fastItemAdd_checkbox').checked) { return; }
939         if (!document.getElementById('fastItemAdd_callnumber').value) { return; }
940         if (!document.getElementById('fastItemAdd_barcode').value) { return; }
941         window.xulG.fast_add_item( doc_id, document.getElementById('fastItemAdd_callnumber').value, document.getElementById('fastItemAdd_barcode').value );
942         document.getElementById('fastItemAdd_barcode').value = '';
943     } catch(E) {
944         alert('fastItemAdd_attempt: ' + E);
945     }
946 }
947
948 function save_attempt(xml_string) {
949     try {
950         var result = window.xulG.save.func( xml_string );   
951         if (result) {
952             oils_unlock_page();
953             if (result.id) fastItemAdd_attempt(result.id);
954             if (typeof result.on_complete == 'function') result.on_complete();
955         }
956     } catch(E) {
957         alert('save_attempt: ' + E);
958     }
959 }
960
961 function marcDatafield (field) {
962     var row = createRow(
963         { class : 'marcDatafieldRow' },
964         createMARCTextbox(
965             field.@tag,
966             { value : field.@tag,
967               class : 'plain marcTag',
968               name : 'marcTag',
969               context : 'tags_popup',
970               oninput : 'if (this.value.length == 3) { this.nextSibling.focus(); }',
971               size : 3,
972               maxlength : 3,
973               onmouseover : 'current_focus = this; getTooltip(this, "tag");' } ),
974         createMARCTextbox(
975             field.@ind1,
976             { value : field.@ind1,
977               class : 'plain marcInd1',
978               name : 'marcInd1',
979               oninput : 'if (this.value.length == 1) { this.nextSibling.focus(); }',
980               size : 1,
981               maxlength : 1,
982               onmouseover : 'current_focus = this; getContextMenu(this, "ind1"); getTooltip(this, "ind1");',
983               oncontextmenu : 'getContextMenu(this, "ind1");' } ),
984         createMARCTextbox(
985             field.@ind2,
986             { value : field.@ind2,
987               class : 'plain marcInd2',
988               name : 'marcInd2',
989               oninput : 'if (this.value.length == 1) { this.nextSibling.firstChild.firstChild.focus(); }',
990               size : 1,
991               maxlength : 1,
992               onmouseover : 'current_focus = this; getContextMenu(this, "ind2"); getTooltip(this, "ind2");',
993               oncontextmenu : 'getContextMenu(this, "ind2");' } ),
994         createHbox({ name : 'sf_box' })
995     );
996
997     if (!current_focus && field.@tag == '') current_focus = row.childNodes[0];
998     if (!current_focus && field.@ind1 == '') current_focus = row.childNodes[1];
999     if (!current_focus && field.@ind2 == '') current_focus = row.childNodes[2];
1000
1001     var sf_box = row.lastChild;
1002     if (document.getElementById('stackSubfields').checked)
1003         sf_box.setAttribute('orient','vertical');
1004
1005     sf_box.addEventListener(
1006         'click',
1007         function (e) {
1008             if (sf_box === e.target) {
1009                 sf_box.lastChild.lastChild.focus();
1010             } else if (e.target.parentNode === sf_box) {
1011                 e.target.lastChild.focus();
1012             }
1013         },
1014         false
1015     );
1016
1017
1018     for (var i in field.subfield) {
1019         var sf = field.subfield[i];
1020         sf_box.appendChild(
1021             marcSubfield(sf)
1022         );
1023
1024         dojo.query('.marcSubfield', sf_box).forEach(wrap_long_fields);
1025
1026         if (sf.@code == '' && (!current_focus || current_focus.className.match(/Ind/)))
1027             current_focus = sf_box.lastChild.childNodes[1];
1028     }
1029
1030     return row;
1031 }
1032
1033 function marcSubfield (sf) {            
1034     return createHbox(
1035         { class : 'marcSubfieldBox' },
1036         createLabel(
1037             { value : "\u2021",
1038               class : 'plain marcSubfieldDelimiter',
1039               onmouseover : 'getTooltip(this.nextSibling, "subfield");',
1040               oncontextmenu : 'getContextMenu(this.nextSibling, "subfield");',
1041                 //onclick : 'this.nextSibling.focus();',
1042                 onfocus : 'this.nextSibling.focus();',
1043               size : 2 } ),
1044         createMARCTextbox(
1045             sf.@code,
1046             { value : sf.@code,
1047               class : 'plain marcSubfieldCode',
1048               name : 'marcSubfieldCode',
1049               onmouseover : 'current_focus = this; getContextMenu(this, "subfield"); getTooltip(this, "subfield");',
1050               oncontextmenu : 'getContextMenu(this, "subfield");',
1051               oninput : 'if (this.value.length == 1) { this.nextSibling.focus(); }',
1052               size : 2,
1053               maxlength : 1 } ),
1054         createMARCTextbox(
1055             sf,
1056             { value : sf.text(),
1057               name : sf.parent().@tag + ':' + sf.@code,
1058               class : 'plain marcSubfield', 
1059               onmouseover : 'getTooltip(this, "subfield");',
1060               contextmenu : function (event) { getAuthorityContextMenu(event.target, sf) },
1061               size : new String(sf.text()).length + 2,
1062               oninput : "this.setAttribute('size', this.value.length + 2);"
1063             } )
1064     );
1065 }
1066
1067 function loadRecord() {
1068     try {
1069             var grid_rows = document.getElementById('recGrid').lastChild;
1070
1071             while (grid_rows.firstChild) grid_rows.removeChild(grid_rows.firstChild);
1072
1073             grid_rows.appendChild( marcLeader( xml_record.leader ) );
1074
1075             for (var i in xml_record.controlfield) {
1076                 grid_rows.appendChild( marcControlfield( xml_record.controlfield[i] ) );
1077             }
1078
1079             for (var i in xml_record.datafield) {
1080                 grid_rows.appendChild( marcDatafield( xml_record.datafield[i] ) );
1081             }
1082
1083             grid_rows.getElementsByAttribute('class','marcDatafieldRow')[0].firstChild.focus();
1084
1085             var marc_rec = new MARC.Record ({ delimiter : '$', marcxml : xml_record.toXMLString() });
1086             changeFFEditor(marc_rec.recordType());
1087             fillFixedFields();
1088     } catch(E) {
1089         alert('FIXME, MARC Editor, loadRecord: ' + E);
1090     }
1091 }
1092
1093
1094 function genToolTips () {
1095     for (var i in bib_data.field) {
1096         var f = bib_data.field[i];
1097     
1098         tag_menu.appendChild(
1099             createMenuitem(
1100                 { label : f.@tag,
1101                   oncommand : 
1102                       'current_focus.value = "' + f.@tag + '";' +
1103                     'var e = document.createEvent("MutationEvents");' +
1104                     'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1105                     'current_focus.inputField.dispatchEvent(e);',
1106                   disabled : f.@tag < '010' ? "true" : "false",
1107                   tooltiptext : f.description }
1108             )
1109         );
1110     
1111         var i1_popup = createPopup({position : 'after_start', id : 't' + f.@tag + 'i1' });
1112         context_menus.appendChild( i1_popup );
1113     
1114         var i2_popup = createPopup({position : 'after_start', id : 't' + f.@tag + 'i2' });
1115         context_menus.appendChild( i2_popup );
1116     
1117         var sf_popup = createPopup({position : 'after_start', id : 't' + f.@tag + 'sf' });
1118         context_menus.appendChild( sf_popup );
1119     
1120         tooltip_hash['tag' + f.@tag] = f.description;
1121         for (var j in f.indicator) {
1122             var ind = f.indicator[j];
1123             tooltip_hash['tag' + f.@tag + 'ind' + ind.@position + 'val' + ind.@value] = ind.description;
1124     
1125             if (ind.@position == 1) {
1126                 i1_popup.appendChild(
1127                     createMenuitem(
1128                         { label : ind.@value,
1129                           oncommand : 
1130                               'current_focus.value = "' + ind.@value + '";' +
1131                             'var e = document.createEvent("MutationEvents");' +
1132                             'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1133                             'current_focus.inputField.dispatchEvent(e);',
1134                           tooltiptext : ind.description }
1135                     )
1136                 );
1137             }
1138     
1139             if (ind.@position == 2) {
1140                 i2_popup.appendChild(
1141                     createMenuitem(
1142                         { label : ind.@value,
1143                           oncommand : 
1144                               'current_focus.value = "' + ind.@value + '";' +
1145                             'var e = document.createEvent("MutationEvents");' +
1146                             'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1147                             'current_focus.inputField.dispatchEvent(e);',
1148                           tooltiptext : ind.description }
1149                     )
1150                 );
1151             }
1152         }
1153     
1154         for (var j in f.subfield) {
1155             var sf = f.subfield[j];
1156             tooltip_hash['tag' + f.@tag + 'sf' + sf.@code] = sf.description;
1157     
1158             sf_popup.appendChild(
1159                 createMenuitem(
1160                     { label : sf.@code,
1161                       oncommand : 
1162                           'current_focus.value = "' + sf.@code + '";' +
1163                         'var e = document.createEvent("MutationEvents");' +
1164                         'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1165                         'current_focus.inputField.dispatchEvent(e);',
1166                       tooltiptext : sf.description
1167                     }
1168                 )
1169             );
1170         }
1171     }
1172 }
1173
1174 function getTooltip (target, type) {
1175
1176     var tt = '';
1177     if (type == 'subfield')
1178         tt = 'tag' + target.parentNode.parentNode.parentNode.firstChild.value + 'sf' + target.parentNode.childNodes[1].value;
1179
1180     if (type == 'ind1')
1181         tt = 'tag' + target.parentNode.firstChild.value + 'ind1val' + target.value;
1182
1183     if (type == 'ind2')
1184         tt = 'tag' + target.parentNode.firstChild.value + 'ind2val' + target.value;
1185
1186     if (type == 'tag')
1187         tt = 'tag' + target.parentNode.firstChild.value;
1188
1189     if (!document.getElementById( tt )) {
1190         p.appendChild(
1191             createTooltip(
1192                 { id : tt,
1193                   flex : "1",
1194                   orient : 'vertical',
1195                   onpopupshown : 'this.width = this.firstChild.boxObject.width + 10; this.height = this.firstChild.boxObject.height + 10;',
1196                   class : 'tooltip' },
1197                 createDescription({}, document.createTextNode( tooltip_hash[tt] ) )
1198             )
1199         );
1200     }
1201
1202     target.tooltip = tt;
1203     return true;
1204 }
1205
1206 function getContextMenu (target, type) {
1207
1208     var tt = '';
1209     if (type == 'subfield')
1210         tt = 't' + target.parentNode.parentNode.parentNode.firstChild.value + 'sf';
1211
1212     if (type == 'ind1')
1213         tt = 't' + target.parentNode.firstChild.value + 'i1';
1214
1215     if (type == 'ind2')
1216         tt = 't' + target.parentNode.firstChild.value + 'i2';
1217
1218     target.setAttribute('context', tt);
1219     return true;
1220 }
1221
1222 var control_map = {
1223     100 : {
1224         'a' : { 100 : 'a' },
1225         'd' : { 100 : 'd' },
1226         'e' : { 100 : 'e' },
1227         'q' : { 100 : 'q' }
1228     },
1229     110 : {
1230         'a' : { 110 : 'a' },
1231         'd' : { 110 : 'd' }
1232     },
1233     111 : {
1234         'a' : { 111 : 'a' },
1235         'd' : { 111 : 'd' }
1236     },
1237     130 : {
1238         'a' : { 130 : 'a' },
1239         'd' : { 130 : 'd' }
1240     },
1241     240 : {
1242         'a' : { 130 : 'a' },
1243         'd' : { 130 : 'd' }
1244     },
1245     400 : {
1246         'a' : { 100 : 'a' },
1247         'd' : { 100 : 'd' }
1248     },
1249     410 : {
1250         'a' : { 110 : 'a' },
1251         'd' : { 110 : 'd' }
1252     },
1253     411 : {
1254         'a' : { 111 : 'a' },
1255         'd' : { 111 : 'd' }
1256     },
1257     440 : {
1258         'a' : { 130 : 'a' },
1259         'n' : { 130 : 'n' },
1260         'p' : { 130 : 'p' }
1261     },
1262     700 : {
1263         'a' : { 100 : 'a' },
1264         'd' : { 100 : 'd' },
1265         'q' : { 100 : 'q' },
1266         't' : { 100 : 't' }
1267     },
1268     710 : {
1269         'a' : { 110 : 'a' },
1270         'd' : { 110 : 'd' }
1271     },
1272     711 : {
1273         'a' : { 111 : 'a' },
1274         'c' : { 111 : 'c' },
1275         'd' : { 111 : 'd' }
1276     },
1277     730 : {
1278         'a' : { 130 : 'a' },
1279         'd' : { 130 : 'd' }
1280     },
1281     800 : {
1282         'a' : { 100 : 'a' },
1283         'd' : { 100 : 'd' }
1284     },
1285     810 : {
1286         'a' : { 110 : 'a' },
1287         'd' : { 110 : 'd' }
1288     },
1289     811 : {
1290         'a' : { 111 : 'a' },
1291         'd' : { 111 : 'd' }
1292     },
1293     830 : {
1294         'a' : { 130 : 'a' },
1295         'd' : { 130 : 'd' }
1296     },
1297     600 : {
1298         'a' : { 100 : 'a' },
1299         'd' : { 100 : 'd' },
1300         'q' : { 100 : 'q' },
1301         't' : { 100 : 't' },
1302         'v' : { 180 : 'v',
1303             100 : 'v',
1304             181 : 'v',
1305             182 : 'v',
1306             185 : 'v'
1307         },
1308         'x' : { 180 : 'x',
1309             100 : 'x',
1310             181 : 'x',
1311             182 : 'x',
1312             185 : 'x'
1313         },
1314         'y' : { 180 : 'y',
1315             100 : 'y',
1316             181 : 'y',
1317             182 : 'y',
1318             185 : 'y'
1319         },
1320         'z' : { 180 : 'z',
1321             100 : 'z',
1322             181 : 'z',
1323             182 : 'z',
1324             185 : 'z'
1325         }
1326     },
1327     610 : {
1328         'a' : { 110 : 'a' },
1329         'd' : { 110 : 'd' },
1330         't' : { 110 : 't' },
1331         'v' : { 180 : 'v',
1332             110 : 'v',
1333             181 : 'v',
1334             182 : 'v',
1335             185 : 'v'
1336         },
1337         'x' : { 180 : 'x',
1338             110 : 'x',
1339             181 : 'x',
1340             182 : 'x',
1341             185 : 'x'
1342         },
1343         'y' : { 180 : 'y',
1344             110 : 'y',
1345             181 : 'y',
1346             182 : 'y',
1347             185 : 'y'
1348         },
1349         'z' : { 180 : 'z',
1350             110 : 'z',
1351             181 : 'z',
1352             182 : 'z',
1353             185 : 'z'
1354         }
1355     },
1356     611 : {
1357         'a' : { 111 : 'a' },
1358         'd' : { 111 : 'd' },
1359         't' : { 111 : 't' },
1360         'v' : { 180 : 'v',
1361             111 : 'v',
1362             181 : 'v',
1363             182 : 'v',
1364             185 : 'v'
1365         },
1366         'x' : { 180 : 'x',
1367             111 : 'x',
1368             181 : 'x',
1369             182 : 'x',
1370             185 : 'x'
1371         },
1372         'y' : { 180 : 'y',
1373             111 : 'y',
1374             181 : 'y',
1375             182 : 'y',
1376             185 : 'y'
1377         },
1378         'z' : { 180 : 'z',
1379             111 : 'z',
1380             181 : 'z',
1381             182 : 'z',
1382             185 : 'z'
1383         }
1384     },
1385     630 : {
1386         'a' : { 130 : 'a' },
1387         'd' : { 130 : 'd' }
1388     },
1389     648 : {
1390         'a' : { 148 : 'a' },
1391         'v' : { 148 : 'v' },
1392         'x' : { 148 : 'x' },
1393         'y' : { 148 : 'y' },
1394         'z' : { 148 : 'z' }
1395     },
1396     650 : {
1397         'a' : { 150 : 'a' },
1398         'b' : { 150 : 'b' },
1399         'v' : { 180 : 'v',
1400             150 : 'v',
1401             181 : 'v',
1402             182 : 'v',
1403             185 : 'v'
1404         },
1405         'x' : { 180 : 'x',
1406             150 : 'x',
1407             181 : 'x',
1408             182 : 'x',
1409             185 : 'x'
1410         },
1411         'y' : { 180 : 'y',
1412             150 : 'y',
1413             181 : 'y',
1414             182 : 'y',
1415             185 : 'y'
1416         },
1417         'z' : { 180 : 'z',
1418             150 : 'z',
1419             181 : 'z',
1420             182 : 'z',
1421             185 : 'z'
1422         }
1423     },
1424     651 : {
1425         'a' : { 151 : 'a' },
1426         'v' : { 180 : 'v',
1427             151 : 'v',
1428             181 : 'v',
1429             182 : 'v',
1430             185 : 'v'
1431         },
1432         'x' : { 180 : 'x',
1433             151 : 'x',
1434             181 : 'x',
1435             182 : 'x',
1436             185 : 'x'
1437         },
1438         'y' : { 180 : 'y',
1439             151 : 'y',
1440             181 : 'y',
1441             182 : 'y',
1442             185 : 'y'
1443         },
1444         'z' : { 180 : 'z',
1445             151 : 'z',
1446             181 : 'z',
1447             182 : 'z',
1448             185 : 'z'
1449         }
1450     },
1451     655 : {
1452         'a' : { 155 : 'a' },
1453         'v' : { 180 : 'v',
1454             155 : 'v',
1455             181 : 'v',
1456             182 : 'v',
1457             185 : 'v'
1458         },
1459         'x' : { 180 : 'x',
1460             155 : 'x',
1461             181 : 'x',
1462             182 : 'x',
1463             185 : 'x'
1464         },
1465         'y' : { 180 : 'y',
1466             155 : 'y',
1467             181 : 'y',
1468             182 : 'y',
1469             185 : 'y'
1470         },
1471         'z' : { 180 : 'z',
1472             155 : 'z',
1473             181 : 'z',
1474             182 : 'z',
1475             185 : 'z'
1476         }
1477     }
1478 };
1479
1480 function getAuthorityContextMenu (target, sf) {
1481     var menu_id = sf.parent().@tag + ':' + sf.@code + '-authority-context-' + sf;
1482
1483     var page = 0;
1484     var old = dojo.byId( menu_id );
1485     if (old) {
1486         page = auth_pages[menu_id];
1487         old.parentNode.removeChild(old);
1488     } else {
1489         auth_pages[menu_id] = 0;
1490     }
1491
1492     var sf_popup = createPopup({ id : menu_id, flex : 1 });
1493
1494     sf_popup.addEventListener("popuphiding", function(event) {
1495         if (show_auth_menu) {
1496             show_auth_menu = false;
1497             getAuthorityContextMenu(target, sf);
1498             dojo.byId(menu_id).openPopup();
1499         }  
1500     }, false);
1501
1502     context_menus.appendChild( sf_popup );
1503
1504     var found_acs = [];
1505     dojo.forEach( acs.controlSetList(), function (acs_id) {
1506         if (acs.controlSet(acs_id).control_map[sf.parent().@tag]) found_acs.push(acs_id);
1507     });
1508
1509     if (!found_acs.length) {
1510         sf_popup.appendChild(createLabel( { value : $('catStrings').getString('staff.cat.marcedit.not_authority_field.label') } ) );
1511         target.setAttribute('context', 'clipboard');
1512         return false;
1513     }
1514
1515     if (sf.toString().replace(/\s*/, '')) {
1516         return browseAuthority(sf_popup, menu_id, target, sf, 20, page);
1517     }
1518
1519     return true;
1520 }
1521
1522 /* Apply the complete 1xx */
1523 function applyFullAuthority ( target, ui_sf, e4x_sf ) {
1524     var new_vals = dojo.query('*[tag^="1"]', target);
1525     return applyAuthority( target, ui_sf, e4x_sf, new_vals );
1526 }
1527
1528 function applySelectedAuthority ( target, ui_sf, e4x_sf ) {
1529     var new_vals = target.getElementsByAttribute('checked','true');
1530     return applyAuthority( target, ui_sf, e4x_sf, new_vals );
1531 }
1532
1533 function applyAuthority ( target, ui_sf, e4x_sf, new_vals ) {
1534     var field = e4x_sf.parent();
1535
1536     for (var i = 0; i < new_vals.length; i++) {
1537
1538         var sf_list = field.subfield;
1539         for (var j in sf_list) {
1540
1541             if (sf_list[j].@code == new_vals[i].getAttribute('subfield')) {
1542                 sf_list[j] = new_vals[i].getAttribute('value');
1543                 new_vals[i].setAttribute('subfield','');
1544                 break;
1545             }
1546         }
1547     }
1548
1549     for (var i = 0; i < new_vals.length; i++) {
1550         if (!new_vals[i].getAttribute('subfield')) continue;
1551
1552         var val = new_vals[i].getAttribute('value');
1553
1554         var sf = <subfield code="" xmlns="http://www.loc.gov/MARC21/slim">{val}</subfield>;
1555         sf.@code = new_vals[i].getAttribute('subfield');
1556
1557         field.insertChildAfter(field.subfield[field.subfield.length() - 1], sf);
1558     }
1559
1560     var row = marcDatafield( field );
1561
1562     var node = ui_sf;
1563     while (node.nodeName != 'row') {
1564         node = node.parentNode;
1565     }
1566
1567     node.parentNode.replaceChild( row, node );
1568     return true;
1569 }
1570
1571 function validateAuthority (button) {
1572     var grid = document.getElementById('recGrid');
1573     var label = button.getAttribute('label');
1574
1575     //loop over rows
1576     var rows = grid.lastChild.childNodes;
1577     for (var i = 0; i < rows.length; i++) {
1578         var row = rows[i];
1579         var tag = row.firstChild;
1580
1581         var done = false;
1582         dojo.forEach(acs.controlSetList(), function (acs_id) {
1583             if (done) return;
1584             var control_map = acs.controlSet(acs_id).control_map;
1585     
1586             if (!control_map[tag.value]) return;
1587             button.setAttribute('label', label + ' - ' + tag.value);
1588     
1589             var ind1 = tag.nextSibling;
1590             var ind2 = ind1.nextSibling;
1591             var subfields = ind2.nextSibling.childNodes;
1592     
1593             var sf_list = [];
1594             for (var j = 0; j < subfields.length; j++) {
1595                 var sf = subfields[j];
1596                 sf_list.push( sf.childNodes[1].value );
1597                 sf_list.push( sf.childNodes[2].value );
1598             }
1599
1600             var matches = acs.findMatchingAuthorities(
1601                 new MARC.Field({
1602                     'tag'       : tag.value,
1603                     'subfields' : sf_list
1604                 })
1605             );
1606     
1607             // XXX If adt, etc should be validated separately from vxz, etc then move this up into the above for loop
1608             for (var j = 0; j < subfields.length; j++) {
1609                 var sf = subfields[j];
1610                 if (!matches.length) {
1611                     dojo.removeClass(sf.childNodes[2], 'marcValidated');
1612                     dojo.addClass(sf.childNodes[2], 'marcUnvalidated');
1613                 } else {
1614                     dojo.removeClass(sf.childNodes[2], 'marcUnvalidated');
1615                     dojo.addClass(sf.childNodes[2], 'marcValidated');
1616                 }
1617             }
1618
1619             if (matches.length) done = true;
1620         });
1621     }
1622
1623     button.setAttribute('label', label);
1624
1625     return true;
1626 }
1627
1628
1629 /*
1630 function validateBibField (tags, searches) {
1631     var url = "/gateway?input_format=json&format=xml&service=open-ils.search&method=open-ils.search.authority.validate.tag";
1632     url += '&param="tags"&param=' + js2JSON(tags);
1633     url += '&param="searches"&param=' + js2JSON(searches);
1634
1635
1636     var req = new XMLHttpRequest();
1637     req.open('GET',url,false);
1638     req.send(null);
1639
1640     return req;
1641
1642 }
1643 */
1644
1645 function searchAuthority (term, tag, sf, limit) {
1646     var url = "/gateway?input_format=json&format=xml&service=open-ils.search&method=open-ils.search.authority.fts";
1647     url += '&param="term"&param="' + term + '"';
1648     url += '&param="limit"&param=' + limit;
1649     url += '&param="tag"&param=' + tag;
1650     url += '&param="subfield"&param="' + sf + '"';
1651
1652
1653     var req = new XMLHttpRequest();
1654     req.open('GET',url,false);
1655     req.send(null);
1656
1657     return req;
1658
1659 }
1660
1661 /* TODO new authority browse support for context sets, and use that here */
1662 function browseAuthority (sf_popup, menu_id, target, sf, limit, page) {
1663     dojo.require('dojox.xml.parser');
1664
1665     // map tag + subfield to the appropriate authority browse axis:
1666     // currently authority.author, authority.subject, authority.title, authority.topic
1667     // based on mappings in OpenILS::Application::SuperCat, though Authority Control
1668     // Sets will change that
1669
1670     var axis_list = acs.bibFieldBrowseAxes( sf.parent().@tag.toString() );
1671
1672     // No matching tag means no authorities to search - shortcut
1673     if (axis_list.length == 0) {
1674         target.setAttribute('context', 'clipboard');
1675         return false;
1676     }
1677
1678     var type = 'authority.' + axis_list[0]; // Just take the first for now
1679                                             // TODO support multiple axes ... loop?
1680     if (!limit) {
1681         limit = 10;
1682     }
1683
1684     if (!page) {
1685         page = 0;
1686     }
1687
1688     var url = '/opac/extras/browse/marcxml/'
1689         + type + '.refs'
1690         + '/1' // OU - currently unscoped
1691         + '/' + sf.toString()
1692         + '/' + page
1693         + '/' + limit
1694     ;
1695
1696     // would be good to carve this out into a separate function
1697     dojo.xhrGet({"url":url, "sync": true, "preventCache": true, "handleAs":"xml", "load": function(records) {
1698         var create_menu = createMenu({ label: $('catStrings').getString('staff.cat.marcedit.create_authority.label')});
1699
1700         var cm_popup = create_menu.appendChild(
1701             createMenuPopup()
1702         );
1703
1704         cm_popup.appendChild(
1705             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.create_authority_now.label'),
1706                 command : function() { 
1707                     // Call middle-layer function to create and save the new authority
1708                     var source_f = summarizeField(sf);
1709                     var new_auth = fieldmapper.standardRequest(
1710                         ["open-ils.cat", "open-ils.cat.authority.record.create_from_bib"],
1711                         [source_f, xulG.marc_control_number_identifier, ses()]
1712                     );
1713                     if (new_auth && new_auth.id()) {
1714                         addNewAuthorityID(new_auth, sf, target);
1715                     }
1716                 }
1717             })
1718         );
1719
1720         cm_popup.appendChild(
1721             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.create_authority_edit.label'),
1722                 command : function() { 
1723                     // Generate the new authority by calling the new middle-layer
1724                     // function (a non-saving variant), then display in another
1725                     // MARC editor
1726                     var source_f = summarizeField(sf);
1727                     var authtoken = ses();
1728                     dojo.require('openils.PermaCrud');
1729                     var pcrud = new openils.PermaCrud({"authtoken": authtoken});
1730                     var rec = fieldmapper.standardRequest(
1731                         ["open-ils.cat", "open-ils.cat.authority.record.create_from_bib.readonly"],
1732                         { "params": [source_f, xulG.marc_control_number_identifier] }
1733                     );
1734                     loadMarcEditor(pcrud, rec, target, sf);
1735                 }
1736             })
1737         );
1738
1739         sf_popup.appendChild(create_menu);
1740         sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
1741
1742         // append "Previous page" results browser
1743         sf_popup.appendChild(
1744             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.previous_page.label'),
1745                 command : function(event) { 
1746                     auth_pages[menu_id] -= 1;
1747                     show_auth_menu = true;
1748                 }
1749             })
1750         );
1751         sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
1752
1753         dojo.query('record', records).forEach(function(record) {
1754             var main_text = '';
1755             var see_from = [];
1756             var see_also = [];
1757             var auth_id = dojox.xml.parser.textContent(dojo.query('datafield[tag="901"] subfield[code="c"]', record)[0]);
1758             var auth_org = dojox.xml.parser.textContent(dojo.query('controlfield[tag="003"]', record)[0]);
1759
1760             // Grab the fields with tags beginning with 1 (main entries) and iterate through the subfields
1761             dojo.query('datafield[tag^="1"]', record).forEach(function(field) {
1762                 dojo.query('subfield', field).forEach(function(subfield) {
1763                     if (main_text) {
1764                         main_text += ' / ';
1765                     }
1766                     main_text += dojox.xml.parser.textContent(subfield);
1767                 });
1768             });
1769
1770             // Grab the fields with tags beginning with 4 (see from entries) and iterate through the subfields
1771             dojo.query('datafield[tag^="4"]', record).forEach(function(field) {
1772                 var see_text = '';
1773                 dojo.query('subfield', field).forEach(function(subfield) {
1774                     if (see_text) {
1775                         see_text += ' / ';
1776                     }
1777                     see_text += dojox.xml.parser.textContent(subfield);
1778                 });
1779                 see_from.push($('catStrings').getFormattedString('staff.cat.marcedit.authority_see_from', [see_text]));
1780             });
1781
1782             // Grab the fields with tags beginning with 5 (see also entries) and iterate through the subfields
1783             dojo.query('datafield[tag^="5"]', record).forEach(function(field) {
1784                 var see_text = '';
1785                 dojo.query('subfield', field).forEach(function(subfield) {
1786                     if (see_text) {
1787                         see_text += ' / ';
1788                     }
1789                     see_text += dojox.xml.parser.textContent(subfield);
1790                 });
1791                 see_also.push($('catStrings').getFormattedString('staff.cat.marcedit.authority_see_also', [see_text]));
1792             });
1793
1794             buildAuthorityPopup(main_text, record, auth_org, auth_id, sf_popup, target, sf);
1795
1796             dojo.forEach(see_from, function(entry_text) {
1797                 buildAuthorityPopup(entry_text, record, auth_org, auth_id, sf_popup, target, sf, "font-style: italic; margin-left: 2em;");
1798             });
1799
1800             // To-do: instead of launching the standard selector menu, invoke
1801             // a new authority search using the 5XX entry text
1802             dojo.forEach(see_also, function(entry_text) {
1803                 buildAuthorityPopup(entry_text, record, auth_org, auth_id, sf_popup, target, sf, "font-style: italic; margin-left: 2em;");
1804             });
1805
1806         });
1807
1808         if (sf_popup.childNodes.length == 0) {
1809             sf_popup.appendChild(createLabel( { value : $('catStrings').getString('staff.cat.marcedit.no_authority_match.label') } ) );
1810         } else {
1811             // append "Next page" results browser
1812             sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
1813             sf_popup.appendChild(
1814                 createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.next_page.label'),
1815                     command : function(event) { 
1816                         auth_pages[menu_id] += 1;
1817                         show_auth_menu = true;
1818                     }
1819                 })
1820             );
1821         }
1822
1823         target.setAttribute('context', menu_id);
1824         return true;
1825     }});
1826
1827 }
1828
1829 function buildAuthorityPopup (entry_text, record, auth_org, auth_id, sf_popup, target, sf, style) {
1830     var grid = dojo.query('[name="authority-marc-template"]')[0].cloneNode(true);
1831     grid.setAttribute('name','-none-');
1832     grid.setAttribute('style','overflow:scroll');
1833
1834     var submenu = createMenu( { "label": entry_text } );
1835
1836     var popup = createMenuPopup({ "flex": "1" });
1837     if (style) {
1838         submenu.setAttribute('style', style);
1839         popup.setAttribute('style', 'font-style: normal; margin-left: 0em;');
1840     }
1841     submenu.appendChild(popup);
1842
1843     dojo.query('datafield[tag^="1"], datafield[tag^="4"], datafield[tag^="5"]', record).forEach(function(field) {
1844         buildAuthorityPopupSelector(field, grid, auth_org, auth_id);
1845     });
1846
1847     grid.hidden = false;
1848     popup.appendChild( grid );
1849
1850     popup.appendChild(
1851         createMenuitem(
1852             { label : $('catStrings').getString('staff.cat.marcedit.apply_selected.label'),
1853               command : function (event) {
1854                     applySelectedAuthority(event.target.previousSibling, target, sf);
1855                     return true;
1856               }
1857             }
1858         )
1859     );
1860
1861     popup.appendChild( createComplexXULElement( 'menuseparator' ) );
1862
1863     popup.appendChild(
1864         createMenuitem(
1865             { label : $('catStrings').getString('staff.cat.marcedit.apply_full.label'),
1866               command : function (event) {
1867                     applyFullAuthority(event.target.previousSibling.previousSibling.previousSibling, target, sf);
1868                     return true;
1869               }
1870             }
1871         )
1872     );
1873
1874     sf_popup.appendChild( submenu );
1875 }
1876
1877 function buildAuthorityPopupSelector (field, grid, auth_org, auth_id) {
1878     var row = createRow(
1879         { },
1880         createLabel( { "value" : dojo.attr(field, 'tag') } ),
1881         createLabel( { "value" : dojo.attr(field, 'ind1') } ),
1882         createLabel( { "value" : dojo.attr(field, 'ind2') } )
1883     );
1884
1885     var sf_box = createHbox();
1886     dojo.query('subfield', field).forEach(function(subfield) {
1887         sf_box.appendChild(
1888             createCheckbox(
1889                 { "label"    : '\u2021' + dojo.attr(subfield, 'code') + ' ' + dojox.xml.parser.textContent(subfield),
1890                   "subfield" : dojo.attr(subfield, 'code'),
1891                   "tag"      : dojo.attr(field, 'tag'),
1892                   "value"    : dojox.xml.parser.textContent(subfield)
1893                 }
1894             )
1895         );
1896         row.appendChild(sf_box);
1897     });
1898
1899     // Append the authority linking subfield only for main entries
1900     if (dojo.attr(field, 'tag').charAt(0) == '1') {
1901         sf_box.appendChild(
1902             createCheckbox(
1903                 { "label"    : '\u2021' + '0' + ' (' + auth_org + ')' + auth_id,
1904                   "subfield" : '0',
1905                   "tag"      : dojo.attr(field, 'tag'),
1906                   "value"    : '(' + auth_org + ')' + auth_id
1907                 }
1908             )
1909         );
1910     }
1911     row.appendChild(sf_box);
1912
1913     grid.lastChild.appendChild(row);
1914 }
1915
1916 function summarizeField(sf) {
1917     var source_f= {
1918         "tag": '',
1919         "ind1": '',
1920         "ind2": '',
1921         "subfields": []
1922     };
1923
1924     source_f.tag = sf.parent().@tag.toString();
1925     source_f.ind1 = sf.parent().@ind1.toString();
1926     source_f.ind1 = sf.parent().@ind2.toString();
1927
1928     for (var i = 0; i < sf.parent().subfield.length(); i++) {
1929         var sf_iter = sf.parent().subfield[i];
1930
1931         /* Filter out subfields that are not controlled for this tag */
1932         if (!control_map[source_f.tag][sf_iter.@code.toString()]) {
1933             continue;
1934         }
1935
1936         source_f.subfields.push([sf_iter.@code.toString(), sf_iter.toString()]);
1937     }
1938
1939     return source_f;
1940 }
1941
1942 function buildBibSourceList (authtoken, recId) {
1943     /* TODO: Work out how to set the bib source of the bre that does not yet
1944      * exist - this is specifically in the case of Z39.50 imports. Right now
1945      * we just avoid populating and showing the config.bib_source list
1946      */
1947     if (!recId) {
1948         return false;
1949     }
1950
1951     var bib = xulG.record.bre;
1952
1953     dojo.require('openils.PermaCrud');
1954
1955     // cbsList = the XUL menulist that contains the available bib sources 
1956     var cbsList = dojo.byId('bib-source-list');
1957
1958     // bibSources = an array containing all of the bib source objects
1959     var bibSources = new openils.PermaCrud({"authtoken": authtoken}).retrieveAll('cbs');
1960
1961     // A tad ugly, but gives us the index of the bib source ID in cbsList
1962     var x = 0;
1963     var cbsListArr = [];
1964     dojo.forEach(bibSources, function (item) {
1965         cbsList.appendItem(item.source(), item.id());
1966         cbsListArr[item.id()] = x;
1967         x++;
1968     });
1969
1970     // Show the current value of the bib source for this record
1971     cbsList.selectedIndex = cbsListArr[bib.source()];
1972
1973     // Display the bib source selection widget
1974     dojo.byId('bib-source-list-caption').hidden = false;
1975     dojo.byId('bib-source-list').hidden = false;
1976     dojo.byId('bib-source-list-button').disabled = true;
1977     dojo.byId('bib-source-list-button').hidden = false;
1978 }
1979
1980 // Fired when the "Update Source" button is clicked
1981 // Updates the value of the bib source for the current record
1982 function updateBibSource() {
1983     var authtoken = ses();
1984     var cbs = dojo.byId('bib-source-list').selectedItem.value;
1985     var recId = xulG.record.id;
1986     var pcrud = new openils.PermaCrud({"authtoken": authtoken});
1987     var bib = pcrud.retrieve('bre', recId);
1988     if (bib.source() != cbs) {
1989         bib.source(cbs);
1990         bib.ischanged = true;
1991         pcrud.update(bib);
1992     }
1993 }
1994
1995 function onBibSourceSelect() {
1996     var cbs = dojo.byId('bib-source-list').selectedItem.value;
1997     var bib = xulG.record.bre;
1998     if (bib.source() != cbs) {
1999         dojo.byId('bib-source-list-button').disabled = false;   
2000     } else {
2001         dojo.byId('bib-source-list-button').disabled = true;   
2002     }
2003 }
2004
2005 function addNewAuthorityID(authority, sf, target) {
2006     var id_sf = <subfield code="0" xmlns="http://www.loc.gov/MARC21/slim">({xulG.marc_control_number_identifier}){authority.id()}</subfield>;
2007     sf.parent().appendChild(id_sf);
2008     var new_sf = marcSubfield(id_sf);
2009
2010     var node = target;
2011     while (dojo.attr(node, 'name') != 'sf_box') {
2012         node = node.parentNode;
2013     }
2014     node.appendChild( new_sf );
2015
2016     alert($('catStrings').getString('staff.cat.marcedit.create_authority_success.label'));
2017 }
2018
2019 function loadMarcEditor(pcrud, marcxml, target, sf) {
2020     /*
2021        To run in Firefox directly, must set signed.applets.codebase_principal_support
2022        to true in about:config
2023      */
2024     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
2025     win = window.open('/xul/server/cat/marcedit.xul'); // XXX version?
2026
2027     // Match marc2are.pl last_xact_id format, roughly
2028     var now = new Date;
2029     var xact_id = 'IMPORT-' + Date.parse(now);
2030     
2031     win.xulG = {
2032         "record": {"marc": marcxml, "rtype": "are"},
2033         "save": {
2034             "label": $('catStrings').getString('staff.cat.marcedit.save.label'),
2035             "func": function(xmlString) {
2036                 var rec = new are();
2037                 rec.marc(xmlString);
2038                 rec.last_xact_id(xact_id);
2039                 rec.isnew(true);
2040                 pcrud.create(rec, {
2041                     "oncomplete": function (r, objs) {
2042                         var new_rec = objs[0];
2043                         if (!new_rec) {
2044                             return '';
2045                         }
2046
2047                         addNewAuthorityID(new_rec, sf, target);
2048
2049                         win.close();
2050                     }
2051                 });
2052             }
2053         }
2054     };
2055 }
2056
2057