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