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