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