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