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