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