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