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