]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/xul/staff_client/server/cat/marcedit.js
Search clicked /and/ preceding sf values
[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 // Pretty printing kills whitespace too, so disable it.
22 XML.prettyPrinting = false;
23 var xmlDeclaration = /^<\?xml version[^>]+?>/;
24
25 var serializer = new XMLSerializer();
26 var marcns = new Namespace("http://www.loc.gov/MARC21/slim");
27 var gw = new Namespace("http://opensrf.org/-/namespaces/gateway/v1");
28 var xulns = new Namespace("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
29 default xml namespace = marcns;
30
31 var tooltip_hash = {};
32 var current_focus;
33 var _record;
34 var _record_type;
35 var bib_data;
36
37 var xml_record;
38
39 var context_menus;
40 var tag_menu;
41 var p;
42 var auth_pages = {};
43 var show_auth_menu = false;
44
45 function $(id) { return document.getElementById(id); }
46
47 var acs; // AuthorityControlSet
48
49 function mangle_005() {
50     var now = new Date();
51     var y = now.getUTCFullYear();
52
53     var m = now.getUTCMonth() + 1;
54     if (m < 10) m = '0' + m;
55     
56     var d = now.getUTCDate();
57     if (d < 10) d = '0' + d;
58     
59     var H = now.getUTCHours();
60     if (H < 10) H = '0' + H;
61     
62     var M = now.getUTCMinutes();
63     if (M < 10) M = '0' + M;
64     
65     var S = now.getUTCSeconds();
66     if (S < 10) S = '0' + S;
67     
68
69     var stamp = '' + y + m + d + H + M + S + '.0';
70     createControlField('005',stamp);
71
72 }
73
74 function createControlField (tag,data) {
75     // first, remove the old field, if any;
76     for (var i in xml_record.controlfield.(@tag == tag)) delete xml_record.controlfield.(@tag == tag)[i];
77
78     var cf = <controlfield tag="" xmlns="http://www.loc.gov/MARC21/slim">{ data }</controlfield>;
79     cf.@tag = tag;
80
81     // then, find the right position and insert it
82     var done = 0;
83     var cfields = xml_record.controlfield;
84     var base = Number(tag.substring(2));
85     for (var i in cfields) {
86         var t = Number(cfields[i].@tag.toString().substring(2));
87         if (t > base) {
88             xml_record.insertChildBefore( cfields[i], cf );
89             done = 1
90             break;
91         }
92     }
93
94     if (!done) xml_record.insertChildBefore( xml_record.datafield[0], cf );
95
96     return cf;
97 }
98
99 function xml_escape_unicode ( str ) {
100     return str.replace(
101         /([\u0080-\ufffe])/g,
102         function (r,s) { return "&#x" + s.charCodeAt(0).toString(16) + ";"; }
103     );
104 }
105
106 function wrap_long_fields (node) {
107     var text_size = dojo.attr(node, 'size');
108     var hard_width = 100; 
109     if (text_size > hard_width) {
110         dojo.attr(node, 'multiline', 'true');
111         dojo.attr(node, 'cols', hard_width);
112         var text_rows = (text_size / hard_width) + 1;
113         dojo.attr(node, 'rows', text_rows);
114     }
115 }
116
117 function set_flat_editor (useFlatText) {
118
119     var xe = $('xul-editor');
120     var te = $('text-editor');
121
122     if (useFlatText) {
123         if (xe.hidden) { return; }
124         te.hidden = false;
125         xe.hidden = true;
126     } else {
127         if (te.hidden) { return; }
128         te.hidden = true;
129         xe.hidden = false;
130     }
131
132     if (te.hidden) {
133         // get the marcxml from the text box
134         var xml_string = new MARC.Record({
135             marcbreaker : $('text-editor-box').value,
136             delimiter : '$'
137         }).toXmlString();
138
139         // reset the xml record and rerender it
140         xml_record = new XML( xml_string );
141         if (xml_record..record[0]) xml_record = xml_record..record[0];
142         loadRecord();
143     } else {
144         var xml_string = xml_record.toXMLString();
145
146         // push the xml record into the textbox
147         var rec = new MARC.Record ({ delimiter : '$', marcxml : xml_string });
148         $('text-editor-box').value = rec.toBreaker();
149     }
150 }
151
152 function my_init() {
153     try {
154
155         if (typeof JSAN == 'undefined') { throw( $("commonStrings").getString('common.jsan.missing') ); }
156         JSAN.errorLevel = "die"; // none, warn, or die
157         JSAN.addRepository('/xul/server/');
158
159         dojo.require('openils.AuthorityControlSet');
160         acs = new openils.AuthorityControlSet ();
161
162         // Fake xulG for standalone...
163         try {
164             window.xulG.record;
165         } catch (e) {
166             window.xulG = {};
167             window.xulG.record = {};
168             window.xulG.save = {};
169             window.xulG.marc_control_number_identifier = 'CONS';
170
171             window.xulG.save.label = $('catStrings').getString('staff.cat.marcedit.save.label');
172             window.xulG.save.func = function (r) { alert(r); }
173
174             var cgi = new CGI();
175             var _rid = cgi.param('record');
176             if (_rid) {
177                 window.xulG.record.id = _rid;
178                 window.xulG.record.url = '/opac/extras/supercat/retrieve/marcxml/record/' + _rid;
179             }
180         }
181
182         // End faking part...
183
184         /* Check for an explicitly passed record type
185          * This is not the same as the fixed-field record type; we can't trust
186          * the fixed fields when making modifications to the attributes for a
187          * given record (in particular, config.bib_source only applies for bib
188          * records, but an auth or MFHD record with the same ID and bad fixed
189          * fields could trample the config.bib_source value for the
190          * corresponding bib record if we're not careful.
191          *
192          * are = authority record
193          * sre = serial record (MFHD)
194          * bre = bibliographic record
195          */
196         if (!window.xulG.record.rtype) {
197             var cgi = new CGI();
198             window.xulG.record.rtype = cgi.param('rtype') || false;
199         }
200
201         document.getElementById('save-button').setAttribute('label', window.xulG.save.label);
202         document.getElementById('save-button').setAttribute('oncommand',
203             'if ($("xul-editor").hidden) set_flat_editor(false); ' +
204             'mangle_005(); ' + 
205             'var xml_string = xml_escape_unicode( xml_record.toXMLString() ); ' + 
206             'save_attempt( xml_string ); ' +
207             'loadRecord();'
208         );
209
210         if (window.xulG.record.url) {
211             var req =  new XMLHttpRequest();
212             req.open('POST',window.xulG.record.url,false);
213             req.send(null);
214             window.xulG.record.marc = req.responseText.replace(xmlDeclaration, '');
215         }
216
217         xml_record = new XML( window.xulG.record.marc );
218         if (xml_record..record[0]) xml_record = xml_record..record[0];
219
220         // Get the tooltip xml all async like
221         req =  new XMLHttpRequest();
222
223         // Set a default locale in case preferences fail us
224         var locale = "en-US";
225
226         // Try to get the locale from our preferences
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 = createMenuPopup({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,117,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,118,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,119,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', row).query('hbox').query('textbox').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) { 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 == 117 && event.ctrlKey) { // ctrl + F6
688                 createControlField('006','                                        ');
689                 loadRecord();
690             } else if (event.keyCode == 118 && event.ctrlKey) { // ctrl + F7
691                 createControlField('007','                                        ');
692                 loadRecord();
693             } else if (event.keyCode == 119 && 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     document.getElementById('recordTypeLabel').setAttribute('value',type);
776
777     // Hide FFEditor rows that we don't need for our current type
778     // If all of the labels for a given row do not include our
779     // desired type in their set attribute, we can hide that row
780     dojo.query('rows', grid).query('row').forEach(function(node, index, arr) {
781         if (dojo.query('label[set~=' + type + ']', node).length == 0) {
782             node.hidden = true;
783         }
784     });
785
786 }
787
788 function fillFixedFields () {
789     try {
790             var grid = document.getElementById('leaderGrid');
791             var marc_rec = new MARC.Record ({ delimiter : '$', marcxml : xml_record.toXMLString() });
792
793             var list = [];
794             var pre_list = grid.getElementsByTagName('label');
795             for (var i in pre_list) {
796                 if ( pre_list[i].getAttribute && pre_list[i].getAttribute('set').indexOf(grid.getAttribute('type')) > -1 ) {
797                     list.push( pre_list[i] );
798                 }
799             }
800
801             for (var i in list) {
802                 var name = list[i].getAttribute('name');
803                 var value = marc_rec.extractFixedField(name, true);
804
805                 if (value === null) continue;
806
807                 list[i].nextSibling.value = value;
808             }
809
810             return true;
811     } catch(E) {
812         alert('FIXME, MARC Editor, fillFixedFields: ' + E);
813     }
814 }
815
816 function updateFixedFields (element) {
817     var grid = document.getElementById('leaderGrid');
818     var recGrid = document.getElementById('recGrid');
819     var new_value = element.value;
820     // Don't take focus away/adjust the record on partial changes
821     var length = element.getAttribute('maxlength');
822     if(new_value.length < length) return true;
823
824     var marc_rec = new MARC.Record ({ delimiter : '$', marcxml : xml_record.toXMLString() });
825     marc_rec.setFixedField(element.getAttribute('name'), new_value);
826
827     var xml_string = marc_rec.toXmlString();
828     xml_record = new XML( xml_string );
829     if (xml_record..record[0]) xml_record = xml_record..record[0];
830     loadRecord();
831     // Put the cursor back to the current fixed field
832     element.select();
833
834     return true;
835 }
836
837 function marcLeader (leader) {
838     var row = createRow(
839         { class : 'marcLeaderRow',
840           tag : 'ldr' },
841         createLabel(
842             { value : 'LDR',
843               class : 'marcTag',
844               tooltiptext : $('catStrings').getString('staff.cat.marcedit.marcTag.LDR.label') } ),
845         createLabel(
846             { value : '',
847               class : 'marcInd1' } ),
848         createLabel(
849             { value : '',
850               class : 'marcInd2' } ),
851         createLabel(
852             { value : leader.text(),
853               class : 'marcLeader' } )
854     );
855
856     return row;
857 }
858
859 function marcControlfield (field) {
860     tagname = field.@tag.toString().substr(2);
861     var row;
862     if (tagname == '1' || tagname == '3' || tagname == '6' || tagname == '7' || tagname == '8') {
863         row = createRow(
864             { class : 'marcControlfieldRow',
865               tag : '_' + tagname },
866             createLabel(
867                 { value : field.@tag,
868                   class : 'marcTag',
869                   context : 'tags_popup',
870                   onmouseover : 'getTooltip(this, "tag");',
871                   tooltipid : 'tag' + field.@tag } ),
872             createLabel(
873                 { value : field.@ind1,
874                   class : 'marcInd1',
875                   onmouseover : 'getTooltip(this, "ind1");',
876                   tooltipid : 'tag' + field.@tag + 'ind1val' + field.@ind1 } ),
877             createLabel(
878                 { value : field.@ind2,
879                   class : 'marcInd2',
880                   onmouseover : 'getTooltip(this, "ind2");',
881                   tooltipid : 'tag' + field.@tag + 'ind2val' + field.@ind2 } ),
882             createMARCTextbox(
883                 field,
884                 { value : field.text(),
885                   class : 'plain marcEditableControlfield',
886                   name : 'CONTROL' + tagname,
887                   context : 'clipboard',
888                   size : 50,
889                   maxlength : 50 } )
890             );
891     } else {
892         row = createRow(
893             { class : 'marcControlfieldRow',
894               tag : '_' + tagname },
895             createLabel(
896                 { value : field.@tag,
897                   class : 'marcTag',
898                   onmouseover : 'getTooltip(this, "tag");',
899                   tooltipid : 'tag' + field.@tag } ),
900             createLabel(
901                 { value : field.@ind1,
902                   class : 'marcInd1',
903                   onmouseover : 'getTooltip(this, "ind1");',
904                   tooltipid : 'tag' + field.@tag + 'ind1val' + field.@ind1 } ),
905             createLabel(
906                 { value : field.@ind2,
907                   class : 'marcInd2',
908                   onmouseover : 'getTooltip(this, "ind2");',
909                   tooltipid : 'tag' + field.@tag + 'ind2val' + field.@ind2 } ),
910             createLabel(
911                 { value : field.text(),
912                   class : 'marcControlfield' } )
913         );
914     }
915
916     return row;
917 }
918
919 function stackSubfields(checkbox) {
920     var list = document.getElementsByAttribute('name','sf_box');
921
922     var o = 'vertical';
923     if (!checkbox.checked) o = 'horizontal';
924     
925     for (var i = 0; i < list.length; i++) {
926         if (list[i]) list[i].setAttribute('orient',o);
927     }
928 }
929
930 function fastItemAdd_toggle(checkbox) {
931     var x = document.getElementById('fastItemAdd_textboxes');
932     if (checkbox.checked) {
933         x.hidden = false;
934         document.getElementById('fastItemAdd_callnumber').focus();
935         document.getElementById('fastItemAdd_callnumber').select();
936     } else {
937         x.hidden = true;
938     }
939 }
940
941 function fastItemAdd_attempt(doc_id) {
942     try {
943         if (typeof window.xulG.fast_add_item != 'function') { return; }
944         if (!document.getElementById('fastItemAdd_checkbox').checked) { return; }
945         if (!document.getElementById('fastItemAdd_callnumber').value) { return; }
946         if (!document.getElementById('fastItemAdd_barcode').value) { return; }
947         window.xulG.fast_add_item( doc_id, document.getElementById('fastItemAdd_callnumber').value, document.getElementById('fastItemAdd_barcode').value );
948         document.getElementById('fastItemAdd_barcode').value = '';
949     } catch(E) {
950         alert('fastItemAdd_attempt: ' + E);
951     }
952 }
953
954 function save_attempt(xml_string) {
955     try {
956         var result = window.xulG.save.func( xml_string );   
957         if (result) {
958             oils_unlock_page();
959             if (result.id) fastItemAdd_attempt(result.id);
960             if (typeof result.on_complete == 'function') result.on_complete();
961         }
962     } catch(E) {
963         alert('save_attempt: ' + E);
964     }
965 }
966
967 function marcDatafield (field) {
968     var row = createRow(
969         { class : 'marcDatafieldRow' },
970         createMARCTextbox(
971             field.@tag,
972             { value : field.@tag,
973               class : 'plain marcTag',
974               name : 'marcTag',
975               context : 'tags_popup',
976               oninput : 'if (this.value.length == 3) { this.nextSibling.focus(); }',
977               size : 3,
978               maxlength : 3,
979               onmouseover : 'current_focus = this; getTooltip(this, "tag");' } ),
980         createMARCTextbox(
981             field.@ind1,
982             { value : field.@ind1,
983               class : 'plain marcInd1',
984               name : 'marcInd1',
985               oninput : 'if (this.value.length == 1) { this.nextSibling.focus(); }',
986               size : 1,
987               maxlength : 1,
988               onmouseover : 'current_focus = this; getContextMenu(this, "ind1"); getTooltip(this, "ind1");',
989               oncontextmenu : 'getContextMenu(this, "ind1");' } ),
990         createMARCTextbox(
991             field.@ind2,
992             { value : field.@ind2,
993               class : 'plain marcInd2',
994               name : 'marcInd2',
995               oninput : 'if (this.value.length == 1) { this.nextSibling.firstChild.firstChild.focus(); }',
996               size : 1,
997               maxlength : 1,
998               onmouseover : 'current_focus = this; getContextMenu(this, "ind2"); getTooltip(this, "ind2");',
999               oncontextmenu : 'getContextMenu(this, "ind2");' } ),
1000         createHbox({ name : 'sf_box' })
1001     );
1002
1003     if (!current_focus && field.@tag == '') current_focus = row.childNodes[0];
1004     if (!current_focus && field.@ind1 == '') current_focus = row.childNodes[1];
1005     if (!current_focus && field.@ind2 == '') current_focus = row.childNodes[2];
1006
1007     var sf_box = row.lastChild;
1008     if (document.getElementById('stackSubfields').checked)
1009         sf_box.setAttribute('orient','vertical');
1010
1011     sf_box.addEventListener(
1012         'click',
1013         function (e) {
1014             if (sf_box === e.target) {
1015                 sf_box.lastChild.lastChild.focus();
1016             } else if (e.target.parentNode === sf_box) {
1017                 e.target.lastChild.focus();
1018             }
1019         },
1020         false
1021     );
1022
1023
1024     for (var i in field.subfield) {
1025         var sf = field.subfield[i];
1026         sf_box.appendChild(
1027             marcSubfield(sf)
1028         );
1029
1030         dojo.query('.marcSubfield', sf_box).forEach(wrap_long_fields);
1031
1032         if (sf.@code == '' && (!current_focus || current_focus.className.match(/Ind/)))
1033             current_focus = sf_box.lastChild.childNodes[1];
1034     }
1035
1036     return row;
1037 }
1038
1039 function marcSubfield (sf) {            
1040     return createHbox(
1041         { class : 'marcSubfieldBox' },
1042         createLabel(
1043             { value : "\u2021",
1044               class : 'plain marcSubfieldDelimiter',
1045               onmouseover : 'getTooltip(this.nextSibling, "subfield");',
1046               oncontextmenu : 'getContextMenu(this.nextSibling, "subfield");',
1047                 //onclick : 'this.nextSibling.focus();',
1048                 onfocus : 'this.nextSibling.focus();',
1049               size : 2 } ),
1050         createMARCTextbox(
1051             sf.@code,
1052             { value : sf.@code,
1053               class : 'plain marcSubfieldCode',
1054               align: 'start',
1055               name : 'marcSubfieldCode',
1056               onmouseover : 'current_focus = this; getContextMenu(this, "subfield"); getTooltip(this, "subfield");',
1057               oncontextmenu : 'getContextMenu(this, "subfield");',
1058               oninput : 'if (this.value.length == 1) { this.nextSibling.focus(); }',
1059               size : 2,
1060               maxlength : 1 } ),
1061         createMARCTextbox(
1062             sf,
1063             { value : sf.text(),
1064               name : sf.parent().@tag + ':' + sf.@code,
1065               class : 'plain marcSubfield', 
1066               align: 'start',
1067               onmouseover : 'getTooltip(this, "subfield");',
1068               contextmenu : function (event) { getAuthorityContextMenu(event.target, sf) },
1069               size : new String(sf.text()).length + 2,
1070               oninput : "this.setAttribute('size', this.value.length + 2);"
1071             } )
1072     );
1073 }
1074
1075 function loadRecord() {
1076     try {
1077             var grid_rows = document.getElementById('recGrid').lastChild;
1078
1079             while (grid_rows.firstChild) grid_rows.removeChild(grid_rows.firstChild);
1080
1081             grid_rows.appendChild( marcLeader( xml_record.leader ) );
1082
1083             for (var i in xml_record.controlfield) {
1084                 grid_rows.appendChild( marcControlfield( xml_record.controlfield[i] ) );
1085             }
1086
1087             for (var i in xml_record.datafield) {
1088                 grid_rows.appendChild( marcDatafield( xml_record.datafield[i] ) );
1089             }
1090
1091             grid_rows.getElementsByAttribute('class','marcDatafieldRow')[0].firstChild.focus();
1092
1093             var marc_rec = new MARC.Record ({ delimiter : '$', marcxml : xml_record.toXMLString() });
1094             changeFFEditor(marc_rec.recordType());
1095             fillFixedFields();
1096     } catch(E) {
1097         alert('FIXME, MARC Editor, loadRecord: ' + E);
1098     }
1099 }
1100
1101
1102 function genToolTips () {
1103     for (var i in bib_data.field) {
1104         var f = bib_data.field[i];
1105     
1106         tag_menu.appendChild(
1107             createMenuitem(
1108                 { label : f.@tag,
1109                   oncommand : 
1110                       'current_focus.value = "' + f.@tag + '";' +
1111                     'var e = document.createEvent("MutationEvents");' +
1112                     'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1113                     'current_focus.inputField.dispatchEvent(e);',
1114                   disabled : f.@tag < '010' ? "true" : "false",
1115                   tooltiptext : f.description }
1116             )
1117         );
1118     
1119         var i1_popup = createMenuPopup({position : 'after_start', id : 't' + f.@tag + 'i1' });
1120         context_menus.appendChild( i1_popup );
1121     
1122         var i2_popup = createMenuPopup({position : 'after_start', id : 't' + f.@tag + 'i2' });
1123         context_menus.appendChild( i2_popup );
1124     
1125         var sf_popup = createMenuPopup({position : 'after_start', id : 't' + f.@tag + 'sf' });
1126         context_menus.appendChild( sf_popup );
1127     
1128         tooltip_hash['tag' + f.@tag] = f.description;
1129         for (var j in f.indicator) {
1130             var ind = f.indicator[j];
1131             tooltip_hash['tag' + f.@tag + 'ind' + ind.@position + 'val' + ind.@value] = ind.description;
1132     
1133             if (ind.@position == 1) {
1134                 i1_popup.appendChild(
1135                     createMenuitem(
1136                         { label : ind.@value,
1137                           oncommand : 
1138                               'current_focus.value = "' + ind.@value + '";' +
1139                             'var e = document.createEvent("MutationEvents");' +
1140                             'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1141                             'current_focus.inputField.dispatchEvent(e);',
1142                           tooltiptext : ind.description }
1143                     )
1144                 );
1145             }
1146     
1147             if (ind.@position == 2) {
1148                 i2_popup.appendChild(
1149                     createMenuitem(
1150                         { label : ind.@value,
1151                           oncommand : 
1152                               'current_focus.value = "' + ind.@value + '";' +
1153                             'var e = document.createEvent("MutationEvents");' +
1154                             'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1155                             'current_focus.inputField.dispatchEvent(e);',
1156                           tooltiptext : ind.description }
1157                     )
1158                 );
1159             }
1160         }
1161     
1162         for (var j in f.subfield) {
1163             var sf = f.subfield[j];
1164             tooltip_hash['tag' + f.@tag + 'sf' + sf.@code] = sf.description;
1165     
1166             sf_popup.appendChild(
1167                 createMenuitem(
1168                     { label : sf.@code,
1169                       oncommand : 
1170                           'current_focus.value = "' + sf.@code + '";' +
1171                         'var e = document.createEvent("MutationEvents");' +
1172                         'e.initMutationEvent("change",1,1,null,0,0,0,0);' +
1173                         'current_focus.inputField.dispatchEvent(e);',
1174                       tooltiptext : sf.description
1175                     }
1176                 )
1177             );
1178         }
1179     }
1180 }
1181
1182 function getTooltip (target, type) {
1183
1184     var tt = '';
1185     if (type == 'subfield')
1186         tt = 'tag' + target.parentNode.parentNode.parentNode.firstChild.value + 'sf' + target.parentNode.childNodes[1].value;
1187
1188     if (type == 'ind1')
1189         tt = 'tag' + target.parentNode.firstChild.value + 'ind1val' + target.value;
1190
1191     if (type == 'ind2')
1192         tt = 'tag' + target.parentNode.firstChild.value + 'ind2val' + target.value;
1193
1194     if (type == 'tag')
1195         tt = 'tag' + target.parentNode.firstChild.value;
1196
1197     if (!document.getElementById( tt )) {
1198         p.appendChild(
1199             createTooltip(
1200                 { id : tt,
1201                   flex : "1",
1202                   orient : 'vertical',
1203                   onpopupshown : 'this.width = this.firstChild.boxObject.width + 10; this.height = this.firstChild.boxObject.height + 10;',
1204                   class : 'tooltip' },
1205                 createDescription({}, document.createTextNode( tooltip_hash[tt] ) )
1206             )
1207         );
1208     }
1209
1210     target.tooltip = tt;
1211     return true;
1212 }
1213
1214 function getContextMenu (target, type) {
1215
1216     var tt = '';
1217     if (type == 'subfield')
1218         tt = 't' + target.parentNode.parentNode.parentNode.firstChild.value + 'sf';
1219
1220     if (type == 'ind1')
1221         tt = 't' + target.parentNode.firstChild.value + 'i1';
1222
1223     if (type == 'ind2')
1224         tt = 't' + target.parentNode.firstChild.value + 'i2';
1225
1226     target.setAttribute('context', tt);
1227     return true;
1228 }
1229
1230 var control_map = {
1231     100 : {
1232         'a' : { 100 : 'a' },
1233         'd' : { 100 : 'd' },
1234         'e' : { 100 : 'e' },
1235         'q' : { 100 : 'q' }
1236     },
1237     110 : {
1238         'a' : { 110 : 'a' },
1239         'd' : { 110 : 'd' }
1240     },
1241     111 : {
1242         'a' : { 111 : 'a' },
1243         'd' : { 111 : 'd' }
1244     },
1245     130 : {
1246         'a' : { 130 : 'a' },
1247         'd' : { 130 : 'd' }
1248     },
1249     240 : {
1250         'a' : { 130 : 'a' },
1251         'd' : { 130 : 'd' }
1252     },
1253     400 : {
1254         'a' : { 100 : 'a' },
1255         'd' : { 100 : 'd' }
1256     },
1257     410 : {
1258         'a' : { 110 : 'a' },
1259         'd' : { 110 : 'd' }
1260     },
1261     411 : {
1262         'a' : { 111 : 'a' },
1263         'd' : { 111 : 'd' }
1264     },
1265     440 : {
1266         'a' : { 130 : 'a' },
1267         'n' : { 130 : 'n' },
1268         'p' : { 130 : 'p' }
1269     },
1270     700 : {
1271         'a' : { 100 : 'a' },
1272         'd' : { 100 : 'd' },
1273         'q' : { 100 : 'q' },
1274         't' : { 100 : 't' }
1275     },
1276     710 : {
1277         'a' : { 110 : 'a' },
1278         'd' : { 110 : 'd' }
1279     },
1280     711 : {
1281         'a' : { 111 : 'a' },
1282         'c' : { 111 : 'c' },
1283         'd' : { 111 : 'd' }
1284     },
1285     730 : {
1286         'a' : { 130 : 'a' },
1287         'd' : { 130 : 'd' }
1288     },
1289     800 : {
1290         'a' : { 100 : 'a' },
1291         'd' : { 100 : 'd' }
1292     },
1293     810 : {
1294         'a' : { 110 : 'a' },
1295         'd' : { 110 : 'd' }
1296     },
1297     811 : {
1298         'a' : { 111 : 'a' },
1299         'd' : { 111 : 'd' }
1300     },
1301     830 : {
1302         'a' : { 130 : 'a' },
1303         'd' : { 130 : 'd' }
1304     },
1305     600 : {
1306         'a' : { 100 : 'a' },
1307         'd' : { 100 : 'd' },
1308         'q' : { 100 : 'q' },
1309         't' : { 100 : 't' },
1310         'v' : { 180 : 'v',
1311             100 : 'v',
1312             181 : 'v',
1313             182 : 'v',
1314             185 : 'v'
1315         },
1316         'x' : { 180 : 'x',
1317             100 : 'x',
1318             181 : 'x',
1319             182 : 'x',
1320             185 : 'x'
1321         },
1322         'y' : { 180 : 'y',
1323             100 : 'y',
1324             181 : 'y',
1325             182 : 'y',
1326             185 : 'y'
1327         },
1328         'z' : { 180 : 'z',
1329             100 : 'z',
1330             181 : 'z',
1331             182 : 'z',
1332             185 : 'z'
1333         }
1334     },
1335     610 : {
1336         'a' : { 110 : 'a' },
1337         'd' : { 110 : 'd' },
1338         't' : { 110 : 't' },
1339         'v' : { 180 : 'v',
1340             110 : 'v',
1341             181 : 'v',
1342             182 : 'v',
1343             185 : 'v'
1344         },
1345         'x' : { 180 : 'x',
1346             110 : 'x',
1347             181 : 'x',
1348             182 : 'x',
1349             185 : 'x'
1350         },
1351         'y' : { 180 : 'y',
1352             110 : 'y',
1353             181 : 'y',
1354             182 : 'y',
1355             185 : 'y'
1356         },
1357         'z' : { 180 : 'z',
1358             110 : 'z',
1359             181 : 'z',
1360             182 : 'z',
1361             185 : 'z'
1362         }
1363     },
1364     611 : {
1365         'a' : { 111 : 'a' },
1366         'd' : { 111 : 'd' },
1367         't' : { 111 : 't' },
1368         'v' : { 180 : 'v',
1369             111 : 'v',
1370             181 : 'v',
1371             182 : 'v',
1372             185 : 'v'
1373         },
1374         'x' : { 180 : 'x',
1375             111 : 'x',
1376             181 : 'x',
1377             182 : 'x',
1378             185 : 'x'
1379         },
1380         'y' : { 180 : 'y',
1381             111 : 'y',
1382             181 : 'y',
1383             182 : 'y',
1384             185 : 'y'
1385         },
1386         'z' : { 180 : 'z',
1387             111 : 'z',
1388             181 : 'z',
1389             182 : 'z',
1390             185 : 'z'
1391         }
1392     },
1393     630 : {
1394         'a' : { 130 : 'a' },
1395         'd' : { 130 : 'd' }
1396     },
1397     648 : {
1398         'a' : { 148 : 'a' },
1399         'v' : { 148 : 'v' },
1400         'x' : { 148 : 'x' },
1401         'y' : { 148 : 'y' },
1402         'z' : { 148 : 'z' }
1403     },
1404     650 : {
1405         'a' : { 150 : 'a' },
1406         'b' : { 150 : 'b' },
1407         'v' : { 180 : 'v',
1408             150 : 'v',
1409             181 : 'v',
1410             182 : 'v',
1411             185 : 'v'
1412         },
1413         'x' : { 180 : 'x',
1414             150 : 'x',
1415             181 : 'x',
1416             182 : 'x',
1417             185 : 'x'
1418         },
1419         'y' : { 180 : 'y',
1420             150 : 'y',
1421             181 : 'y',
1422             182 : 'y',
1423             185 : 'y'
1424         },
1425         'z' : { 180 : 'z',
1426             150 : 'z',
1427             181 : 'z',
1428             182 : 'z',
1429             185 : 'z'
1430         }
1431     },
1432     651 : {
1433         'a' : { 151 : 'a' },
1434         'v' : { 180 : 'v',
1435             151 : 'v',
1436             181 : 'v',
1437             182 : 'v',
1438             185 : 'v'
1439         },
1440         'x' : { 180 : 'x',
1441             151 : 'x',
1442             181 : 'x',
1443             182 : 'x',
1444             185 : 'x'
1445         },
1446         'y' : { 180 : 'y',
1447             151 : 'y',
1448             181 : 'y',
1449             182 : 'y',
1450             185 : 'y'
1451         },
1452         'z' : { 180 : 'z',
1453             151 : 'z',
1454             181 : 'z',
1455             182 : 'z',
1456             185 : 'z'
1457         }
1458     },
1459     655 : {
1460         'a' : { 155 : 'a' },
1461         'v' : { 180 : 'v',
1462             155 : 'v',
1463             181 : 'v',
1464             182 : 'v',
1465             185 : 'v'
1466         },
1467         'x' : { 180 : 'x',
1468             155 : 'x',
1469             181 : 'x',
1470             182 : 'x',
1471             185 : 'x'
1472         },
1473         'y' : { 180 : 'y',
1474             155 : 'y',
1475             181 : 'y',
1476             182 : 'y',
1477             185 : 'y'
1478         },
1479         'z' : { 180 : 'z',
1480             155 : 'z',
1481             181 : 'z',
1482             182 : 'z',
1483             185 : 'z'
1484         }
1485     }
1486 };
1487
1488 function getAuthorityContextMenu (target, sf) {
1489     var menu_id = sf.parent().@tag + ':' + sf.@code + '-authority-context-' + sf;
1490
1491     var page = 0;
1492     var old = dojo.byId( menu_id );
1493     if (old) {
1494         page = auth_pages[menu_id];
1495         old.parentNode.removeChild(old);
1496     } else {
1497         auth_pages[menu_id] = 0;
1498     }
1499
1500     var sf_popup = createMenuPopup({ id : menu_id, flex : 1 });
1501
1502     sf_popup.addEventListener("popuphiding", function(event) {
1503         if (show_auth_menu) {
1504             show_auth_menu = false;
1505             getAuthorityContextMenu(target, sf);
1506             dojo.byId(menu_id).openPopup();
1507         }  
1508     }, false);
1509
1510     context_menus.appendChild( sf_popup );
1511
1512     var found_acs = [];
1513     dojo.forEach( acs.controlSetList(), function (acs_id) {
1514         if (acs.controlSet(acs_id).control_map[sf.parent().@tag]) found_acs.push(acs_id);
1515     });
1516
1517     if (!found_acs.length) {
1518         sf_popup.appendChild(createLabel( { value : $('catStrings').getString('staff.cat.marcedit.not_authority_field.label') } ) );
1519         target.setAttribute('context', 'clipboard');
1520         return false;
1521     }
1522
1523     if (sf.toString().replace(/\s*/, '')) {
1524         return browseAuthority(sf_popup, menu_id, target, sf, 20, page);
1525     }
1526
1527     return true;
1528 }
1529
1530 /* Apply the complete 1xx */
1531 function applyFullAuthority ( target, ui_sf, e4x_sf ) {
1532     var new_vals = dojo.query('*[tag^="1"]', target);
1533     return applyAuthority( target, ui_sf, e4x_sf, new_vals );
1534 }
1535
1536 function applySelectedAuthority ( target, ui_sf, e4x_sf ) {
1537     var new_vals = target.getElementsByAttribute('checked','true');
1538     return applyAuthority( target, ui_sf, e4x_sf, new_vals );
1539 }
1540
1541 function applyAuthority ( target, ui_sf, e4x_sf, new_vals ) {
1542     var field = e4x_sf.parent();
1543
1544     for (var i = 0; i < new_vals.length; i++) {
1545
1546         var sf_list = field.subfield;
1547         for (var j in sf_list) {
1548
1549             if (sf_list[j].@code == new_vals[i].getAttribute('subfield')) {
1550                 sf_list[j] = new_vals[i].getAttribute('value');
1551                 new_vals[i].setAttribute('subfield','');
1552                 break;
1553             }
1554         }
1555     }
1556
1557     for (var i = 0; i < new_vals.length; i++) {
1558
1559         /* indicators for the authority datafield are carried over in the main entry linking subfield */
1560         if (new_vals[i].getAttribute('subfield') == '0') {
1561             field.@ind1 = new_vals[i].getAttribute('ind1');
1562             field.@ind2 = new_vals[i].getAttribute('ind2');
1563         }
1564
1565         if (!new_vals[i].getAttribute('subfield')) continue;
1566
1567         var val = new_vals[i].getAttribute('value');
1568
1569         var sf = <subfield code="" xmlns="http://www.loc.gov/MARC21/slim">{val}</subfield>;
1570         sf.@code = new_vals[i].getAttribute('subfield');
1571
1572         field.insertChildAfter(field.subfield[field.subfield.length() - 1], sf);
1573     }
1574
1575     var row = marcDatafield( field );
1576
1577     var node = ui_sf;
1578     while (node.nodeName != 'row') {
1579         node = node.parentNode;
1580     }
1581
1582     node.parentNode.replaceChild( row, node );
1583     return true;
1584 }
1585
1586 function validateAuthority (button) {
1587     var grid = document.getElementById('recGrid');
1588     var label = button.getAttribute('label');
1589
1590     //loop over rows
1591     var rows = grid.lastChild.childNodes;
1592     for (var i = 0; i < rows.length; i++) {
1593         var row = rows[i];
1594         var tag = row.firstChild;
1595
1596         var done = false;
1597         dojo.forEach(acs.controlSetList(), function (acs_id) {
1598             if (done) return;
1599             var control_map = acs.controlSet(acs_id).control_map;
1600     
1601             if (!control_map[tag.value]) return;
1602             button.setAttribute('label', label + ' - ' + tag.value);
1603     
1604             var ind1 = tag.nextSibling;
1605             var ind2 = ind1.nextSibling;
1606             var subfields = ind2.nextSibling.childNodes;
1607     
1608             var sf_list = [];
1609             for (var j = 0; j < subfields.length; j++) {
1610                 var sf = subfields[j];
1611                 sf_list.push( [ sf.childNodes[1].value, sf.childNodes[2].value ] );
1612             }
1613
1614             var matches = acs.findMatchingAuthorities(
1615                 new MARC.Field({
1616                     'tag'       : tag.value,
1617                     'subfields' : sf_list
1618                 })
1619             );
1620
1621             // matches = [ { "$csetId" : [ ... ] } ]
1622
1623             var found = false;
1624             if (matches[0]) { // probably set
1625                 for (var cset in matches[0]) {
1626                     var arr = matches[0][cset];
1627                     if (arr.length) {
1628                         // protect against errant empty string values
1629                         if (arr.length == 1 && arr[0] == '')
1630                             continue;
1631                         found = true;
1632                         break;
1633                     }
1634                 }
1635             }
1636
1637     
1638             // XXX If adt, etc should be validated separately from vxz, etc then move this up into the above for loop
1639             for (var j = 0; j < subfields.length; j++) {
1640                 var sf = subfields[j];
1641                 if (!found) {
1642                     dojo.removeClass(sf.childNodes[2], 'marcValidated');
1643                     dojo.addClass(sf.childNodes[2], 'marcUnvalidated');
1644                 } else {
1645                     dojo.removeClass(sf.childNodes[2], 'marcUnvalidated');
1646                     dojo.addClass(sf.childNodes[2], 'marcValidated');
1647                 }
1648             }
1649
1650             if (found) done = true;
1651         });
1652     }
1653
1654     button.setAttribute('label', label);
1655
1656     return true;
1657 }
1658
1659
1660 /*
1661 function validateBibField (tags, searches) {
1662     var url = "/gateway?input_format=json&format=xml&service=open-ils.search&method=open-ils.search.authority.validate.tag";
1663     url += '&param="tags"&param=' + js2JSON(tags);
1664     url += '&param="searches"&param=' + js2JSON(searches);
1665
1666
1667     var req = new XMLHttpRequest();
1668     req.open('GET',url,false);
1669     req.send(null);
1670
1671     return req;
1672
1673 }
1674 */
1675
1676 function searchAuthority (term, tag, sf, limit) {
1677     var url = "/gateway?input_format=json&format=xml&service=open-ils.search&method=open-ils.search.authority.fts";
1678     url += '&param="term"&param="' + term + '"';
1679     url += '&param="limit"&param=' + limit;
1680     url += '&param="tag"&param=' + tag;
1681     url += '&param="subfield"&param="' + sf + '"';
1682
1683
1684     var req = new XMLHttpRequest();
1685     req.open('GET',url,false);
1686     req.send(null);
1687
1688     return req;
1689
1690 }
1691
1692 /* TODO new authority browse support for context sets, and use that here */
1693 function browseAuthority (sf_popup, menu_id, target, sf, limit, page) {
1694     dojo.require('dojox.xml.parser');
1695
1696     // map tag + subfield to the appropriate authority browse axis:
1697     // currently authority.author, authority.subject, authority.title, authority.topic
1698     // based on mappings in OpenILS::Application::SuperCat, though Authority Control
1699     // Sets will change that
1700
1701     var axis_list = acs.bibFieldBrowseAxes( sf.parent().@tag.toString() );
1702
1703     // No matching tag means no authorities to search - shortcut
1704     if (axis_list.length == 0) {
1705         target.setAttribute('context', 'clipboard');
1706         return false;
1707     }
1708
1709     var type = 'authority.' + axis_list[0]; // Just take the first for now
1710                                             // TODO support multiple axes ... loop?
1711     if (!limit) {
1712         limit = 10;
1713     }
1714
1715     if (!page) {
1716         page = 0;
1717     }
1718
1719     var sf_string = '';
1720     var sf_list = sf.parent().subfield;
1721     for ( var i in sf_list) {
1722         sf_string += sf_list[i].toString() + ' ';
1723         if (sf_list[i] === sf) break;
1724     }
1725
1726     var url = '/opac/extras/browse/marcxml/'
1727         + type + '.refs'
1728         + '/1' // OU - currently unscoped
1729         + '/' + sf_string
1730         + '/' + page
1731         + '/' + limit
1732     ;
1733
1734     // would be good to carve this out into a separate function
1735     dojo.xhrGet({"url":url, "sync": true, "preventCache": true, "handleAs":"xml", "load": function(records) {
1736         var create_menu = createMenu({ label: $('catStrings').getString('staff.cat.marcedit.create_authority.label')});
1737
1738         var cm_popup = create_menu.appendChild(
1739             createMenuPopup()
1740         );
1741
1742         cm_popup.appendChild(
1743             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.create_authority_now.label'),
1744                 command : function() { 
1745                     // Call middle-layer function to create and save the new authority
1746                     var source_f = summarizeField(sf);
1747                     var new_auth = fieldmapper.standardRequest(
1748                         ["open-ils.cat", "open-ils.cat.authority.record.create_from_bib"],
1749                         [source_f, xulG.marc_control_number_identifier, ses()]
1750                     );
1751                     if (new_auth && new_auth.id()) {
1752                         addNewAuthorityID(new_auth, sf, target);
1753                     }
1754                 }
1755             })
1756         );
1757
1758         cm_popup.appendChild(
1759             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.create_authority_edit.label'),
1760                 command : function() { 
1761                     // Generate the new authority by calling the new middle-layer
1762                     // function (a non-saving variant), then display in another
1763                     // MARC editor
1764                     var source_f = summarizeField(sf);
1765                     var authtoken = ses();
1766                     dojo.require('openils.PermaCrud');
1767                     var pcrud = new openils.PermaCrud({"authtoken": authtoken});
1768                     var rec = fieldmapper.standardRequest(
1769                         ["open-ils.cat", "open-ils.cat.authority.record.create_from_bib.readonly"],
1770                         { "params": [source_f, xulG.marc_control_number_identifier] }
1771                     );
1772                     loadMarcEditor(pcrud, rec, target, sf);
1773                 }
1774             })
1775         );
1776
1777         sf_popup.appendChild(create_menu);
1778         sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
1779
1780         // append "Previous page" results browser
1781         sf_popup.appendChild(
1782             createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.previous_page.label'),
1783                 command : function(event) { 
1784                     auth_pages[menu_id] -= 1;
1785                     show_auth_menu = true;
1786                 }
1787             })
1788         );
1789         sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
1790
1791         dojo.query('record', records).forEach(function(record) {
1792             var main_text = '';
1793             var see_from = [];
1794             var see_also = [];
1795             var auth_id = dojox.xml.parser.textContent(dojo.query('datafield[tag="901"]', record).query('subfield[code="c"]')[0]);
1796             var auth_org = dojox.xml.parser.textContent(dojo.query('controlfield[tag="003"]', record)[0]);
1797
1798             // Grab the fields with tags beginning with 1 (main entries) and iterate through the subfields
1799             dojo.query('datafield[tag^="1"]', record).forEach(function(field) {
1800                 dojo.query('subfield', field).forEach(function(subfield) {
1801                     if (main_text) {
1802                         main_text += ' / ';
1803                     }
1804                     main_text += dojox.xml.parser.textContent(subfield);
1805                 });
1806             });
1807
1808             // Grab the fields with tags beginning with 4 (see from entries) and iterate through the subfields
1809             dojo.query('datafield[tag^="4"]', record).forEach(function(field) {
1810                 var see_text = '';
1811                 dojo.query('subfield', field).forEach(function(subfield) {
1812                     if (see_text) {
1813                         see_text += ' / ';
1814                     }
1815                     see_text += dojox.xml.parser.textContent(subfield);
1816                 });
1817                 see_from.push($('catStrings').getFormattedString('staff.cat.marcedit.authority_see_from', [see_text]));
1818             });
1819
1820             // Grab the fields with tags beginning with 5 (see also entries) and iterate through the subfields
1821             dojo.query('datafield[tag^="5"]', record).forEach(function(field) {
1822                 var see_text = '';
1823                 dojo.query('subfield', field).forEach(function(subfield) {
1824                     if (see_text) {
1825                         see_text += ' / ';
1826                     }
1827                     see_text += dojox.xml.parser.textContent(subfield);
1828                 });
1829                 see_also.push($('catStrings').getFormattedString('staff.cat.marcedit.authority_see_also', [see_text]));
1830             });
1831
1832             buildAuthorityPopup(main_text, record, auth_org, auth_id, sf_popup, target, sf);
1833
1834             dojo.forEach(see_from, function(entry_text) {
1835                 buildAuthorityPopup(entry_text, record, auth_org, auth_id, sf_popup, target, sf, "font-style: italic; margin-left: 2em;");
1836             });
1837
1838             // To-do: instead of launching the standard selector menu, invoke
1839             // a new authority search using the 5XX entry text
1840             dojo.forEach(see_also, function(entry_text) {
1841                 buildAuthorityPopup(entry_text, record, auth_org, auth_id, sf_popup, target, sf, "font-style: italic; margin-left: 2em;");
1842             });
1843
1844         });
1845
1846         if (sf_popup.childNodes.length == 0) {
1847             sf_popup.appendChild(createLabel( { value : $('catStrings').getString('staff.cat.marcedit.no_authority_match.label') } ) );
1848         } else {
1849             // append "Next page" results browser
1850             sf_popup.appendChild( createComplexXULElement( 'menuseparator' ) );
1851             sf_popup.appendChild(
1852                 createMenuitem({ label : $('catStrings').getString('staff.cat.marcedit.next_page.label'),
1853                     command : function(event) { 
1854                         auth_pages[menu_id] += 1;
1855                         show_auth_menu = true;
1856                     }
1857                 })
1858             );
1859         }
1860
1861         target.setAttribute('context', menu_id);
1862         return true;
1863     }});
1864
1865 }
1866
1867 function buildAuthorityPopup (entry_text, record, auth_org, auth_id, sf_popup, target, sf, style) {
1868     var grid = dojo.query('[name="authority-marc-template"]')[0].cloneNode(true);
1869     grid.setAttribute('name','-none-');
1870     grid.setAttribute('style','overflow:scroll');
1871
1872     var submenu = createMenu( { "label": entry_text } );
1873
1874     var popup = createMenuPopup({ "flex": "1" });
1875     if (style) {
1876         submenu.setAttribute('style', style);
1877         popup.setAttribute('style', 'font-style: normal; margin-left: 0em;');
1878     }
1879     submenu.appendChild(popup);
1880
1881     dojo.query('datafield[tag^="1"]', record).forEach(function(field) {
1882         buildAuthorityPopupSelector(field, grid, auth_org, auth_id);
1883     });
1884     dojo.query('datafield[tag^="4"]', record).forEach(function(field) {
1885         buildAuthorityPopupSelector(field, grid, auth_org, auth_id);
1886     });
1887     dojo.query('datafield[tag^="5"]', record).forEach(function(field) {
1888         buildAuthorityPopupSelector(field, grid, auth_org, auth_id);
1889     });
1890
1891     grid.hidden = false;
1892     popup.appendChild( grid );
1893
1894     popup.appendChild(
1895         createMenuitem(
1896             { label : $('catStrings').getString('staff.cat.marcedit.apply_selected.label'),
1897               command : function (event) {
1898                     applySelectedAuthority(event.target.previousSibling, target, sf);
1899                     return true;
1900               }
1901             }
1902         )
1903     );
1904
1905     popup.appendChild( createComplexXULElement( 'menuseparator' ) );
1906
1907     popup.appendChild(
1908         createMenuitem(
1909             { label : $('catStrings').getString('staff.cat.marcedit.apply_full.label'),
1910               command : function (event) {
1911                     applyFullAuthority(event.target.previousSibling.previousSibling.previousSibling, target, sf);
1912                     return true;
1913               }
1914             }
1915         )
1916     );
1917
1918     sf_popup.appendChild( submenu );
1919 }
1920
1921 function buildAuthorityPopupSelector (field, grid, auth_org, auth_id) {
1922     var row = createRow(
1923         { },
1924         createLabel( { "value" : dojo.attr(field, 'tag') } ),
1925         createLabel( { "value" : dojo.attr(field, 'ind1') } ),
1926         createLabel( { "value" : dojo.attr(field, 'ind2') } )
1927     );
1928
1929     var sf_box = createHbox();
1930     dojo.query('subfield', field).forEach(function(subfield) {
1931         sf_box.appendChild(
1932             createCheckbox(
1933                 { "label"    : '\u2021' + dojo.attr(subfield, 'code') + ' ' + dojox.xml.parser.textContent(subfield),
1934                   "subfield" : dojo.attr(subfield, 'code'),
1935                   "tag"      : dojo.attr(field, 'tag'),
1936                   "value"    : dojox.xml.parser.textContent(subfield)
1937                 }
1938             )
1939         );
1940         row.appendChild(sf_box);
1941     });
1942
1943     // Append the authority linking subfield only for main entries
1944     if (dojo.attr(field, 'tag').charAt(0) == '1') {
1945         sf_box.appendChild(
1946             createCheckbox(
1947                 { "label"    : '\u2021' + '0' + ' (' + auth_org + ')' + auth_id,
1948                   "subfield" : '0',
1949                   "tag"      : dojo.attr(field, 'tag'),
1950                   "ind1"     : dojo.attr(field, 'ind1'),
1951                   "ind2"     : dojo.attr(field, 'ind2'),
1952                   "value"    : '(' + auth_org + ')' + auth_id
1953                 }
1954             )
1955         );
1956     }
1957     row.appendChild(sf_box);
1958
1959     grid.lastChild.appendChild(row);
1960 }
1961
1962 function summarizeField(sf) {
1963     var source_f= {
1964         "tag": '',
1965         "ind1": '',
1966         "ind2": '',
1967         "subfields": []
1968     };
1969
1970     source_f.tag = sf.parent().@tag.toString();
1971     source_f.ind1 = sf.parent().@ind1.toString();
1972     source_f.ind2 = sf.parent().@ind2.toString();
1973
1974     var found_acs = [];
1975     dojo.forEach( acs.controlSetList(), function (acs_id) {
1976         if (acs.controlSet(acs_id).control_map[sf.parent().@tag]) found_acs.push(acs_id);
1977     });
1978
1979     var cmap;
1980     if (!found_acs.length) {
1981         return false;
1982     } else {
1983         cmap = acs.controlSet(found_acs[0]).control_map;
1984     }
1985
1986     for (var i = 0; i < sf.parent().subfield.length(); i++) {
1987         var sf_iter = sf.parent().subfield[i];
1988
1989         /* Filter out subfields that are not controlled for this tag */
1990         if (!cmap[source_f.tag][sf_iter.@code.toString()]) {
1991             continue;
1992         }
1993
1994         source_f.subfields.push([sf_iter.@code.toString(), sf_iter.toString()]);
1995     }
1996
1997     return source_f;
1998 }
1999
2000 function buildBibSourceList (authtoken, recId) {
2001     /* TODO: Work out how to set the bib source of the bre that does not yet
2002      * exist - this is specifically in the case of Z39.50 imports. Right now
2003      * we just avoid populating and showing the config.bib_source list
2004      */
2005     if (!recId) {
2006         return false;
2007     }
2008
2009     var bib = xulG.record.bre;
2010
2011     dojo.require('openils.PermaCrud');
2012
2013     // cbsList = the XUL menulist that contains the available bib sources 
2014     var cbsList = dojo.byId('bib-source-list');
2015
2016     // bibSources = an array containing all of the bib source objects
2017     var bibSources = new openils.PermaCrud({"authtoken": authtoken}).retrieveAll('cbs');
2018
2019     // A tad ugly, but gives us the index of the bib source ID in cbsList
2020     var x = 0;
2021     var cbsListArr = [];
2022     dojo.forEach(bibSources, function (item) {
2023         cbsList.appendItem(item.source(), item.id());
2024         cbsListArr[item.id()] = x;
2025         x++;
2026     });
2027
2028     // Show the current value of the bib source for this record
2029     cbsList.selectedIndex = cbsListArr[bib.source()];
2030
2031     // Display the bib source selection widget
2032     dojo.byId('bib-source-list-caption').hidden = false;
2033     dojo.byId('bib-source-list').hidden = false;
2034     dojo.byId('bib-source-list-button').disabled = true;
2035     dojo.byId('bib-source-list-button').hidden = false;
2036 }
2037
2038 // Fired when the "Update Source" button is clicked
2039 // Updates the value of the bib source for the current record
2040 function updateBibSource() {
2041     var authtoken = ses();
2042     var cbs = dojo.byId('bib-source-list').selectedItem.value;
2043     var recId = xulG.record.id;
2044     var pcrud = new openils.PermaCrud({"authtoken": authtoken});
2045     var bib = pcrud.retrieve('bre', recId);
2046     if (bib.source() != cbs) {
2047         bib.source(cbs);
2048         bib.ischanged = true;
2049         pcrud.update(bib);
2050     }
2051 }
2052
2053 function onBibSourceSelect() {
2054     var cbs = dojo.byId('bib-source-list').selectedItem.value;
2055     var bib = xulG.record.bre;
2056     if (bib.source() != cbs) {
2057         dojo.byId('bib-source-list-button').disabled = false;   
2058     } else {
2059         dojo.byId('bib-source-list-button').disabled = true;   
2060     }
2061 }
2062
2063 function addNewAuthorityID(authority, sf, target) {
2064     var id_sf = <subfield code="0" xmlns="http://www.loc.gov/MARC21/slim">({xulG.marc_control_number_identifier}){authority.id()}</subfield>;
2065     sf.parent().appendChild(id_sf);
2066     var new_sf = marcSubfield(id_sf);
2067
2068     var node = target;
2069     while (dojo.attr(node, 'name') != 'sf_box') {
2070         node = node.parentNode;
2071     }
2072     node.appendChild( new_sf );
2073
2074     alert($('catStrings').getString('staff.cat.marcedit.create_authority_success.label'));
2075 }
2076
2077 function loadMarcEditor(pcrud, marcxml, target, sf) {
2078     /*
2079        To run in Firefox directly, must set signed.applets.codebase_principal_support
2080        to true in about:config
2081      */
2082     win = window.open('/xul/server/cat/marcedit.xul', '_blank', 'chrome'); // XXX version?
2083
2084     // Match marc2are.pl last_xact_id format, roughly
2085     var now = new Date;
2086     var xact_id = 'IMPORT-' + Date.parse(now);
2087     
2088     win.xulG = {
2089         "record": {"marc": marcxml, "rtype": "are"},
2090         "save": {
2091             "label": $('catStrings').getString('staff.cat.marcedit.save.label'),
2092             "func": function(xmlString) {
2093                 var rec = new are();
2094                 rec.marc(xmlString);
2095                 rec.last_xact_id(xact_id);
2096                 rec.isnew(true);
2097                 pcrud.create(rec, {
2098                     "oncomplete": function (r, objs) {
2099                         var new_rec = objs[0];
2100                         if (!new_rec) {
2101                             return '';
2102                         }
2103
2104                         addNewAuthorityID(new_rec, sf, target);
2105
2106                         win.close();
2107                     }
2108                 });
2109             }
2110         }
2111     };
2112 }
2113
2114