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