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