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