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