]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/services/marcedit.js
webstaff: add Mark as Overlay Target to MARC editor
[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                   '</div>',
440         scope: { field: "=", onKeydown: '=' }
441     }
442 })
443
444 .directive("egMarcEditLeader", function () {
445     return {
446         transclude: true,
447         restrict: 'E',
448         template: '<div>'+
449                     '<span><eg-marc-edit-editable '+
450                       'class="marcedit marctag" '+
451                       'content="tag" '+
452                       'on-keydown="onKeydown" '+
453                       'id="leadertag" '+
454                       'disabled="disabled"'+
455                       '/></span>'+
456                     '<span><eg-marc-edit-editable '+
457                       'class="marcedit marcdata" '+
458                       'itype="ldr" '+
459                       'max="{{record.leader.length}}" '+
460                       'content="record.leader" '+
461                       'id="r{{record.subfield(\'901\',\'c\')[1]}}leaderdata" '+
462                       'on-keydown="onKeydown"'+
463                       '/></span>'+
464                   '</div>',
465         controller : ['$scope',
466             function ( $scope ) {
467                 $scope.tag = 'LDR';
468             }
469         ],
470         scope: { record: "=", onKeydown: '=' }
471     }
472 })
473
474 /// TODO: fixed field editor and such
475 .directive("egMarcEditRecord", function () {
476     return {
477         templateUrl : './cat/share/t_marcedit',
478         restrict: 'E',
479         replace: true,
480         scope: {
481             dirtyFlag : '=',
482             recordId : '=',
483             marcXml : '=',
484             // in-place mode means that the editor is being
485             // used just to munge some MARCXML client-side, rather
486             // than to (immediately) update the database
487             inPlaceMode : '@',
488             recordType : '@',
489             maxUndo : '@'
490         },
491         link: function (scope, element, attrs) {
492
493             element.bind('click', function(e) {;
494                 scope.current_event_target = $(e.target).attr('id');
495                 if (scope.current_event_target) {
496                     console.log('Recording click event on ' + scope.current_event_target);
497                     scope.current_event_target_cursor_pos =
498                         e.target.selectionDirection=='backward' ?
499                             e.target.selectionStart :
500                             e.target.selectionEnd;
501                 }
502             });
503
504         },
505         controller : ['$timeout','$scope','$q','$window','egCore', 'egTagTable',
506             function ( $timeout , $scope , $q,  $window , egCore ,  egTagTable ) {
507
508                 MARC21.Record.delimiter = '$';
509
510                 $scope.enable_fast_add = false;
511                 $scope.fast_item_callnumber = '';
512                 $scope.fast_item_barcode = '';
513                 $scope.flatEditor = false;
514                 $scope.brandNewRecord = false;
515                 $scope.bib_source = null;
516                 $scope.record_type = $scope.recordType || 'bre';
517                 $scope.max_undo = $scope.maxUndo || 100;
518                 $scope.record_undo_stack = [];
519                 $scope.record_redo_stack = [];
520                 $scope.in_undo = false;
521                 $scope.in_redo = false;
522                 $scope.record = new MARC21.Record();
523                 $scope.save_stack_depth = 0;
524                 $scope.controlfields = [];
525                 $scope.datafields = [];
526                 $scope.controlSet = egTagTable.getAuthorityControlSet();
527
528                 egTagTable.loadTagTable({ marcRecordType : $scope.record_type });
529
530                 $scope.saveFlatTextMARC = function () {
531                     $scope.record = new MARC21.Record({ marcbreaker : $scope.flat_text_marc });
532                 };
533
534                 $scope.refreshVisual = function () {
535                     if (!$scope.flatEditor) {
536                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
537                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
538                     }
539                 };
540
541                 $scope.onKeydown = function (event) {
542                     var event_return = true;
543
544                     console.log(
545                         'keydown: which='+event.which+
546                         ', ctrlKey='+event.ctrlKey+
547                         ', shiftKey='+event.shiftKey+
548                         ', altKey='+event.altKey+
549                         ', metaKey='+event.altKey
550                     );
551
552                     if (event.which == 89 && event.ctrlKey) { // ctrl+y, redo
553                         event_return = $scope.processRedo();
554                     } else if (event.which == 90 && event.ctrlKey) { // ctrl+z, undo
555                         event_return = $scope.processUndo();
556                     } else if ((event.which == 68 || event.which == 73) && event.ctrlKey) { // ctrl+d or ctrl+i, insert subfield
557
558                         var element = $(event.target);
559                         var new_sf, index_sf, move_data;
560
561                         if (element.hasClass('marcsfvalue')) {
562                             index_sf = event.data.scope.subfield[2];
563                             new_sf = index_sf + 1;
564
565                             var start = event.target.selectionStart;
566                             var end = event.target.selectionEnd - event.target.selectionStart ?
567                                     event.target.selectionEnd :
568                                     event.target.value.length;
569
570                             move_data = event.target.value.substring(start,end);
571
572                         } else if (element.hasClass('marcsfcode')) {
573                             index_sf = event.data.scope.subfield[2];
574                             new_sf = index_sf + 1;
575                         } else if (element.hasClass('marctag') || element.hasClass('marcind')) {
576                             index_sf = 0;
577                             new_sf = index_sf;
578                         }
579
580                         $scope.current_event_target = 'r' + $scope.recordId +
581                                                       'f' + event.data.scope.field.position + 
582                                                       's' + new_sf + 'code';
583
584                         event.data.scope.field.subfields.forEach(function(sf) {
585                             if (sf[2] >= new_sf) sf[2]++;
586                             if (sf[2] == index_sf) sf[1] = event.target.value.substring(0,start) + event.target.value.substring(end);
587                         });
588                         event.data.scope.field.subfields.splice(
589                             new_sf,
590                             0,
591                             [' ', move_data, new_sf ]
592                         );
593
594                         $scope.current_event_target_cursor_pos = 0;
595                         $scope.current_event_target_cursor_pos_end = 1;
596
597                         $timeout(function(){$scope.$digest()}).then(setCaret);
598
599                         event_return = false;
600
601                     } else if (event.which == 117 && event.shiftKey) { // shift + F6, insert 006
602                         event.data.scope.field.record.insertOrderedFields(
603                             new MARC21.Field({
604                                 tag : '006',
605                                 data : '                                        '
606                             })
607                         );
608
609                         $scope.force_render = true;
610                         $timeout(function(){$scope.$digest()}).then(setCaret);
611
612                         event_return = false;
613
614                     } else if (event.which == 118 && event.shiftKey) { // shift + F7, insert 007
615                         event.data.scope.field.record.insertOrderedFields(
616                             new MARC21.Field({
617                                 tag : '007',
618                                 data : '                                        '
619                             })
620                         );
621
622                         $scope.force_render = true;
623                         $timeout(function(){$scope.$digest()}).then(setCaret);
624
625                         event_return = false;
626
627                     } else if (event.which == 119 && event.shiftKey) { // shift + F8, insert/replace 008
628                         var new_008_data = event.data.scope.field.record.generate008();
629
630
631                         var old_008s = event.data.scope.field.record.field('008',true);
632                         old_008s.forEach(function(o) {
633                             var domnode = $('#r'+o.record.subfield('901','c')[1] + 'f' + o.position);
634                             domnode.scope().$destroy();
635                             domnode.remove();
636                             event.data.scope.field.record.deleteFields(o);
637                         });
638
639                         event.data.scope.field.record.insertOrderedFields(
640                             new MARC21.Field({
641                                 tag : '008',
642                                 data : new_008_data
643                             })
644                         );
645
646                         $scope.force_render = true;
647                         $timeout(function(){$scope.$digest()}).then(setCaret);
648
649                         event_return = false;
650
651                     } else if (event.which == 13 && event.ctrlKey) { // ctrl+enter, insert datafield
652
653                         var element = $(event.target);
654
655                         var index_field = event.data.scope.field.position;
656                         var new_field = index_field + 1;
657
658                         event.data.scope.field.record.insertFieldsAfter(
659                             event.data.scope.field,
660                             new MARC21.Field({
661                                 tag : '999',
662                                 subfields : [[' ','',0]]
663                             })
664                         );
665
666                         $scope.current_event_target = 'r' + $scope.recordId +
667                                                       'f' + new_field + 'tag';
668
669                         $scope.current_event_target_cursor_pos = 0;
670                         $scope.current_event_target_cursor_pos_end = 3;
671                         $scope.force_render = true;
672
673                         $timeout(function(){$scope.$digest()}).then(setCaret);
674
675                         event_return = false;
676
677                     } else if (event.which == 46 && event.ctrlKey) { // ctrl+del, remove field
678
679                         var del_field = event.data.scope.field.position;
680
681                         var domnode = $('#r'+event.data.scope.field.record.subfield('901','c')[1] + 'f' + del_field);
682
683                         event.data.scope.field.record.deleteFields(
684                             event.data.scope.field
685                         );
686
687                         domnode.scope().$destroy();
688                         domnode.remove();
689
690                         $scope.current_event_target = 'r' + $scope.recordId +
691                                                       'f' + del_field + 'tag';
692
693                         $scope.current_event_target_cursor_pos = 0;
694                         $scope.current_event_target_cursor_pos_end = 0
695                         $scope.force_render = true;
696
697                         $timeout(function(){$scope.$digest()}).then(setCaret);
698
699                         event_return = false;
700
701                     } else if (event.which == 46 && event.shiftKey && $(event.target).hasClass('marcsf')) { // shift+del, remove subfield
702
703                         var sf = event.data.scope.subfield[2] - 1;
704                         if (sf == -1) sf = 0;
705
706                         event.data.scope.field.deleteExactSubfields(
707                             event.data.scope.subfield
708                         );
709
710                         if (!event.data.scope.field.subfields[sf]) {
711                             $scope.current_event_target = 'r' + $scope.recordId +
712                                                           'f' + event.data.scope.field.position + 
713                                                           'tag';
714                         } else {
715                             $scope.current_event_target = 'r' + $scope.recordId +
716                                                           'f' + event.data.scope.field.position + 
717                                                           's' + sf + 'value';
718                         }
719
720                         $scope.current_event_target_cursor_pos = 0;
721                         $scope.current_event_target_cursor_pos_end = 0;
722                         $scope.force_render = true;
723
724                         $timeout(function(){$scope.$digest()}).then(setCaret);
725
726                         event_return = false;
727
728                     } else if (event.keyCode == 38) {
729                         if (event.ctrlKey) { // copy the field up
730                             var index_field = event.data.scope.field.position;
731
732                             var field_obj;
733                             if (event.data.scope.field.isControlfield()) {
734                                 field_obj = new MARC21.Field({
735                                     tag : event.data.scope.field.tag,
736                                     data : event.data.scope.field.data
737                                 });
738                             } else {
739                                 var sf_clone = [];
740                                 for (var i in event.data.scope.field.subfields) {
741                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
742                                 }
743                                 field_obj = new MARC21.Field({
744                                     tag : event.data.scope.field.tag,
745                                     ind1 : event.data.scope.field.ind1,
746                                     ind2 : event.data.scope.field.ind2,
747                                     subfields : sf_clone
748                                 });
749                             }
750
751
752                             event.data.scope.field.record.insertFieldsBefore(
753                                 event.data.scope.field,
754                                 field_obj
755                             );
756
757                             $scope.current_event_target = 'r' + $scope.recordId +
758                                                           'f' + index_field + 'tag';
759
760                             $scope.current_event_target_cursor_pos = 0;
761                             $scope.current_event_target_cursor_pos_end = 3;
762                             $scope.force_render = true;
763
764                             $timeout(function(){$scope.$digest()}).then(setCaret);
765
766                         } else { // jump to prev field
767                             if (event.data.scope.field.position > 0) {
768                                 $timeout(function(){
769                                     $scope.current_event_target_cursor_pos = 0;
770                                     $scope.current_event_target_cursor_pos_end = 0;
771                                     $scope.current_event_target = 'r' + $scope.recordId +
772                                                                   'f' + (event.data.scope.field.position - 1) +
773                                                                   'tag';
774                                 }).then(setCaret);
775                             }
776                         }
777
778                         event_return = false;
779
780                     } else if (event.keyCode == 40) { // down arrow...
781                         if (event.ctrlKey) { // copy the field down
782
783                             var index_field = event.data.scope.field.position;
784                             var new_field = index_field + 1;
785
786                             var field_obj;
787                             if (event.data.scope.field.isControlfield()) {
788                                 field_obj = new MARC21.Field({
789                                     tag : event.data.scope.field.tag,
790                                     data : event.data.scope.field.data
791                                 });
792                             } else {
793                                 var sf_clone = [];
794                                 for (var i in event.data.scope.field.subfields) {
795                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
796                                 }
797                                 field_obj = new MARC21.Field({
798                                     tag : event.data.scope.field.tag,
799                                     ind1 : event.data.scope.field.ind1,
800                                     ind2 : event.data.scope.field.ind2,
801                                     subfields : sf_clone
802                                 });
803                             }
804
805                             event.data.scope.field.record.insertFieldsAfter(
806                                 event.data.scope.field,
807                                 field_obj
808                             );
809
810                             $scope.current_event_target = 'r' + $scope.recordId +
811                                                           'f' + new_field + 'tag';
812
813                             $scope.current_event_target_cursor_pos = 0;
814                             $scope.current_event_target_cursor_pos_end = 3;
815                             $scope.force_render = true;
816
817                             $timeout(function(){$scope.$digest()}).then(setCaret);
818
819                         } else { // jump to next field
820                             if (event.data.scope.field.record.fields[event.data.scope.field.position + 1]) {
821                                 $timeout(function(){
822                                     $scope.current_event_target_cursor_pos = 0;
823                                     $scope.current_event_target_cursor_pos_end = 0;
824                                     $scope.current_event_target = 'r' + $scope.recordId +
825                                                                   'f' + (event.data.scope.field.position + 1) +
826                                                                   'tag';
827                                 }).then(setCaret);
828                             }
829                         }
830
831                         event_return = false;
832
833                     } else { // Assumes only marc editor elements have IDs that can trigger this event handler.
834                         $scope.current_event_target = $(event.target).attr('id');
835                         if ($scope.current_event_target) {
836                             $scope.current_event_target_cursor_pos =
837                                 event.target.selectionDirection=='backward' ?
838                                     event.target.selectionStart :
839                                     event.target.selectionEnd;
840                         }
841                     }
842
843                     return event_return;
844                 };
845
846                 function setCaret() {
847                     if ($scope.current_event_target) {
848                         console.log("Putting caret in " + $scope.current_event_target);
849                         if (!$scope.current_event_target_cursor_pos_end)
850                             $scope.current_event_target_cursor_pos_end = $scope.current_event_target_cursor_pos
851
852                         var element = $('#'+$scope.current_event_target).get(0);
853                         if (element) {
854                             element.focus();
855                             if (element.setSelectionRange) {
856                                 element.setSelectionRange(
857                                     $scope.current_event_target_cursor_pos,
858                                     $scope.current_event_target_cursor_pos_end
859                                 );
860                             }
861                             $scope.current_event_cursor_pos_end = null;
862                             $scope.current_event_target = null;
863                         }
864                     }
865                 }
866
867                 function loadRecord() {
868                     return (function() {
869                         var deferred = $q.defer();
870                         if ($scope.recordId) {
871                             egCore.pcrud.retrieve(
872                                 $scope.record_type, $scope.recordId
873                             ).then(function(rec) {
874                                 deferred.resolve(rec);
875                             });
876                         } else {
877                             if ($scope.recordType == 'bre') {
878                                 var bre = new egCore.idl.bre();
879                                 bre.marc($scope.marcXml);
880                                 deferred.resolve(bre);
881                             } else if ($scope.recordType == 'are') {
882                                 var are = new egCore.idl.are();
883                                 are.marc($scope.marcXml);
884                                 deferred.resolve(are);
885                             }
886                             $scope.brandNewRecord = true;
887                         }
888                         return deferred.promise;
889                     })().then(function(rec) {
890                         $scope.in_redo = true;
891                         $scope[$scope.record_type] = rec;
892                         $scope.record = new MARC21.Record({ marcxml : $scope.Record().marc() });
893                         $scope.calculated_record_type = $scope.record.recordType();
894                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
895                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
896                         $scope.save_stack_depth = $scope.record_undo_stack.length;
897                         $scope.flat_text_marc = $scope.record.toBreaker();
898
899                         if ($scope.record_type == 'bre') {
900                             $scope.bib_source = $scope.Record().source();
901                         }
902
903                     }).then(function(){
904                         return egTagTable.fetchFFPosTable($scope.calculated_record_type)
905                     }).then(function(){
906                         return egTagTable.fetchFFValueTable($scope.calculated_record_type)
907                     }).then(setCaret);
908                 }
909
910                 $scope.$watch('record.toBreaker()', function (newVal, oldVal) {
911                     if (!$scope.in_undo && !$scope.in_redo && oldVal != newVal) {
912                         $scope.record_undo_stack.push({
913                             breaker: oldVal,
914                             target: $scope.current_event_target,
915                             pos: $scope.current_event_target_cursor_pos
916                         });
917
918                         if ($scope.force_render) {
919                             $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
920                             $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
921                             $scope.force_render = false;
922                         }
923
924                         $scope.flat_text_marc = newVal;
925                     }
926
927                     if ($scope.record_undo_stack.length != $scope.save_stack_depth) {
928                         $scope.dirtyFlag = true;
929                     } else {
930                         $scope.dirtyFlag = false;
931                     }
932
933                     if ($scope.record_undo_stack.length > $scope.max_undo)
934                         $scope.record_undo_stack.shift();
935
936                     console.log('undo stack is ' + $scope.record_undo_stack.length + ' deep');
937                     $scope.in_redo = false;
938                     $scope.in_undo = false;
939                 });
940
941                 $scope.processUndo = function () {
942                     if ($scope.record_undo_stack.length) {
943                         $scope.in_undo = true;
944
945                         var undo_item = $scope.record_undo_stack.pop();
946                         $scope.record_redo_stack.push(undo_item);
947
948                         $scope.record = new MARC21.Record({ marcbreaker : undo_item.breaker });
949                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
950                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
951
952                         $scope.current_event_target = undo_item.target;
953                         $scope.current_event_target_cursor_pos = undo_item.pos;
954                         console.log('Undo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
955
956                         $timeout(function(){$scope.$digest()}).then(setCaret);
957                         return false;
958                     }
959
960                     return true;
961                 };
962
963                 $scope.processRedo = function () {
964                     if ($scope.record_redo_stack.length) {
965                         $scope.in_redo = true;
966
967                         var redo_item = $scope.record_redo_stack.pop();
968                         $scope.record_undo_stack.push(redo_item);
969
970                         $scope.record = new MARC21.Record({ marcbreaker : redo_item.breaker });
971                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
972                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
973
974                         $scope.current_event_target = redo_item.target;
975                         $scope.current_event_target_cursor_pos = redo_item.pos;
976                         console.log('Redo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
977
978                         $timeout(function(){$scope.$digest()}).then(setCaret);
979                         return false;
980                     }
981
982                     return true;
983                 };
984
985                 $scope.Record = function () {
986                     return $scope[$scope.record_type];
987                 };
988
989                 $scope.deleteRecord = function () {
990                     $scope.Record().deleted(true);
991                     return $scope.saveRecord();
992                 };
993
994                 $scope.undeleteRecord = function () {
995                     $scope.Record().deleted(false);
996                     return $scope.saveRecord();
997                 };
998
999                 $scope.validateHeadings = function () {
1000                     if ($scope.record_type != 'bre') return;
1001                     var chain = $q.when();
1002                     angular.forEach($scope.record.fields, function(f) {
1003                         if (!$scope.controlSet.bibFieldByTag(f.tag)) return;
1004                         // if heading already has a $0, assume it's good
1005                         if (f.subfield('0', true).length) {
1006                             f.heading_checked = true;
1007                             f.heading_valid = true;
1008                             return;
1009                         }
1010                         var auth_match = $scope.controlSet.bibToAuthorities(f);
1011                         chain = chain.then(function() {
1012                             var promise = egCore.net.request(
1013                                 'open-ils.search',
1014                                 'open-ils.search.authority.simple_heading.from_xml.batch.atomic',
1015                                 auth_match[0]
1016                             ).then(function (matches) {
1017                                 f.heading_valid = false;
1018                                 if (matches[0]) { // probably set
1019                                     for (var cset in matches[0]) {
1020                                         var arr = matches[0][cset];
1021                                         if (arr.length) {
1022                                             // protect against errant empty string values
1023                                             if (arr.length == 1 && arr[0] == '')
1024                                                 continue;
1025                                             f.heading_valid = true;
1026                                             break;
1027                                         }
1028                                     }
1029                                 }
1030                                 f.heading_checked = true;
1031                             });
1032                             return promise;
1033                         });
1034                     });
1035                 }
1036
1037                 $scope.saveRecord = function () {
1038                     if ($scope.inPlaceMode) {
1039                         $scope.marcXml = $scope.record.toXmlString();
1040                         return;
1041                     }
1042                     $scope.mangle_005();
1043                     $scope.Record().editor(egCore.auth.user().id());
1044                     $scope.Record().edit_date('now');
1045                     $scope.record.pruneEmptyFieldsAndSubfields();
1046                     $scope.Record().marc($scope.record.toXmlString());
1047                     if ($scope.recordId) {
1048                         return egCore.pcrud.update(
1049                             $scope.Record()
1050                         ).then(function() {
1051                             if ($scope.enable_fast_add) {
1052                                 egCore.net.request(
1053                                     'open-ils.actor',
1054                                     'open-ils.actor.anon_cache.set_value',
1055                                     null, 'edit-these-copies', {
1056                                         record_id: $scope.recordId,
1057                                         raw: [{
1058                                             label : $scope.fast_item_callnumber,
1059                                             barcode : $scope.fast_item_barcode,
1060                                         }],
1061                                         hide_vols : false,
1062                                         hide_copies : false
1063                                     }
1064                                 ).then(function(key) {
1065                                     if (key) {
1066                                         var url = egCore.env.basePath + 'cat/volcopy/' + key;
1067                                         $timeout(function() { $window.open(url, '_blank') });
1068                                     } else {
1069                                         alert('Could not create anonymous cache key!');
1070                                     }
1071                                 });
1072                             }
1073                         }).then(loadRecord);
1074                     } else {
1075                         $scope.Record().creator(egCore.auth.user().id());
1076                         $scope.Record().create_date('now');
1077                         return egCore.pcrud.create(
1078                             $scope.Record()
1079                         ).then(function(bre) {
1080                             $scope.recordId = bre.id(); 
1081                             if ($scope.enable_fast_add) {
1082                                 egCore.net.request(
1083                                     'open-ils.actor',
1084                                     'open-ils.actor.anon_cache.set_value',
1085                                     null, 'edit-these-copies', {
1086                                         record_id: $scope.recordId,
1087                                         raw: [{
1088                                             label : $scope.fast_item_callnumber,
1089                                             barcode : $scope.fast_item_barcode,
1090                                         }],
1091                                         hide_vols : false,
1092                                         hide_copies : false
1093                                     }
1094                                 ).then(function(key) {
1095                                     if (key) {
1096                                         var url = egCore.env.basePath + 'cat/volcopy/' + key;
1097                                         $timeout(function() { $window.open(url, '_blank') });
1098                                     } else {
1099                                         alert('Could not create anonymous cache key!');
1100                                     }
1101                                 });
1102                             }
1103                         }).then(loadRecord);
1104                     }
1105
1106
1107                 };
1108
1109                 $scope.seeBreaker = function () {
1110                     alert($scope.record.toBreaker());
1111                 };
1112
1113                 $scope.markOverlay = function () {
1114                     egCore.hatch.setLocalItem('eg.cat.marked_overlay_record',$scope.recordId);
1115                 };
1116
1117                 $scope.$watch('recordId',
1118                     function(newVal, oldVal) {
1119                         if (newVal && newVal !== oldVal) {
1120                             loadRecord();
1121                         }
1122                     }
1123                 );
1124                 $scope.$watch('marcXml',
1125                     function(newVal, oldVal) {
1126                         if (newVal && newVal !== oldVal) {
1127                             loadRecord();
1128                         }
1129                     }
1130                 );
1131
1132                 var unregister = $scope.$watch(function() {
1133                     return egTagTable.initialized();
1134                 }, function(val) {
1135                     if (val) {
1136                         unregister();
1137                         if ($scope.recordId || $scope.marcXml) {
1138                             loadRecord();
1139                         }
1140                     }
1141                 });
1142
1143                 $scope.mangle_005 = function () {
1144                     var now = new Date();
1145                     var y = now.getUTCFullYear();
1146                 
1147                     var m = now.getUTCMonth() + 1;
1148                     if (m < 10) m = '0' + m;
1149                 
1150                     var d = now.getUTCDate();
1151                     if (d < 10) d = '0' + d;
1152                 
1153                     var H = now.getUTCHours();
1154                     if (H < 10) H = '0' + H;
1155                 
1156                     var M = now.getUTCMinutes();
1157                     if (M < 10) M = '0' + M;
1158                 
1159                     var S = now.getUTCSeconds();
1160                     if (S < 10) S = '0' + S;
1161                 
1162                     var stamp = '' + y + m + d + H + M + S + '.0';
1163                     var f = $scope.record.field('005',true)[0];
1164                     if (f) {
1165                         f.data = stamp;
1166                     } else {
1167                         $scope.record.insertOrderedFields(
1168                             new MARC21.Field({
1169                                 tag : '005',
1170                                 data: stamp
1171                             })
1172                         );
1173                     }
1174                 
1175                 }
1176
1177             }
1178         ]          
1179     }
1180 })
1181
1182 .directive("egMarcEditBibsource", ['$timeout',function ($timeout) {
1183     return {
1184         restrict: 'E',
1185         replace: true,
1186         template: '<span class="nullable">'+
1187                     '<select class="form-control" ng-model="bib_source" ng-options="s.id() as s.source() for s in bib_sources">'+
1188                       '<option value="">Select a Source</option>'+
1189                     '</select>'+
1190                   '</span>',
1191         controller: ['$scope','egCore',
1192             function ($scope , egCore) {
1193
1194                 egCore.pcrud.retrieveAll('cbs', {}, {atomic : true})
1195                     .then(function(list) { $scope.bib_sources = list; });
1196
1197                 $scope.$watch('bib_source',
1198                     function(newVal, oldVal) {
1199                         if (newVal !== oldVal) {
1200                             $scope.bre.source(newVal);
1201                         }
1202                     }
1203                 );
1204
1205             }
1206         ]
1207     }
1208 }])
1209
1210 .directive("egMarcEditAuthorityLinker", function () {
1211     return {
1212         restrict: 'E',
1213         replace: true,
1214         templateUrl: './cat/share/t_authority_linker',
1215         scope : {
1216             bibField : '=',
1217             controlSet : '=',
1218             changed : '='
1219         },
1220         controller: ['$scope','$modal','egCore','egAuth',
1221             function ($scope , $modal,  egCore,  egAuth) {
1222
1223                 $scope.searchStr = '';
1224                 var cni = egCore.env.aous['cat.marc_control_number_identifier'] ||
1225                   'Set cat.marc_control_number_identifier in Library Settings';
1226
1227                 var axis_list = $scope.controlSet.bibFieldBrowseAxes($scope.bibField.tag);
1228                 $scope.axis = axis_list[0];
1229
1230                 $scope._controlled_sf_list = {};
1231                 $scope._controlled_auth_sf_list = {};
1232                 var found_acs = [];
1233                 angular.forEach($scope.controlSet.controlSetList(), function(acs_id) {
1234                     if ($scope.controlSet.controlSet(acs_id).control_map[$scope.bibField.tag])
1235                         found_acs.push(acs_id);
1236                 });
1237                 if (found_acs.length) {
1238                      angular.forEach($scope.controlSet.controlSet(found_acs[0]).control_map[$scope.bibField.tag],
1239                         function(value, sf_label) {
1240                             $scope._controlled_sf_list[ sf_label ] = 1;
1241                             angular.forEach($scope.controlSet.controlSet(found_acs[0]).control_map[$scope.bibField.tag][sf_label],
1242                                 function(auth_sf, auth_tag) {
1243                                     if (!$scope._controlled_auth_sf_list[auth_tag]) {
1244                                         $scope._controlled_auth_sf_list[auth_tag] = { };
1245                                     }
1246                                     $scope._controlled_auth_sf_list[auth_tag][auth_sf] = 1;
1247                                 }
1248                             );
1249                         }
1250                     )
1251                 }
1252
1253                 $scope.bibField.subfields.forEach(function (sf) {
1254                     if (sf[0] in $scope._controlled_sf_list) {
1255                         sf.selected = true;
1256                         sf.selectable = true;
1257                     } else {
1258                         sf.selectable = false;
1259                     }
1260                 });
1261                 $scope.summarizeField = function() {
1262                     var source_f = {
1263                         'tag': $scope.bibField.tag,
1264                         'ind1': $scope.bibField.ind1,
1265                         'ind2': $scope.bibField.ind2,
1266                         'subfields': []
1267                     };
1268                     $scope.bibField.subfields.forEach(function(sf) {
1269                         if (sf.selected) {
1270                             source_f.subfields.push([ sf[0], sf[1] ]);
1271                         }
1272                     });
1273                     return source_f;
1274                 }
1275                 $scope.getSearchString = function() {
1276                     var source_f = $scope.summarizeField();
1277                     var values = [];
1278                     angular.forEach(source_f.subfields, function(val) {
1279                         values.push(val[1]);
1280                     });
1281                     return values.join(' ');
1282                 }
1283                 $scope.searchStr = $scope.getSearchString();
1284                 $scope.$watch(function() {
1285                     var ct = 0;
1286                     angular.forEach($scope.bibField.subfields, function(sf) {
1287                         if (sf.selected) ct++
1288                         });
1289                     return ct;
1290                 },
1291                 function(newVal, oldVal) {
1292                     $scope.searchStr = $scope.getSearchString();
1293                 });
1294
1295                 $scope.updateSubfieldZero = function(value) {
1296                     $scope.changed = true;
1297                     $scope.bibField.deleteSubfield({ code : ['0'] });
1298                     $scope.bibField.subfields.push([
1299                         '0', '(' + cni + ')' + value
1300                     ]);
1301                 };
1302
1303                 $scope.applyHeading = function(headingField) {
1304                     // TODO: move the MARC21 rules for copying indicators
1305                     // out of here
1306                     if (headingField.tag == '130' && $scope.bibField.tag == '130') {
1307                         $scope.bibField.ind1 = headingField.ind2;
1308                     } else {
1309                         $scope.bibField.ind1 = headingField.ind1;
1310                     }
1311                     // deal with 4xx and 5xx
1312                     var authFallbackTag = '1' + headingField.tag.substr(1, 2);
1313                     var _valid_auth_sfs = (headingField.tag in $scope._controlled_auth_sf_list) ?
1314                                           $scope._controlled_auth_sf_list[headingField.tag] :
1315                                           (authFallbackTag in $scope._controlled_auth_sf_list) ?
1316                                           $scope._controlled_auth_sf_list[authFallbackTag] :
1317                                           [];
1318                     // save the $0 for later use
1319                     var sfZero = '';
1320                     if (headingField.subfield('0')) {
1321                         sfZero = headingField.subfield('0')[1];
1322                     }
1323                     // grab any bib subfields not under authority control
1324                     // TODO do something about uncontrolled subdivisions
1325                     var uncontrolledBibSf = [];
1326                     angular.forEach($scope.bibField.subfields, function(sf) {
1327                         if (!(sf[0] in $scope._controlled_sf_list) && (sf[0] != '0')) {
1328                             uncontrolledBibSf.push([ sf[0], sf[1] ]);
1329                         }
1330                     });
1331                     // grab the authority subfields
1332                     var authoritySf = [];
1333                     angular.forEach(headingField.subfields, function(sf) {
1334                         if (sf[0] in _valid_auth_sfs) {
1335                             authoritySf.push([ sf[0], sf[1] ]);
1336                         }
1337                     });
1338                     $scope.bibField.subfields.length = 0;
1339                     angular.forEach(authoritySf, function(sf) {
1340                         $scope.bibField.addSubfields(sf[0], sf[1]);
1341                     });
1342                     angular.forEach(uncontrolledBibSf, function(sf) {
1343                         $scope.bibField.addSubfields(sf[0], sf[1]);
1344                     });
1345                     if (sfZero) {
1346                         $scope.bibField.addSubfields('0', sfZero);
1347                     }
1348                     $scope.bibField.subfields.forEach(function (sf) {
1349                     if (sf[0] in $scope._controlled_sf_list) {
1350                             // intentionally not selecting any subfields
1351                             // after we've applied an authority heading
1352                             sf.selected = false;
1353                             sf.selectable = true;
1354                         } else {
1355                             sf.selectable = false;
1356                         }
1357                     });
1358                     $scope.changed = true;
1359                 }
1360
1361                 $scope.createAuthorityFromBib = function(spawn_editor) {
1362                     var source_f = $scope.summarizeField();
1363
1364                     var args = { authority_id : 0 };
1365                     var method = (spawn_editor) ?
1366                         'open-ils.cat.authority.record.create_from_bib.readonly' :
1367                         'open-ils.cat.authority.record.create_from_bib';
1368                     egCore.net.request(
1369                         'open-ils.cat',
1370                         method,
1371                         source_f,
1372                         cni,
1373                         egAuth.token()
1374                     ).then(function(newAuthority) {
1375                         if (spawn_editor) {
1376                             $modal.open({
1377                                 templateUrl: './cat/share/t_edit_new_authority',
1378                                 size: 'lg',
1379                                 controller:
1380                                     ['$scope', '$modalInstance', function($scope, $modalInstance) {
1381                                     $scope.focusMe = true;
1382                                     $scope.args = args;
1383                                     $scope.dirty_flag = false;
1384                                     $scope.marc_xml = newAuthority,
1385                                     $scope.ok = function(args) { $modalInstance.close(args) }
1386                                     $scope.cancel = function () { $modalInstance.dismiss() }
1387                                 }]
1388                             }).result.then(function (args) {
1389                                 if (!args || !args.authority_id) return;
1390                                 $scope.updateSubfieldZero(args.authority_id);
1391                             });
1392                         } else {
1393                             $scope.updateSubfieldZero(newAuthority.id());
1394                         }
1395                     });
1396                 }
1397
1398             }
1399         ]
1400     }
1401 })
1402
1403 .directive("egMarcEditAuthorityBrowser", function () {
1404     return {
1405         restrict: 'E',
1406         replace: true,
1407         templateUrl: './cat/share/t_authority_browser',
1408         scope : {
1409             searchString : '=',
1410             controlSet : '=',
1411             axis : '=',
1412             applyHeading : '&'
1413         },
1414         controller: ['$scope','$http',
1415             function ($scope , $http) {
1416
1417                 $scope.page = 0;
1418                 $scope.limit = 5;
1419                 $scope.main_headings = [];
1420
1421                 function getHeadingString(headingField) {
1422                     var heading = '';
1423                     angular.forEach(headingField.subfields, function (sf) {
1424                         if (['x', 'y', 'z'].indexOf(sf[0]) > -1) {
1425                             heading += ' --';
1426                         }
1427                         if (heading) {
1428                             heading += ' ';
1429                         }
1430                         heading += sf[1];
1431                     });
1432                     return heading;
1433                 }
1434
1435                 $scope.doBrowse = function() {
1436                     $scope.main_headings.length = 0;
1437                     if ($scope.searchString.length == 0) return;
1438                     var type = 'authority.'
1439                     var url = '/opac/extras/browse/marcxml/'
1440                             + 'authority.' + $scope.axis + '.refs'
1441                             + '/1' // OU - currently unscoped
1442                             + '/' + $scope.searchString
1443                             + '/' + $scope.page
1444                             + '/' + $scope.limit;
1445                     $http({
1446                         url : url,
1447                         method : 'GET',
1448                         transformResponse : function(data) {
1449                             // use a bit of jQuery to deal with the XML
1450                             var $xml = $( $.parseXML(data) );
1451                             var marc = [];
1452                             $xml.find('record').each(function() {
1453                                 var rec = new MARC21.Record();
1454                                 rec.fromXmlDocument($(this)[0].outerHTML);
1455                                 marc.push(rec);
1456                             });
1457                             return marc;
1458                         }
1459                     }).then(function(response) {
1460                         angular.forEach(response.data, function(rec) {
1461                             var authId = rec.subfield('901', 'c')[1];
1462                             var auth_org = '';
1463                             if (rec.field('003')) {
1464                                 auth_org = rec.field('003').data;
1465                             }
1466                             var headingField = rec.field('1..');
1467                             var seeFroms = rec.field('4..', true);
1468                             var seeAlsos = rec.field('5..', true);
1469
1470                             var main_heading = {
1471                                 authority_id : authId,
1472                                 heading : getHeadingString(headingField),
1473                                 seealso_headings : [ ],
1474                                 seefrom_headings : [ ],
1475                             };
1476
1477                             var sfZero = '';
1478                             if (auth_org) {
1479                                 sfZero = '(' + auth_org + ')';
1480                             }
1481                             sfZero += authId;
1482                             headingField.addSubfields('0', sfZero);
1483
1484                             main_heading['headingField'] = headingField;
1485                             angular.forEach(seeAlsos, function(headingField) {
1486                                 main_heading.seealso_headings.push({
1487                                     heading : getHeadingString(headingField),
1488                                     headingField : headingField
1489                                 });
1490                             });
1491                             angular.forEach(seeFroms, function(headingField) {
1492                                 main_heading.seefrom_headings.push({
1493                                     heading : getHeadingString(headingField),
1494                                     headingField : headingField
1495                                 });
1496                             });
1497                             $scope.main_headings.push(main_heading);
1498                         });
1499                     });
1500                 }
1501
1502                 $scope.$watch('searchString',
1503                     function(newVal, oldVal) {
1504                         if (newVal !== oldVal) {
1505                             $scope.doBrowse();
1506                         }
1507                     }
1508                 );
1509                 $scope.$watch('page',
1510                     function(newVal, oldVal) {
1511                         if (newVal !== oldVal) {
1512                             $scope.doBrowse();
1513                         }
1514                     }
1515                 );
1516
1517                 $scope.doBrowse();
1518             }
1519         ]
1520     }
1521 })
1522
1523 ;