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