]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/services/marcedit.js
3967267aa76138624274d149f06377938f17d0b9
[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',
700                       'egConfirmDialog','egAlertDialog','ngToast','egStrings',
701             function ( $timeout , $scope , $q,  $window , egCore ,  egTagTable , 
702                        egConfirmDialog , egAlertDialog , ngToast , egStrings) {
703
704
705                 $scope.onSaveCallback = $scope.onSave;
706                 if (typeof $scope.onSaveCallback !== 'undefined' && !angular.isArray($scope.onSaveCallback))
707                     $scope.onSaveCallback = [ $scope.onSaveCallback ];
708
709                 $scope.$watch('dirtyFlag',
710                     function(newVal, oldVal) {
711                         if (newVal && newVal != oldVal && !$scope.opac_iframe) {
712                             $($window).on('beforeunload', function(){
713                                 return egCore.strings.DIRTY_MARC_WARNING;
714                             });
715                         } else {
716                             if (!$scope.opac_iframe)
717                                 $($window).off('beforeunload');
718                         }
719                     }
720                 );
721
722                 MARC21.Record.delimiter = '$';
723
724                 $scope.enable_fast_add = false;
725                 $scope.fast_item_callnumber = '';
726                 $scope.fast_item_barcode = '';
727
728                 $scope.flatEditor = { isEnabled : $scope.flatOnly ? true : false };
729                 
730                 egCore.hatch.getItem('cat.marcedit.flateditor').then(function(val) {
731                     $scope.flatEditor.isEnabled = val;
732                 });
733                 
734                 $scope.$watch('flatEditor.isEnabled', function (newVal, oldVal) {
735                     if (newVal != oldVal) egCore.hatch.setItem('cat.marcedit.flateditor', newVal);
736                 });
737
738                 // necessary to prevent ng-model scope hiding ugliness in egMarcEditBibSource:
739                 $scope.bib_source = {
740                     id : $scope.bibSource ? $scope.bibSource : null,
741                     name: null
742                 };
743                 $scope.brandNewRecord = false;
744                 $scope.record_type = $scope.recordType || 'bre';
745                 $scope.max_undo = $scope.maxUndo || 100;
746                 $scope.record_undo_stack = [];
747                 $scope.record_redo_stack = [];
748                 $scope.in_undo = false;
749                 $scope.in_redo = false;
750                 $scope.record = new MARC21.Record();
751                 $scope.save_stack_depth = 0;
752                 $scope.controlfields = [];
753                 $scope.datafields = [];
754                 $scope.controlSet = egTagTable.getAuthorityControlSet();
755                 $scope.showHelp = false;
756                 $scope.stackSubfields = { enabled : false };
757                 egCore.hatch.getItem('cat.marcedit.stack_subfields').then(function(val) {
758                     $scope.stackSubfields.enabled = val;
759                 });
760                 $scope.$watch('stackSubfields.enabled', function (newVal, oldVal) {
761                     if (newVal != oldVal) egCore.hatch.setItem('cat.marcedit.stack_subfields', newVal);
762                 });
763                 $scope.caretRecId = $scope.recordId;
764
765                 egTagTable.loadTagTable({ marcRecordType : $scope.record_type });
766
767                 $scope.saveFlatTextMARC = function () {
768                     $scope.record = new MARC21.Record({ marcbreaker : $scope.flat_text_marc });
769                 };
770
771                 $scope.refreshVisual = function () {
772                     if (!$scope.flatEditor.isEnabled) {
773                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
774                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
775                     }
776                 };
777
778                 var addDatafield = function (e,before) {
779                     var element = $(e.target);
780
781                     var index_field = e.data.scope.field.position;
782                     var new_field_index = index_field;
783
784                     var new_field = new MARC21.Field({
785                         tag : '999',
786                         subfields : [[' ','',0]]
787                     });
788
789                     if (Boolean(before)) {
790                         e.data.scope.field.record.insertFieldsBefore(
791                             e.data.scope.field,
792                             new_field
793                         );
794                     } else {
795                         e.data.scope.field.record.insertFieldsAfter(
796                             e.data.scope.field,
797                             new_field
798                         );
799                         new_field_index++;
800                     }
801
802                     $scope.current_event_target = 'r' + $scope.caretRecId +
803                                                   'f' + new_field_index + 'tag';
804
805                     $scope.current_event_target_cursor_pos = 0;
806                     $scope.current_event_target_cursor_pos_end = 3;
807                     $scope.force_render = true;
808
809                     $timeout(function(){$scope.$digest()}).then(setCaret);
810                 };
811
812                 var deleteDatafield = function (e) {
813                     var del_field = e.data.scope.field.position;
814
815                     var sf901c = e.data.scope.field.record.subfield('901','c');
816                     var recId = (sf901c === null) ? '' : sf901c[1];
817                     var domnode = $('#r' + recId + 'f' + del_field);
818
819                     e.data.scope.field.record.deleteFields(
820                         e.data.scope.field
821                     );
822
823                     domnode.scope().$destroy();
824                     domnode.remove();
825
826                     $scope.current_event_target = 'r' + $scope.caretRecId +
827                                                   'f' + del_field + 'tag';
828
829                     $scope.current_event_target_cursor_pos = 0;
830                     $scope.current_event_target_cursor_pos_end = 0
831                     $scope.force_render = true;
832
833                     $timeout(function(){$scope.$digest()}).then(setCaret);
834                 };
835
836                 var add006 = function (e) {
837                     e.data.scope.field.record.insertOrderedFields(
838                         new MARC21.Field({
839                             tag : '006',
840                             data : '                                        '
841                         })
842                     );
843
844                     $scope.force_render = true;
845                     $timeout(function(){$scope.$digest()}).then(setCaret);
846                 };
847
848                 var add007 = function (e) {
849                     e.data.scope.field.record.insertOrderedFields(
850                         new MARC21.Field({
851                             tag : '007',
852                             data : '                                        '
853                         })
854                     );
855
856                     $scope.force_render = true;
857                     $timeout(function(){$scope.$digest()}).then(setCaret);
858                 };
859
860                 var reify008 = function (e) {
861                     var new_008_data = e.data.scope.field.record.generate008();
862
863
864                     var old_008s = e.data.scope.field.record.field('008',true);
865                     old_008s.forEach(function(o) {
866                         var domnode = $('#r'+o.record.subfield('901','c')[1] + 'f' + o.position);
867                         domnode.scope().$destroy();
868                         domnode.remove();
869                         e.data.scope.field.record.deleteFields(o);
870                     });
871
872                     e.data.scope.field.record.insertOrderedFields(
873                         new MARC21.Field({
874                             tag : '008',
875                             data : new_008_data
876                         })
877                     );
878
879                     $scope.force_render = true;
880                     $timeout(function(){$scope.$digest()}).then(setCaret);
881                 };
882
883                 $scope.context_functions = {
884                     addDatafield : addDatafield,
885                     deleteDatafield : deleteDatafield,
886                     add006 : add006,
887                     add007 : add007,
888                     reify008 : reify008
889                 };
890
891                 $scope.onKeydown = function (event) {
892                     var event_return = true;
893
894                     console.log(
895                         'keydown: which='+event.which+
896                         ', ctrlKey='+event.ctrlKey+
897                         ', shiftKey='+event.shiftKey+
898                         ', altKey='+event.altKey+
899                         ', metaKey='+event.altKey
900                     );
901
902                     if (event.which == 89 && event.ctrlKey) { // ctrl+y, redo
903                         event_return = $scope.processRedo();
904                     } else if (event.which == 90 && event.ctrlKey) { // ctrl+z, undo
905                         event_return = $scope.processUndo();
906                     } else if ((event.which == 68 || event.which == 73) && event.ctrlKey) { // ctrl+d or ctrl+i, insert subfield
907
908                         var element = $(event.target);
909                         var new_sf, index_sf, move_data;
910
911                         if (element.hasClass('marcsfvalue')) {
912                             index_sf = event.data.scope.subfield[2];
913                             new_sf = index_sf + 1;
914
915                             var start = event.target.selectionStart || getCaretPosEditableDiv(element);
916                             var end;
917                             if (event.target.value){
918                                 end = event.target.selectionEnd - event.target.selectionStart ?
919                                         event.target.selectionEnd :
920                                         event.target.value.length;
921                             } else {
922                                 end = element.text().length;
923                             }
924
925                             move_data = element.value ?
926                                 element.value.substring(start,end) :
927                                 element.text().substring(start, end);
928
929                         } else if (element.hasClass('marcsfcode')) {
930                             index_sf = event.data.scope.subfield[2];
931                             new_sf = index_sf + 1;
932                         } else if (element.hasClass('marctag') || element.hasClass('marcind')) {
933                             index_sf = 0;
934                             new_sf = index_sf;
935                         }
936
937                         $scope.current_event_target = 'r' + $scope.caretRecId +
938                                                       'f' + event.data.scope.field.position + 
939                                                       's' + new_sf + 'code';
940
941                         event.data.scope.field.subfields.forEach(function(sf) {
942                             if (sf[2] >= new_sf) sf[2]++;
943                             if (sf[2] == index_sf) {
944                                 sf[1] = event.target.value ?
945                                     event.target.value.substring(0,start) + event.target.value.substring(end) :
946                                     element.text().substring(0, start);
947                             }
948                         });
949                         event.data.scope.field.subfields.splice(
950                             new_sf,
951                             0,
952                             [' ', move_data, new_sf ]
953                         );
954
955                         $scope.current_event_target_cursor_pos = 0;
956                         $scope.current_event_target_cursor_pos_end = 1;
957
958                         $timeout(function(){$scope.$digest()}).then(setCaret);
959
960                         event_return = false;
961
962                     } else if (event.which == 117 && event.shiftKey) { // shift + F6, insert 006
963                         add006(event);
964                         event_return = false;
965
966                     } else if (event.which == 118 && event.shiftKey) { // shift + F7, insert 007
967                         add007(event);
968                         event_return = false;
969
970                     } else if (event.which == 119 && event.shiftKey) { // shift + F8, insert/replace 008
971                         reify008(event);
972                         event_return = false;
973
974                     } else if (event.which == 13 && event.ctrlKey) { // ctrl+enter, insert datafield
975                         addDatafield(event, event.shiftKey); // shift key inserts before
976                         event_return = false;
977
978                     } else if (event.which == 13 &&
979                               ($(event.target).hasClass('marcsf') || $(event.target.parentNode).hasClass('marcsf'))
980                               ) {
981                         // bare return; don't allow it
982                         event_return = false;
983
984                     } else if (event.which == 46 && event.ctrlKey) { // ctrl+del, remove field
985                         deleteDatafield(event);
986                         event_return = false;
987
988                     } else if (event.which == 46 && event.shiftKey && ($(event.target).hasClass('marcsf') || $(event.target.parentNode).hasClass('marcsf'))) { 
989                         // shift+del, remove subfield
990
991                         var sf = event.data.scope.subfield[2] - 1;
992                         if (sf == -1) sf = 0;
993
994                         event.data.scope.field.deleteExactSubfields(
995                             event.data.scope.subfield
996                         );
997
998                         if (!event.data.scope.field.subfields[sf]) {
999                             $scope.current_event_target = 'r' + $scope.caretRecId +
1000                                                           'f' + event.data.scope.field.position + 
1001                                                           'tag';
1002                         } else {
1003                             $scope.current_event_target = 'r' + $scope.caretRecId +
1004                                                           'f' + event.data.scope.field.position + 
1005                                                           's' + sf + 'value';
1006                         }
1007
1008                         $scope.current_event_target_cursor_pos = 0;
1009                         $scope.current_event_target_cursor_pos_end = 0;
1010                         $scope.force_render = true;
1011
1012                         $timeout(function(){$scope.$digest()}).then(setCaret);
1013
1014                         event_return = false;
1015
1016                     } else if (event.keyCode == 38) {
1017                         if (event.ctrlKey) { // copy the field up
1018                             var index_field = event.data.scope.field.position;
1019
1020                             var field_obj;
1021                             if (event.data.scope.field.isControlfield()) {
1022                                 field_obj = new MARC21.Field({
1023                                     tag : event.data.scope.field.tag,
1024                                     data : event.data.scope.field.data
1025                                 });
1026                             } else {
1027                                 var sf_clone = [];
1028                                 for (var i in event.data.scope.field.subfields) {
1029                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
1030                                 }
1031                                 field_obj = new MARC21.Field({
1032                                     tag : event.data.scope.field.tag,
1033                                     ind1 : event.data.scope.field.ind1,
1034                                     ind2 : event.data.scope.field.ind2,
1035                                     subfields : sf_clone
1036                                 });
1037                             }
1038
1039
1040                             event.data.scope.field.record.insertFieldsBefore(
1041                                 event.data.scope.field,
1042                                 field_obj
1043                             );
1044
1045                             $scope.current_event_target = 'r' + $scope.caretRecId +
1046                                                           'f' + index_field + 'tag';
1047
1048                             $scope.current_event_target_cursor_pos = 0;
1049                             $scope.current_event_target_cursor_pos_end = 3;
1050                             $scope.force_render = true;
1051
1052                             $timeout(function(){$scope.$digest()}).then(setCaret);
1053
1054                         } else { // jump to prev field
1055                             if (event.data.scope.field.position > 0) {
1056                                 $timeout(function(){
1057                                     $scope.current_event_target_cursor_pos = 0;
1058                                     $scope.current_event_target_cursor_pos_end = 0;
1059                                     $scope.current_event_target = 'r' + $scope.caretRecId +
1060                                                                   'f' + (event.data.scope.field.position - 1) +
1061                                                                   'tag';
1062                                 }).then(setCaret);
1063                             }
1064                         }
1065
1066                         event_return = false;
1067
1068                     } else if (event.keyCode == 40) { // down arrow...
1069                         if (event.ctrlKey) { // copy the field down
1070
1071                             var index_field = event.data.scope.field.position;
1072                             var new_field = index_field + 1;
1073
1074                             var field_obj;
1075                             if (event.data.scope.field.isControlfield()) {
1076                                 field_obj = new MARC21.Field({
1077                                     tag : event.data.scope.field.tag,
1078                                     data : event.data.scope.field.data
1079                                 });
1080                             } else {
1081                                 var sf_clone = [];
1082                                 for (var i in event.data.scope.field.subfields) {
1083                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
1084                                 }
1085                                 field_obj = new MARC21.Field({
1086                                     tag : event.data.scope.field.tag,
1087                                     ind1 : event.data.scope.field.ind1,
1088                                     ind2 : event.data.scope.field.ind2,
1089                                     subfields : sf_clone
1090                                 });
1091                             }
1092
1093                             event.data.scope.field.record.insertFieldsAfter(
1094                                 event.data.scope.field,
1095                                 field_obj
1096                             );
1097
1098                             $scope.current_event_target = 'r' + $scope.caretRecId +
1099                                                           'f' + new_field + 'tag';
1100
1101                             $scope.current_event_target_cursor_pos = 0;
1102                             $scope.current_event_target_cursor_pos_end = 3;
1103                             $scope.force_render = true;
1104
1105                             $timeout(function(){$scope.$digest()}).then(setCaret);
1106
1107                         } else { // jump to next field
1108                             if (event.data.scope.field.record.fields[event.data.scope.field.position + 1]) {
1109                                 $timeout(function(){
1110                                     $scope.current_event_target_cursor_pos = 0;
1111                                     $scope.current_event_target_cursor_pos_end = 0;
1112                                     $scope.current_event_target = 'r' + $scope.caretRecId +
1113                                                                   'f' + (event.data.scope.field.position + 1) +
1114                                                                   'tag';
1115                                 }).then(setCaret);
1116                             }
1117                         }
1118
1119                         event_return = false;
1120
1121                     } else { // Assumes only marc editor elements have IDs that can trigger this event handler.
1122                         $scope.current_event_target = $(event.target).hasClass('focusable') ? $(event.target) : null;//.attr('id');
1123                         if ($scope.current_event_target) {
1124                             $scope.current_event_target_cursor_pos =
1125                                 event.target.selectionDirection=='backward' ?
1126                                     event.target.selectionStart :
1127                                     event.target.selectionEnd;
1128                         }
1129                     }
1130
1131                     return event_return;
1132                 };
1133
1134                 function setCaret() {
1135                     if ($scope.current_event_target) {
1136                         console.log("Putting caret in " + $scope.current_event_target);
1137                         if (!$scope.current_event_target_cursor_pos_end)
1138                             $scope.current_event_target_cursor_pos_end = $scope.current_event_target_cursor_pos
1139
1140                         var element = $('#'+$scope.current_event_target + " .focusable").get(0);
1141                         if (element) {
1142                             element.focus();
1143                             if (element.setSelectionRange) {
1144                                 element.setSelectionRange(
1145                                     $scope.current_event_target_cursor_pos,
1146                                     $scope.current_event_target_cursor_pos_end
1147                                 );
1148                             }
1149                         }
1150                         $scope.current_event_cursor_pos_end = null;
1151                         $scope.current_event_target = null;
1152                     }
1153                 }
1154
1155                 function getCaretPosEditableDiv(editableDiv){
1156                     var caretPos = 0, sel, range;
1157                     if (window.getSelection) {
1158                         sel = window.getSelection();
1159                         if (sel.rangeCount) {
1160                             range = sel.getRangeAt(0);
1161                             if (range.commonAncestorContainer.parentNode == editableDiv[0]) {
1162                                 caretPos = range.endOffset;
1163                             }
1164                         }
1165                     }
1166                     return caretPos;
1167                 }
1168
1169                 function loadRecord() {
1170                     return (function() {
1171                         var deferred = $q.defer();
1172                         if ($scope.recordId) {
1173                             egCore.pcrud.retrieve(
1174                                 $scope.record_type, $scope.recordId
1175                             ).then(function(rec) {
1176                                 deferred.resolve(rec);
1177                             });
1178                         } else {
1179                             if ($scope.recordType == 'bre') {
1180                                 var bre = new egCore.idl.bre();
1181                                 bre.marc($scope.marcXml);
1182                                 deferred.resolve(bre);
1183                             } else if ($scope.recordType == 'are') {
1184                                 var are = new egCore.idl.are();
1185                                 are.marc($scope.marcXml);
1186                                 deferred.resolve(are);
1187                             } else if ($scope.recordType == 'sre') {
1188                                 var sre = new egCore.idl.sre();
1189                                 sre.marc($scope.marcXml);
1190                                 deferred.resolve(sre);
1191                             }
1192                             $scope.brandNewRecord = true;
1193                         }
1194                         return deferred.promise;
1195                     })().then(function(rec) {
1196                         $scope.in_redo = true;
1197                         $scope[$scope.record_type] = rec;
1198                         $scope.record = new MARC21.Record({ marcxml : $scope.Record().marc() });
1199                         if (!$scope.recordId) {
1200                             var sf901c = $scope.record.subfield('901', 'c');
1201                             if (sf901c !== null) {
1202                                 $scope.caretRecId = sf901c[1];
1203                             }
1204                         }
1205                         $scope.calculated_record_type = $scope.record.recordType();
1206                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1207                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1208                         $scope.save_stack_depth = $scope.record_undo_stack.length;
1209                         $scope.dirtyFlag = false;
1210                         $scope.flat_text_marc = $scope.record.toBreaker();
1211
1212                         if ($scope.record_type == 'bre' && !$scope.brandNewRecord) {
1213                             $scope.bib_source.id = $scope.bibSource = rec.source(); //$scope.Record().source();
1214                         }
1215
1216                     }).then(function(){
1217                         return egTagTable.fetchFFPosTable($scope.calculated_record_type)
1218                     }).then(function(){
1219                         return egTagTable.fetchFFValueTable($scope.calculated_record_type)
1220                     }).then(setCaret);
1221                 }
1222
1223                 $scope.$watch('record.toBreaker()', function (newVal, oldVal) {
1224                     if (!$scope.in_undo && !$scope.in_redo && oldVal != newVal) {
1225                         $scope.record_undo_stack.push({
1226                             breaker: oldVal,
1227                             target: $scope.current_event_target,
1228                             pos: $scope.current_event_target_cursor_pos
1229                         });
1230
1231                         if ($scope.force_render) {
1232                             $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1233                             $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1234                             $scope.force_render = false;
1235                         }
1236
1237                         $scope.flat_text_marc = newVal;
1238                     }
1239
1240                     if ($scope.record_undo_stack.length != $scope.save_stack_depth) {
1241                         $scope.dirtyFlag = true;
1242                     } else {
1243                         $scope.dirtyFlag = false;
1244                     }
1245
1246                     if ($scope.record_undo_stack.length > $scope.max_undo)
1247                         $scope.record_undo_stack.shift();
1248
1249                     console.log('undo stack is ' + $scope.record_undo_stack.length + ' deep');
1250                     $scope.in_redo = false;
1251                     $scope.in_undo = false;
1252                 });
1253
1254                 $scope.processUndo = function () {
1255                     if ($scope.record_undo_stack.length) {
1256                         $scope.in_undo = true;
1257
1258                         var undo_item = $scope.record_undo_stack.pop();
1259                         $scope.record_redo_stack.push(undo_item);
1260
1261                         $scope.record = new MARC21.Record({ marcbreaker : undo_item.breaker });
1262                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1263                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1264
1265                         $scope.current_event_target = undo_item.target;
1266                         $scope.current_event_target_cursor_pos = undo_item.pos;
1267                         console.log('Undo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
1268
1269                         $timeout(function(){$scope.$digest()}).then(setCaret);
1270                         return false;
1271                     }
1272
1273                     return true;
1274                 };
1275
1276                 $scope.processRedo = function () {
1277                     if ($scope.record_redo_stack.length) {
1278                         $scope.in_redo = true;
1279
1280                         var redo_item = $scope.record_redo_stack.pop();
1281                         $scope.record_undo_stack.push(redo_item);
1282
1283                         $scope.record = new MARC21.Record({ marcbreaker : redo_item.breaker });
1284                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1285                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1286
1287                         $scope.current_event_target = redo_item.target;
1288                         $scope.current_event_target_cursor_pos = redo_item.pos;
1289                         console.log('Redo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
1290
1291                         $timeout(function(){$scope.$digest()}).then(setCaret);
1292                         return false;
1293                     }
1294
1295                     return true;
1296                 };
1297
1298                 $scope.Record = function () {
1299                     return $scope[$scope.record_type];
1300                 };
1301
1302                 $scope.deleteRecord = function () {
1303                     egConfirmDialog.open(
1304                         egCore.strings.CONFIRM_DELETE_RECORD,
1305                         (($scope.record_type == 'bre') ?
1306                             egCore.strings.CONFIRM_DELETE_BRE_MSG :
1307                             egCore.strings.CONFIRM_DELETE_ARE_MSG),
1308                         { id : $scope.recordId }
1309                     ).result.then(function() {
1310                         if ($scope.record_type == 'bre') {
1311                             egCore.net.request(
1312                                 'open-ils.cat',
1313                                 'open-ils.cat.biblio.record_entry.delete',
1314                                 egCore.auth.token(), $scope.recordId
1315                             ).then(function(resp) {
1316                                 var evt = egCore.evt.parse(resp);
1317                                 if (evt) {
1318                                     return egAlertDialog.open(
1319                                         egCore.strings.ALERT_DELETE_FAILED,
1320                                         { id : $scope.recordId, desc : evt.desc }
1321                                     );
1322                                 } else {
1323                                     loadRecord().then(processOnSaveCallbacks);
1324                                 }
1325                             });
1326                         } else {
1327                             $scope.Record().deleted(true);
1328                             return $scope.saveRecord();
1329                         }
1330                     });
1331                 };
1332
1333                 $scope.undeleteRecord = function () {
1334                     $scope.Record().deleted(false);
1335                     return $scope.saveRecord();
1336                 };
1337
1338                 $scope.validateHeadings = function () {
1339                     if ($scope.record_type != 'bre') return;
1340                     var chain = $q.when();
1341                     angular.forEach($scope.record.fields, function(f) {
1342                         if (!$scope.controlSet.bibFieldByTag(f.tag)) return;
1343                         // if heading already has a $0, assume it's good
1344                         if (f.subfield('0', true).length) {
1345                             f.heading_checked = true;
1346                             f.heading_valid = true;
1347                             return;
1348                         }
1349                         var auth_match = $scope.controlSet.bibToAuthorities(f);
1350                         if (auth_match.length == 0) return;
1351                         chain = chain.then(function() {
1352                             var promise = egCore.net.request(
1353                                 'open-ils.search',
1354                                 'open-ils.search.authority.simple_heading.from_xml.batch.atomic',
1355                                 auth_match[0]
1356                             ).then(function (matches) {
1357                                 f.heading_valid = false;
1358                                 if (matches[0]) { // probably set
1359                                     for (var cset in matches[0]) {
1360                                         var arr = matches[0][cset];
1361                                         if (arr.length) {
1362                                             // protect against errant empty string values
1363                                             if (arr.length == 1 && arr[0] == '')
1364                                                 continue;
1365                                             f.heading_valid = true;
1366                                             break;
1367                                         }
1368                                     }
1369                                 }
1370                                 f.heading_checked = true;
1371                             });
1372                             return promise;
1373                         });
1374                     });
1375                 }
1376
1377                 processOnSaveCallbacks = function() {
1378                     var deferred = $q.defer();
1379                     if (typeof $scope.onSaveCallback !== 'undefined') {
1380                         var promise = deferred.promise;
1381
1382                         angular.forEach($scope.onSaveCallback, function (f) {
1383                             if (angular.isFunction(f)) promise = promise.then(f);
1384                         });
1385
1386                     }
1387                     return deferred.resolve($scope.recordId)
1388                 };
1389
1390                 // Returns a promise 
1391                 function createOrUpdateRecord() {
1392
1393                     var promise;
1394                     if ($scope.recordId) {  
1395
1396                         var method = $scope.record_type === 'bre' ?
1397                             'open-ils.cat.biblio.record.xml.update' :
1398                             'open-ils.cat.authority.record.overlay';
1399
1400                         promise = egCore.net.request(
1401                             'open-ils.cat', method,
1402                             egCore.auth.token(), $scope.recordId, 
1403                             $scope.Record().marc(), $scope.bib_source.name
1404                         );
1405
1406                     } else {
1407
1408                         var method = $scope.record_type === 'bre' ?
1409                             'open-ils.cat.biblio.record.xml.create' :
1410                             'open-ils.cat.authority.record.import';
1411
1412                         promise = egCore.net.request(
1413                             'open-ils.cat', method,
1414                             egCore.auth.token(), 
1415                             $scope.Record().marc(),
1416                             $scope.bib_source.name
1417                         );
1418                     }
1419
1420                     return promise.then(handleCreateOrUpdateResult);
1421                 }
1422
1423                 function handleCreateOrUpdateResult(result) {
1424
1425                     var evt = egCore.evt.parse(result)
1426                     var mode = $scope.recordId ? 'update' : 'create';
1427
1428                     if (evt) {
1429                         var msg = mode === 'update' ? 
1430                             egStrings.MARC_ALERT_UPDATE_FAILED :
1431                             egStrings.MARC_ALERT_CREATE_FAILED;
1432                         ngToast.warning(msg, {error: '' + evt});
1433                         return $q.reject();
1434                     }
1435
1436                     var msg = mode === 'update' ? 
1437                         egStrings.MARC_ALERT_UPDATE_SUCCESS :
1438                         egStrings.MARC_ALERT_CREATE_SUCCESS;
1439                     ngToast.create(msg);
1440
1441                     console.debug('MARC create/update returned', result);
1442
1443                     // synchronize values 
1444                     if (!$scope.recordId) {
1445                         $scope.recordId = $scope.caretRecId = result.id(); 
1446                     }
1447
1448                     $scope.dirtyFlag = false;
1449
1450                     return result;
1451                 }
1452
1453                 $scope.saveRecord = function () {
1454                     
1455                     if ($scope.inPlaceMode) {
1456                         $scope.marcXml = $scope.record.toXmlString();
1457                         
1458                         if ($scope.record_type == 'bre'){
1459                             $scope.bibSource = $scope.bib_source.id;
1460                         }
1461
1462                         return $timeout(processOnSaveCallbacks);
1463                     }
1464
1465                     $scope.mangle_005();
1466                     $scope.record.pruneEmptyFieldsAndSubfields();
1467                     $scope.Record().marc($scope.record.toXmlString());
1468
1469                     var updating = Boolean($scope.recordId);
1470                     return createOrUpdateRecord().then(function(record) {
1471
1472                         if (updating) {
1473                             $scope.save_stack_depth = $scope.record_undo_stack.length;
1474                         }
1475
1476                         if (!$scope.enable_fast_add) {
1477                             return record;
1478                         }
1479
1480                         egCore.net.request(
1481                             'open-ils.actor',
1482                             'open-ils.actor.anon_cache.set_value',
1483                             null, 'edit-these-copies', {
1484                                 record_id: $scope.recordId,
1485                                 raw: [{
1486                                     label : $scope.fast_item_callnumber,
1487                                     barcode : $scope.fast_item_barcode,
1488                                     fast_add : true
1489                                 }],
1490                                 hide_vols : false,
1491                                 hide_copies : false
1492                             }
1493                         ).then(function(key) {
1494                             if (key) {
1495                                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
1496                                 $timeout(function() { $window.open(url, '_blank') });
1497                             } else {
1498                                 alert('Could not create anonymous cache key!');
1499                             }
1500                         });
1501                     }).then(loadRecord).then(processOnSaveCallbacks);
1502                 };
1503
1504                 $scope.seeBreaker = function () {
1505                     alert($scope.record.toBreaker());
1506                 };
1507
1508                 $scope.$watch('recordId',
1509                     function(newVal, oldVal) {
1510                         if (newVal && newVal !== oldVal) {
1511                             loadRecord();
1512                         }
1513                     }
1514                 );
1515                 $scope.$watch('marcXml',
1516                     function(newVal, oldVal) {
1517                         if (newVal && newVal !== oldVal) {
1518                             loadRecord();
1519                         }
1520                     }
1521                 );
1522
1523                 var unregister = $scope.$watch(function() {
1524                     return egTagTable.initialized();
1525                 }, function(val) {
1526                     if (val) {
1527                         unregister();
1528                         if ($scope.recordId || $scope.marcXml) {
1529                             loadRecord();
1530                         }
1531                     }
1532                 });
1533
1534                 $scope.mangle_005 = function () {
1535                     var now = new Date();
1536                     var y = now.getUTCFullYear();
1537                 
1538                     var m = now.getUTCMonth() + 1;
1539                     if (m < 10) m = '0' + m;
1540                 
1541                     var d = now.getUTCDate();
1542                     if (d < 10) d = '0' + d;
1543                 
1544                     var H = now.getUTCHours();
1545                     if (H < 10) H = '0' + H;
1546                 
1547                     var M = now.getUTCMinutes();
1548                     if (M < 10) M = '0' + M;
1549                 
1550                     var S = now.getUTCSeconds();
1551                     if (S < 10) S = '0' + S;
1552                 
1553                     var stamp = '' + y + m + d + H + M + S + '.0';
1554                     var f = $scope.record.field('005',true)[0];
1555                     if (f) {
1556                         f.data = stamp;
1557                     } else {
1558                         $scope.record.insertOrderedFields(
1559                             new MARC21.Field({
1560                                 tag : '005',
1561                                 data: stamp
1562                             })
1563                         );
1564                     }
1565                 
1566                 }
1567
1568             }
1569         ]          
1570     }
1571 })
1572
1573 .directive("egMarcEditBibsource", ['$timeout',function ($timeout) {
1574     return {
1575         restrict: 'E',
1576         replace: true,
1577         template: '<span class="nullable">'+
1578                     '<select class="form-control" ng-model="bib_source.id" ng-options="s.id() as s.source() for s in bib_sources | orderBy: \'source()\'">'+
1579                       '<option value="">Select a Source</option>'+
1580                     '</select>'+
1581                   '</span>',
1582         controller: ['$scope','egCore',
1583             function ($scope , egCore) {
1584
1585                 egCore.pcrud.retrieveAll('cbs', {}, {atomic : true})
1586                     .then(function(list) {
1587                         $scope.bib_sources = list;
1588                     });
1589
1590                 $scope.$watch('bib_source.id',
1591                     function(newVal, oldVal) {
1592                         if (newVal !== oldVal) {
1593                             $scope.bre.source(newVal);
1594                             var cbs = $scope.bib_sources.filter(function(s) { return s.id() == newVal });
1595                             $scope.$parent.bib_source.name = (cbs && cbs[0]) ? cbs[0].source() : null;
1596                         }
1597                     }
1598                 );
1599
1600             }
1601         ]
1602     }
1603 }])
1604
1605 .directive("egMarcEditAuthorityLinker", function () {
1606     return {
1607         restrict: 'E',
1608         replace: true,
1609         templateUrl: './cat/share/t_authority_linker',
1610         scope : {
1611             bibField : '=',
1612             controlSet : '=',
1613             changed : '='
1614         },
1615         controller: ['$scope','$uibModal','egCore','egAuth',
1616             function ($scope , $uibModal,  egCore,  egAuth) {
1617
1618                 $scope.searchStr = '';
1619                 var cni = egCore.env.aous['cat.marc_control_number_identifier'] ||
1620                   'Set cat.marc_control_number_identifier in Library Settings';
1621
1622                 var axis_list = $scope.controlSet.bibFieldBrowseAxes($scope.bibField.tag);
1623                 $scope.axis = axis_list[0];
1624
1625                 $scope._controlled_sf_list = {};
1626                 $scope._controlled_auth_sf_list = {};
1627                 var found_acs = [];
1628                 angular.forEach($scope.controlSet.controlSetList(), function(acs_id) {
1629                     if ($scope.controlSet.controlSet(acs_id).control_map[$scope.bibField.tag])
1630                         found_acs.push(acs_id);
1631                 });
1632                 if (found_acs.length) {
1633                      angular.forEach($scope.controlSet.controlSet(found_acs[0]).control_map[$scope.bibField.tag],
1634                         function(value, sf_label) {
1635                             $scope._controlled_sf_list[ sf_label ] = 1;
1636                             angular.forEach($scope.controlSet.controlSet(found_acs[0]).control_map[$scope.bibField.tag][sf_label],
1637                                 function(auth_sf, auth_tag) {
1638                                     if (!$scope._controlled_auth_sf_list[auth_tag]) {
1639                                         $scope._controlled_auth_sf_list[auth_tag] = { };
1640                                     }
1641                                     $scope._controlled_auth_sf_list[auth_tag][auth_sf] = 1;
1642                                 }
1643                             );
1644                         }
1645                     )
1646                 }
1647
1648                 $scope.bibField.subfields.forEach(function (sf) {
1649                     if (sf[0] in $scope._controlled_sf_list) {
1650                         sf.selected = true;
1651                         sf.selectable = true;
1652                     } else {
1653                         sf.selectable = false;
1654                     }
1655                 });
1656                 $scope.summarizeField = function() {
1657                     var source_f = {
1658                         'tag': $scope.bibField.tag,
1659                         'ind1': $scope.bibField.ind1,
1660                         'ind2': $scope.bibField.ind2,
1661                         'subfields': []
1662                     };
1663                     $scope.bibField.subfields.forEach(function(sf) {
1664                         if (sf.selected) {
1665                             source_f.subfields.push([ sf[0], sf[1] ]);
1666                         }
1667                     });
1668                     return source_f;
1669                 }
1670                 $scope.getSearchString = function() {
1671                     var source_f = $scope.summarizeField();
1672                     var values = [];
1673                     angular.forEach(source_f.subfields, function(val) {
1674                         values.push(val[1]);
1675                     });
1676                     return values.join(' ');
1677                 }
1678                 $scope.searchStr = $scope.getSearchString();
1679                 $scope.$watch(function() {
1680                     var ct = 0;
1681                     angular.forEach($scope.bibField.subfields, function(sf) {
1682                         if (sf.selected) ct++
1683                         });
1684                     return ct;
1685                 },
1686                 function(newVal, oldVal) {
1687                     $scope.searchStr = $scope.getSearchString();
1688                 });
1689
1690                 $scope.updateSubfieldZero = function(value) {
1691                     $scope.changed = true;
1692                     $scope.bibField.deleteSubfield({ code : ['0'] });
1693                     $scope.bibField.subfields.push([
1694                         '0', '(' + cni + ')' + value
1695                     ]);
1696                 };
1697
1698                 $scope.applyHeading = function(headingField) {
1699                     // TODO: move the MARC21 rules for copying indicators
1700                     // out of here
1701                     if (headingField.tag == '130' && $scope.bibField.tag == '130') {
1702                         $scope.bibField.ind1 = headingField.ind2;
1703                     } else {
1704                         $scope.bibField.ind1 = headingField.ind1;
1705                     }
1706                     // deal with 4xx and 5xx
1707                     var authFallbackTag = '1' + headingField.tag.substr(1, 2);
1708                     var _valid_auth_sfs = (headingField.tag in $scope._controlled_auth_sf_list) ?
1709                                           $scope._controlled_auth_sf_list[headingField.tag] :
1710                                           (authFallbackTag in $scope._controlled_auth_sf_list) ?
1711                                           $scope._controlled_auth_sf_list[authFallbackTag] :
1712                                           [];
1713                     // save the $0 for later use
1714                     var sfZero = '';
1715                     if (headingField.subfield('0')) {
1716                         sfZero = headingField.subfield('0')[1];
1717                     }
1718                     // grab any bib subfields not under authority control
1719                     // TODO do something about uncontrolled subdivisions
1720                     var uncontrolledBibSf = [];
1721                     angular.forEach($scope.bibField.subfields, function(sf) {
1722                         if (!(sf[0] in $scope._controlled_sf_list) && (sf[0] != '0')) {
1723                             uncontrolledBibSf.push([ sf[0], sf[1] ]);
1724                         }
1725                     });
1726                     // grab the authority subfields
1727                     var authoritySf = [];
1728                     angular.forEach(headingField.subfields, function(sf) {
1729                         if (sf[0] in _valid_auth_sfs) {
1730                             authoritySf.push([ sf[0], sf[1] ]);
1731                         }
1732                     });
1733                     $scope.bibField.subfields.length = 0;
1734                     angular.forEach(authoritySf, function(sf) {
1735                         $scope.bibField.addSubfields(sf[0], sf[1]);
1736                     });
1737                     angular.forEach(uncontrolledBibSf, function(sf) {
1738                         $scope.bibField.addSubfields(sf[0], sf[1]);
1739                     });
1740                     if (sfZero) {
1741                         $scope.bibField.addSubfields('0', sfZero);
1742                     }
1743                     $scope.bibField.subfields.forEach(function (sf) {
1744                     if (sf[0] in $scope._controlled_sf_list) {
1745                             // intentionally not selecting any subfields
1746                             // after we've applied an authority heading
1747                             sf.selected = false;
1748                             sf.selectable = true;
1749                         } else {
1750                             sf.selectable = false;
1751                         }
1752                     });
1753                     $scope.changed = true;
1754                 }
1755
1756                 $scope.createAuthorityFromBib = function(spawn_editor) {
1757                     var source_f = $scope.summarizeField();
1758
1759                     var args = { authority_id : 0 };
1760                     var method = (spawn_editor) ?
1761                         'open-ils.cat.authority.record.create_from_bib.readonly' :
1762                         'open-ils.cat.authority.record.create_from_bib';
1763                     egCore.net.request(
1764                         'open-ils.cat',
1765                         method,
1766                         source_f,
1767                         cni,
1768                         egAuth.token()
1769                     ).then(function(newAuthority) {
1770                         if (spawn_editor) {
1771                             $uibModal.open({
1772                                 templateUrl: './cat/share/t_edit_new_authority',
1773                                 size: 'lg',
1774                                 controller:
1775                                     ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
1776                                     $scope.focusMe = true;
1777                                     $scope.args = args;
1778                                     $scope.dirty_flag = false;
1779                                     $scope.marc_xml = newAuthority,
1780                                     $scope.ok = function(args) { $uibModalInstance.close(args) }
1781                                     $scope.cancel = function () { $uibModalInstance.dismiss() }
1782                                 }]
1783                             }).result.then(function (args) {
1784                                 if (!args || !args.authority_id) return;
1785                                 $scope.updateSubfieldZero(args.authority_id);
1786                             });
1787                         } else {
1788                             $scope.updateSubfieldZero(newAuthority.id());
1789                         }
1790                     });
1791                 }
1792
1793             }
1794         ]
1795     }
1796 })
1797
1798 .directive("egPhyscharWizard", ['$sce', function ($sce) {
1799     return {
1800         restrict: 'E',
1801         replace: true,
1802         templateUrl: './cat/share/t_physchar_wizard',
1803         scope : {
1804             field : '='
1805         },
1806         controller: ['$scope','$q','egTagTable',
1807             function ($scope , $q , egTagTable) {
1808
1809                 // $scope.step is the 1-based position in the list of 
1810                 // subfields for the currently selected type.
1811                 // step==0 means we are currently selecting the type
1812                 $scope.step = 0;
1813
1814                 // position and offset of the "subfields" we're
1815                 // currently editing; this is maintained as a convenience
1816                 // for the highlighting of the currently active position
1817                 $scope.offset = 0;
1818                 $scope.len = 1;
1819
1820                 if (!$scope.field.data) 
1821                     $scope.field.data = '';
1822
1823                 // currently selected subfield value selector option
1824                 $scope.selected_option = null;
1825
1826                 function current_ptype() {
1827                     return $scope.field.data.substr(0, 1);   
1828                 }
1829
1830                 function current_subfield() {
1831                     return egTagTable.getPhysCharSubfieldMap(current_ptype())
1832                     .then(function(sf_list) {return sf_list[$scope.step-1]});
1833                 }
1834
1835                 $scope.values_for_step = [];
1836                 function set_values_for_step() {
1837                     var promise;
1838
1839                     if ($scope.step == 0) {
1840                         $scope.offset = 0;
1841                         $scope.len    = 1;
1842                         promise = egTagTable.getPhysCharTypeMap();
1843                     } else {
1844                         promise = current_subfield().then(
1845                             function(subfield) {
1846                                 return egTagTable
1847                                     .getPhysCharValueMap(subfield.id());
1848                             }
1849                         );
1850                     }
1851
1852                     return promise.then(function(list) { 
1853                         $scope.values_for_step = list;
1854                         set_selected_option_from_field();
1855                         set_label_for_step();
1856                     });
1857                 }
1858
1859                 $scope.change_ptype = function(option) {
1860                     $scope.selected_option = option;
1861                     var new_val = option.ptype_key();
1862                     if (current_ptype() != new_val) {
1863                         $scope.field.data = new_val; // total reset
1864                     }
1865                 }
1866
1867                 $scope.change_option = function(option) {
1868                     $scope.selected_option = option;
1869                     var new_val = option.value();
1870                     get_step_slot().then(function(slot) {
1871                         var value = $scope.field.data;
1872                         while (value.length < (slot[0] + slot[1])) 
1873                             value += ' ';
1874                         var before = value.substr(0, slot[0]);
1875                         var after = value.substr(slot[0] + slot[1]);
1876                         $scope.field.data = 
1877                             before + new_val.substr(0, slot[1]) + after;
1878                         $scope.offset = slot[0];
1879                         $scope.len    = slot[1];
1880                     });
1881                 }
1882
1883                 function get_step_slot() {
1884                     if ($scope.step == 0) return $q.when([0, 1]);
1885                     return current_subfield().then(function(sf) {
1886                         return [sf.start_pos(), sf.length()]
1887                     });
1888                 }
1889
1890                 $scope.is_last_step = function() {
1891                     // This one is called w/ every digest, so avoid async
1892                     // calls.  Wait until we have loaded the current ptype
1893                     // subfields to determine if this is the last step.
1894                     return (
1895                         current_ptype() && 
1896                         egTagTable.phys_char_sf_map[current_ptype()] &&
1897                         egTagTable.phys_char_sf_map[current_ptype()].length 
1898                             == $scope.step
1899                     );
1900                 }
1901
1902                 $scope.label_for_step = '';
1903                 function set_label_for_step() {
1904                     if ($scope.step > 0) {
1905                         current_subfield().then(function(sf) {
1906                             $scope.label_for_step = sf.label();
1907                         });
1908                     }
1909                 }
1910                 
1911                 $scope.next_step = function() {
1912                     $scope.step++;
1913                     set_values_for_step();
1914                 }
1915
1916                 $scope.prev_step = function() {
1917                     $scope.step--;
1918                     set_values_for_step();
1919                 }
1920
1921                 function set_selected_option_from_field() {
1922                     if ($scope.step == 0) {
1923                         $scope.selected_option = $scope.values_for_step
1924                         .filter(function(opt) {
1925                             return (opt.ptype_key() == current_ptype())})[0];
1926                     } else {
1927                         get_step_slot().then(function(slot) {
1928                             $scope.offset = slot[0];
1929                             $scope.len    = slot[1];
1930                             var val = String.prototype.substr.apply(                      
1931                                 $scope.field.data, slot);
1932                             if (val) {
1933                                 $scope.selected_option = $scope.values_for_step
1934                                 .filter(function(opt) { 
1935                                     return (opt.value() == val)})[0];
1936                             } else {
1937                                 $scope.selected_option = null;
1938                             }
1939                         })
1940                     }
1941                 }
1942
1943                 $scope.highlightedFieldData = function() {
1944                     if (
1945                             $scope.len && $scope.field.data &&
1946                             $scope.field.data.length > 0 &&
1947                             $scope.field.data.length >= $scope.offset
1948                         ) {
1949                         return $sce.trustAsHtml(
1950                             $scope.field.data.substring(0, $scope.offset) + 
1951                             '<span class="active-physchar">' +
1952                             $scope.field.data.substr($scope.offset, $scope.len) +
1953                             '</span>' +
1954                             $scope.field.data.substr($scope.offset + $scope.len)
1955                         );
1956                     } else {
1957                         return $scope.field.data;
1958                     }
1959                 };
1960
1961                 set_values_for_step();
1962             }
1963         ]
1964     }
1965 }])
1966
1967
1968 .directive("egMarcEditAuthorityBrowser", function () {
1969     return {
1970         restrict: 'E',
1971         replace: true,
1972         templateUrl: './cat/share/t_authority_browser',
1973         scope : {
1974             searchString : '=',
1975             controlSet : '=',
1976             axis : '=',
1977             applyHeading : '&'
1978         },
1979         controller: ['$scope','$http',
1980             function ($scope , $http) {
1981
1982                 $scope.page = 0;
1983                 $scope.limit = 5;
1984                 $scope.main_headings = [];
1985
1986                 function getHeadingString(headingField) {
1987                     var heading = '';
1988                     angular.forEach(headingField.subfields, function (sf) {
1989                         if (['x', 'y', 'z'].indexOf(sf[0]) > -1) {
1990                             heading += ' --';
1991                         }
1992                         if (heading) {
1993                             heading += ' ';
1994                         }
1995                         heading += sf[1];
1996                     });
1997                     return heading;
1998                 }
1999
2000                 $scope.doBrowse = function() {
2001                     $scope.main_headings.length = 0;
2002                     if ($scope.searchString.length == 0) return;
2003                     var type = 'authority.'
2004                     var url = '/opac/extras/browse/marcxml/'
2005                             + 'authority.' + $scope.axis + '.refs'
2006                             + '/1' // OU - currently unscoped
2007                             + '/' + $scope.searchString
2008                             + '/' + $scope.page
2009                             + '/' + $scope.limit;
2010                     $http({
2011                         url : url,
2012                         method : 'GET',
2013                         transformResponse : function(data) {
2014                             // use a bit of jQuery to deal with the XML
2015                             var $xml = $( $.parseXML(data) );
2016                             var marc = [];
2017                             $xml.find('record').each(function() {
2018                                 var rec = new MARC21.Record();
2019                                 rec.fromXmlDocument($(this)[0].outerHTML);
2020                                 marc.push(rec);
2021                             });
2022                             return marc;
2023                         }
2024                     }).then(function(response) {
2025                         angular.forEach(response.data, function(rec) {
2026                             var authId = rec.subfield('901', 'c')[1];
2027                             var auth_org = '';
2028                             if (rec.field('003')) {
2029                                 auth_org = rec.field('003').data;
2030                             }
2031                             var headingField = rec.field('1..');
2032                             var seeFroms = rec.field('4..', true);
2033                             var seeAlsos = rec.field('5..', true);
2034
2035                             var main_heading = {
2036                                 authority_id : authId,
2037                                 heading : getHeadingString(headingField),
2038                                 seealso_headings : [ ],
2039                                 seefrom_headings : [ ],
2040                             };
2041
2042                             var sfZero = '';
2043                             if (auth_org) {
2044                                 sfZero = '(' + auth_org + ')';
2045                             }
2046                             sfZero += authId;
2047                             headingField.addSubfields('0', sfZero);
2048
2049                             main_heading['headingField'] = headingField;
2050                             angular.forEach(seeAlsos, function(headingField) {
2051                                 main_heading.seealso_headings.push({
2052                                     heading : getHeadingString(headingField),
2053                                     headingField : headingField
2054                                 });
2055                             });
2056                             angular.forEach(seeFroms, function(headingField) {
2057                                 main_heading.seefrom_headings.push({
2058                                     heading : getHeadingString(headingField),
2059                                     headingField : headingField
2060                                 });
2061                             });
2062                             $scope.main_headings.push(main_heading);
2063                         });
2064                     });
2065                 }
2066
2067                 $scope.$watch('searchString',
2068                     function(newVal, oldVal) {
2069                         if (newVal !== oldVal) {
2070                             $scope.doBrowse();
2071                         }
2072                     }
2073                 );
2074                 $scope.$watch('page',
2075                     function(newVal, oldVal) {
2076                         if (newVal !== oldVal) {
2077                             $scope.doBrowse();
2078                         }
2079                     }
2080                 );
2081
2082                 $scope.doBrowse();
2083             }
2084         ]
2085     }
2086 })
2087
2088 ;