]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/services/marcedit.js
webstaff: teach MARC editor how to build context menus for subfield values
[working/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: '=' },
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.style.borderTop = 'solid 1px';
18                 }
19
20                 $scope.setContent = function (v, a) {
21                     var replace_with = v;
22                     if (a) replace_with = a($scope,$element,$scope.item.value,$scope.$parent.$parent.content);
23                     $timeout(function(){
24                         $scope.$parent.$parent.$apply(function(){
25                             $scope.$parent.$parent.content = replace_with
26                         })
27                     }, 0);
28                     $($element).parent().css({display: 'none'});
29                 }
30             }
31         ]
32     }
33 }])
34
35 .directive("egMarcEditEditable", ['$timeout', '$compile', '$document', function ($timeout, $compile, $document) {
36     return {
37         restrict: 'E',
38         replace: true,
39         template: '<input '+
40                       'style="font-family: \'Lucida Console\', Monaco, monospace;" '+
41                       'ng-model="content" '+
42                       'size="{{content.length * 1.1}}" '+
43                       'maxlength="{{max}}" '+
44                       'class="" '+
45                       'type="text" '+
46                   '/>',
47         scope: {
48             field: '=',
49             onKeydown: '=',
50             subfield: '=',
51             content: '=',
52             contextItemContainer: '@',
53             contextItemGenerator: '=',
54             max: '@',
55             itype: '@'
56         },
57         controller : ['$scope',
58             function ( $scope ) {
59
60                 if ($scope.contextItemContainer && angular.isArray($scope.$parent[$scope.contextItemContainer]))
61                     $scope.item_container = $scope.$parent[$scope.contextItemContainer];
62                 else if ($scope.contextItemGenerator)
63                     $scope.item_container = $scope.contextItemGenerator();
64
65                 $scope.showContext = function (event) {
66                     if ($scope.context_menu_element) {
67                         console.log('Reshowing context menu...');
68                         $('body').trigger('click');
69                         $($scope.context_menu_element).css({ display: 'block', top: event.pageY, left: event.pageX });
70                         $('body').on('click.context_menu',function() {
71                             $($scope.context_menu_element).css('display','none');
72                             $('body').off('click.context_menu');
73                         });
74                         return false;
75                     }
76
77                     if (angular.isArray($scope.item_container)) { // we have a list of values or transforms
78                         console.log('Showing context menu...');
79                         $('body').trigger('click');
80
81                         var tmpl = 
82                             '<ul class="dropdown-menu" role="menu">'+
83                                 '<eg-context-menu-item ng-repeat="item in item_container" item="item" content="content"/>'+
84                             '</ul>';
85             
86                         var tnode = angular.element(tmpl);
87                         $document.find('body').append(tnode);
88
89                         $(tnode).css({
90                             display: 'block',
91                             top: event.pageY,
92                             left: event.pageX
93                         });
94
95                         $scope.context_menu_element = tnode;
96
97                         $timeout(function() {
98                             var e = $compile(tnode)($scope);
99                         }, 0);
100
101
102                         $('body').on('click.context_menu',function() {
103                             $(tnode).css('display','none');
104                             $('body').off('click.context_menu');
105                         });
106
107                         return false;
108                     }
109             
110                     return true;
111                 }
112
113             }
114         ],
115         link: function (scope, element, attrs) {
116
117             if (scope.onKeydown) element.bind('keydown', {scope : scope}, scope.onKeydown);
118
119             element.bind('change', function (e) { element.size = scope.max || parseInt(scope.content.length * 1.1) });
120
121             if (scope.item_container && scope.item_container.length)
122                 element.bind('contextmenu', scope.showContext);
123         }
124     }
125 }])
126
127 .directive("egMarcEditFixedField", ['$timeout', '$compile', '$document', function ($timeout, $compile, $document) {
128     return {
129         transclude: true,
130         restrict: 'E',
131         template: '<div class="col-md-2">'+
132                     '<div class="col-md-1"><label name="{{fixedField}}" for="{{fixedField}}_ff_input">{{fixedField}}</label></div>'+
133                     '<div class="col-md-1"><input type="text" style="padding-left: 5px; margin-left: 1em" size="4" id="{{fixedField}}_ff_input"/></div>'+
134                   '</div>',
135         scope: { record: "=", fixedField: "@" },
136         replace: true,
137         controller : ['$scope', '$element', 'egTagTable',
138             function ( $scope ,  $element ,  egTagTable) {
139                 $($element).children().css({ display : 'none' });
140                 $scope.me = null;
141                 $scope.content = null; // this is where context menus dump their values
142                 $scope.item_container = [];
143                 $scope.in_handler = false;
144                 $scope.ready = false;
145
146                 $scope.$watch('content', function (newVal, oldVal) {
147                     var input = $($element).find('input');
148                     input.val(newVal);
149                     input.trigger('keyup'); // cascade the update
150                 });
151
152                 $scope.$watch('record.ready', function (newVal, oldVal) { // wait for the record to be loaded
153                     if (newVal && !$scope.ready) {
154                         $scope.rtype = $scope.record.recordType();
155
156                         egTagTable.fetchFFPosTable( $scope.rtype ).then(function (ff_list) {
157                             angular.forEach(ff_list, function (ff) {
158                                 if (!$scope.me) {
159                                     if (ff.fixed_field == $scope.fixedField && ff.rec_type == $scope.rtype) {
160                                         $scope.me = ff;
161                                         $scope.ready = true;
162                                         $($element).children().css({ display : 'inline' });
163
164                                         var input = $($element).find('input');
165                                         input.attr('maxlength', $scope.me.length);
166                                         input.val($scope.record.extractFixedField($scope.me.fixed_field));
167                                         input.on('keyup', function(e) {
168                                             $scope.in_handler = true;
169                                             $scope.record.setFixedField($scope.me.fixed_field, input.val());
170                                             try { $scope.$parent.$digest(); } catch(e) {};
171                                         });
172                                     }
173                                 }
174                             });
175                             return $scope.me;
176                         }).then(function (me) {
177                             if (me) {
178                                 $scope.$watch(
179                                     function() {
180                                         return $scope.record.extractFixedField($scope.fixedField);
181                                     },
182                                     function (newVal, oldVal) {
183                                         if ($scope.in_handler) {
184                                             $scope.in_handler = false;
185                                         } else if (oldVal != newVal) {
186                                             $($element).find('input').val(newVal);
187                                         }
188                                     }
189                                 );
190                             }
191                         }).then(function () {
192                             return egTagTable.fetchFFValueTable( $scope.rtype );
193                         }).then(function (vlist) {
194                             if (vlist[$scope.fixedField]) {
195                                 vlist[$scope.fixedField].forEach(function (v) {
196                                     if (v[0].length <= v[2]) {
197                                         $scope.item_container.push({ value : v[0], label : v[0] + ': ' + v[1] });
198                                     }
199                                 });
200                             }
201                         }).then(function () {
202                             if ($scope.item_container && $scope.item_container.length)
203                                 $($element).bind('contextmenu', $scope.showContext);
204                         });
205
206                     }
207                 });
208
209                 $scope.showContext = function (event) {
210                     if ($scope.context_menu_element) {
211                         console.log('Reshowing context menu...');
212                         $('body').trigger('click');
213                         $($scope.context_menu_element).css({ display: 'block', top: event.pageY, left: event.pageX });
214                         $('body').on('click.context_menu',function() {
215                             $($scope.context_menu_element).css('display','none');
216                             $('body').off('click.context_menu');
217                         });
218                         return false;
219                     }
220
221                     if (angular.isArray($scope.item_container)) { // we have a list of values or transforms
222                         console.log('Showing context menu...');
223                         $('body').trigger('click');
224
225                         var tmpl = 
226                             '<ul class="dropdown-menu" role="menu">'+
227                                 '<eg-context-menu-item ng-repeat="item in item_container" item="item" content="content"/>'+
228                             '</ul>';
229             
230                         var tnode = angular.element(tmpl);
231                         $document.find('body').append(tnode);
232
233                         $(tnode).css({
234                             display: 'block',
235                             top: event.pageY,
236                             left: event.pageX
237                         });
238
239                         $scope.context_menu_element = tnode;
240
241                         $timeout(function() {
242                             var e = $compile(tnode)($scope);
243                         }, 0);
244
245
246                         $('body').on('click.context_menu',function() {
247                             $(tnode).css('display','none');
248                             $('body').off('click.context_menu');
249                         });
250
251                         return false;
252                     }
253             
254                     return true;
255                 }
256
257             }
258         ]
259     }
260 }])
261
262 .directive("egMarcEditSubfield", function () {
263     return {
264         transclude: true,
265         restrict: 'E',
266         template: '<span>'+
267                     '<span><label class="marcedit marcsfcodedelimiter"'+
268                         'for="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}s{{subfield[2]}}code" '+
269                         '>‡</label><eg-marc-edit-editable '+
270                         'itype="sfc" '+
271                         'class="marcedit marcsf marcsfcode" '+
272                         'field="field" '+
273                         'subfield="subfield" '+
274                         'content="subfield[0]" '+
275                         'max="1" '+
276                         'on-keydown="onKeydown" '+
277                         'context-item-generator="sf_code_options" '+
278                         'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}s{{subfield[2]}}code" '+
279                     '/></span>'+
280                     '<span><eg-marc-edit-editable '+
281                         'itype="sfv" '+
282                         'class="marcedit marcsf marcsfvalue" '+
283                         'field="field" '+
284                         'subfield="subfield" '+
285                         'content="subfield[1]" '+
286                         'on-keydown="onKeydown" '+
287                         'context-item-generator="sf_val_options" '+
288                         'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}s{{subfield[2]}}value" '+
289                     '/></span>'+
290                   '</span>',
291         scope: { field: "=", subfield: "=", onKeydown: '=' },
292         replace: true,
293         controller : ['$scope', 'egTagTable',
294             function ( $scope ,  egTagTable) {
295
296                 $scope.sf_code_options = function () {
297                     return egTagTable.getSubfieldCodes($scope.field.tag);
298                 }
299                 $scope.sf_val_options = function () {
300                     return egTagTable.getSubfieldValues($scope.field.tag, $scope.subfield[0]);
301                 }
302             }
303         ]
304     }
305 })
306
307 .directive("egMarcEditInd", function () {
308     return {
309         transclude: true,
310         restrict: 'E',
311         template: '<span><eg-marc-edit-editable '+
312                       'itype="ind" '+
313                       'class="marcedit marcind" '+
314                       'field="field" '+
315                       'content="ind" '+
316                       'max="1" '+
317                       'on-keydown="onKeydown" '+
318                       'context-item-generator="ind_val_options" '+
319                       'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}i{{indNumber}}"'+
320                       '/></span>',
321         scope: { ind : '=', field: '=', onKeydown: '=', indNumber: '@' },
322         replace: true,
323         controller : ['$scope', 'egTagTable',
324             function ( $scope ,  egTagTable) {
325
326                 $scope.ind_val_options = function () {
327                     return egTagTable.getIndicatorValues($scope.field.tag, $scope.indNumber);
328                 }
329             }
330         ]
331     }
332 })
333
334 .directive("egMarcEditTag", function () {
335     return {
336         transclude: true,
337         restrict: 'E',
338         template: '<span><eg-marc-edit-editable '+
339                       'itype="tag" '+
340                       'class="marcedit marctag" '+
341                       'field="field" '+
342                       'content="tag" '+
343                       'max="3" '+
344                       'on-keydown="onKeydown" '+
345                       'context-item-generator="tag_options" '+
346                       'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}tag"'+
347                       '/></span>',
348         scope: { tag : '=', field: '=', onKeydown: '=' },
349         replace: true,
350         controller : ['$scope', 'egTagTable',
351             function ( $scope ,  egTagTable) {
352
353                 $scope.tag_options = function () {
354                     return egTagTable.getFieldTags();
355                 }
356             }
357         ]
358     }
359 })
360
361 .directive("egMarcEditDatafield", function () {
362     return {
363         transclude: true,
364         restrict: 'E',
365         template: '<div>'+
366                     '<span><eg-marc-edit-tag field="field" tag="field.tag" on-keydown="onKeydown"/></span>'+
367                     '<span><eg-marc-edit-ind field="field" ind="field.ind1" on-keydown="onKeydown" ind-number="1"/></span>'+
368                     '<span><eg-marc-edit-ind field="field" ind="field.ind2" on-keydown="onKeydown" ind-number="2"/></span>'+
369                     '<span><eg-marc-edit-subfield ng-repeat="subfield in field.subfields" subfield="subfield" field="field" on-keydown="onKeydown"/></span>'+
370                   '</div>',
371         scope: { field: "=", onKeydown: '=' },
372         replace: true
373     }
374 })
375
376 .directive("egMarcEditControlfield", function () {
377     return {
378         transclude: true,
379         restrict: 'E',
380         template: '<div>'+
381                     '<span><eg-marc-edit-tag field="field" tag="field.tag" on-keydown="onKeydown"/></span>'+
382                     '<span><eg-marc-edit-editable '+
383                       'itype="cfld" '+
384                       'field="field" '+
385                       'class="marcedit marcdata" '+
386                       'content="field.data" '+
387                       'on-keydown="onKeydown" '+
388                       'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}data"'+
389                       '/></span>'+
390                   '</div>',
391         scope: { field: "=", onKeydown: '=' }
392     }
393 })
394
395 .directive("egMarcEditLeader", function () {
396     return {
397         transclude: true,
398         restrict: 'E',
399         template: '<div>'+
400                     '<span><eg-marc-edit-editable '+
401                       'class="marcedit marctag" '+
402                       'content="tag" '+
403                       'on-keydown="onKeydown" '+
404                       'id="leadertag" '+
405                       'disabled="disabled"'+
406                       '/></span>'+
407                     '<span><eg-marc-edit-editable '+
408                       'class="marcedit marcdata" '+
409                       'itype="ldr" '+
410                       'max="{{record.leader.length}}" '+
411                       'content="record.leader" '+
412                       'id="r{{record.subfield(\'901\',\'c\')[1]}}leaderdata" '+
413                       'on-keydown="onKeydown"'+
414                       '/></span>'+
415                   '</div>',
416         controller : ['$scope',
417             function ( $scope ) {
418                 $scope.tag = 'LDR';
419             }
420         ],
421         scope: { record: "=", onKeydown: '=' }
422     }
423 })
424
425 /// TODO: fixed field editor and such
426 .directive("egMarcEditRecord", function () {
427     return {
428         templateUrl : './cat/share/t_marcedit',
429         restrict: 'E',
430         replace: true,
431         scope: {
432             dirtyFlag : '=',
433             recordId : '=',
434             recordType : '@',
435             maxUndo : '@'
436         },
437         link: function (scope, element, attrs) {
438
439             element.bind('click', function(e) {;
440                 scope.current_event_target = $(e.target).attr('id');
441                 if (scope.current_event_target) {
442                     console.log('Recording click event on ' + scope.current_event_target);
443                     scope.current_event_target_cursor_pos =
444                         e.target.selectionDirection=='backward' ?
445                             e.target.selectionStart :
446                             e.target.selectionEnd;
447                 }
448             });
449
450         },
451         controller : ['$timeout','$scope','egCore', 'egTagTable',
452             function ( $timeout , $scope , egCore ,  egTagTable ) {
453
454                 MARC21.Record.delimiter = '$';
455
456                 $scope.flatEditor = false;
457                 $scope.bib_source = null;
458                 $scope.record_type = $scope.recordType || 'bre';
459                 $scope.max_undo = $scope.maxUndo || 100;
460                 $scope.record_undo_stack = [];
461                 $scope.record_redo_stack = [];
462                 $scope.in_undo = false;
463                 $scope.in_redo = false;
464                 $scope.record = new MARC21.Record();
465                 $scope.save_stack_depth = 0;
466                 $scope.controlfields = [];
467                 $scope.datafields = [];
468
469                 egTagTable.loadTagTable();
470
471                 $scope.saveFlatTextMARC = function () {
472                     $scope.record = new MARC21.Record({ marcbreaker : $scope.flat_text_marc });
473                 };
474
475                 $scope.refreshVisual = function () {
476                     if (!$scope.flatEditor) {
477                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
478                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
479                     }
480                 };
481
482                 $scope.onKeydown = function (event) {
483                     var event_return = true;
484
485                     console.log(
486                         'keydown: which='+event.which+
487                         ', ctrlKey='+event.ctrlKey+
488                         ', shiftKey='+event.shiftKey+
489                         ', altKey='+event.altKey+
490                         ', metaKey='+event.altKey
491                     );
492
493                     if (event.which == 89 && event.ctrlKey) { // ctrl+y, redo
494                         event_return = $scope.processRedo();
495                     } else if (event.which == 90 && event.ctrlKey) { // ctrl+z, undo
496                         event_return = $scope.processUndo();
497                     } else if ((event.which == 68 || event.which == 73) && event.ctrlKey) { // ctrl+d or ctrl+i, insert subfield
498
499                         var element = $(event.target);
500                         var new_sf, index_sf, move_data;
501
502                         if (element.hasClass('marcsfvalue')) {
503                             index_sf = event.data.scope.subfield[2];
504                             new_sf = index_sf + 1;
505
506                             var start = event.target.selectionStart;
507                             var end = event.target.selectionEnd - event.target.selectionStart ?
508                                     event.target.selectionEnd :
509                                     event.target.value.length;
510
511                             move_data = event.target.value.substring(start,end);
512
513                         } else if (element.hasClass('marcsfcode')) {
514                             index_sf = event.data.scope.subfield[2];
515                             new_sf = index_sf + 1;
516                         } else if (element.hasClass('marctag') || element.hasClass('marcind')) {
517                             index_sf = 0;
518                             new_sf = index_sf;
519                         }
520
521                         $scope.current_event_target = 'r' + $scope.recordId +
522                                                       'f' + event.data.scope.field.position + 
523                                                       's' + new_sf + 'code';
524
525                         event.data.scope.field.subfields.forEach(function(sf) {
526                             if (sf[2] >= new_sf) sf[2]++;
527                             if (sf[2] == index_sf) sf[1] = event.target.value.substring(0,start) + event.target.value.substring(end);
528                         });
529                         event.data.scope.field.subfields.splice(
530                             new_sf,
531                             0,
532                             [' ', move_data, new_sf ]
533                         );
534
535                         $scope.current_event_target_cursor_pos = 0;
536                         $scope.current_event_target_cursor_pos_end = 1;
537
538                         $timeout(function(){$scope.$digest()}).then(setCaret);
539
540                         event_return = false;
541
542                     } else if (event.which == 117 && event.shiftKey) { // shift + F6, insert 006
543                         event.data.scope.field.record.insertOrderedFields(
544                             new MARC21.Field({
545                                 tag : '006',
546                                 data : '                                        '
547                             })
548                         );
549
550                         $scope.force_render = true;
551                         $timeout(function(){$scope.$digest()}).then(setCaret);
552
553                         event_return = false;
554
555                     } else if (event.which == 118 && event.shiftKey) { // shift + F7, insert 007
556                         event.data.scope.field.record.insertOrderedFields(
557                             new MARC21.Field({
558                                 tag : '007',
559                                 data : '                                        '
560                             })
561                         );
562
563                         $scope.force_render = true;
564                         $timeout(function(){$scope.$digest()}).then(setCaret);
565
566                         event_return = false;
567
568                     } else if (event.which == 119 && event.shiftKey) { // shift + F8, insert/replace 008
569                         var new_008_data = event.data.scope.field.record.generate008();
570
571
572                         var old_008s = event.data.scope.field.record.field('008',true);
573                         old_008s.forEach(function(o) {
574                             var domnode = $('#r'+o.record.subfield('901','c')[1] + 'f' + o.position);
575                             domnode.scope().$destroy();
576                             domnode.remove();
577                             event.data.scope.field.record.deleteFields(o);
578                         });
579
580                         event.data.scope.field.record.insertOrderedFields(
581                             new MARC21.Field({
582                                 tag : '008',
583                                 data : new_008_data
584                             })
585                         );
586
587                         $scope.force_render = true;
588                         $timeout(function(){$scope.$digest()}).then(setCaret);
589
590                         event_return = false;
591
592                     } else if (event.which == 13 && event.ctrlKey) { // ctrl+enter, insert datafield
593
594                         var element = $(event.target);
595
596                         var index_field = event.data.scope.field.position;
597                         var new_field = index_field + 1;
598
599                         event.data.scope.field.record.insertFieldsAfter(
600                             event.data.scope.field,
601                             new MARC21.Field({
602                                 tag : '999',
603                                 subfields : [[' ','',0]]
604                             })
605                         );
606
607                         $scope.current_event_target = 'r' + $scope.recordId +
608                                                       'f' + new_field + 'tag';
609
610                         $scope.current_event_target_cursor_pos = 0;
611                         $scope.current_event_target_cursor_pos_end = 3;
612                         $scope.force_render = true;
613
614                         $timeout(function(){$scope.$digest()}).then(setCaret);
615
616                         event_return = false;
617
618                     } else if (event.which == 46 && event.ctrlKey) { // ctrl+del, remove field
619
620                         var del_field = event.data.scope.field.position;
621
622                         var domnode = $('#r'+event.data.scope.field.record.subfield('901','c')[1] + 'f' + del_field);
623
624                         event.data.scope.field.record.deleteFields(
625                             event.data.scope.field
626                         );
627
628                         domnode.scope().$destroy();
629                         domnode.remove();
630
631                         $scope.current_event_target = 'r' + $scope.recordId +
632                                                       'f' + del_field + 'tag';
633
634                         $scope.current_event_target_cursor_pos = 0;
635                         $scope.current_event_target_cursor_pos_end = 0
636                         $scope.force_render = true;
637
638                         $timeout(function(){$scope.$digest()}).then(setCaret);
639
640                         event_return = false;
641
642                     } else if (event.which == 46 && event.shiftKey && $(event.target).hasClass('marcsf')) { // shift+del, remove subfield
643
644                         var sf = event.data.scope.subfield[2] - 1;
645                         if (sf == -1) sf = 0;
646
647                         event.data.scope.field.deleteExactSubfields(
648                             event.data.scope.subfield
649                         );
650
651                         if (!event.data.scope.field.subfields[sf]) {
652                             $scope.current_event_target = 'r' + $scope.recordId +
653                                                           'f' + event.data.scope.field.position + 
654                                                           'tag';
655                         } else {
656                             $scope.current_event_target = 'r' + $scope.recordId +
657                                                           'f' + event.data.scope.field.position + 
658                                                           's' + sf + 'value';
659                         }
660
661                         $scope.current_event_target_cursor_pos = 0;
662                         $scope.current_event_target_cursor_pos_end = 0;
663                         $scope.force_render = true;
664
665                         $timeout(function(){$scope.$digest()}).then(setCaret);
666
667                         event_return = false;
668
669                     } else if (event.keyCode == 38) {
670                         if (event.ctrlKey) { // copy the field up
671                             var index_field = event.data.scope.field.position;
672
673                             var field_obj;
674                             if (event.data.scope.field.isControlfield()) {
675                                 field_obj = new MARC21.Field({
676                                     tag : event.data.scope.field.tag,
677                                     data : event.data.scope.field.data
678                                 });
679                             } else {
680                                 var sf_clone = [];
681                                 for (var i in event.data.scope.field.subfields) {
682                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
683                                 }
684                                 field_obj = new MARC21.Field({
685                                     tag : event.data.scope.field.tag,
686                                     ind1 : event.data.scope.field.ind1,
687                                     ind2 : event.data.scope.field.ind2,
688                                     subfields : sf_clone
689                                 });
690                             }
691
692
693                             event.data.scope.field.record.insertFieldsBefore(
694                                 event.data.scope.field,
695                                 field_obj
696                             );
697
698                             $scope.current_event_target = 'r' + $scope.recordId +
699                                                           'f' + index_field + 'tag';
700
701                             $scope.current_event_target_cursor_pos = 0;
702                             $scope.current_event_target_cursor_pos_end = 3;
703                             $scope.force_render = true;
704
705                             $timeout(function(){$scope.$digest()}).then(setCaret);
706
707                         } else { // jump to prev field
708                             if (event.data.scope.field.position > 0) {
709                                 $timeout(function(){
710                                     $scope.current_event_target_cursor_pos = 0;
711                                     $scope.current_event_target_cursor_pos_end = 0;
712                                     $scope.current_event_target = 'r' + $scope.recordId +
713                                                                   'f' + (event.data.scope.field.position - 1) +
714                                                                   'tag';
715                                 }).then(setCaret);
716                             }
717                         }
718
719                         event_return = false;
720
721                     } else if (event.keyCode == 40) { // down arrow...
722                         if (event.ctrlKey) { // copy the field down
723
724                             var index_field = event.data.scope.field.position;
725                             var new_field = index_field + 1;
726
727                             var field_obj;
728                             if (event.data.scope.field.isControlfield()) {
729                                 field_obj = new MARC21.Field({
730                                     tag : event.data.scope.field.tag,
731                                     data : event.data.scope.field.data
732                                 });
733                             } else {
734                                 var sf_clone = [];
735                                 for (var i in event.data.scope.field.subfields) {
736                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
737                                 }
738                                 field_obj = new MARC21.Field({
739                                     tag : event.data.scope.field.tag,
740                                     ind1 : event.data.scope.field.ind1,
741                                     ind2 : event.data.scope.field.ind2,
742                                     subfields : sf_clone
743                                 });
744                             }
745
746                             event.data.scope.field.record.insertFieldsAfter(
747                                 event.data.scope.field,
748                                 field_obj
749                             );
750
751                             $scope.current_event_target = 'r' + $scope.recordId +
752                                                           'f' + new_field + 'tag';
753
754                             $scope.current_event_target_cursor_pos = 0;
755                             $scope.current_event_target_cursor_pos_end = 3;
756                             $scope.force_render = true;
757
758                             $timeout(function(){$scope.$digest()}).then(setCaret);
759
760                         } else { // jump to next field
761                             if (event.data.scope.field.record.fields[event.data.scope.field.position + 1]) {
762                                 $timeout(function(){
763                                     $scope.current_event_target_cursor_pos = 0;
764                                     $scope.current_event_target_cursor_pos_end = 0;
765                                     $scope.current_event_target = 'r' + $scope.recordId +
766                                                                   'f' + (event.data.scope.field.position + 1) +
767                                                                   'tag';
768                                 }).then(setCaret);
769                             }
770                         }
771
772                         event_return = false;
773
774                     } else { // Assumes only marc editor elements have IDs that can trigger this event handler.
775                         $scope.current_event_target = $(event.target).attr('id');
776                         if ($scope.current_event_target) {
777                             $scope.current_event_target_cursor_pos =
778                                 event.target.selectionDirection=='backward' ?
779                                     event.target.selectionStart :
780                                     event.target.selectionEnd;
781                         }
782                     }
783
784                     return event_return;
785                 };
786
787                 function setCaret() {
788                     if ($scope.current_event_target) {
789                         console.log("Putting caret in " + $scope.current_event_target);
790                         if (!$scope.current_event_target_cursor_pos_end)
791                             $scope.current_event_target_cursor_pos_end = $scope.current_event_target_cursor_pos
792
793                         var element = $('#'+$scope.current_event_target).get(0);
794                         if (element) {
795                             element.focus();
796                             if (element.setSelectionRange) {
797                                 element.setSelectionRange(
798                                     $scope.current_event_target_cursor_pos,
799                                     $scope.current_event_target_cursor_pos_end
800                                 );
801                             }
802                             $scope.current_event_cursor_pos_end = null;
803                             $scope.current_event_target = null;
804                         }
805                     }
806                 }
807
808                 function loadRecord() {
809                     return egCore.pcrud.retrieve(
810                         $scope.record_type, $scope.recordId
811                     ).then(function(rec) {
812                         $scope.in_redo = true;
813                         $scope[$scope.record_type] = rec;
814                         $scope.record = new MARC21.Record({ marcxml : $scope[$scope.record_type].marc() });
815                         $scope.calculated_record_type = $scope.record.recordType();
816                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
817                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
818                         $scope.save_stack_depth = $scope.record_undo_stack.length;
819                         $scope.flat_text_marc = $scope.record.toBreaker();
820
821                         if ($scope.record_type == 'bre') {
822                             $scope.bib_source = $scope[$scope.record_type].source();
823                         }
824
825                     }).then(function(){
826                         return egTagTable.fetchFFPosTable($scope.calculated_record_type)
827                     }).then(function(){
828                         return egTagTable.fetchFFValueTable($scope.calculated_record_type)
829                     }).then(setCaret);
830                 }
831
832                 $scope.$watch('record.toBreaker()', function (newVal, oldVal) {
833                     if (!$scope.in_undo && !$scope.in_redo && oldVal != newVal) {
834                         $scope.record_undo_stack.push({
835                             breaker: oldVal,
836                             target: $scope.current_event_target,
837                             pos: $scope.current_event_target_cursor_pos
838                         });
839
840                         if ($scope.force_render) {
841                             $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
842                             $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
843                             $scope.force_render = false;
844                         }
845
846                         $scope.flat_text_marc = newVal;
847                     }
848
849                     if ($scope.record_undo_stack.length != $scope.save_stack_depth) {
850                         $scope.dirtyFlag = true;
851                     } else {
852                         $scope.dirtyFlag = false;
853                     }
854
855                     if ($scope.record_undo_stack.length > $scope.max_undo)
856                         $scope.record_undo_stack.shift();
857
858                     console.log('undo stack is ' + $scope.record_undo_stack.length + ' deep');
859                     $scope.in_redo = false;
860                     $scope.in_undo = false;
861                 });
862
863                 $scope.processUndo = function () {
864                     if ($scope.record_undo_stack.length) {
865                         $scope.in_undo = true;
866
867                         var undo_item = $scope.record_undo_stack.pop();
868                         $scope.record_redo_stack.push(undo_item);
869
870                         $scope.record = new MARC21.Record({ marcbreaker : undo_item.breaker });
871                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
872                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
873
874                         $scope.current_event_target = undo_item.target;
875                         $scope.current_event_target_cursor_pos = undo_item.pos;
876                         console.log('Undo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
877
878                         $timeout(function(){$scope.$digest()}).then(setCaret);
879                         return false;
880                     }
881
882                     return true;
883                 };
884
885                 $scope.processRedo = function () {
886                     if ($scope.record_redo_stack.length) {
887                         $scope.in_redo = true;
888
889                         var redo_item = $scope.record_redo_stack.pop();
890                         $scope.record_undo_stack.push(redo_item);
891
892                         $scope.record = new MARC21.Record({ marcbreaker : redo_item.breaker });
893                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
894                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
895
896                         $scope.current_event_target = redo_item.target;
897                         $scope.current_event_target_cursor_pos = redo_item.pos;
898                         console.log('Redo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
899
900                         $timeout(function(){$scope.$digest()}).then(setCaret);
901                         return false;
902                     }
903
904                     return true;
905                 };
906
907                 $scope.saveRecord = function () {
908                     $scope.mangle_005();
909                     $scope[$scope.record_type].marc($scope.record.toXmlString());
910                     return egCore.pcrud.update(
911                         $scope[$scope.record_type]
912                     ).then(loadRecord);
913                 };
914
915                 $scope.seeBreaker = function () {
916                     alert($scope.record.toBreaker());
917                 };
918
919                 $scope.$watch('recordId',
920                     function(newVal, oldVal) {
921                         if (newVal && newVal !== oldVal) {
922                             loadRecord();
923                         }
924                     }
925                 );
926
927                 if ($scope.recordId)
928                     loadRecord();
929
930                 $scope.mangle_005 = function () {
931                     var now = new Date();
932                     var y = now.getUTCFullYear();
933                 
934                     var m = now.getUTCMonth() + 1;
935                     if (m < 10) m = '0' + m;
936                 
937                     var d = now.getUTCDate();
938                     if (d < 10) d = '0' + d;
939                 
940                     var H = now.getUTCHours();
941                     if (H < 10) H = '0' + H;
942                 
943                     var M = now.getUTCMinutes();
944                     if (M < 10) M = '0' + M;
945                 
946                     var S = now.getUTCSeconds();
947                     if (S < 10) S = '0' + S;
948                 
949                     var stamp = '' + y + m + d + H + M + S + '.0';
950                     var f = $scope.record.field('005',true)[0];
951                     if (f) {
952                         f.data = stamp;
953                     } else {
954                         $scope.record.insertOrderedFields(
955                             new MARC21.Field({
956                                 tag : '005',
957                                 data: stamp
958                             })
959                         );
960                     }
961                 
962                 }
963
964             }
965         ]          
966     }
967 })
968
969 .directive("egMarcEditBibsource", ['$timeout',function ($timeout) {
970     return {
971         restrict: 'E',
972         replace: true,
973         template: '<span class="nullable">'+
974                     '<select class="form-control" ng-model="bib_source" ng-options="s.id() as s.source() for s in bib_sources">'+
975                       '<option value="">Select a Source</option>'+
976                     '</select>'+
977                   '</span>',
978         controller: ['$scope','egCore',
979             function ($scope , egCore) {
980
981                 egCore.pcrud.retrieveAll('cbs', {}, {atomic : true})
982                     .then(function(list) { $scope.bib_sources = list; });
983
984                 $scope.$watch('bib_source',
985                     function(newVal, oldVal) {
986                         if (newVal !== oldVal) {
987                             $scope.bre.source(newVal);
988                         }
989                     }
990                 );
991
992             }
993         ]
994     }
995 }])
996
997 ;