]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/services/marcedit.js
webstaff: Phys Char Wiz : launcher link
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / services / marcedit.js
1 /**
2  *  A MARC editor...
3  */
4
5 angular.module('egMarcMod', ['egCoreMod', 'ui.bootstrap'])
6
7 .directive("egContextMenuItem", ['$timeout',function ($timeout) {
8     return {
9         restrict: 'E',
10         replace: true,
11         template: '<li><a ng-click="setContent(item.value,item.action)">{{item.label}}</a></li>',
12         scope: { item: '=', content: '=' },
13         controller: ['$scope','$element',
14             function ($scope , $element) {
15                 if (!$scope.item.label) $scope.item.label = $scope.item.value;
16                 if ($scope.item.divider) {
17                     $element.style.borderTop = 'solid 1px';
18                 }
19
20                 $scope.setContent = function (v, a) {
21                     var replace_with = v;
22                     if (a) replace_with = a($scope,$element,$scope.item.value,$scope.$parent.$parent.content);
23                     $timeout(function(){
24                         $scope.$parent.$parent.$apply(function(){
25                             $scope.$parent.$parent.content = replace_with
26                         })
27                     }, 0);
28                     $($element).parent().css({display: 'none'});
29                 }
30             }
31         ]
32     }
33 }])
34
35 .directive("egMarcEditEditable", ['$timeout', '$compile', '$document', function ($timeout, $compile, $document) {
36     return {
37         restrict: 'E',
38         replace: true,
39         template: '<input '+
40                       'style="font-family: \'Lucida Console\', Monaco, monospace;" '+
41                       'ng-model="content" '+
42                       'size="{{content.length * 1.1}}" '+
43                       'maxlength="{{max}}" '+
44                       'class="" '+
45                       'type="text" '+
46                   '/>',
47         scope: {
48             field: '=',
49             onKeydown: '=',
50             subfield: '=',
51             content: '=',
52             contextItemContainer: '@',
53             contextItemGenerator: '=',
54             max: '@',
55             itype: '@'
56         },
57         controller : ['$scope',
58             function ( $scope ) {
59
60                 if ($scope.contextItemContainer && angular.isArray($scope.$parent[$scope.contextItemContainer]))
61                     $scope.item_container = $scope.$parent[$scope.contextItemContainer];
62                 else if ($scope.contextItemGenerator)
63                     $scope.item_generator = $scope.contextItemGenerator;
64
65                 $scope.showContext = function (event) {
66                     $scope.item_list = [];
67                     if ($scope.item_container) {
68                         $scope.item_list = $scope.item_container;
69                     } else if ($scope.item_generator) {
70                         // always recalculate; tag and/or subfield
71                         // codes may have changed
72                         $scope.item_list = $scope.item_generator();
73                     } else {
74                         return true;
75                     }
76
77                     if (angular.isArray($scope.item_list) && $scope.item_list.length > 0) { // we have a list of values or transforms
78                         console.log('Showing context menu...');
79                         $('body').trigger('click');
80
81                         var tmpl = 
82                             '<ul class="dropdown-menu" role="menu" style="z-index: 2000;">'+
83                                 '<eg-context-menu-item ng-repeat="item in item_list" item="item" content="content"/>'+
84                             '</ul>';
85             
86                         var tnode = angular.element(tmpl);
87                         $document.find('body').append(tnode);
88
89                         $(tnode).css({
90                             display: 'block',
91                             top: event.pageY,
92                             left: event.pageX
93                         });
94
95                         $timeout(function() {
96                             var e = $compile(tnode)($scope);
97                         }, 0);
98
99
100                         $('body').on('click.context_menu',function() {
101                             $(tnode).css('display','none');
102                             $('body').off('click.context_menu');
103                         });
104
105                         return false;
106                     }
107             
108                     return true;
109                 }
110
111             }
112         ],
113         link: function (scope, element, attrs) {
114
115             if (scope.onKeydown) element.bind('keydown', {scope : scope}, scope.onKeydown);
116
117             element.bind('change', function (e) { element.size = scope.max || parseInt(scope.content.length * 1.1) });
118
119             element.bind('contextmenu', scope.showContext);
120         }
121     }
122 }])
123
124 .directive("egMarcEditFixedField", ['$timeout', '$compile', '$document', function ($timeout, $compile, $document) {
125     return {
126         transclude: true,
127         restrict: 'E',
128         template: '<div class="col-md-2">'+
129                     '<div class="col-md-1"><label name="{{fixedField}}" for="{{fixedField}}_ff_input">{{fixedField}}</label></div>'+
130                     '<div class="col-md-1"><input type="text" style="padding-left: 5px; margin-left: 1em" size="4" id="{{fixedField}}_ff_input"/></div>'+
131                   '</div>',
132         scope: { record: "=", fixedField: "@" },
133         replace: true,
134         controller : ['$scope', '$element', 'egTagTable',
135             function ( $scope ,  $element ,  egTagTable) {
136                 $($element).children().css({ display : 'none' });
137                 $scope.me = null;
138                 $scope.content = null; // this is where context menus dump their values
139                 $scope.item_container = [];
140                 $scope.in_handler = false;
141                 $scope.ready = false;
142
143                 $scope.$watch('content', function (newVal, oldVal) {
144                     var input = $($element).find('input');
145                     input.val(newVal);
146                     input.trigger('keyup'); // cascade the update
147                 });
148
149                 $scope.$watch('record.ready', function (newVal, oldVal) { // wait for the record to be loaded
150                     if (newVal && !$scope.ready) {
151                         $scope.rtype = $scope.record.recordType();
152
153                         egTagTable.fetchFFPosTable( $scope.rtype ).then(function (ff_list) {
154                             angular.forEach(ff_list, function (ff) {
155                                 if (!$scope.me) {
156                                     if (ff.fixed_field == $scope.fixedField && ff.rec_type == $scope.rtype) {
157                                         $scope.me = ff;
158                                         $scope.ready = true;
159                                         $($element).children().css({ display : 'inline' });
160
161                                         var input = $($element).find('input');
162                                         input.attr('maxlength', $scope.me.length);
163                                         input.val($scope.record.extractFixedField($scope.me.fixed_field));
164                                         input.on('keyup', function(e) {
165                                             $scope.in_handler = true;
166                                             $scope.record.setFixedField($scope.me.fixed_field, input.val());
167                                             try { $scope.$parent.$digest(); } catch(e) {};
168                                         });
169                                     }
170                                 }
171                             });
172                             return $scope.me;
173                         }).then(function (me) {
174                             if (me) {
175                                 $scope.$watch(
176                                     function() {
177                                         return $scope.record.extractFixedField($scope.fixedField);
178                                     },
179                                     function (newVal, oldVal) {
180                                         if ($scope.in_handler) {
181                                             $scope.in_handler = false;
182                                         } else if (oldVal != newVal) {
183                                             $($element).find('input').val(newVal);
184                                         }
185                                     }
186                                 );
187                             }
188                         }).then(function () {
189                             return egTagTable.fetchFFValueTable( $scope.rtype );
190                         }).then(function (vlist) {
191                             if (vlist[$scope.fixedField]) {
192                                 vlist[$scope.fixedField].forEach(function (v) {
193                                     if (v[0].length <= v[2]) {
194                                         $scope.item_container.push({ value : v[0], label : v[0] + ': ' + v[1] });
195                                     }
196                                 });
197                             }
198                         }).then(function () {
199                             if ($scope.item_container && $scope.item_container.length)
200                                 $($element).bind('contextmenu', $scope.showContext);
201                         });
202
203                     }
204                 });
205
206                 $scope.showContext = function (event) {
207                     if ($scope.context_menu_element) {
208                         console.log('Reshowing context menu...');
209                         $('body').trigger('click');
210                         $($scope.context_menu_element).css({ display: 'block', top: event.pageY, left: event.pageX });
211                         $('body').on('click.context_menu',function() {
212                             $($scope.context_menu_element).css('display','none');
213                             $('body').off('click.context_menu');
214                         });
215                         return false;
216                     }
217
218                     if (angular.isArray($scope.item_container)) { // we have a list of values or transforms
219                         console.log('Showing context menu...');
220                         $('body').trigger('click');
221
222                         var tmpl = 
223                             '<ul class="dropdown-menu" role="menu" style="z-index: 2000;">'+
224                                 '<eg-context-menu-item ng-repeat="item in item_container" item="item" content="content"/>'+
225                             '</ul>';
226             
227                         var tnode = angular.element(tmpl);
228                         $document.find('body').append(tnode);
229
230                         $(tnode).css({
231                             display: 'block',
232                             top: event.pageY,
233                             left: event.pageX
234                         });
235
236                         $scope.context_menu_element = tnode;
237
238                         $timeout(function() {
239                             var e = $compile(tnode)($scope);
240                         }, 0);
241
242
243                         $('body').on('click.context_menu',function() {
244                             $(tnode).css('display','none');
245                             $('body').off('click.context_menu');
246                         });
247
248                         return false;
249                     }
250             
251                     return true;
252                 }
253
254             }
255         ]
256     }
257 }])
258
259 .directive("egMarcEditSubfield", function () {
260     return {
261         transclude: true,
262         restrict: 'E',
263         template: '<span>'+
264                     '<span><label class="marcedit marcsfcodedelimiter"'+
265                         'for="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}s{{subfield[2]}}code" '+
266                         '>‡</label><eg-marc-edit-editable '+
267                         'itype="sfc" '+
268                         'class="marcedit marcsf marcsfcode" '+
269                         'field="field" '+
270                         'subfield="subfield" '+
271                         'content="subfield[0]" '+
272                         'max="1" '+
273                         'on-keydown="onKeydown" '+
274                         'context-item-generator="sf_code_options" '+
275                         'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}s{{subfield[2]}}code" '+
276                     '/></span>'+
277                     '<span><eg-marc-edit-editable '+
278                         'itype="sfv" '+
279                         'class="marcedit marcsf marcsfvalue" '+
280                         'field="field" '+
281                         'subfield="subfield" '+
282                         'content="subfield[1]" '+
283                         'on-keydown="onKeydown" '+
284                         'context-item-generator="sf_val_options" '+
285                         'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}s{{subfield[2]}}value" '+
286                     '/></span>'+
287                   '</span>',
288         scope: { field: "=", subfield: "=", onKeydown: '=' },
289         replace: true,
290         controller : ['$scope', 'egTagTable',
291             function ( $scope ,  egTagTable) {
292
293                 $scope.sf_code_options = function () {
294                     return egTagTable.getSubfieldCodes($scope.field.tag);
295                 }
296                 $scope.sf_val_options = function () {
297                     return egTagTable.getSubfieldValues($scope.field.tag, $scope.subfield[0]);
298                 }
299             }
300         ]
301     }
302 })
303
304 .directive("egMarcEditInd", function () {
305     return {
306         transclude: true,
307         restrict: 'E',
308         template: '<span><eg-marc-edit-editable '+
309                       'itype="ind" '+
310                       'class="marcedit marcind" '+
311                       'field="field" '+
312                       'content="ind" '+
313                       'max="1" '+
314                       'on-keydown="onKeydown" '+
315                       'context-item-generator="ind_val_options" '+
316                       'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}i{{indNumber}}"'+
317                       '/></span>',
318         scope: { ind : '=', field: '=', onKeydown: '=', indNumber: '@' },
319         replace: true,
320         controller : ['$scope', 'egTagTable',
321             function ( $scope ,  egTagTable) {
322
323                 $scope.ind_val_options = function () {
324                     return egTagTable.getIndicatorValues($scope.field.tag, $scope.indNumber);
325                 }
326             }
327         ]
328     }
329 })
330
331 .directive("egMarcEditTag", function () {
332     return {
333         transclude: true,
334         restrict: 'E',
335         template: '<span><eg-marc-edit-editable '+
336                       'itype="tag" '+
337                       'class="marcedit marctag" '+
338                       'field="field" '+
339                       'content="tag" '+
340                       'max="3" '+
341                       'on-keydown="onKeydown" '+
342                       'context-item-generator="tag_options" '+
343                       'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}tag"'+
344                       '/></span>',
345         scope: { tag : '=', field: '=', onKeydown: '=' },
346         replace: true,
347         controller : ['$scope', 'egTagTable',
348             function ( $scope ,  egTagTable) {
349
350                 $scope.tag_options = function () {
351                     return egTagTable.getFieldTags();
352                 }
353             }
354         ]
355     }
356 })
357
358 .directive("egMarcEditDatafield", function () {
359     return {
360         transclude: true,
361         restrict: 'E',
362         template: '<div>'+
363                     '<span><eg-marc-edit-tag field="field" tag="field.tag" on-keydown="onKeydown"/></span>'+
364                     '<span><eg-marc-edit-ind field="field" ind="field.ind1" on-keydown="onKeydown" ind-number="1"/></span>'+
365                     '<span><eg-marc-edit-ind field="field" ind="field.ind2" on-keydown="onKeydown" ind-number="2"/></span>'+
366                     '<span><eg-marc-edit-subfield ng-class="{ \'unvalidatedheading\' : field.heading_checked && !field.heading_valid}" ng-repeat="subfield in field.subfields" subfield="subfield" field="field" on-keydown="onKeydown"/></span>'+
367                     // FIXME: template should probably be moved to file to improve
368                     // translatibility
369                     '<button class="btn btn-info btn-xs" '+
370                     'aria-label="Manage authority record links" '+
371                     'ng-show="isAuthorityControlled(field)"'+
372                     'ng-click="spawnAuthorityLinker()"'+
373                     '>'+
374                     '<span class="glyphicon glyphicon-link"></span>'+
375                     '</button>'+
376                     '<span ng-show="field.heading_checked && field.heading_valid" class="glyphicon glyphicon-ok-sign"></span>'+
377                     '<span ng-show="field.heading_checked && !field.heading_valid" class="glyphicon glyphicon-question-sign"></span>'+
378                   '</div>',
379         scope: { field: "=", onKeydown: '=' },
380         replace: true,
381         controller : ['$scope','$modal',
382             function ( $scope,  $modal ) {
383                 $scope.isAuthorityControlled = function () {
384                     return ($scope.$parent.$parent.record_type == 'bre') &&
385                            $scope.$parent.$parent.controlSet.bibFieldByTag($scope.field.tag);
386                 }
387                 $scope.spawnAuthorityLinker = function() {
388                     // intentionally making a clone in case
389                     // user decides to abandon the linking
390                     var fieldCopy = new MARC21.Field({
391                         tag       : $scope.field.tag,
392                         ind1      : $scope.field.ind1,
393                         ind2      : $scope.field.ind2
394                     });
395                     angular.forEach($scope.field.subfields, function(sf) {
396                         fieldCopy.subfields.push(sf.slice(0));
397                     });
398                     var cs = $scope.$parent.$parent.controlSet;
399                     var args = { changed : false };
400                     $modal.open({
401                         templateUrl: './cat/share/t_authority_link_dialog',
402                         size: 'lg',
403                         controller: ['$scope', '$modalInstance', function($scope, $modalInstance) {
404                             $scope.controlSet = cs;
405                             $scope.bibField = fieldCopy;
406                             $scope.focusMe = true;
407                             $scope.args = args;
408                             $scope.ok = function(args) { $modalInstance.close(args) };
409                             $scope.cancel = function () { $modalInstance.dismiss() };
410                         }]
411                     }).result.then(function (args) {
412                         if (args.changed) {
413                             $scope.field.subfields.length = 0;
414                             angular.forEach(fieldCopy.subfields, function(sf) {
415                                 $scope.field.addSubfields(sf[0], sf[1]);
416                             });
417                         }
418                     });
419                 }
420             }
421         ]
422     }
423 })
424
425 .directive("egMarcEditControlfield", function () {
426     return {
427         transclude: true,
428         restrict: 'E',
429         template: '<div>'+
430                     '<span><eg-marc-edit-tag field="field" tag="field.tag" on-keydown="onKeydown"/></span>'+
431                     '<span><eg-marc-edit-editable '+
432                       'itype="cfld" '+
433                       'field="field" '+
434                       'class="marcedit marcdata" '+
435                       'content="field.data" '+
436                       'on-keydown="onKeydown" '+
437                       'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}data"'+
438                       '/></span>'+
439                       // TODO: move to TT2 template
440                       '<button class="btn btn-info btn-xs" '+
441                       'aria-label="Physical Characteristics Wizard" '+
442                       'ng-show="showPhysCharLink()"'+
443                       'ng-click="spawnPhysCharWizard()"'+
444                       '>'+
445                       '<span class="glyphicon glyphicon-link"></span>'+
446                       '</button>'+
447                   '</div>',
448         scope: { field: "=", onKeydown: '=' },
449         controller : ['$scope','$modal',
450             function ( $scope,  $modal ) {
451                 $scope.showPhysCharLink = function () {
452                     return ($scope.$parent.$parent.record_type == 'bre') 
453                         && $scope.field.tag == '007';
454                 }
455                 $scope.spawnPhysCharWizard = function() {
456                     console.log('HERE');
457                 }
458             }
459         ]
460     }
461 })
462
463 .directive("egMarcEditLeader", function () {
464     return {
465         transclude: true,
466         restrict: 'E',
467         template: '<div>'+
468                     '<span><eg-marc-edit-editable '+
469                       'class="marcedit marctag" '+
470                       'content="tag" '+
471                       'on-keydown="onKeydown" '+
472                       'id="leadertag" '+
473                       'disabled="disabled"'+
474                       '/></span>'+
475                     '<span><eg-marc-edit-editable '+
476                       'class="marcedit marcdata" '+
477                       'itype="ldr" '+
478                       'max="{{record.leader.length}}" '+
479                       'content="record.leader" '+
480                       'id="r{{record.subfield(\'901\',\'c\')[1]}}leaderdata" '+
481                       'on-keydown="onKeydown"'+
482                       '/></span>'+
483                   '</div>',
484         controller : ['$scope',
485             function ( $scope ) {
486                 $scope.tag = 'LDR';
487             }
488         ],
489         scope: { record: "=", onKeydown: '=' }
490     }
491 })
492
493 /// TODO: fixed field editor and such
494 .directive("egMarcEditRecord", function () {
495     return {
496         templateUrl : './cat/share/t_marcedit',
497         restrict: 'E',
498         replace: true,
499         scope: {
500             dirtyFlag : '=',
501             recordId : '=',
502             marcXml : '=',
503             // in-place mode means that the editor is being
504             // used just to munge some MARCXML client-side, rather
505             // than to (immediately) update the database
506             inPlaceMode : '@',
507             recordType : '@',
508             maxUndo : '@'
509         },
510         link: function (scope, element, attrs) {
511
512             element.bind('click', function(e) {;
513                 scope.current_event_target = $(e.target).attr('id');
514                 if (scope.current_event_target) {
515                     console.log('Recording click event on ' + scope.current_event_target);
516                     scope.current_event_target_cursor_pos =
517                         e.target.selectionDirection=='backward' ?
518                             e.target.selectionStart :
519                             e.target.selectionEnd;
520                 }
521             });
522
523         },
524         controller : ['$timeout','$scope','$q','$window','egCore', 'egTagTable',
525             function ( $timeout , $scope , $q,  $window , egCore ,  egTagTable ) {
526
527                 MARC21.Record.delimiter = '$';
528
529                 $scope.enable_fast_add = false;
530                 $scope.fast_item_callnumber = '';
531                 $scope.fast_item_barcode = '';
532                 $scope.flatEditor = false;
533                 $scope.brandNewRecord = false;
534                 $scope.bib_source = null;
535                 $scope.record_type = $scope.recordType || 'bre';
536                 $scope.max_undo = $scope.maxUndo || 100;
537                 $scope.record_undo_stack = [];
538                 $scope.record_redo_stack = [];
539                 $scope.in_undo = false;
540                 $scope.in_redo = false;
541                 $scope.record = new MARC21.Record();
542                 $scope.save_stack_depth = 0;
543                 $scope.controlfields = [];
544                 $scope.datafields = [];
545                 $scope.controlSet = egTagTable.getAuthorityControlSet();
546
547                 egTagTable.loadTagTable({ marcRecordType : $scope.record_type });
548
549                 $scope.saveFlatTextMARC = function () {
550                     $scope.record = new MARC21.Record({ marcbreaker : $scope.flat_text_marc });
551                 };
552
553                 $scope.refreshVisual = function () {
554                     if (!$scope.flatEditor) {
555                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
556                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
557                     }
558                 };
559
560                 $scope.onKeydown = function (event) {
561                     var event_return = true;
562
563                     console.log(
564                         'keydown: which='+event.which+
565                         ', ctrlKey='+event.ctrlKey+
566                         ', shiftKey='+event.shiftKey+
567                         ', altKey='+event.altKey+
568                         ', metaKey='+event.altKey
569                     );
570
571                     if (event.which == 89 && event.ctrlKey) { // ctrl+y, redo
572                         event_return = $scope.processRedo();
573                     } else if (event.which == 90 && event.ctrlKey) { // ctrl+z, undo
574                         event_return = $scope.processUndo();
575                     } else if ((event.which == 68 || event.which == 73) && event.ctrlKey) { // ctrl+d or ctrl+i, insert subfield
576
577                         var element = $(event.target);
578                         var new_sf, index_sf, move_data;
579
580                         if (element.hasClass('marcsfvalue')) {
581                             index_sf = event.data.scope.subfield[2];
582                             new_sf = index_sf + 1;
583
584                             var start = event.target.selectionStart;
585                             var end = event.target.selectionEnd - event.target.selectionStart ?
586                                     event.target.selectionEnd :
587                                     event.target.value.length;
588
589                             move_data = event.target.value.substring(start,end);
590
591                         } else if (element.hasClass('marcsfcode')) {
592                             index_sf = event.data.scope.subfield[2];
593                             new_sf = index_sf + 1;
594                         } else if (element.hasClass('marctag') || element.hasClass('marcind')) {
595                             index_sf = 0;
596                             new_sf = index_sf;
597                         }
598
599                         $scope.current_event_target = 'r' + $scope.recordId +
600                                                       'f' + event.data.scope.field.position + 
601                                                       's' + new_sf + 'code';
602
603                         event.data.scope.field.subfields.forEach(function(sf) {
604                             if (sf[2] >= new_sf) sf[2]++;
605                             if (sf[2] == index_sf) sf[1] = event.target.value.substring(0,start) + event.target.value.substring(end);
606                         });
607                         event.data.scope.field.subfields.splice(
608                             new_sf,
609                             0,
610                             [' ', move_data, new_sf ]
611                         );
612
613                         $scope.current_event_target_cursor_pos = 0;
614                         $scope.current_event_target_cursor_pos_end = 1;
615
616                         $timeout(function(){$scope.$digest()}).then(setCaret);
617
618                         event_return = false;
619
620                     } else if (event.which == 117 && event.shiftKey) { // shift + F6, insert 006
621                         event.data.scope.field.record.insertOrderedFields(
622                             new MARC21.Field({
623                                 tag : '006',
624                                 data : '                                        '
625                             })
626                         );
627
628                         $scope.force_render = true;
629                         $timeout(function(){$scope.$digest()}).then(setCaret);
630
631                         event_return = false;
632
633                     } else if (event.which == 118 && event.shiftKey) { // shift + F7, insert 007
634                         event.data.scope.field.record.insertOrderedFields(
635                             new MARC21.Field({
636                                 tag : '007',
637                                 data : '                                        '
638                             })
639                         );
640
641                         $scope.force_render = true;
642                         $timeout(function(){$scope.$digest()}).then(setCaret);
643
644                         event_return = false;
645
646                     } else if (event.which == 119 && event.shiftKey) { // shift + F8, insert/replace 008
647                         var new_008_data = event.data.scope.field.record.generate008();
648
649
650                         var old_008s = event.data.scope.field.record.field('008',true);
651                         old_008s.forEach(function(o) {
652                             var domnode = $('#r'+o.record.subfield('901','c')[1] + 'f' + o.position);
653                             domnode.scope().$destroy();
654                             domnode.remove();
655                             event.data.scope.field.record.deleteFields(o);
656                         });
657
658                         event.data.scope.field.record.insertOrderedFields(
659                             new MARC21.Field({
660                                 tag : '008',
661                                 data : new_008_data
662                             })
663                         );
664
665                         $scope.force_render = true;
666                         $timeout(function(){$scope.$digest()}).then(setCaret);
667
668                         event_return = false;
669
670                     } else if (event.which == 13 && event.ctrlKey) { // ctrl+enter, insert datafield
671
672                         var element = $(event.target);
673
674                         var index_field = event.data.scope.field.position;
675                         var new_field = index_field + 1;
676
677                         event.data.scope.field.record.insertFieldsAfter(
678                             event.data.scope.field,
679                             new MARC21.Field({
680                                 tag : '999',
681                                 subfields : [[' ','',0]]
682                             })
683                         );
684
685                         $scope.current_event_target = 'r' + $scope.recordId +
686                                                       'f' + new_field + 'tag';
687
688                         $scope.current_event_target_cursor_pos = 0;
689                         $scope.current_event_target_cursor_pos_end = 3;
690                         $scope.force_render = true;
691
692                         $timeout(function(){$scope.$digest()}).then(setCaret);
693
694                         event_return = false;
695
696                     } else if (event.which == 46 && event.ctrlKey) { // ctrl+del, remove field
697
698                         var del_field = event.data.scope.field.position;
699
700                         var domnode = $('#r'+event.data.scope.field.record.subfield('901','c')[1] + 'f' + del_field);
701
702                         event.data.scope.field.record.deleteFields(
703                             event.data.scope.field
704                         );
705
706                         domnode.scope().$destroy();
707                         domnode.remove();
708
709                         $scope.current_event_target = 'r' + $scope.recordId +
710                                                       'f' + del_field + 'tag';
711
712                         $scope.current_event_target_cursor_pos = 0;
713                         $scope.current_event_target_cursor_pos_end = 0
714                         $scope.force_render = true;
715
716                         $timeout(function(){$scope.$digest()}).then(setCaret);
717
718                         event_return = false;
719
720                     } else if (event.which == 46 && event.shiftKey && $(event.target).hasClass('marcsf')) { // shift+del, remove subfield
721
722                         var sf = event.data.scope.subfield[2] - 1;
723                         if (sf == -1) sf = 0;
724
725                         event.data.scope.field.deleteExactSubfields(
726                             event.data.scope.subfield
727                         );
728
729                         if (!event.data.scope.field.subfields[sf]) {
730                             $scope.current_event_target = 'r' + $scope.recordId +
731                                                           'f' + event.data.scope.field.position + 
732                                                           'tag';
733                         } else {
734                             $scope.current_event_target = 'r' + $scope.recordId +
735                                                           'f' + event.data.scope.field.position + 
736                                                           's' + sf + 'value';
737                         }
738
739                         $scope.current_event_target_cursor_pos = 0;
740                         $scope.current_event_target_cursor_pos_end = 0;
741                         $scope.force_render = true;
742
743                         $timeout(function(){$scope.$digest()}).then(setCaret);
744
745                         event_return = false;
746
747                     } else if (event.keyCode == 38) {
748                         if (event.ctrlKey) { // copy the field up
749                             var index_field = event.data.scope.field.position;
750
751                             var field_obj;
752                             if (event.data.scope.field.isControlfield()) {
753                                 field_obj = new MARC21.Field({
754                                     tag : event.data.scope.field.tag,
755                                     data : event.data.scope.field.data
756                                 });
757                             } else {
758                                 var sf_clone = [];
759                                 for (var i in event.data.scope.field.subfields) {
760                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
761                                 }
762                                 field_obj = new MARC21.Field({
763                                     tag : event.data.scope.field.tag,
764                                     ind1 : event.data.scope.field.ind1,
765                                     ind2 : event.data.scope.field.ind2,
766                                     subfields : sf_clone
767                                 });
768                             }
769
770
771                             event.data.scope.field.record.insertFieldsBefore(
772                                 event.data.scope.field,
773                                 field_obj
774                             );
775
776                             $scope.current_event_target = 'r' + $scope.recordId +
777                                                           'f' + index_field + 'tag';
778
779                             $scope.current_event_target_cursor_pos = 0;
780                             $scope.current_event_target_cursor_pos_end = 3;
781                             $scope.force_render = true;
782
783                             $timeout(function(){$scope.$digest()}).then(setCaret);
784
785                         } else { // jump to prev field
786                             if (event.data.scope.field.position > 0) {
787                                 $timeout(function(){
788                                     $scope.current_event_target_cursor_pos = 0;
789                                     $scope.current_event_target_cursor_pos_end = 0;
790                                     $scope.current_event_target = 'r' + $scope.recordId +
791                                                                   'f' + (event.data.scope.field.position - 1) +
792                                                                   'tag';
793                                 }).then(setCaret);
794                             }
795                         }
796
797                         event_return = false;
798
799                     } else if (event.keyCode == 40) { // down arrow...
800                         if (event.ctrlKey) { // copy the field down
801
802                             var index_field = event.data.scope.field.position;
803                             var new_field = index_field + 1;
804
805                             var field_obj;
806                             if (event.data.scope.field.isControlfield()) {
807                                 field_obj = new MARC21.Field({
808                                     tag : event.data.scope.field.tag,
809                                     data : event.data.scope.field.data
810                                 });
811                             } else {
812                                 var sf_clone = [];
813                                 for (var i in event.data.scope.field.subfields) {
814                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
815                                 }
816                                 field_obj = new MARC21.Field({
817                                     tag : event.data.scope.field.tag,
818                                     ind1 : event.data.scope.field.ind1,
819                                     ind2 : event.data.scope.field.ind2,
820                                     subfields : sf_clone
821                                 });
822                             }
823
824                             event.data.scope.field.record.insertFieldsAfter(
825                                 event.data.scope.field,
826                                 field_obj
827                             );
828
829                             $scope.current_event_target = 'r' + $scope.recordId +
830                                                           'f' + new_field + 'tag';
831
832                             $scope.current_event_target_cursor_pos = 0;
833                             $scope.current_event_target_cursor_pos_end = 3;
834                             $scope.force_render = true;
835
836                             $timeout(function(){$scope.$digest()}).then(setCaret);
837
838                         } else { // jump to next field
839                             if (event.data.scope.field.record.fields[event.data.scope.field.position + 1]) {
840                                 $timeout(function(){
841                                     $scope.current_event_target_cursor_pos = 0;
842                                     $scope.current_event_target_cursor_pos_end = 0;
843                                     $scope.current_event_target = 'r' + $scope.recordId +
844                                                                   'f' + (event.data.scope.field.position + 1) +
845                                                                   'tag';
846                                 }).then(setCaret);
847                             }
848                         }
849
850                         event_return = false;
851
852                     } else { // Assumes only marc editor elements have IDs that can trigger this event handler.
853                         $scope.current_event_target = $(event.target).attr('id');
854                         if ($scope.current_event_target) {
855                             $scope.current_event_target_cursor_pos =
856                                 event.target.selectionDirection=='backward' ?
857                                     event.target.selectionStart :
858                                     event.target.selectionEnd;
859                         }
860                     }
861
862                     return event_return;
863                 };
864
865                 function setCaret() {
866                     if ($scope.current_event_target) {
867                         console.log("Putting caret in " + $scope.current_event_target);
868                         if (!$scope.current_event_target_cursor_pos_end)
869                             $scope.current_event_target_cursor_pos_end = $scope.current_event_target_cursor_pos
870
871                         var element = $('#'+$scope.current_event_target).get(0);
872                         if (element) {
873                             element.focus();
874                             if (element.setSelectionRange) {
875                                 element.setSelectionRange(
876                                     $scope.current_event_target_cursor_pos,
877                                     $scope.current_event_target_cursor_pos_end
878                                 );
879                             }
880                             $scope.current_event_cursor_pos_end = null;
881                             $scope.current_event_target = null;
882                         }
883                     }
884                 }
885
886                 function loadRecord() {
887                     return (function() {
888                         var deferred = $q.defer();
889                         if ($scope.recordId) {
890                             egCore.pcrud.retrieve(
891                                 $scope.record_type, $scope.recordId
892                             ).then(function(rec) {
893                                 deferred.resolve(rec);
894                             });
895                         } else {
896                             if ($scope.recordType == 'bre') {
897                                 var bre = new egCore.idl.bre();
898                                 bre.marc($scope.marcXml);
899                                 deferred.resolve(bre);
900                             } else if ($scope.recordType == 'are') {
901                                 var are = new egCore.idl.are();
902                                 are.marc($scope.marcXml);
903                                 deferred.resolve(are);
904                             }
905                             $scope.brandNewRecord = true;
906                         }
907                         return deferred.promise;
908                     })().then(function(rec) {
909                         $scope.in_redo = true;
910                         $scope[$scope.record_type] = rec;
911                         $scope.record = new MARC21.Record({ marcxml : $scope.Record().marc() });
912                         $scope.calculated_record_type = $scope.record.recordType();
913                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
914                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
915                         $scope.save_stack_depth = $scope.record_undo_stack.length;
916                         $scope.flat_text_marc = $scope.record.toBreaker();
917
918                         if ($scope.record_type == 'bre') {
919                             $scope.bib_source = $scope.Record().source();
920                         }
921
922                     }).then(function(){
923                         return egTagTable.fetchFFPosTable($scope.calculated_record_type)
924                     }).then(function(){
925                         return egTagTable.fetchFFValueTable($scope.calculated_record_type)
926                     }).then(setCaret);
927                 }
928
929                 $scope.$watch('record.toBreaker()', function (newVal, oldVal) {
930                     if (!$scope.in_undo && !$scope.in_redo && oldVal != newVal) {
931                         $scope.record_undo_stack.push({
932                             breaker: oldVal,
933                             target: $scope.current_event_target,
934                             pos: $scope.current_event_target_cursor_pos
935                         });
936
937                         if ($scope.force_render) {
938                             $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
939                             $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
940                             $scope.force_render = false;
941                         }
942
943                         $scope.flat_text_marc = newVal;
944                     }
945
946                     if ($scope.record_undo_stack.length != $scope.save_stack_depth) {
947                         $scope.dirtyFlag = true;
948                     } else {
949                         $scope.dirtyFlag = false;
950                     }
951
952                     if ($scope.record_undo_stack.length > $scope.max_undo)
953                         $scope.record_undo_stack.shift();
954
955                     console.log('undo stack is ' + $scope.record_undo_stack.length + ' deep');
956                     $scope.in_redo = false;
957                     $scope.in_undo = false;
958                 });
959
960                 $scope.processUndo = function () {
961                     if ($scope.record_undo_stack.length) {
962                         $scope.in_undo = true;
963
964                         var undo_item = $scope.record_undo_stack.pop();
965                         $scope.record_redo_stack.push(undo_item);
966
967                         $scope.record = new MARC21.Record({ marcbreaker : undo_item.breaker });
968                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
969                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
970
971                         $scope.current_event_target = undo_item.target;
972                         $scope.current_event_target_cursor_pos = undo_item.pos;
973                         console.log('Undo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
974
975                         $timeout(function(){$scope.$digest()}).then(setCaret);
976                         return false;
977                     }
978
979                     return true;
980                 };
981
982                 $scope.processRedo = function () {
983                     if ($scope.record_redo_stack.length) {
984                         $scope.in_redo = true;
985
986                         var redo_item = $scope.record_redo_stack.pop();
987                         $scope.record_undo_stack.push(redo_item);
988
989                         $scope.record = new MARC21.Record({ marcbreaker : redo_item.breaker });
990                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
991                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
992
993                         $scope.current_event_target = redo_item.target;
994                         $scope.current_event_target_cursor_pos = redo_item.pos;
995                         console.log('Redo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
996
997                         $timeout(function(){$scope.$digest()}).then(setCaret);
998                         return false;
999                     }
1000
1001                     return true;
1002                 };
1003
1004                 $scope.Record = function () {
1005                     return $scope[$scope.record_type];
1006                 };
1007
1008                 $scope.deleteRecord = function () {
1009                     $scope.Record().deleted(true);
1010                     return $scope.saveRecord();
1011                 };
1012
1013                 $scope.undeleteRecord = function () {
1014                     $scope.Record().deleted(false);
1015                     return $scope.saveRecord();
1016                 };
1017
1018                 $scope.validateHeadings = function () {
1019                     if ($scope.record_type != 'bre') return;
1020                     var chain = $q.when();
1021                     angular.forEach($scope.record.fields, function(f) {
1022                         if (!$scope.controlSet.bibFieldByTag(f.tag)) return;
1023                         // if heading already has a $0, assume it's good
1024                         if (f.subfield('0', true).length) {
1025                             f.heading_checked = true;
1026                             f.heading_valid = true;
1027                             return;
1028                         }
1029                         var auth_match = $scope.controlSet.bibToAuthorities(f);
1030                         chain = chain.then(function() {
1031                             var promise = egCore.net.request(
1032                                 'open-ils.search',
1033                                 'open-ils.search.authority.simple_heading.from_xml.batch.atomic',
1034                                 auth_match[0]
1035                             ).then(function (matches) {
1036                                 f.heading_valid = false;
1037                                 if (matches[0]) { // probably set
1038                                     for (var cset in matches[0]) {
1039                                         var arr = matches[0][cset];
1040                                         if (arr.length) {
1041                                             // protect against errant empty string values
1042                                             if (arr.length == 1 && arr[0] == '')
1043                                                 continue;
1044                                             f.heading_valid = true;
1045                                             break;
1046                                         }
1047                                     }
1048                                 }
1049                                 f.heading_checked = true;
1050                             });
1051                             return promise;
1052                         });
1053                     });
1054                 }
1055
1056                 $scope.saveRecord = function () {
1057                     if ($scope.inPlaceMode) {
1058                         $scope.marcXml = $scope.record.toXmlString();
1059                         return;
1060                     }
1061                     $scope.mangle_005();
1062                     $scope.Record().editor(egCore.auth.user().id());
1063                     $scope.Record().edit_date('now');
1064                     $scope.record.pruneEmptyFieldsAndSubfields();
1065                     $scope.Record().marc($scope.record.toXmlString());
1066                     if ($scope.recordId) {
1067                         return egCore.pcrud.update(
1068                             $scope.Record()
1069                         ).then(function() {
1070                             if ($scope.enable_fast_add) {
1071                                 egCore.net.request(
1072                                     'open-ils.actor',
1073                                     'open-ils.actor.anon_cache.set_value',
1074                                     null, 'edit-these-copies', {
1075                                         record_id: $scope.recordId,
1076                                         raw: [{
1077                                             label : $scope.fast_item_callnumber,
1078                                             barcode : $scope.fast_item_barcode,
1079                                         }],
1080                                         hide_vols : false,
1081                                         hide_copies : false
1082                                     }
1083                                 ).then(function(key) {
1084                                     if (key) {
1085                                         var url = egCore.env.basePath + 'cat/volcopy/' + key;
1086                                         $timeout(function() { $window.open(url, '_blank') });
1087                                     } else {
1088                                         alert('Could not create anonymous cache key!');
1089                                     }
1090                                 });
1091                             }
1092                         }).then(loadRecord);
1093                     } else {
1094                         $scope.Record().creator(egCore.auth.user().id());
1095                         $scope.Record().create_date('now');
1096                         return egCore.pcrud.create(
1097                             $scope.Record()
1098                         ).then(function(bre) {
1099                             $scope.recordId = bre.id(); 
1100                             if ($scope.enable_fast_add) {
1101                                 egCore.net.request(
1102                                     'open-ils.actor',
1103                                     'open-ils.actor.anon_cache.set_value',
1104                                     null, 'edit-these-copies', {
1105                                         record_id: $scope.recordId,
1106                                         raw: [{
1107                                             label : $scope.fast_item_callnumber,
1108                                             barcode : $scope.fast_item_barcode,
1109                                         }],
1110                                         hide_vols : false,
1111                                         hide_copies : false
1112                                     }
1113                                 ).then(function(key) {
1114                                     if (key) {
1115                                         var url = egCore.env.basePath + 'cat/volcopy/' + key;
1116                                         $timeout(function() { $window.open(url, '_blank') });
1117                                     } else {
1118                                         alert('Could not create anonymous cache key!');
1119                                     }
1120                                 });
1121                             }
1122                         }).then(loadRecord);
1123                     }
1124
1125
1126                 };
1127
1128                 $scope.seeBreaker = function () {
1129                     alert($scope.record.toBreaker());
1130                 };
1131
1132                 $scope.markConjoined = function () {
1133                     egCore.hatch.setLocalItem('eg.cat.marked_conjoined_record',$scope.recordId);
1134                 };
1135
1136                 $scope.markVolTransfer = function () {
1137                     egCore.hatch.setLocalItem('eg.cat.marked_volume_transfer_record',$scope.recordId);
1138                 };
1139
1140                 $scope.markOverlay = function () {
1141                     egCore.hatch.setLocalItem('eg.cat.marked_overlay_record',$scope.recordId);
1142                 };
1143
1144                 $scope.$watch('recordId',
1145                     function(newVal, oldVal) {
1146                         if (newVal && newVal !== oldVal) {
1147                             loadRecord();
1148                         }
1149                     }
1150                 );
1151                 $scope.$watch('marcXml',
1152                     function(newVal, oldVal) {
1153                         if (newVal && newVal !== oldVal) {
1154                             loadRecord();
1155                         }
1156                     }
1157                 );
1158
1159                 var unregister = $scope.$watch(function() {
1160                     return egTagTable.initialized();
1161                 }, function(val) {
1162                     if (val) {
1163                         unregister();
1164                         if ($scope.recordId || $scope.marcXml) {
1165                             loadRecord();
1166                         }
1167                     }
1168                 });
1169
1170                 $scope.mangle_005 = function () {
1171                     var now = new Date();
1172                     var y = now.getUTCFullYear();
1173                 
1174                     var m = now.getUTCMonth() + 1;
1175                     if (m < 10) m = '0' + m;
1176                 
1177                     var d = now.getUTCDate();
1178                     if (d < 10) d = '0' + d;
1179                 
1180                     var H = now.getUTCHours();
1181                     if (H < 10) H = '0' + H;
1182                 
1183                     var M = now.getUTCMinutes();
1184                     if (M < 10) M = '0' + M;
1185                 
1186                     var S = now.getUTCSeconds();
1187                     if (S < 10) S = '0' + S;
1188                 
1189                     var stamp = '' + y + m + d + H + M + S + '.0';
1190                     var f = $scope.record.field('005',true)[0];
1191                     if (f) {
1192                         f.data = stamp;
1193                     } else {
1194                         $scope.record.insertOrderedFields(
1195                             new MARC21.Field({
1196                                 tag : '005',
1197                                 data: stamp
1198                             })
1199                         );
1200                     }
1201                 
1202                 }
1203
1204             }
1205         ]          
1206     }
1207 })
1208
1209 .directive("egMarcEditBibsource", ['$timeout',function ($timeout) {
1210     return {
1211         restrict: 'E',
1212         replace: true,
1213         template: '<span class="nullable">'+
1214                     '<select class="form-control" ng-model="bib_source" ng-options="s.id() as s.source() for s in bib_sources">'+
1215                       '<option value="">Select a Source</option>'+
1216                     '</select>'+
1217                   '</span>',
1218         controller: ['$scope','egCore',
1219             function ($scope , egCore) {
1220
1221                 egCore.pcrud.retrieveAll('cbs', {}, {atomic : true})
1222                     .then(function(list) { $scope.bib_sources = list; });
1223
1224                 $scope.$watch('bib_source',
1225                     function(newVal, oldVal) {
1226                         if (newVal !== oldVal) {
1227                             $scope.bre.source(newVal);
1228                         }
1229                     }
1230                 );
1231
1232             }
1233         ]
1234     }
1235 }])
1236
1237 .directive("egMarcEditAuthorityLinker", function () {
1238     return {
1239         restrict: 'E',
1240         replace: true,
1241         templateUrl: './cat/share/t_authority_linker',
1242         scope : {
1243             bibField : '=',
1244             controlSet : '=',
1245             changed : '='
1246         },
1247         controller: ['$scope','$modal','egCore','egAuth',
1248             function ($scope , $modal,  egCore,  egAuth) {
1249
1250                 $scope.searchStr = '';
1251                 var cni = egCore.env.aous['cat.marc_control_number_identifier'] ||
1252                   'Set cat.marc_control_number_identifier in Library Settings';
1253
1254                 var axis_list = $scope.controlSet.bibFieldBrowseAxes($scope.bibField.tag);
1255                 $scope.axis = axis_list[0];
1256
1257                 $scope._controlled_sf_list = {};
1258                 $scope._controlled_auth_sf_list = {};
1259                 var found_acs = [];
1260                 angular.forEach($scope.controlSet.controlSetList(), function(acs_id) {
1261                     if ($scope.controlSet.controlSet(acs_id).control_map[$scope.bibField.tag])
1262                         found_acs.push(acs_id);
1263                 });
1264                 if (found_acs.length) {
1265                      angular.forEach($scope.controlSet.controlSet(found_acs[0]).control_map[$scope.bibField.tag],
1266                         function(value, sf_label) {
1267                             $scope._controlled_sf_list[ sf_label ] = 1;
1268                             angular.forEach($scope.controlSet.controlSet(found_acs[0]).control_map[$scope.bibField.tag][sf_label],
1269                                 function(auth_sf, auth_tag) {
1270                                     if (!$scope._controlled_auth_sf_list[auth_tag]) {
1271                                         $scope._controlled_auth_sf_list[auth_tag] = { };
1272                                     }
1273                                     $scope._controlled_auth_sf_list[auth_tag][auth_sf] = 1;
1274                                 }
1275                             );
1276                         }
1277                     )
1278                 }
1279
1280                 $scope.bibField.subfields.forEach(function (sf) {
1281                     if (sf[0] in $scope._controlled_sf_list) {
1282                         sf.selected = true;
1283                         sf.selectable = true;
1284                     } else {
1285                         sf.selectable = false;
1286                     }
1287                 });
1288                 $scope.summarizeField = function() {
1289                     var source_f = {
1290                         'tag': $scope.bibField.tag,
1291                         'ind1': $scope.bibField.ind1,
1292                         'ind2': $scope.bibField.ind2,
1293                         'subfields': []
1294                     };
1295                     $scope.bibField.subfields.forEach(function(sf) {
1296                         if (sf.selected) {
1297                             source_f.subfields.push([ sf[0], sf[1] ]);
1298                         }
1299                     });
1300                     return source_f;
1301                 }
1302                 $scope.getSearchString = function() {
1303                     var source_f = $scope.summarizeField();
1304                     var values = [];
1305                     angular.forEach(source_f.subfields, function(val) {
1306                         values.push(val[1]);
1307                     });
1308                     return values.join(' ');
1309                 }
1310                 $scope.searchStr = $scope.getSearchString();
1311                 $scope.$watch(function() {
1312                     var ct = 0;
1313                     angular.forEach($scope.bibField.subfields, function(sf) {
1314                         if (sf.selected) ct++
1315                         });
1316                     return ct;
1317                 },
1318                 function(newVal, oldVal) {
1319                     $scope.searchStr = $scope.getSearchString();
1320                 });
1321
1322                 $scope.updateSubfieldZero = function(value) {
1323                     $scope.changed = true;
1324                     $scope.bibField.deleteSubfield({ code : ['0'] });
1325                     $scope.bibField.subfields.push([
1326                         '0', '(' + cni + ')' + value
1327                     ]);
1328                 };
1329
1330                 $scope.applyHeading = function(headingField) {
1331                     // TODO: move the MARC21 rules for copying indicators
1332                     // out of here
1333                     if (headingField.tag == '130' && $scope.bibField.tag == '130') {
1334                         $scope.bibField.ind1 = headingField.ind2;
1335                     } else {
1336                         $scope.bibField.ind1 = headingField.ind1;
1337                     }
1338                     // deal with 4xx and 5xx
1339                     var authFallbackTag = '1' + headingField.tag.substr(1, 2);
1340                     var _valid_auth_sfs = (headingField.tag in $scope._controlled_auth_sf_list) ?
1341                                           $scope._controlled_auth_sf_list[headingField.tag] :
1342                                           (authFallbackTag in $scope._controlled_auth_sf_list) ?
1343                                           $scope._controlled_auth_sf_list[authFallbackTag] :
1344                                           [];
1345                     // save the $0 for later use
1346                     var sfZero = '';
1347                     if (headingField.subfield('0')) {
1348                         sfZero = headingField.subfield('0')[1];
1349                     }
1350                     // grab any bib subfields not under authority control
1351                     // TODO do something about uncontrolled subdivisions
1352                     var uncontrolledBibSf = [];
1353                     angular.forEach($scope.bibField.subfields, function(sf) {
1354                         if (!(sf[0] in $scope._controlled_sf_list) && (sf[0] != '0')) {
1355                             uncontrolledBibSf.push([ sf[0], sf[1] ]);
1356                         }
1357                     });
1358                     // grab the authority subfields
1359                     var authoritySf = [];
1360                     angular.forEach(headingField.subfields, function(sf) {
1361                         if (sf[0] in _valid_auth_sfs) {
1362                             authoritySf.push([ sf[0], sf[1] ]);
1363                         }
1364                     });
1365                     $scope.bibField.subfields.length = 0;
1366                     angular.forEach(authoritySf, function(sf) {
1367                         $scope.bibField.addSubfields(sf[0], sf[1]);
1368                     });
1369                     angular.forEach(uncontrolledBibSf, function(sf) {
1370                         $scope.bibField.addSubfields(sf[0], sf[1]);
1371                     });
1372                     if (sfZero) {
1373                         $scope.bibField.addSubfields('0', sfZero);
1374                     }
1375                     $scope.bibField.subfields.forEach(function (sf) {
1376                     if (sf[0] in $scope._controlled_sf_list) {
1377                             // intentionally not selecting any subfields
1378                             // after we've applied an authority heading
1379                             sf.selected = false;
1380                             sf.selectable = true;
1381                         } else {
1382                             sf.selectable = false;
1383                         }
1384                     });
1385                     $scope.changed = true;
1386                 }
1387
1388                 $scope.createAuthorityFromBib = function(spawn_editor) {
1389                     var source_f = $scope.summarizeField();
1390
1391                     var args = { authority_id : 0 };
1392                     var method = (spawn_editor) ?
1393                         'open-ils.cat.authority.record.create_from_bib.readonly' :
1394                         'open-ils.cat.authority.record.create_from_bib';
1395                     egCore.net.request(
1396                         'open-ils.cat',
1397                         method,
1398                         source_f,
1399                         cni,
1400                         egAuth.token()
1401                     ).then(function(newAuthority) {
1402                         if (spawn_editor) {
1403                             $modal.open({
1404                                 templateUrl: './cat/share/t_edit_new_authority',
1405                                 size: 'lg',
1406                                 controller:
1407                                     ['$scope', '$modalInstance', function($scope, $modalInstance) {
1408                                     $scope.focusMe = true;
1409                                     $scope.args = args;
1410                                     $scope.dirty_flag = false;
1411                                     $scope.marc_xml = newAuthority,
1412                                     $scope.ok = function(args) { $modalInstance.close(args) }
1413                                     $scope.cancel = function () { $modalInstance.dismiss() }
1414                                 }]
1415                             }).result.then(function (args) {
1416                                 if (!args || !args.authority_id) return;
1417                                 $scope.updateSubfieldZero(args.authority_id);
1418                             });
1419                         } else {
1420                             $scope.updateSubfieldZero(newAuthority.id());
1421                         }
1422                     });
1423                 }
1424
1425             }
1426         ]
1427     }
1428 })
1429
1430 .directive("egMarcEditAuthorityBrowser", function () {
1431     return {
1432         restrict: 'E',
1433         replace: true,
1434         templateUrl: './cat/share/t_authority_browser',
1435         scope : {
1436             searchString : '=',
1437             controlSet : '=',
1438             axis : '=',
1439             applyHeading : '&'
1440         },
1441         controller: ['$scope','$http',
1442             function ($scope , $http) {
1443
1444                 $scope.page = 0;
1445                 $scope.limit = 5;
1446                 $scope.main_headings = [];
1447
1448                 function getHeadingString(headingField) {
1449                     var heading = '';
1450                     angular.forEach(headingField.subfields, function (sf) {
1451                         if (['x', 'y', 'z'].indexOf(sf[0]) > -1) {
1452                             heading += ' --';
1453                         }
1454                         if (heading) {
1455                             heading += ' ';
1456                         }
1457                         heading += sf[1];
1458                     });
1459                     return heading;
1460                 }
1461
1462                 $scope.doBrowse = function() {
1463                     $scope.main_headings.length = 0;
1464                     if ($scope.searchString.length == 0) return;
1465                     var type = 'authority.'
1466                     var url = '/opac/extras/browse/marcxml/'
1467                             + 'authority.' + $scope.axis + '.refs'
1468                             + '/1' // OU - currently unscoped
1469                             + '/' + $scope.searchString
1470                             + '/' + $scope.page
1471                             + '/' + $scope.limit;
1472                     $http({
1473                         url : url,
1474                         method : 'GET',
1475                         transformResponse : function(data) {
1476                             // use a bit of jQuery to deal with the XML
1477                             var $xml = $( $.parseXML(data) );
1478                             var marc = [];
1479                             $xml.find('record').each(function() {
1480                                 var rec = new MARC21.Record();
1481                                 rec.fromXmlDocument($(this)[0].outerHTML);
1482                                 marc.push(rec);
1483                             });
1484                             return marc;
1485                         }
1486                     }).then(function(response) {
1487                         angular.forEach(response.data, function(rec) {
1488                             var authId = rec.subfield('901', 'c')[1];
1489                             var auth_org = '';
1490                             if (rec.field('003')) {
1491                                 auth_org = rec.field('003').data;
1492                             }
1493                             var headingField = rec.field('1..');
1494                             var seeFroms = rec.field('4..', true);
1495                             var seeAlsos = rec.field('5..', true);
1496
1497                             var main_heading = {
1498                                 authority_id : authId,
1499                                 heading : getHeadingString(headingField),
1500                                 seealso_headings : [ ],
1501                                 seefrom_headings : [ ],
1502                             };
1503
1504                             var sfZero = '';
1505                             if (auth_org) {
1506                                 sfZero = '(' + auth_org + ')';
1507                             }
1508                             sfZero += authId;
1509                             headingField.addSubfields('0', sfZero);
1510
1511                             main_heading['headingField'] = headingField;
1512                             angular.forEach(seeAlsos, function(headingField) {
1513                                 main_heading.seealso_headings.push({
1514                                     heading : getHeadingString(headingField),
1515                                     headingField : headingField
1516                                 });
1517                             });
1518                             angular.forEach(seeFroms, function(headingField) {
1519                                 main_heading.seefrom_headings.push({
1520                                     heading : getHeadingString(headingField),
1521                                     headingField : headingField
1522                                 });
1523                             });
1524                             $scope.main_headings.push(main_heading);
1525                         });
1526                     });
1527                 }
1528
1529                 $scope.$watch('searchString',
1530                     function(newVal, oldVal) {
1531                         if (newVal !== oldVal) {
1532                             $scope.doBrowse();
1533                         }
1534                     }
1535                 );
1536                 $scope.$watch('page',
1537                     function(newVal, oldVal) {
1538                         if (newVal !== oldVal) {
1539                             $scope.doBrowse();
1540                         }
1541                     }
1542                 );
1543
1544                 $scope.doBrowse();
1545             }
1546         ]
1547     }
1548 })
1549
1550 ;