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