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