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