]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/services/marcedit.js
c41b1d5b374ff1c736b8b5ab7cf8d359eb071065
[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: '=', contextMenuEvent: '=' },
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.css('borderTop','solid 1px');
18                 }
19
20                 $scope.setContent = function (v, a) {
21                     var replace_with = v;
22
23                     if (a) {
24                         replace_with = a(
25                             $scope,
26                             $element,
27                             $scope.item.value,
28                             $scope.$parent.$parent.content,
29                             $scope.contextMenuEvent
30                         );
31                     }
32
33                     if (typeof replace_with !== 'undefined') {
34                         $timeout(function(){
35                             $scope.$parent.$parent.$apply(function(){
36                                 $scope.$parent.$parent.content = replace_with
37                             })
38                         }, 0);
39                     }
40                     $($element).parent().css({display: 'none'});
41                 }
42             }
43         ]
44     }
45 }])
46
47 .directive("contenteditable", function() {
48     return {
49         restrict: "A",
50         require: "ngModel",
51         link: function(scope,element,attrs,ngModel){
52
53             function read(){
54                 // save new text into model
55                 var elhtml = element.text();
56                 ngModel.$setViewValue(elhtml);
57             }
58
59             ngModel.$render = function(){
60                 element.text(ngModel.$viewValue || "");
61             };
62
63             element.bind("blur.c_e keyup.c_e change.c_e", function(){
64                 scope.$apply(read);
65             });
66         }
67     };
68 })
69
70 .directive("egMarcEditEditable", ['$timeout', '$compile', '$document', function ($timeout, $compile, $document) {
71     return {
72         restrict: 'E',
73         replace: true,
74         templateUrl: './cat/share/t_marcedit_editable',
75         scope: {
76             field: '=',
77             onKeydown: '=',
78             subfield: '=',
79             content: '=',
80             contextItemContainer: '@',
81             contextItemGenerator: '=',
82             max: '@',
83             itype: '@',
84             selectOnFocus: '=',
85             advanceFocusAfterInput: '=',
86             isDisabled: "="
87         },
88         controller : ['$scope',
89             function ( $scope ) {
90                 $scope.isInputDisabled = $scope.isDisabled == 'disabled';
91                 if ($scope.contextItemContainer && angular.isArray($scope.$parent[$scope.contextItemContainer]))
92                     $scope.item_container = $scope.$parent[$scope.contextItemContainer];
93                 else if ($scope.contextItemGenerator)
94                     $scope.item_generator = $scope.contextItemGenerator;
95
96                 $scope.showContext = function (event) {
97                     $scope.item_list = [];
98                     if ($scope.item_container) {
99                         $scope.item_list = $scope.item_container;
100                     } else if ($scope.item_generator) {
101                         // always recalculate; tag and/or subfield
102                         // codes may have changed
103
104                         var generator = $scope.item_generator;
105                         if (!angular.isArray(generator)) generator = [generator];
106
107                         var is_first = true;
108                         angular.forEach(generator, function (g) {
109                             var sub_list = g();
110
111                             if (is_first)
112                                 is_first = false;
113                             else if (Boolean(sub_list[0]))
114                                 sub_list[0].divider = true;
115
116                             $scope.item_list = $scope.item_list.concat(sub_list);
117                         });
118
119                     } else {
120                         return true;
121                     }
122
123                     if (angular.isArray($scope.item_list) && $scope.item_list.length > 0) { // we have a list of values or transforms
124                         console.log('Showing context menu...');
125                         $('body').trigger('click');
126
127                         $scope.contextMenuEvent = event;
128                         var tmpl = 
129                             '<ul class="dropdown-menu scrollable-menu" role="menu" style="z-index: 2000;">'+
130                                 '<eg-context-menu-item context-menu-event="contextMenuEvent" ng-repeat="item in item_list" item="item" content="content"/>'+
131                             '</ul>';
132             
133                         var tnode = angular.element(tmpl);
134                         $document.find('body').append(tnode);
135
136                         $(tnode).css({
137                             display: 'block',
138                             top: event.pageY,
139                             left: event.pageX
140                         });
141
142                         $timeout(function() {
143                             var e = $compile(tnode)($scope);
144                         }, 0);
145
146
147                         $('body').on('click.context_menu',function() {
148                             $(tnode).css('display','none');
149                             $('body').off('click.context_menu');
150                         });
151
152                         return false;
153                     }
154             
155                     return true;
156                 }
157
158             }
159         ],
160         link: function (scope, element, attrs) {
161
162             if (scope.onKeydown) element.bind('keydown', {scope : scope}, scope.onKeydown);
163
164             if (Boolean(scope.selectOnFocus)) {
165                 element.addClass('noSelection');
166                 element.bind('focus', function (e) {
167                     var el = $(e.target).children('input').first();
168                     if (el.select) { el.select(); }
169                 });
170             }
171
172             element.children("div[contenteditable]").each(function() {
173                 $(this).focus(function(e) {
174                     var tNode = e.target.firstChild;
175                     var range = document.createRange();
176                     range.setStart(tNode, 0);
177                     range.setEnd(tNode, tNode.length);
178                     var sel = window.getSelection();
179                     sel.removeAllRanges();
180                     sel.addRange(range);
181                 });
182             });
183
184             function findCaretTarget(id, itype) {
185                 var tgt = null;
186                 if (itype == 'tag') {
187                     tgt = id.replace(/tag$/, 'i1');
188                 } else if (itype == 'ind') {
189                     if (id.match(/i1$/)) {
190                         tgt = id.replace(/i1$/, 'i2');
191                     } else if (id.match(/i2$/)) {
192                         tgt = id.replace(/i2$/, 's0code');
193                     }
194                 } else if (itype == 'sfc') {
195                     tgt = id.replace(/code$/, 'value');
196                 }
197                 return tgt;
198             }
199             if (Boolean(scope.advanceFocusAfterInput)) {
200                 element.bind('input', function (e) {
201                     if (scope.content.length == scope.max) {
202                         var tgt = findCaretTarget(e.currentTarget.id, scope.itype);
203                         if (tgt) {
204                             var element = $('#' + tgt).get(0);
205                             if (element) {
206                                 element.focus();
207                             }
208                         }
209                     }
210                 });
211             }
212
213             element.bind('change', function (e) { element.size = scope.max || parseInt(scope.content.length * 1.1) });
214
215             element.bind('contextmenu', {scope : scope}, scope.showContext);
216         }
217     }
218 }])
219
220 .directive("egMarcEditFixedField", ['$timeout', '$compile', '$document', function ($timeout, $compile, $document) {
221     return {
222         transclude: true,
223         restrict: 'E',
224         template: '<div class="col-md-2">'+
225                     '<div class="col-md-1"><label name="{{fixedField}}" for="{{fixedField}}_ff_input">{{fixedFieldLabel}}</label></div>'+
226                     '<div class="col-md-1"><input type="text" style="padding-left: 5px; margin-left: 1em" size="4" id="{{fixedField}}_ff_input"/></div>'+
227                   '</div>',
228         scope: { record: "=", fixedField: "@", fixedFieldLabel: "@" },
229         replace: true,
230         controller : ['$scope', '$element', 'egTagTable',
231             function ( $scope ,  $element ,  egTagTable) {
232                 $($element).removeClass('fixed-field-box');
233                 $($element).children().css({ display : 'none' });
234                 $scope.fixedFieldLabel = $scope.fixedFieldLabel || $scope.fixedField;
235                 $scope.me = null;
236                 $scope.content = null; // this is where context menus dump their values
237                 $scope.item_container = [];
238                 $scope.in_handler = false;
239                 $scope.ready = false;
240                 $element.find('input').bind('focus', function (e) { e.target.select() });
241                 $element.find('input').bind('mouseup', function(e) {
242                     e.preventDefault()
243                     return false;
244                 });
245
246                 $scope.$watch('content', function (newVal, oldVal) {
247                     var input = $($element).find('input');
248                     input.val(newVal);
249                     input.trigger('keyup'); // cascade the update
250                 });
251
252                 $scope.$watch('record.ready', function (newVal, oldVal) { // wait for the record to be loaded
253                     if (newVal && !$scope.ready) {
254                         $scope.rtype = $scope.record.recordType();
255
256                         egTagTable.fetchFFPosTable( $scope.rtype ).then(function (ff_list) {
257                             angular.forEach(ff_list, function (ff) {
258                                 if (!$scope.me) {
259                                     if (ff.fixed_field == $scope.fixedField && ff.rec_type == $scope.rtype) {
260                                         $scope.me = ff;
261                                         $scope.ready = true;
262                                         $($element).addClass('fixed-field-box');
263                                         $($element).children().css({ display : 'inline' });
264
265                                         var input = $($element).find('input');
266                                         input.attr('maxlength', $scope.me.length);
267                                         input.val($scope.record.extractFixedField($scope.me.fixed_field));
268                                         input.on('keyup', function(e) {
269                                             $scope.in_handler = true;
270                                             $scope.record.setFixedField($scope.me.fixed_field, input.val());
271                                             try { $scope.$parent.$digest(); } catch(e) {};
272                                         });
273                                     }
274                                 }
275                             });
276                             return $scope.me;
277                         }).then(function (me) {
278                             if (me) {
279                                 $scope.$watch(
280                                     function() {
281                                         return $scope.record.extractFixedField($scope.fixedField);
282                                     },
283                                     function (newVal, oldVal) {
284                                         if ($scope.in_handler) {
285                                             $scope.in_handler = false;
286                                         } else if (oldVal != newVal) {
287                                             $($element).find('input').val(newVal);
288                                         }
289                                     }
290                                 );
291                             }
292                         }).then(function () {
293                             return egTagTable.fetchFFValueTable( $scope.rtype );
294                         }).then(function (vlist) {
295                             if (vlist[$scope.fixedField]) {
296                                 vlist[$scope.fixedField].forEach(function (v) {
297                                     if (v[0].length <= v[2]) {
298                                         $scope.item_container.push({ value : v[0], label : v[0] + ': ' + v[1] });
299                                     }
300                                 });
301                             }
302                         }).then(function () {
303                             if ($scope.item_container && $scope.item_container.length)
304                                 $($element).bind('contextmenu', $scope.showContext);
305                         });
306
307                     }
308                 });
309
310                 $scope.showContext = function (event) {
311                     if ($scope.context_menu_element) {
312                         console.log('Reshowing context menu...');
313                         $('body').trigger('click');
314                         $($scope.context_menu_element).css({ display: 'block', top: event.pageY, left: event.pageX });
315                         $('body').on('click.context_menu',function() {
316                             $($scope.context_menu_element).css('display','none');
317                             $('body').off('click.context_menu');
318                         });
319                         return false;
320                     }
321
322                     if (angular.isArray($scope.item_container)) { // we have a list of values or transforms
323                         console.log('Showing context menu...');
324                         $('body').trigger('click');
325
326                         var tmpl = 
327                             '<ul class="dropdown-menu scrollable-menu" role="menu" style="z-index: 2000;">'+
328                                 '<eg-context-menu-item ng-repeat="item in item_container" item="item" content="content"/>'+
329                             '</ul>';
330             
331                         var tnode = angular.element(tmpl);
332                         $document.find('body').append(tnode);
333
334                         $(tnode).css({
335                             display: 'block',
336                             top: event.pageY,
337                             left: event.pageX
338                         });
339
340                         $scope.context_menu_element = tnode;
341
342                         $timeout(function() {
343                             var e = $compile(tnode)($scope);
344                         }, 0);
345
346
347                         $('body').on('click.context_menu',function() {
348                             $(tnode).css('display','none');
349                             $('body').off('click.context_menu');
350                         });
351
352                         return false;
353                     }
354             
355                     return true;
356                 }
357
358             }
359         ]
360     }
361 }])
362
363 .directive("egMarcEditSubfield", function () {
364     return {
365         transclude: true,
366         restrict: 'E',
367         template: '<span>'+
368                     '<span><label class="marcedit marcsfcodedelimiter"'+
369                         'for="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}s{{subfield[2]}}code" '+
370                         '>‡</label><eg-marc-edit-editable '+
371                         'itype="sfc" '+
372                         'select-on-focus="true" '+
373                         'advance-focus-after-input="true" '+
374                         'class="marcedit marcsf marcsfcode" '+
375                         'field="field" '+
376                         'subfield="subfield" '+
377                         'content="subfield[0]" '+
378                         'max="1" '+
379                         'on-keydown="onKeydown" '+
380                         'context-item-generator="sf_code_options" '+
381                         'id="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}s{{subfield[2]}}code" '+
382                     '/></span>'+
383                     '<span><eg-marc-edit-editable '+
384                         'itype="sfv" '+
385                         'select-on-focus="true" '+
386                         'class="marcedit marcsf marcsfvalue" '+
387                         'field="field" '+
388                         'subfield="subfield" '+
389                         'content="subfield[1]" '+
390                         'on-keydown="onKeydown" '+
391                         'context-item-generator="sf_val_options" '+
392                         'id="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}s{{subfield[2]}}value" '+
393                     '/></span>'+
394                   '</span>',
395         scope: { field: "=", subfield: "=", onKeydown: '=' },
396         replace: true,
397         controller : ['$scope', 'egTagTable',
398             function ( $scope ,  egTagTable) {
399
400                 $scope.sf_code_options = function () {
401                     return egTagTable.getSubfieldCodes($scope.field.tag);
402                 }
403                 $scope.sf_val_options = function () {
404                     return egTagTable.getSubfieldValues($scope.field.tag, $scope.subfield[0]);
405                 }
406             }
407         ]
408     }
409 })
410
411 .directive("egMarcEditInd", function () {
412     return {
413         transclude: true,
414         restrict: 'E',
415         template: '<span><eg-marc-edit-editable '+
416                       'itype="ind" '+
417                       'class="marcedit marcind" '+
418                       'select-on-focus="true" '+
419                       'advance-focus-after-input="true" '+
420                       'field="field" '+
421                       'content="ind" '+
422                       'max="1" '+
423                       'on-keydown="onKeydown" '+
424                       'context-item-generator="ind_val_options" '+
425                       'id="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}i{{indNumber}}"'+
426                       '/></span>',
427         scope: { ind : '=', field: '=', onKeydown: '=', indNumber: '@' },
428         replace: true,
429         controller : ['$scope', 'egTagTable',
430             function ( $scope ,  egTagTable) {
431
432                 $scope.ind_val_options = function () {
433                     return egTagTable.getIndicatorValues($scope.field.tag, $scope.indNumber);
434                 }
435             }
436         ]
437     }
438 })
439
440 .directive("egMarcEditTag", function () {
441     return {
442         transclude: true,
443         restrict: 'E',
444         template: '<span><eg-marc-edit-editable '+
445                       'itype="tag" '+
446                       'class="marcedit marctag" '+
447                       'select-on-focus="true" '+
448                       'advance-focus-after-input="true" '+
449                       'field="field" '+
450                       'content="tag" '+
451                       'max="3" '+
452                       'on-keydown="onKeydown" '+
453                       'context-item-generator="tag_options" '+
454                       'id="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}tag"'+
455                       '/></span>',
456         scope: { tag : '=', field: '=', onKeydown: '=', contextFunctions: '=' },
457         replace: true,
458         controller : ['$scope', 'egTagTable', 'egCore',
459             function ( $scope ,  egTagTable,   egCore) {
460
461                 $scope.tag_options = [
462                     function () {
463                         var options = [
464                             { label : egCore.strings.ADD_006, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.add006(e) } },
465                             { label : egCore.strings.ADD_007, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.add007(e) } },
466                             { label : egCore.strings.ADD_REPLACE_008, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.reify008(e) } },
467                         ];
468
469                         if (!$scope.field.isControlfield()) {
470                             options = options.concat([
471                                 { label : egCore.strings.INSERT_FIELD_AFTER, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.addDatafield(e) } },
472                                 { label : egCore.strings.INSERT_FIELD_BEFORE, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.addDatafield(e,true) } },
473                             ]);
474                         }
475
476                         options.push({ label : egCore.strings.DELETE_FIELD, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.deleteDatafield(e) } });
477                         return options;
478                     },
479                     function () { return egTagTable.getFieldTags() }
480                 ];
481
482             }
483         ]
484     }
485 })
486
487 .directive("egMarcEditDatafield", function () {
488     return {
489         transclude: true,
490         restrict: 'E',
491         template: '<div>'+
492                     '<span><eg-marc-edit-tag context-functions="contextFunctions" field="field" tag="field.tag" on-keydown="onKeydown"/></span>'+
493                     '<span><eg-marc-edit-ind field="field" ind="field.ind1" on-keydown="onKeydown" ind-number="1"/></span>'+
494                     '<span><eg-marc-edit-ind field="field" ind="field.ind2" on-keydown="onKeydown" ind-number="2"/></span>'+
495                     '<span><eg-marc-edit-subfield ng-class="{ \'unvalidatedheading\' : field.heading_checked && !field.heading_valid, \'marcedit_stacked_subfield\' : stackSubfields.enabled }" ng-repeat="subfield in field.subfields" subfield="subfield" field="field" on-keydown="onKeydown"/></span>'+
496                     // FIXME: template should probably be moved to file to improve
497                     // translatibility
498                     '<span  ng-class="{ \'marcedit_stacked_subfield\' : stackSubfields.enabled }">' +
499                     '<button class="btn btn-info btn-xs" '+
500                     'aria-label="Manage authority record links" '+
501                     'ng-show="isAuthorityControlled(field)"'+
502                     'ng-click="spawnAuthorityLinker()"'+
503                     '>'+
504                     '<span class="glyphicon glyphicon-link"></span>'+
505                     '</button>'+
506                     '<span ng-show="field.heading_checked && field.heading_valid" class="glyphicon glyphicon-ok-sign"></span>'+
507                     '<span ng-show="field.heading_checked && !field.heading_valid" class="glyphicon glyphicon-question-sign"></span>'+
508                     '</span>'+
509                   '</div>',
510         scope: { field: "=", onKeydown: '=', contextFunctions: '=' },
511         replace: true,
512         controller : ['$scope','$uibModal',
513             function ( $scope,  $uibModal ) {
514                 $scope.stackSubfields = $scope.$parent.$parent.stackSubfields;
515                 $scope.isAuthorityControlled = function () {
516                     return ($scope.$parent.$parent.record_type == 'bre') &&
517                            $scope.$parent.$parent.controlSet.bibFieldByTag($scope.field.tag);
518                 }
519                 $scope.spawnAuthorityLinker = function() {
520                     // intentionally making a clone in case
521                     // user decides to abandon the linking
522                     var fieldCopy = new MARC21.Field({
523                         tag       : $scope.field.tag,
524                         ind1      : $scope.field.ind1,
525                         ind2      : $scope.field.ind2
526                     });
527                     angular.forEach($scope.field.subfields, function(sf) {
528                         fieldCopy.subfields.push(sf.slice(0));
529                     });
530                     var cs = $scope.$parent.$parent.controlSet;
531                     var args = { changed : false };
532                     $uibModal.open({
533                         templateUrl: './cat/share/t_authority_link_dialog',
534                         backdrop: 'static',
535                         size: 'lg',
536                         controller: ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
537                             $scope.controlSet = cs;
538                             $scope.bibField = fieldCopy;
539                             $scope.focusMe = true;
540                             $scope.args = args;
541                             $scope.ok = function(args) { $uibModalInstance.close(args) };
542                             $scope.cancel = function () { $uibModalInstance.dismiss() };
543                         }]
544                     }).result.then(function (args) {
545                         if (args.changed) {
546                             $scope.field.subfields.length = 0;
547                             angular.forEach(fieldCopy.subfields, function(sf) {
548                                 $scope.field.addSubfields(sf[0], sf[1]);
549                             });
550                         }
551                     });
552                 }
553             }
554         ]
555     }
556 })
557
558 .directive("egMarcEditControlfield", function () {
559     return {
560         transclude: true,
561         restrict: 'E',
562         template: '<div>'+
563                     '<span><eg-marc-edit-tag context-functions="contextFunctions" field="field" tag="field.tag" on-keydown="onKeydown"/></span>'+
564                     '<span><eg-marc-edit-editable '+
565                       'itype="cfld" '+
566                       'field="field" '+
567                       'class="marcedit marcdata" '+
568                       'content="field.data" '+
569                       'on-keydown="onKeydown" '+
570                       'id="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}data"'+
571                       '/></span>'+
572                       // TODO: move to TT2 template
573                       '<button class="btn btn-info btn-xs" '+
574                       'aria-label="Physical Characteristics Wizard" '+
575                       'ng-show="showPhysCharLink()"'+
576                       'ng-click="spawnPhysCharWizard()"'+
577                       '>'+
578                       '<span class="glyphicon glyphicon-edit"></span>'+
579                       '</button>'+
580                   '</div>',
581         scope: { field: "=", onKeydown: '=', contextFunctions: '=' },
582         controller : ['$scope','$uibModal',
583             function ( $scope,  $uibModal) {
584                 $scope.showPhysCharLink = function () {
585                     return ($scope.$parent.$parent.record_type == 'bre') 
586                         && $scope.field.tag == '007';
587                 }
588                 $scope.spawnPhysCharWizard = function() {
589                     var args = {
590                         changed : false,
591                         field : $scope.field,
592                         orig_value : $scope.field.data
593                     };
594                     $uibModal.open({
595                         templateUrl: './cat/share/t_physchar_dialog',
596                         controller: ['$scope','$uibModalInstance',
597                             function( $scope , $uibModalInstance) {
598                             $scope.focusMe = true;
599                             $scope.args = args;
600                             $scope.ok = function(args) { $uibModalInstance.close(args) };
601                             $scope.cancel = function () { 
602                                 $uibModalInstance.dismiss();
603                                 args.field.data = args.orig_value;
604                             };
605                         }],
606                     }).result.then(function (args) {
607                         // $scope.field.data is changed within the 
608                         // wizard.  Nothing left to do on submit.
609                     });
610
611                 }
612             }
613         ]
614     }
615 })
616
617 .directive("egMarcEditLeader", function () {
618     return {
619         transclude: true,
620         restrict: 'E',
621         template: '<div>'+
622                     '<span><eg-marc-edit-editable '+
623                       'class="marcedit marctag" '+
624                       'content="tag" '+
625                       'on-keydown="onKeydown" '+
626                       'id="leadertag" '+
627                       'is-disabled="disabled"'+
628                       '/></span>'+
629                     '<span><eg-marc-edit-editable '+
630                       'class="marcedit marcdata" '+
631                       'itype="ldr" '+
632                       'max="{{record.leader.length}}" '+
633                       'content="record.leader" '+
634                       'id="r{{record.subfield(\'901\',\'c\')[1] || 0}}leaderdata" '+
635                       'on-keydown="onKeydown"'+
636                       '/></span>'+
637                   '</div>',
638         controller : ['$scope',
639             function ( $scope ) {
640                 $scope.tag = 'LDR';
641             }
642         ],
643         scope: { record: "=", onKeydown: '=' }
644     }
645 })
646
647 /// TODO: fixed field editor and such
648 .directive("egMarcEditRecord", function () {
649     return {
650         templateUrl : './cat/share/t_marcedit',
651         restrict: 'E',
652         replace: true,
653         scope: {
654             dirtyFlag : '=',
655             recordId : '=',
656             marcXml : '=',
657             bibSource : '=?',
658             onSave : '=',
659             // in-place mode means that the editor is being
660             // used just to munge some MARCXML client-side, rather
661             // than to (immediately) update the database
662             //
663             // In short, we can use inPlaceMode as a way to skip
664             // "normal" bre saving and then process the MARC ourselves
665             // via a callback
666             //
667             // inPlaceMode is r/w to allow our Z39.50 import editor to be
668             // switched back into a normal editor after the initial import
669             inPlaceMode : '=',
670             fastAdd : '@',
671             flatOnly : '@',
672             embedded : '@',
673             recordType : '@',
674             maxUndo : '@',
675             saveLabel : '@'
676         },
677         link: function (scope, element, attrs) {
678
679             element.bind('mouseup', function(e) {;
680                 scope.current_event_target = $(e.target).attr('id');
681                 if (scope.current_event_target && $(e.target).hasClass('noSelection')) {
682                     e.preventDefault()
683                     return false;
684                 }
685             });
686
687             element.bind('click', function(e) {;
688                 scope.current_event_target = $(e.target).attr('id');
689                 if (scope.current_event_target) {
690                     console.log('Recording click event on ' + scope.current_event_target);
691                     scope.current_event_target_cursor_pos =
692                         e.target.selectionDirection=='backward' ?
693                             e.target.selectionStart :
694                             e.target.selectionEnd;
695                 }
696             });
697
698         },
699         controller : ['$timeout','$scope','$q','$window','egCore', 'egTagTable','egConfirmDialog','egAlertDialog',
700             function ( $timeout , $scope , $q,  $window , egCore ,  egTagTable , egConfirmDialog , egAlertDialog ) {
701
702
703                 $scope.onSaveCallback = $scope.onSave;
704                 if (typeof $scope.onSaveCallback !== 'undefined' && !angular.isArray($scope.onSaveCallback))
705                     $scope.onSaveCallback = [ $scope.onSaveCallback ];
706
707                 $scope.$watch('dirtyFlag',
708                     function(newVal, oldVal) {
709                         if (newVal && newVal != oldVal && !$scope.opac_iframe) {
710                             $($window).on('beforeunload', function(){
711                                 return egCore.strings.DIRTY_MARC_WARNING;
712                             });
713                         } else {
714                             if (!$scope.opac_iframe)
715                                 $($window).off('beforeunload');
716                         }
717                     }
718                 );
719
720                 MARC21.Record.delimiter = '$';
721
722                 $scope.enable_fast_add = false;
723                 $scope.fast_item_callnumber = '';
724                 $scope.fast_item_barcode = '';
725
726                 $scope.flatEditor = { isEnabled : $scope.flatOnly ? true : false };
727                 
728                 egCore.hatch.getItem('cat.marcedit.flateditor').then(function(val) {
729                     $scope.flatEditor.isEnabled = val;
730                 });
731                 
732                 $scope.$watch('flatEditor.isEnabled', function (newVal, oldVal) {
733                     if (newVal != oldVal) egCore.hatch.setItem('cat.marcedit.flateditor', newVal);
734                 });
735
736                 // necessary to prevent ng-model scope hiding ugliness in egMarcEditBibSource:
737                 $scope.bib_source = {
738                     id : $scope.bibSource ? $scope.bibSource : null
739                 };
740                 $scope.brandNewRecord = false;
741                 $scope.record_type = $scope.recordType || 'bre';
742                 $scope.max_undo = $scope.maxUndo || 100;
743                 $scope.record_undo_stack = [];
744                 $scope.record_redo_stack = [];
745                 $scope.in_undo = false;
746                 $scope.in_redo = false;
747                 $scope.record = new MARC21.Record();
748                 $scope.save_stack_depth = 0;
749                 $scope.controlfields = [];
750                 $scope.datafields = [];
751                 $scope.controlSet = egTagTable.getAuthorityControlSet();
752                 $scope.showHelp = false;
753                 $scope.stackSubfields = { enabled : false };
754                 egCore.hatch.getItem('cat.marcedit.stack_subfields').then(function(val) {
755                     $scope.stackSubfields.enabled = val;
756                 });
757                 $scope.$watch('stackSubfields.enabled', function (newVal, oldVal) {
758                     if (newVal != oldVal) egCore.hatch.setItem('cat.marcedit.stack_subfields', newVal);
759                 });
760                 $scope.caretRecId = $scope.recordId;
761
762                 egTagTable.loadTagTable({ marcRecordType : $scope.record_type });
763
764                 $scope.saveFlatTextMARC = function () {
765                     $scope.record = new MARC21.Record({ marcbreaker : $scope.flat_text_marc });
766                 };
767
768                 $scope.refreshVisual = function () {
769                     if (!$scope.flatEditor.isEnabled) {
770                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
771                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
772                     }
773                 };
774
775                 var addDatafield = function (e,before) {
776                     var element = $(e.target);
777
778                     var index_field = e.data.scope.field.position;
779                     var new_field_index = index_field;
780
781                     var new_field = new MARC21.Field({
782                         tag : '999',
783                         subfields : [[' ','',0]]
784                     });
785
786                     if (Boolean(before)) {
787                         e.data.scope.field.record.insertFieldsBefore(
788                             e.data.scope.field,
789                             new_field
790                         );
791                     } else {
792                         e.data.scope.field.record.insertFieldsAfter(
793                             e.data.scope.field,
794                             new_field
795                         );
796                         new_field_index++;
797                     }
798
799                     $scope.current_event_target = 'r' + $scope.caretRecId +
800                                                   'f' + new_field_index + 'tag';
801
802                     $scope.current_event_target_cursor_pos = 0;
803                     $scope.current_event_target_cursor_pos_end = 3;
804                     $scope.force_render = true;
805
806                     $timeout(function(){$scope.$digest()}).then(setCaret);
807                 };
808
809                 var deleteDatafield = function (e) {
810                     var del_field = e.data.scope.field.position;
811
812                     var sf901c = e.data.scope.field.record.subfield('901','c');
813                     var recId = (sf901c === null) ? '' : sf901c[1];
814                     var domnode = $('#r' + recId + 'f' + del_field);
815
816                     e.data.scope.field.record.deleteFields(
817                         e.data.scope.field
818                     );
819
820                     domnode.scope().$destroy();
821                     domnode.remove();
822
823                     $scope.current_event_target = 'r' + $scope.caretRecId +
824                                                   'f' + del_field + 'tag';
825
826                     $scope.current_event_target_cursor_pos = 0;
827                     $scope.current_event_target_cursor_pos_end = 0
828                     $scope.force_render = true;
829
830                     $timeout(function(){$scope.$digest()}).then(setCaret);
831                 };
832
833                 var add006 = function (e) {
834                     e.data.scope.field.record.insertOrderedFields(
835                         new MARC21.Field({
836                             tag : '006',
837                             data : '                                        '
838                         })
839                     );
840
841                     $scope.force_render = true;
842                     $timeout(function(){$scope.$digest()}).then(setCaret);
843                 };
844
845                 var add007 = function (e) {
846                     e.data.scope.field.record.insertOrderedFields(
847                         new MARC21.Field({
848                             tag : '007',
849                             data : '                                        '
850                         })
851                     );
852
853                     $scope.force_render = true;
854                     $timeout(function(){$scope.$digest()}).then(setCaret);
855                 };
856
857                 var reify008 = function (e) {
858                     var new_008_data = e.data.scope.field.record.generate008();
859
860
861                     var old_008s = e.data.scope.field.record.field('008',true);
862                     old_008s.forEach(function(o) {
863                         var domnode = $('#r'+o.record.subfield('901','c')[1] + 'f' + o.position);
864                         domnode.scope().$destroy();
865                         domnode.remove();
866                         e.data.scope.field.record.deleteFields(o);
867                     });
868
869                     e.data.scope.field.record.insertOrderedFields(
870                         new MARC21.Field({
871                             tag : '008',
872                             data : new_008_data
873                         })
874                     );
875
876                     $scope.force_render = true;
877                     $timeout(function(){$scope.$digest()}).then(setCaret);
878                 };
879
880                 $scope.context_functions = {
881                     addDatafield : addDatafield,
882                     deleteDatafield : deleteDatafield,
883                     add006 : add006,
884                     add007 : add007,
885                     reify008 : reify008
886                 };
887
888                 $scope.onKeydown = function (event) {
889                     var event_return = true;
890
891                     console.log(
892                         'keydown: which='+event.which+
893                         ', ctrlKey='+event.ctrlKey+
894                         ', shiftKey='+event.shiftKey+
895                         ', altKey='+event.altKey+
896                         ', metaKey='+event.altKey
897                     );
898
899                     if (event.which == 89 && event.ctrlKey) { // ctrl+y, redo
900                         event_return = $scope.processRedo();
901                     } else if (event.which == 90 && event.ctrlKey) { // ctrl+z, undo
902                         event_return = $scope.processUndo();
903                     } else if ((event.which == 68 || event.which == 73) && event.ctrlKey) { // ctrl+d or ctrl+i, insert subfield
904
905                         var element = $(event.target);
906                         var new_sf, index_sf, move_data;
907
908                         if (element.hasClass('marcsfvalue')) {
909                             index_sf = event.data.scope.subfield[2];
910                             new_sf = index_sf + 1;
911
912                             var start = event.target.selectionStart || getCaretPosEditableDiv(element);
913                             var end;
914                             if (event.target.value){
915                                 end = event.target.selectionEnd - event.target.selectionStart ?
916                                         event.target.selectionEnd :
917                                         event.target.value.length;
918                             } else {
919                                 end = element.text().length;
920                             }
921
922                             move_data = element.value ?
923                                 element.value.substring(start,end) :
924                                 element.text().substring(start, end);
925
926                         } else if (element.hasClass('marcsfcode')) {
927                             index_sf = event.data.scope.subfield[2];
928                             new_sf = index_sf + 1;
929                         } else if (element.hasClass('marctag') || element.hasClass('marcind')) {
930                             index_sf = 0;
931                             new_sf = index_sf;
932                         }
933
934                         $scope.current_event_target = 'r' + $scope.caretRecId +
935                                                       'f' + event.data.scope.field.position + 
936                                                       's' + new_sf + 'code';
937
938                         event.data.scope.field.subfields.forEach(function(sf) {
939                             if (sf[2] >= new_sf) sf[2]++;
940                             if (sf[2] == index_sf) {
941                                 sf[1] = event.target.value ?
942                                     event.target.value.substring(0,start) + event.target.value.substring(end) :
943                                     element.text().substring(0, start);
944                             }
945                         });
946                         event.data.scope.field.subfields.splice(
947                             new_sf,
948                             0,
949                             [' ', move_data, new_sf ]
950                         );
951
952                         $scope.current_event_target_cursor_pos = 0;
953                         $scope.current_event_target_cursor_pos_end = 1;
954
955                         $timeout(function(){$scope.$digest()}).then(setCaret);
956
957                         event_return = false;
958
959                     } else if (event.which == 117 && event.shiftKey) { // shift + F6, insert 006
960                         add006(event);
961                         event_return = false;
962
963                     } else if (event.which == 118 && event.shiftKey) { // shift + F7, insert 007
964                         add007(event);
965                         event_return = false;
966
967                     } else if (event.which == 119 && event.shiftKey) { // shift + F8, insert/replace 008
968                         reify008(event);
969                         event_return = false;
970
971                     } else if (event.which == 13 && event.ctrlKey) { // ctrl+enter, insert datafield
972                         addDatafield(event, event.shiftKey); // shift key inserts before
973                         event_return = false;
974
975                     } else if (event.which == 13 &&
976                               ($(event.target).hasClass('marcsf') || $(event.target.parentNode).hasClass('marcsf'))
977                               ) {
978                         // bare return; don't allow it
979                         event_return = false;
980
981                     } else if (event.which == 46 && event.ctrlKey) { // ctrl+del, remove field
982                         deleteDatafield(event);
983                         event_return = false;
984
985                     } else if (event.which == 46 && event.shiftKey && ($(event.target).hasClass('marcsf') || $(event.target.parentNode).hasClass('marcsf'))) { 
986                         // shift+del, remove subfield
987
988                         var sf = event.data.scope.subfield[2] - 1;
989                         if (sf == -1) sf = 0;
990
991                         event.data.scope.field.deleteExactSubfields(
992                             event.data.scope.subfield
993                         );
994
995                         if (!event.data.scope.field.subfields[sf]) {
996                             $scope.current_event_target = 'r' + $scope.caretRecId +
997                                                           'f' + event.data.scope.field.position + 
998                                                           'tag';
999                         } else {
1000                             $scope.current_event_target = 'r' + $scope.caretRecId +
1001                                                           'f' + event.data.scope.field.position + 
1002                                                           's' + sf + 'value';
1003                         }
1004
1005                         $scope.current_event_target_cursor_pos = 0;
1006                         $scope.current_event_target_cursor_pos_end = 0;
1007                         $scope.force_render = true;
1008
1009                         $timeout(function(){$scope.$digest()}).then(setCaret);
1010
1011                         event_return = false;
1012
1013                     } else if (event.keyCode == 38) {
1014                         if (event.ctrlKey) { // copy the field up
1015                             var index_field = event.data.scope.field.position;
1016
1017                             var field_obj;
1018                             if (event.data.scope.field.isControlfield()) {
1019                                 field_obj = new MARC21.Field({
1020                                     tag : event.data.scope.field.tag,
1021                                     data : event.data.scope.field.data
1022                                 });
1023                             } else {
1024                                 var sf_clone = [];
1025                                 for (var i in event.data.scope.field.subfields) {
1026                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
1027                                 }
1028                                 field_obj = new MARC21.Field({
1029                                     tag : event.data.scope.field.tag,
1030                                     ind1 : event.data.scope.field.ind1,
1031                                     ind2 : event.data.scope.field.ind2,
1032                                     subfields : sf_clone
1033                                 });
1034                             }
1035
1036
1037                             event.data.scope.field.record.insertFieldsBefore(
1038                                 event.data.scope.field,
1039                                 field_obj
1040                             );
1041
1042                             $scope.current_event_target = 'r' + $scope.caretRecId +
1043                                                           'f' + index_field + 'tag';
1044
1045                             $scope.current_event_target_cursor_pos = 0;
1046                             $scope.current_event_target_cursor_pos_end = 3;
1047                             $scope.force_render = true;
1048
1049                             $timeout(function(){$scope.$digest()}).then(setCaret);
1050
1051                         } else { // jump to prev field
1052                             if (event.data.scope.field.position > 0) {
1053                                 $timeout(function(){
1054                                     $scope.current_event_target_cursor_pos = 0;
1055                                     $scope.current_event_target_cursor_pos_end = 0;
1056                                     $scope.current_event_target = 'r' + $scope.caretRecId +
1057                                                                   'f' + (event.data.scope.field.position - 1) +
1058                                                                   'tag';
1059                                 }).then(setCaret);
1060                             }
1061                         }
1062
1063                         event_return = false;
1064
1065                     } else if (event.keyCode == 40) { // down arrow...
1066                         if (event.ctrlKey) { // copy the field down
1067
1068                             var index_field = event.data.scope.field.position;
1069                             var new_field = index_field + 1;
1070
1071                             var field_obj;
1072                             if (event.data.scope.field.isControlfield()) {
1073                                 field_obj = new MARC21.Field({
1074                                     tag : event.data.scope.field.tag,
1075                                     data : event.data.scope.field.data
1076                                 });
1077                             } else {
1078                                 var sf_clone = [];
1079                                 for (var i in event.data.scope.field.subfields) {
1080                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
1081                                 }
1082                                 field_obj = new MARC21.Field({
1083                                     tag : event.data.scope.field.tag,
1084                                     ind1 : event.data.scope.field.ind1,
1085                                     ind2 : event.data.scope.field.ind2,
1086                                     subfields : sf_clone
1087                                 });
1088                             }
1089
1090                             event.data.scope.field.record.insertFieldsAfter(
1091                                 event.data.scope.field,
1092                                 field_obj
1093                             );
1094
1095                             $scope.current_event_target = 'r' + $scope.caretRecId +
1096                                                           'f' + new_field + 'tag';
1097
1098                             $scope.current_event_target_cursor_pos = 0;
1099                             $scope.current_event_target_cursor_pos_end = 3;
1100                             $scope.force_render = true;
1101
1102                             $timeout(function(){$scope.$digest()}).then(setCaret);
1103
1104                         } else { // jump to next field
1105                             if (event.data.scope.field.record.fields[event.data.scope.field.position + 1]) {
1106                                 $timeout(function(){
1107                                     $scope.current_event_target_cursor_pos = 0;
1108                                     $scope.current_event_target_cursor_pos_end = 0;
1109                                     $scope.current_event_target = 'r' + $scope.caretRecId +
1110                                                                   'f' + (event.data.scope.field.position + 1) +
1111                                                                   'tag';
1112                                 }).then(setCaret);
1113                             }
1114                         }
1115
1116                         event_return = false;
1117
1118                     } else { // Assumes only marc editor elements have IDs that can trigger this event handler.
1119                         $scope.current_event_target = $(event.target).hasClass('focusable') ? $(event.target) : null;//.attr('id');
1120                         if ($scope.current_event_target) {
1121                             $scope.current_event_target_cursor_pos =
1122                                 event.target.selectionDirection=='backward' ?
1123                                     event.target.selectionStart :
1124                                     event.target.selectionEnd;
1125                         }
1126                     }
1127
1128                     return event_return;
1129                 };
1130
1131                 function setCaret() {
1132                     if ($scope.current_event_target) {
1133                         console.log("Putting caret in " + $scope.current_event_target);
1134                         if (!$scope.current_event_target_cursor_pos_end)
1135                             $scope.current_event_target_cursor_pos_end = $scope.current_event_target_cursor_pos
1136
1137                         var element = $('#'+$scope.current_event_target + " .focusable").get(0);
1138                         if (element) {
1139                             element.focus();
1140                             if (element.setSelectionRange) {
1141                                 element.setSelectionRange(
1142                                     $scope.current_event_target_cursor_pos,
1143                                     $scope.current_event_target_cursor_pos_end
1144                                 );
1145                             }
1146                         }
1147                         $scope.current_event_cursor_pos_end = null;
1148                         $scope.current_event_target = null;
1149                     }
1150                 }
1151
1152                 function getCaretPosEditableDiv(editableDiv){
1153                     var caretPos = 0, sel, range;
1154                     if (window.getSelection) {
1155                         sel = window.getSelection();
1156                         if (sel.rangeCount) {
1157                             range = sel.getRangeAt(0);
1158                             if (range.commonAncestorContainer.parentNode == editableDiv[0]) {
1159                                 caretPos = range.endOffset;
1160                             }
1161                         }
1162                     }
1163                     return caretPos;
1164                 }
1165
1166                 function loadRecord() {
1167                     return (function() {
1168                         var deferred = $q.defer();
1169                         if ($scope.recordId) {
1170                             egCore.pcrud.retrieve(
1171                                 $scope.record_type, $scope.recordId
1172                             ).then(function(rec) {
1173                                 deferred.resolve(rec);
1174                             });
1175                         } else {
1176                             if ($scope.recordType == 'bre') {
1177                                 var bre = new egCore.idl.bre();
1178                                 bre.marc($scope.marcXml);
1179                                 deferred.resolve(bre);
1180                             } else if ($scope.recordType == 'are') {
1181                                 var are = new egCore.idl.are();
1182                                 are.marc($scope.marcXml);
1183                                 deferred.resolve(are);
1184                             } else if ($scope.recordType == 'sre') {
1185                                 var sre = new egCore.idl.sre();
1186                                 sre.marc($scope.marcXml);
1187                                 deferred.resolve(sre);
1188                             }
1189                             $scope.brandNewRecord = true;
1190                         }
1191                         return deferred.promise;
1192                     })().then(function(rec) {
1193                         $scope.in_redo = true;
1194                         $scope[$scope.record_type] = rec;
1195                         $scope.record = new MARC21.Record({ marcxml : $scope.Record().marc() });
1196                         if (!$scope.recordId) {
1197                             var sf901c = $scope.record.subfield('901', 'c');
1198                             if (sf901c !== null) {
1199                                 $scope.caretRecId = sf901c[1];
1200                             }
1201                         }
1202                         $scope.calculated_record_type = $scope.record.recordType();
1203                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1204                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1205                         $scope.save_stack_depth = $scope.record_undo_stack.length;
1206                         $scope.dirtyFlag = false;
1207                         $scope.flat_text_marc = $scope.record.toBreaker();
1208
1209                         if ($scope.record_type == 'bre' && !$scope.brandNewRecord) {
1210                             $scope.bib_source.id = $scope.bibSource = rec.source(); //$scope.Record().source();
1211                         }
1212
1213                     }).then(function(){
1214                         return egTagTable.fetchFFPosTable($scope.calculated_record_type)
1215                     }).then(function(){
1216                         return egTagTable.fetchFFValueTable($scope.calculated_record_type)
1217                     }).then(setCaret);
1218                 }
1219
1220                 $scope.$watch('record.toBreaker()', function (newVal, oldVal) {
1221                     if (!$scope.in_undo && !$scope.in_redo && oldVal != newVal) {
1222                         $scope.record_undo_stack.push({
1223                             breaker: oldVal,
1224                             target: $scope.current_event_target,
1225                             pos: $scope.current_event_target_cursor_pos
1226                         });
1227
1228                         if ($scope.force_render) {
1229                             $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1230                             $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1231                             $scope.force_render = false;
1232                         }
1233
1234                         $scope.flat_text_marc = newVal;
1235                     }
1236
1237                     if ($scope.record_undo_stack.length != $scope.save_stack_depth) {
1238                         $scope.dirtyFlag = true;
1239                     } else {
1240                         $scope.dirtyFlag = false;
1241                     }
1242
1243                     if ($scope.record_undo_stack.length > $scope.max_undo)
1244                         $scope.record_undo_stack.shift();
1245
1246                     console.log('undo stack is ' + $scope.record_undo_stack.length + ' deep');
1247                     $scope.in_redo = false;
1248                     $scope.in_undo = false;
1249                 });
1250
1251                 $scope.processUndo = function () {
1252                     if ($scope.record_undo_stack.length) {
1253                         $scope.in_undo = true;
1254
1255                         var undo_item = $scope.record_undo_stack.pop();
1256                         $scope.record_redo_stack.push(undo_item);
1257
1258                         $scope.record = new MARC21.Record({ marcbreaker : undo_item.breaker });
1259                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1260                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1261
1262                         $scope.current_event_target = undo_item.target;
1263                         $scope.current_event_target_cursor_pos = undo_item.pos;
1264                         console.log('Undo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
1265
1266                         $timeout(function(){$scope.$digest()}).then(setCaret);
1267                         return false;
1268                     }
1269
1270                     return true;
1271                 };
1272
1273                 $scope.processRedo = function () {
1274                     if ($scope.record_redo_stack.length) {
1275                         $scope.in_redo = true;
1276
1277                         var redo_item = $scope.record_redo_stack.pop();
1278                         $scope.record_undo_stack.push(redo_item);
1279
1280                         $scope.record = new MARC21.Record({ marcbreaker : redo_item.breaker });
1281                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1282                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1283
1284                         $scope.current_event_target = redo_item.target;
1285                         $scope.current_event_target_cursor_pos = redo_item.pos;
1286                         console.log('Redo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
1287
1288                         $timeout(function(){$scope.$digest()}).then(setCaret);
1289                         return false;
1290                     }
1291
1292                     return true;
1293                 };
1294
1295                 $scope.Record = function () {
1296                     return $scope[$scope.record_type];
1297                 };
1298
1299                 $scope.deleteRecord = function () {
1300                     egConfirmDialog.open(
1301                         egCore.strings.CONFIRM_DELETE_RECORD,
1302                         (($scope.record_type == 'bre') ?
1303                             egCore.strings.CONFIRM_DELETE_BRE_MSG :
1304                             egCore.strings.CONFIRM_DELETE_ARE_MSG),
1305                         { id : $scope.recordId }
1306                     ).result.then(function() {
1307                         if ($scope.record_type == 'bre') {
1308                             egCore.net.request(
1309                                 'open-ils.cat',
1310                                 'open-ils.cat.biblio.record_entry.delete',
1311                                 egCore.auth.token(), $scope.recordId
1312                             ).then(function(resp) {
1313                                 var evt = egCore.evt.parse(resp);
1314                                 if (evt) {
1315                                     return egAlertDialog.open(
1316                                         egCore.strings.ALERT_DELETE_FAILED,
1317                                         { id : $scope.recordId, desc : evt.desc }
1318                                     );
1319                                 } else {
1320                                     loadRecord().then(processOnSaveCallbacks);
1321                                 }
1322                             });
1323                         } else {
1324                             $scope.Record().deleted(true);
1325                             return $scope.saveRecord();
1326                         }
1327                     });
1328                 };
1329
1330                 $scope.undeleteRecord = function () {
1331                     $scope.Record().deleted(false);
1332                     return $scope.saveRecord();
1333                 };
1334
1335                 $scope.validateHeadings = function () {
1336                     if ($scope.record_type != 'bre') return;
1337                     var chain = $q.when();
1338                     angular.forEach($scope.record.fields, function(f) {
1339                         if (!$scope.controlSet.bibFieldByTag(f.tag)) return;
1340                         // if heading already has a $0, assume it's good
1341                         if (f.subfield('0', true).length) {
1342                             f.heading_checked = true;
1343                             f.heading_valid = true;
1344                             return;
1345                         }
1346                         var auth_match = $scope.controlSet.bibToAuthorities(f);
1347                         if (auth_match.length == 0) return;
1348                         chain = chain.then(function() {
1349                             var promise = egCore.net.request(
1350                                 'open-ils.search',
1351                                 'open-ils.search.authority.simple_heading.from_xml.batch.atomic',
1352                                 auth_match[0]
1353                             ).then(function (matches) {
1354                                 f.heading_valid = false;
1355                                 if (matches[0]) { // probably set
1356                                     for (var cset in matches[0]) {
1357                                         var arr = matches[0][cset];
1358                                         if (arr.length) {
1359                                             // protect against errant empty string values
1360                                             if (arr.length == 1 && arr[0] == '')
1361                                                 continue;
1362                                             f.heading_valid = true;
1363                                             break;
1364                                         }
1365                                     }
1366                                 }
1367                                 f.heading_checked = true;
1368                             });
1369                             return promise;
1370                         });
1371                     });
1372                 }
1373
1374                 processOnSaveCallbacks = function() {
1375                     var deferred = $q.defer();
1376                     if (typeof $scope.onSaveCallback !== 'undefined') {
1377                         var promise = deferred.promise;
1378
1379                         angular.forEach($scope.onSaveCallback, function (f) {
1380                             if (angular.isFunction(f)) promise = promise.then(f);
1381                         });
1382
1383                     }
1384                     return deferred.resolve($scope.recordId)
1385                 };
1386
1387                 $scope.saveRecord = function () {
1388                     
1389                     if ($scope.inPlaceMode) {
1390                         $scope.marcXml = $scope.record.toXmlString();
1391                         
1392                         if ($scope.record_type == 'bre'){
1393                             $scope.bibSource = $scope.bib_source.id;
1394                         }
1395
1396                         return $timeout(processOnSaveCallbacks);
1397                     }
1398
1399                     $scope.mangle_005();
1400                     $scope.Record().editor(egCore.auth.user().id());
1401                     $scope.Record().edit_date('now');
1402                     $scope.record.pruneEmptyFieldsAndSubfields();
1403                     $scope.Record().marc($scope.record.toXmlString());
1404                     if ($scope.recordId) {
1405                         return egCore.pcrud.update(
1406                             $scope.Record()
1407                         ).then(function() { // success
1408                             $scope.save_stack_depth = $scope.record_undo_stack.length;
1409                             $scope.dirtyFlag = false;
1410                             if ($scope.enable_fast_add) {
1411                                 egCore.net.request(
1412                                     'open-ils.actor',
1413                                     'open-ils.actor.anon_cache.set_value',
1414                                     null, 'edit-these-copies', {
1415                                         record_id: $scope.recordId,
1416                                         raw: [{
1417                                             label : $scope.fast_item_callnumber,
1418                                             barcode : $scope.fast_item_barcode,
1419                                             fast_add : true
1420                                         }],
1421                                         hide_vols : false,
1422                                         hide_copies : false
1423                                     }
1424                                 ).then(function(key) {
1425                                     if (key) {
1426                                         var url = egCore.env.basePath + 'cat/volcopy/' + key;
1427                                         $timeout(function() { $window.open(url, '_blank') });
1428                                     } else {
1429                                         alert('Could not create anonymous cache key!');
1430                                     }
1431                                 });
1432                             }
1433                         }, function() { // failure
1434                             alert('Could not save the record!');
1435                         }).then(loadRecord).then(processOnSaveCallbacks);
1436                     } else {
1437                         $scope.Record().creator(egCore.auth.user().id());
1438                         $scope.Record().create_date('now');
1439                         return egCore.pcrud.create(
1440                             $scope.Record()
1441                         ).then(function(bre) {
1442                             $scope.dirtyFlag = false;
1443                             $scope.recordId = bre.id(); 
1444                             $scope.caretRecId = $scope.recordId;
1445                             if ($scope.enable_fast_add) {
1446                                 egCore.net.request(
1447                                     'open-ils.actor',
1448                                     'open-ils.actor.anon_cache.set_value',
1449                                     null, 'edit-these-copies', {
1450                                         record_id: $scope.recordId,
1451                                         raw: [{
1452                                             label : $scope.fast_item_callnumber,
1453                                             barcode : $scope.fast_item_barcode,
1454                                         }],
1455                                         hide_vols : false,
1456                                         hide_copies : false
1457                                     }
1458                                 ).then(function(key) {
1459                                     if (key) {
1460                                         var url = egCore.env.basePath + 'cat/volcopy/' + key;
1461                                         $timeout(function() { $window.open(url, '_blank') });
1462                                     } else {
1463                                         alert('Could not create anonymous cache key!');
1464                                     }
1465                                 });
1466                             }
1467                         }).then(loadRecord).then(processOnSaveCallbacks);
1468                     }
1469
1470
1471                 };
1472
1473                 $scope.seeBreaker = function () {
1474                     alert($scope.record.toBreaker());
1475                 };
1476
1477                 $scope.$watch('recordId',
1478                     function(newVal, oldVal) {
1479                         if (newVal && newVal !== oldVal) {
1480                             loadRecord();
1481                         }
1482                     }
1483                 );
1484                 $scope.$watch('marcXml',
1485                     function(newVal, oldVal) {
1486                         if (newVal && newVal !== oldVal) {
1487                             loadRecord();
1488                         }
1489                     }
1490                 );
1491
1492                 var unregister = $scope.$watch(function() {
1493                     return egTagTable.initialized();
1494                 }, function(val) {
1495                     if (val) {
1496                         unregister();
1497                         if ($scope.recordId || $scope.marcXml) {
1498                             loadRecord();
1499                         }
1500                     }
1501                 });
1502
1503                 $scope.mangle_005 = function () {
1504                     var now = new Date();
1505                     var y = now.getUTCFullYear();
1506                 
1507                     var m = now.getUTCMonth() + 1;
1508                     if (m < 10) m = '0' + m;
1509                 
1510                     var d = now.getUTCDate();
1511                     if (d < 10) d = '0' + d;
1512                 
1513                     var H = now.getUTCHours();
1514                     if (H < 10) H = '0' + H;
1515                 
1516                     var M = now.getUTCMinutes();
1517                     if (M < 10) M = '0' + M;
1518                 
1519                     var S = now.getUTCSeconds();
1520                     if (S < 10) S = '0' + S;
1521                 
1522                     var stamp = '' + y + m + d + H + M + S + '.0';
1523                     var f = $scope.record.field('005',true)[0];
1524                     if (f) {
1525                         f.data = stamp;
1526                     } else {
1527                         $scope.record.insertOrderedFields(
1528                             new MARC21.Field({
1529                                 tag : '005',
1530                                 data: stamp
1531                             })
1532                         );
1533                     }
1534                 
1535                 }
1536
1537             }
1538         ]          
1539     }
1540 })
1541
1542 .directive("egMarcEditBibsource", ['$timeout',function ($timeout) {
1543     return {
1544         restrict: 'E',
1545         replace: true,
1546         template: '<span class="nullable">'+
1547                     '<select class="form-control" ng-model="bib_source.id" ng-options="s.id() as s.source() for s in bib_sources | orderBy: \'source()\'">'+
1548                       '<option value="">Select a Source</option>'+
1549                     '</select>'+
1550                   '</span>',
1551         controller: ['$scope','egCore',
1552             function ($scope , egCore) {
1553
1554                 egCore.pcrud.retrieveAll('cbs', {}, {atomic : true})
1555                     .then(function(list) {
1556                         $scope.bib_sources = list;
1557                     });
1558
1559                 $scope.$watch('bib_source.id',
1560                     function(newVal, oldVal) {
1561                         if (newVal !== oldVal) {
1562                             $scope.bre.source(newVal);
1563                         }
1564                     }
1565                 );
1566
1567             }
1568         ]
1569     }
1570 }])
1571
1572 .directive("egMarcEditAuthorityLinker", function () {
1573     return {
1574         restrict: 'E',
1575         replace: true,
1576         templateUrl: './cat/share/t_authority_linker',
1577         scope : {
1578             bibField : '=',
1579             controlSet : '=',
1580             changed : '='
1581         },
1582         controller: ['$scope','$uibModal','egCore','egAuth',
1583             function ($scope , $uibModal,  egCore,  egAuth) {
1584
1585                 $scope.searchStr = '';
1586                 var cni = egCore.env.aous['cat.marc_control_number_identifier'] ||
1587                   'Set cat.marc_control_number_identifier in Library Settings';
1588
1589                 var axis_list = $scope.controlSet.bibFieldBrowseAxes($scope.bibField.tag);
1590                 $scope.axis = axis_list[0];
1591
1592                 $scope._controlled_sf_list = {};
1593                 $scope._controlled_auth_sf_list = {};
1594                 var found_acs = [];
1595                 angular.forEach($scope.controlSet.controlSetList(), function(acs_id) {
1596                     if ($scope.controlSet.controlSet(acs_id).control_map[$scope.bibField.tag])
1597                         found_acs.push(acs_id);
1598                 });
1599                 if (found_acs.length) {
1600                      angular.forEach($scope.controlSet.controlSet(found_acs[0]).control_map[$scope.bibField.tag],
1601                         function(value, sf_label) {
1602                             $scope._controlled_sf_list[ sf_label ] = 1;
1603                             angular.forEach($scope.controlSet.controlSet(found_acs[0]).control_map[$scope.bibField.tag][sf_label],
1604                                 function(auth_sf, auth_tag) {
1605                                     if (!$scope._controlled_auth_sf_list[auth_tag]) {
1606                                         $scope._controlled_auth_sf_list[auth_tag] = { };
1607                                     }
1608                                     $scope._controlled_auth_sf_list[auth_tag][auth_sf] = 1;
1609                                 }
1610                             );
1611                         }
1612                     )
1613                 }
1614
1615                 $scope.bibField.subfields.forEach(function (sf) {
1616                     if (sf[0] in $scope._controlled_sf_list) {
1617                         sf.selected = true;
1618                         sf.selectable = true;
1619                     } else {
1620                         sf.selectable = false;
1621                     }
1622                 });
1623                 $scope.summarizeField = function() {
1624                     var source_f = {
1625                         'tag': $scope.bibField.tag,
1626                         'ind1': $scope.bibField.ind1,
1627                         'ind2': $scope.bibField.ind2,
1628                         'subfields': []
1629                     };
1630                     $scope.bibField.subfields.forEach(function(sf) {
1631                         if (sf.selected) {
1632                             source_f.subfields.push([ sf[0], sf[1] ]);
1633                         }
1634                     });
1635                     return source_f;
1636                 }
1637                 $scope.getSearchString = function() {
1638                     var source_f = $scope.summarizeField();
1639                     var values = [];
1640                     angular.forEach(source_f.subfields, function(val) {
1641                         values.push(val[1]);
1642                     });
1643                     return values.join(' ');
1644                 }
1645                 $scope.searchStr = $scope.getSearchString();
1646                 $scope.$watch(function() {
1647                     var ct = 0;
1648                     angular.forEach($scope.bibField.subfields, function(sf) {
1649                         if (sf.selected) ct++
1650                         });
1651                     return ct;
1652                 },
1653                 function(newVal, oldVal) {
1654                     $scope.searchStr = $scope.getSearchString();
1655                 });
1656
1657                 $scope.updateSubfieldZero = function(value) {
1658                     $scope.changed = true;
1659                     $scope.bibField.deleteSubfield({ code : ['0'] });
1660                     $scope.bibField.subfields.push([
1661                         '0', '(' + cni + ')' + value
1662                     ]);
1663                 };
1664
1665                 $scope.applyHeading = function(headingField) {
1666                     // TODO: move the MARC21 rules for copying indicators
1667                     // out of here
1668                     if (headingField.tag == '130' && $scope.bibField.tag == '130') {
1669                         $scope.bibField.ind1 = headingField.ind2;
1670                     } else {
1671                         $scope.bibField.ind1 = headingField.ind1;
1672                     }
1673                     // deal with 4xx and 5xx
1674                     var authFallbackTag = '1' + headingField.tag.substr(1, 2);
1675                     var _valid_auth_sfs = (headingField.tag in $scope._controlled_auth_sf_list) ?
1676                                           $scope._controlled_auth_sf_list[headingField.tag] :
1677                                           (authFallbackTag in $scope._controlled_auth_sf_list) ?
1678                                           $scope._controlled_auth_sf_list[authFallbackTag] :
1679                                           [];
1680                     // save the $0 for later use
1681                     var sfZero = '';
1682                     if (headingField.subfield('0')) {
1683                         sfZero = headingField.subfield('0')[1];
1684                     }
1685                     // grab any bib subfields not under authority control
1686                     // TODO do something about uncontrolled subdivisions
1687                     var uncontrolledBibSf = [];
1688                     angular.forEach($scope.bibField.subfields, function(sf) {
1689                         if (!(sf[0] in $scope._controlled_sf_list) && (sf[0] != '0')) {
1690                             uncontrolledBibSf.push([ sf[0], sf[1] ]);
1691                         }
1692                     });
1693                     // grab the authority subfields
1694                     var authoritySf = [];
1695                     angular.forEach(headingField.subfields, function(sf) {
1696                         if (sf[0] in _valid_auth_sfs) {
1697                             authoritySf.push([ sf[0], sf[1] ]);
1698                         }
1699                     });
1700                     $scope.bibField.subfields.length = 0;
1701                     angular.forEach(authoritySf, function(sf) {
1702                         $scope.bibField.addSubfields(sf[0], sf[1]);
1703                     });
1704                     angular.forEach(uncontrolledBibSf, function(sf) {
1705                         $scope.bibField.addSubfields(sf[0], sf[1]);
1706                     });
1707                     if (sfZero) {
1708                         $scope.bibField.addSubfields('0', sfZero);
1709                     }
1710                     $scope.bibField.subfields.forEach(function (sf) {
1711                     if (sf[0] in $scope._controlled_sf_list) {
1712                             // intentionally not selecting any subfields
1713                             // after we've applied an authority heading
1714                             sf.selected = false;
1715                             sf.selectable = true;
1716                         } else {
1717                             sf.selectable = false;
1718                         }
1719                     });
1720                     $scope.changed = true;
1721                 }
1722
1723                 $scope.createAuthorityFromBib = function(spawn_editor) {
1724                     var source_f = $scope.summarizeField();
1725
1726                     var args = { authority_id : 0 };
1727                     var method = (spawn_editor) ?
1728                         'open-ils.cat.authority.record.create_from_bib.readonly' :
1729                         'open-ils.cat.authority.record.create_from_bib';
1730                     egCore.net.request(
1731                         'open-ils.cat',
1732                         method,
1733                         source_f,
1734                         cni,
1735                         egAuth.token()
1736                     ).then(function(newAuthority) {
1737                         if (spawn_editor) {
1738                             $uibModal.open({
1739                                 templateUrl: './cat/share/t_edit_new_authority',
1740                                 size: 'lg',
1741                                 controller:
1742                                     ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
1743                                     $scope.focusMe = true;
1744                                     $scope.args = args;
1745                                     $scope.dirty_flag = false;
1746                                     $scope.marc_xml = newAuthority,
1747                                     $scope.ok = function(args) { $uibModalInstance.close(args) }
1748                                     $scope.cancel = function () { $uibModalInstance.dismiss() }
1749                                 }]
1750                             }).result.then(function (args) {
1751                                 if (!args || !args.authority_id) return;
1752                                 $scope.updateSubfieldZero(args.authority_id);
1753                             });
1754                         } else {
1755                             $scope.updateSubfieldZero(newAuthority.id());
1756                         }
1757                     });
1758                 }
1759
1760             }
1761         ]
1762     }
1763 })
1764
1765 .directive("egPhyscharWizard", ['$sce', function ($sce) {
1766     return {
1767         restrict: 'E',
1768         replace: true,
1769         templateUrl: './cat/share/t_physchar_wizard',
1770         scope : {
1771             field : '='
1772         },
1773         controller: ['$scope','$q','egTagTable',
1774             function ($scope , $q , egTagTable) {
1775
1776                 // $scope.step is the 1-based position in the list of 
1777                 // subfields for the currently selected type.
1778                 // step==0 means we are currently selecting the type
1779                 $scope.step = 0;
1780
1781                 // position and offset of the "subfields" we're
1782                 // currently editing; this is maintained as a convenience
1783                 // for the highlighting of the currently active position
1784                 $scope.offset = 0;
1785                 $scope.len = 1;
1786
1787                 if (!$scope.field.data) 
1788                     $scope.field.data = '';
1789
1790                 // currently selected subfield value selector option
1791                 $scope.selected_option = null;
1792
1793                 function current_ptype() {
1794                     return $scope.field.data.substr(0, 1);   
1795                 }
1796
1797                 function current_subfield() {
1798                     return egTagTable.getPhysCharSubfieldMap(current_ptype())
1799                     .then(function(sf_list) {return sf_list[$scope.step-1]});
1800                 }
1801
1802                 $scope.values_for_step = [];
1803                 function set_values_for_step() {
1804                     var promise;
1805
1806                     if ($scope.step == 0) {
1807                         $scope.offset = 0;
1808                         $scope.len    = 1;
1809                         promise = egTagTable.getPhysCharTypeMap();
1810                     } else {
1811                         promise = current_subfield().then(
1812                             function(subfield) {
1813                                 return egTagTable
1814                                     .getPhysCharValueMap(subfield.id());
1815                             }
1816                         );
1817                     }
1818
1819                     return promise.then(function(list) { 
1820                         $scope.values_for_step = list;
1821                         set_selected_option_from_field();
1822                         set_label_for_step();
1823                     });
1824                 }
1825
1826                 $scope.change_ptype = function(option) {
1827                     $scope.selected_option = option;
1828                     var new_val = option.ptype_key();
1829                     if (current_ptype() != new_val) {
1830                         $scope.field.data = new_val; // total reset
1831                     }
1832                 }
1833
1834                 $scope.change_option = function(option) {
1835                     $scope.selected_option = option;
1836                     var new_val = option.value();
1837                     get_step_slot().then(function(slot) {
1838                         var value = $scope.field.data;
1839                         while (value.length < (slot[0] + slot[1])) 
1840                             value += ' ';
1841                         var before = value.substr(0, slot[0]);
1842                         var after = value.substr(slot[0] + slot[1]);
1843                         $scope.field.data = 
1844                             before + new_val.substr(0, slot[1]) + after;
1845                         $scope.offset = slot[0];
1846                         $scope.len    = slot[1];
1847                     });
1848                 }
1849
1850                 function get_step_slot() {
1851                     if ($scope.step == 0) return $q.when([0, 1]);
1852                     return current_subfield().then(function(sf) {
1853                         return [sf.start_pos(), sf.length()]
1854                     });
1855                 }
1856
1857                 $scope.is_last_step = function() {
1858                     // This one is called w/ every digest, so avoid async
1859                     // calls.  Wait until we have loaded the current ptype
1860                     // subfields to determine if this is the last step.
1861                     return (
1862                         current_ptype() && 
1863                         egTagTable.phys_char_sf_map[current_ptype()] &&
1864                         egTagTable.phys_char_sf_map[current_ptype()].length 
1865                             == $scope.step
1866                     );
1867                 }
1868
1869                 $scope.label_for_step = '';
1870                 function set_label_for_step() {
1871                     if ($scope.step > 0) {
1872                         current_subfield().then(function(sf) {
1873                             $scope.label_for_step = sf.label();
1874                         });
1875                     }
1876                 }
1877                 
1878                 $scope.next_step = function() {
1879                     $scope.step++;
1880                     set_values_for_step();
1881                 }
1882
1883                 $scope.prev_step = function() {
1884                     $scope.step--;
1885                     set_values_for_step();
1886                 }
1887
1888                 function set_selected_option_from_field() {
1889                     if ($scope.step == 0) {
1890                         $scope.selected_option = $scope.values_for_step
1891                         .filter(function(opt) {
1892                             return (opt.ptype_key() == current_ptype())})[0];
1893                     } else {
1894                         get_step_slot().then(function(slot) {
1895                             $scope.offset = slot[0];
1896                             $scope.len    = slot[1];
1897                             var val = String.prototype.substr.apply(                      
1898                                 $scope.field.data, slot);
1899                             if (val) {
1900                                 $scope.selected_option = $scope.values_for_step
1901                                 .filter(function(opt) { 
1902                                     return (opt.value() == val)})[0];
1903                             } else {
1904                                 $scope.selected_option = null;
1905                             }
1906                         })
1907                     }
1908                 }
1909
1910                 $scope.highlightedFieldData = function() {
1911                     if (
1912                             $scope.len && $scope.field.data &&
1913                             $scope.field.data.length > 0 &&
1914                             $scope.field.data.length >= $scope.offset
1915                         ) {
1916                         return $sce.trustAsHtml(
1917                             $scope.field.data.substring(0, $scope.offset) + 
1918                             '<span class="active-physchar">' +
1919                             $scope.field.data.substr($scope.offset, $scope.len) +
1920                             '</span>' +
1921                             $scope.field.data.substr($scope.offset + $scope.len)
1922                         );
1923                     } else {
1924                         return $scope.field.data;
1925                     }
1926                 };
1927
1928                 set_values_for_step();
1929             }
1930         ]
1931     }
1932 }])
1933
1934
1935 .directive("egMarcEditAuthorityBrowser", function () {
1936     return {
1937         restrict: 'E',
1938         replace: true,
1939         templateUrl: './cat/share/t_authority_browser',
1940         scope : {
1941             searchString : '=',
1942             controlSet : '=',
1943             axis : '=',
1944             applyHeading : '&'
1945         },
1946         controller: ['$scope','$http',
1947             function ($scope , $http) {
1948
1949                 $scope.page = 0;
1950                 $scope.limit = 5;
1951                 $scope.main_headings = [];
1952
1953                 function getHeadingString(headingField) {
1954                     var heading = '';
1955                     angular.forEach(headingField.subfields, function (sf) {
1956                         if (['x', 'y', 'z'].indexOf(sf[0]) > -1) {
1957                             heading += ' --';
1958                         }
1959                         if (heading) {
1960                             heading += ' ';
1961                         }
1962                         heading += sf[1];
1963                     });
1964                     return heading;
1965                 }
1966
1967                 $scope.doBrowse = function() {
1968                     $scope.main_headings.length = 0;
1969                     if ($scope.searchString.length == 0) return;
1970                     var type = 'authority.'
1971                     var url = '/opac/extras/browse/marcxml/'
1972                             + 'authority.' + $scope.axis + '.refs'
1973                             + '/1' // OU - currently unscoped
1974                             + '/' + $scope.searchString
1975                             + '/' + $scope.page
1976                             + '/' + $scope.limit;
1977                     $http({
1978                         url : url,
1979                         method : 'GET',
1980                         transformResponse : function(data) {
1981                             // use a bit of jQuery to deal with the XML
1982                             var $xml = $( $.parseXML(data) );
1983                             var marc = [];
1984                             $xml.find('record').each(function() {
1985                                 var rec = new MARC21.Record();
1986                                 rec.fromXmlDocument($(this)[0].outerHTML);
1987                                 marc.push(rec);
1988                             });
1989                             return marc;
1990                         }
1991                     }).then(function(response) {
1992                         angular.forEach(response.data, function(rec) {
1993                             var authId = rec.subfield('901', 'c')[1];
1994                             var auth_org = '';
1995                             if (rec.field('003')) {
1996                                 auth_org = rec.field('003').data;
1997                             }
1998                             var headingField = rec.field('1..');
1999                             var seeFroms = rec.field('4..', true);
2000                             var seeAlsos = rec.field('5..', true);
2001
2002                             var main_heading = {
2003                                 authority_id : authId,
2004                                 heading : getHeadingString(headingField),
2005                                 seealso_headings : [ ],
2006                                 seefrom_headings : [ ],
2007                             };
2008
2009                             var sfZero = '';
2010                             if (auth_org) {
2011                                 sfZero = '(' + auth_org + ')';
2012                             }
2013                             sfZero += authId;
2014                             headingField.addSubfields('0', sfZero);
2015
2016                             main_heading['headingField'] = headingField;
2017                             angular.forEach(seeAlsos, function(headingField) {
2018                                 main_heading.seealso_headings.push({
2019                                     heading : getHeadingString(headingField),
2020                                     headingField : headingField
2021                                 });
2022                             });
2023                             angular.forEach(seeFroms, function(headingField) {
2024                                 main_heading.seefrom_headings.push({
2025                                     heading : getHeadingString(headingField),
2026                                     headingField : headingField
2027                                 });
2028                             });
2029                             $scope.main_headings.push(main_heading);
2030                         });
2031                     });
2032                 }
2033
2034                 $scope.$watch('searchString',
2035                     function(newVal, oldVal) {
2036                         if (newVal !== oldVal) {
2037                             $scope.doBrowse();
2038                         }
2039                     }
2040                 );
2041                 $scope.$watch('page',
2042                     function(newVal, oldVal) {
2043                         if (newVal !== oldVal) {
2044                             $scope.doBrowse();
2045                         }
2046                     }
2047                 );
2048
2049                 $scope.doBrowse();
2050             }
2051         ]
2052     }
2053 })
2054
2055 ;