]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/services/marcedit.js
webstaff: Flat Text MARC editor support
[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                         'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}s{{subfield[2]}}value" '+
288                     '/></span>'+
289                   '</span>',
290         scope: { field: "=", subfield: "=", onKeydown: '=' },
291         replace: true,
292         controller : ['$scope', 'egTagTable',
293             function ( $scope ,  egTagTable) {
294
295                 $scope.sf_code_options = function () {
296                     return egTagTable.getSubfieldCodes($scope.field.tag);
297                 }
298             }
299         ]
300     }
301 })
302
303 .directive("egMarcEditInd", function () {
304     return {
305         transclude: true,
306         restrict: 'E',
307         template: '<span><eg-marc-edit-editable '+
308                       'itype="ind" '+
309                       'class="marcedit marcind" '+
310                       'field="field" '+
311                       'content="ind" '+
312                       'max="1" '+
313                       'on-keydown="onKeydown" '+
314                       'context-item-generator="ind_val_options" '+
315                       'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}i{{indNumber}}"'+
316                       '/></span>',
317         scope: { ind : '=', field: '=', onKeydown: '=', indNumber: '@' },
318         replace: true,
319         controller : ['$scope', 'egTagTable',
320             function ( $scope ,  egTagTable) {
321
322                 $scope.ind_val_options = function () {
323                     return egTagTable.getIndicatorValues($scope.field.tag, $scope.indNumber);
324                 }
325             }
326         ]
327     }
328 })
329
330 .directive("egMarcEditTag", function () {
331     return {
332         transclude: true,
333         restrict: 'E',
334         template: '<span><eg-marc-edit-editable '+
335                       'itype="tag" '+
336                       'class="marcedit marctag" '+
337                       'field="field" '+
338                       'content="tag" '+
339                       'max="3" '+
340                       'on-keydown="onKeydown" '+
341                       'context-item-generator="tag_options" '+
342                       'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}tag"'+
343                       '/></span>',
344         scope: { tag : '=', field: '=', onKeydown: '=' },
345         replace: true,
346         controller : ['$scope', 'egTagTable',
347             function ( $scope ,  egTagTable) {
348
349                 $scope.tag_options = function () {
350                     return egTagTable.getFieldTags();
351                 }
352             }
353         ]
354     }
355 })
356
357 .directive("egMarcEditDatafield", function () {
358     return {
359         transclude: true,
360         restrict: 'E',
361         template: '<div>'+
362                     '<span><eg-marc-edit-tag field="field" tag="field.tag" on-keydown="onKeydown"/></span>'+
363                     '<span><eg-marc-edit-ind field="field" ind="field.ind1" on-keydown="onKeydown" ind-number="1"/></span>'+
364                     '<span><eg-marc-edit-ind field="field" ind="field.ind2" on-keydown="onKeydown" ind-number="2"/></span>'+
365                     '<span><eg-marc-edit-subfield ng-repeat="subfield in field.subfields" subfield="subfield" field="field" on-keydown="onKeydown"/></span>'+
366                   '</div>',
367         scope: { field: "=", onKeydown: '=' },
368         replace: true
369     }
370 })
371
372 .directive("egMarcEditControlfield", function () {
373     return {
374         transclude: true,
375         restrict: 'E',
376         template: '<div>'+
377                     '<span><eg-marc-edit-tag field="field" tag="field.tag" on-keydown="onKeydown"/></span>'+
378                     '<span><eg-marc-edit-editable '+
379                       'itype="cfld" '+
380                       'field="field" '+
381                       'class="marcedit marcdata" '+
382                       'content="field.data" '+
383                       'on-keydown="onKeydown" '+
384                       'id="r{{field.record.subfield(\'901\',\'c\')[1]}}f{{field.position}}data"'+
385                       '/></span>'+
386                   '</div>',
387         scope: { field: "=", onKeydown: '=' }
388     }
389 })
390
391 .directive("egMarcEditLeader", function () {
392     return {
393         transclude: true,
394         restrict: 'E',
395         template: '<div>'+
396                     '<span><eg-marc-edit-editable '+
397                       'class="marcedit marctag" '+
398                       'content="tag" '+
399                       'on-keydown="onKeydown" '+
400                       'id="leadertag" '+
401                       'disabled="disabled"'+
402                       '/></span>'+
403                     '<span><eg-marc-edit-editable '+
404                       'class="marcedit marcdata" '+
405                       'itype="ldr" '+
406                       'max="{{record.leader.length}}" '+
407                       'content="record.leader" '+
408                       'id="r{{record.subfield(\'901\',\'c\')[1]}}leaderdata" '+
409                       'on-keydown="onKeydown"'+
410                       '/></span>'+
411                   '</div>',
412         controller : ['$scope',
413             function ( $scope ) {
414                 $scope.tag = 'LDR';
415             }
416         ],
417         scope: { record: "=", onKeydown: '=' }
418     }
419 })
420
421 /// TODO: fixed field editor and such
422 .directive("egMarcEditRecord", function () {
423     return {
424         templateUrl : './cat/share/t_marcedit',
425         restrict: 'E',
426         replace: true,
427         scope: {
428             dirtyFlag : '=',
429             recordId : '=',
430             recordType : '@',
431             maxUndo : '@'
432         },
433         link: function (scope, element, attrs) {
434
435             element.bind('click', function(e) {;
436                 scope.current_event_target = $(e.target).attr('id');
437                 if (scope.current_event_target) {
438                     console.log('Recording click event on ' + scope.current_event_target);
439                     scope.current_event_target_cursor_pos =
440                         e.target.selectionDirection=='backward' ?
441                             e.target.selectionStart :
442                             e.target.selectionEnd;
443                 }
444             });
445
446         },
447         controller : ['$timeout','$scope','egCore', 'egTagTable',
448             function ( $timeout , $scope , egCore ,  egTagTable ) {
449
450                 MARC21.Record.delimiter = '$';
451
452                 $scope.flatEditor = false;
453                 $scope.bib_source = null;
454                 $scope.record_type = $scope.recordType || 'bre';
455                 $scope.max_undo = $scope.maxUndo || 100;
456                 $scope.record_undo_stack = [];
457                 $scope.record_redo_stack = [];
458                 $scope.in_undo = false;
459                 $scope.in_redo = false;
460                 $scope.record = new MARC21.Record();
461                 $scope.save_stack_depth = 0;
462                 $scope.controlfields = [];
463                 $scope.datafields = [];
464
465                 egTagTable.loadTagTable();
466
467                 $scope.saveFlatTextMARC = function () {
468                     $scope.record = new MARC21.Record({ marcbreaker : $scope.flat_text_marc });
469                 };
470
471                 $scope.refreshVisual = function () {
472                     if (!$scope.flatEditor) {
473                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
474                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
475                     }
476                 };
477
478                 $scope.onKeydown = function (event) {
479                     var event_return = true;
480
481                     console.log(
482                         'keydown: which='+event.which+
483                         ', ctrlKey='+event.ctrlKey+
484                         ', shiftKey='+event.shiftKey+
485                         ', altKey='+event.altKey+
486                         ', metaKey='+event.altKey
487                     );
488
489                     if (event.which == 89 && event.ctrlKey) { // ctrl+y, redo
490                         event_return = $scope.processRedo();
491                     } else if (event.which == 90 && event.ctrlKey) { // ctrl+z, undo
492                         event_return = $scope.processUndo();
493                     } else if ((event.which == 68 || event.which == 73) && event.ctrlKey) { // ctrl+d or ctrl+i, insert subfield
494
495                         var element = $(event.target);
496                         var new_sf, index_sf, move_data;
497
498                         if (element.hasClass('marcsfvalue')) {
499                             index_sf = event.data.scope.subfield[2];
500                             new_sf = index_sf + 1;
501
502                             var start = event.target.selectionStart;
503                             var end = event.target.selectionEnd - event.target.selectionStart ?
504                                     event.target.selectionEnd :
505                                     event.target.value.length;
506
507                             move_data = event.target.value.substring(start,end);
508
509                         } else if (element.hasClass('marcsfcode')) {
510                             index_sf = event.data.scope.subfield[2];
511                             new_sf = index_sf + 1;
512                         } else if (element.hasClass('marctag') || element.hasClass('marcind')) {
513                             index_sf = 0;
514                             new_sf = index_sf;
515                         }
516
517                         $scope.current_event_target = 'r' + $scope.recordId +
518                                                       'f' + event.data.scope.field.position + 
519                                                       's' + new_sf + 'code';
520
521                         event.data.scope.field.subfields.forEach(function(sf) {
522                             if (sf[2] >= new_sf) sf[2]++;
523                             if (sf[2] == index_sf) sf[1] = event.target.value.substring(0,start) + event.target.value.substring(end);
524                         });
525                         event.data.scope.field.subfields.splice(
526                             new_sf,
527                             0,
528                             [' ', move_data, new_sf ]
529                         );
530
531                         $scope.current_event_target_cursor_pos = 0;
532                         $scope.current_event_target_cursor_pos_end = 1;
533
534                         $timeout(function(){$scope.$digest()}).then(setCaret);
535
536                         event_return = false;
537
538                     } else if (event.which == 117 && event.shiftKey) { // shift + F6, insert 006
539                         event.data.scope.field.record.insertOrderedFields(
540                             new MARC21.Field({
541                                 tag : '006',
542                                 data : '                                        '
543                             })
544                         );
545
546                         $scope.force_render = true;
547                         $timeout(function(){$scope.$digest()}).then(setCaret);
548
549                         event_return = false;
550
551                     } else if (event.which == 118 && event.shiftKey) { // shift + F7, insert 007
552                         event.data.scope.field.record.insertOrderedFields(
553                             new MARC21.Field({
554                                 tag : '007',
555                                 data : '                                        '
556                             })
557                         );
558
559                         $scope.force_render = true;
560                         $timeout(function(){$scope.$digest()}).then(setCaret);
561
562                         event_return = false;
563
564                     } else if (event.which == 119 && event.shiftKey) { // shift + F8, insert/replace 008
565                         var new_008_data = event.data.scope.field.record.generate008();
566
567
568                         var old_008s = event.data.scope.field.record.field('008',true);
569                         old_008s.forEach(function(o) {
570                             var domnode = $('#r'+o.record.subfield('901','c')[1] + 'f' + o.position);
571                             domnode.scope().$destroy();
572                             domnode.remove();
573                             event.data.scope.field.record.deleteFields(o);
574                         });
575
576                         event.data.scope.field.record.insertOrderedFields(
577                             new MARC21.Field({
578                                 tag : '008',
579                                 data : new_008_data
580                             })
581                         );
582
583                         $scope.force_render = true;
584                         $timeout(function(){$scope.$digest()}).then(setCaret);
585
586                         event_return = false;
587
588                     } else if (event.which == 13 && event.ctrlKey) { // ctrl+enter, insert datafield
589
590                         var element = $(event.target);
591
592                         var index_field = event.data.scope.field.position;
593                         var new_field = index_field + 1;
594
595                         event.data.scope.field.record.insertFieldsAfter(
596                             event.data.scope.field,
597                             new MARC21.Field({
598                                 tag : '999',
599                                 subfields : [[' ','',0]]
600                             })
601                         );
602
603                         $scope.current_event_target = 'r' + $scope.recordId +
604                                                       'f' + new_field + 'tag';
605
606                         $scope.current_event_target_cursor_pos = 0;
607                         $scope.current_event_target_cursor_pos_end = 3;
608                         $scope.force_render = true;
609
610                         $timeout(function(){$scope.$digest()}).then(setCaret);
611
612                         event_return = false;
613
614                     } else if (event.which == 46 && event.ctrlKey) { // ctrl+del, remove field
615
616                         var del_field = event.data.scope.field.position;
617
618                         var domnode = $('#r'+event.data.scope.field.record.subfield('901','c')[1] + 'f' + del_field);
619
620                         event.data.scope.field.record.deleteFields(
621                             event.data.scope.field
622                         );
623
624                         domnode.scope().$destroy();
625                         domnode.remove();
626
627                         $scope.current_event_target = 'r' + $scope.recordId +
628                                                       'f' + del_field + 'tag';
629
630                         $scope.current_event_target_cursor_pos = 0;
631                         $scope.current_event_target_cursor_pos_end = 0
632                         $scope.force_render = true;
633
634                         $timeout(function(){$scope.$digest()}).then(setCaret);
635
636                         event_return = false;
637
638                     } else if (event.which == 46 && event.shiftKey && $(event.target).hasClass('marcsf')) { // shift+del, remove subfield
639
640                         var sf = event.data.scope.subfield[2] - 1;
641                         if (sf == -1) sf = 0;
642
643                         event.data.scope.field.deleteExactSubfields(
644                             event.data.scope.subfield
645                         );
646
647                         if (!event.data.scope.field.subfields[sf]) {
648                             $scope.current_event_target = 'r' + $scope.recordId +
649                                                           'f' + event.data.scope.field.position + 
650                                                           'tag';
651                         } else {
652                             $scope.current_event_target = 'r' + $scope.recordId +
653                                                           'f' + event.data.scope.field.position + 
654                                                           's' + sf + 'value';
655                         }
656
657                         $scope.current_event_target_cursor_pos = 0;
658                         $scope.current_event_target_cursor_pos_end = 0;
659                         $scope.force_render = true;
660
661                         $timeout(function(){$scope.$digest()}).then(setCaret);
662
663                         event_return = false;
664
665                     } else if (event.keyCode == 38) {
666                         if (event.ctrlKey) { // copy the field up
667                             var index_field = event.data.scope.field.position;
668
669                             var field_obj;
670                             if (event.data.scope.field.isControlfield()) {
671                                 field_obj = new MARC21.Field({
672                                     tag : event.data.scope.field.tag,
673                                     data : event.data.scope.field.data
674                                 });
675                             } else {
676                                 var sf_clone = [];
677                                 for (var i in event.data.scope.field.subfields) {
678                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
679                                 }
680                                 field_obj = new MARC21.Field({
681                                     tag : event.data.scope.field.tag,
682                                     ind1 : event.data.scope.field.ind1,
683                                     ind2 : event.data.scope.field.ind2,
684                                     subfields : sf_clone
685                                 });
686                             }
687
688
689                             event.data.scope.field.record.insertFieldsBefore(
690                                 event.data.scope.field,
691                                 field_obj
692                             );
693
694                             $scope.current_event_target = 'r' + $scope.recordId +
695                                                           'f' + index_field + 'tag';
696
697                             $scope.current_event_target_cursor_pos = 0;
698                             $scope.current_event_target_cursor_pos_end = 3;
699                             $scope.force_render = true;
700
701                             $timeout(function(){$scope.$digest()}).then(setCaret);
702
703                         } else { // jump to prev field
704                             if (event.data.scope.field.position > 0) {
705                                 $timeout(function(){
706                                     $scope.current_event_target_cursor_pos = 0;
707                                     $scope.current_event_target_cursor_pos_end = 0;
708                                     $scope.current_event_target = 'r' + $scope.recordId +
709                                                                   'f' + (event.data.scope.field.position - 1) +
710                                                                   'tag';
711                                 }).then(setCaret);
712                             }
713                         }
714
715                         event_return = false;
716
717                     } else if (event.keyCode == 40) { // down arrow...
718                         if (event.ctrlKey) { // copy the field down
719
720                             var index_field = event.data.scope.field.position;
721                             var new_field = index_field + 1;
722
723                             var field_obj;
724                             if (event.data.scope.field.isControlfield()) {
725                                 field_obj = new MARC21.Field({
726                                     tag : event.data.scope.field.tag,
727                                     data : event.data.scope.field.data
728                                 });
729                             } else {
730                                 var sf_clone = [];
731                                 for (var i in event.data.scope.field.subfields) {
732                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
733                                 }
734                                 field_obj = new MARC21.Field({
735                                     tag : event.data.scope.field.tag,
736                                     ind1 : event.data.scope.field.ind1,
737                                     ind2 : event.data.scope.field.ind2,
738                                     subfields : sf_clone
739                                 });
740                             }
741
742                             event.data.scope.field.record.insertFieldsAfter(
743                                 event.data.scope.field,
744                                 field_obj
745                             );
746
747                             $scope.current_event_target = 'r' + $scope.recordId +
748                                                           'f' + new_field + 'tag';
749
750                             $scope.current_event_target_cursor_pos = 0;
751                             $scope.current_event_target_cursor_pos_end = 3;
752                             $scope.force_render = true;
753
754                             $timeout(function(){$scope.$digest()}).then(setCaret);
755
756                         } else { // jump to next field
757                             if (event.data.scope.field.record.fields[event.data.scope.field.position + 1]) {
758                                 $timeout(function(){
759                                     $scope.current_event_target_cursor_pos = 0;
760                                     $scope.current_event_target_cursor_pos_end = 0;
761                                     $scope.current_event_target = 'r' + $scope.recordId +
762                                                                   'f' + (event.data.scope.field.position + 1) +
763                                                                   'tag';
764                                 }).then(setCaret);
765                             }
766                         }
767
768                         event_return = false;
769
770                     } else { // Assumes only marc editor elements have IDs that can trigger this event handler.
771                         $scope.current_event_target = $(event.target).attr('id');
772                         if ($scope.current_event_target) {
773                             $scope.current_event_target_cursor_pos =
774                                 event.target.selectionDirection=='backward' ?
775                                     event.target.selectionStart :
776                                     event.target.selectionEnd;
777                         }
778                     }
779
780                     return event_return;
781                 };
782
783                 function setCaret() {
784                     if ($scope.current_event_target) {
785                         console.log("Putting caret in " + $scope.current_event_target);
786                         if (!$scope.current_event_target_cursor_pos_end)
787                             $scope.current_event_target_cursor_pos_end = $scope.current_event_target_cursor_pos
788
789                         var element = $('#'+$scope.current_event_target).get(0);
790                         if (element) {
791                             element.focus();
792                             if (element.setSelectionRange) {
793                                 element.setSelectionRange(
794                                     $scope.current_event_target_cursor_pos,
795                                     $scope.current_event_target_cursor_pos_end
796                                 );
797                             }
798                             $scope.current_event_cursor_pos_end = null;
799                             $scope.current_event_target = null;
800                         }
801                     }
802                 }
803
804                 function loadRecord() {
805                     return egCore.pcrud.retrieve(
806                         $scope.record_type, $scope.recordId
807                     ).then(function(rec) {
808                         $scope.in_redo = true;
809                         $scope[$scope.record_type] = rec;
810                         $scope.record = new MARC21.Record({ marcxml : $scope[$scope.record_type].marc() });
811                         $scope.calculated_record_type = $scope.record.recordType();
812                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
813                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
814                         $scope.save_stack_depth = $scope.record_undo_stack.length;
815                         $scope.flat_text_marc = $scope.record.toBreaker();
816
817                         if ($scope.record_type == 'bre') {
818                             $scope.bib_source = $scope[$scope.record_type].source();
819                         }
820
821                     }).then(function(){
822                         return egTagTable.fetchFFPosTable($scope.calculated_record_type)
823                     }).then(function(){
824                         return egTagTable.fetchFFValueTable($scope.calculated_record_type)
825                     }).then(setCaret);
826                 }
827
828                 $scope.$watch('record.toBreaker()', function (newVal, oldVal) {
829                     if (!$scope.in_undo && !$scope.in_redo && oldVal != newVal) {
830                         $scope.record_undo_stack.push({
831                             breaker: oldVal,
832                             target: $scope.current_event_target,
833                             pos: $scope.current_event_target_cursor_pos
834                         });
835
836                         if ($scope.force_render) {
837                             $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
838                             $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
839                             $scope.force_render = false;
840                         }
841
842                         $scope.flat_text_marc = newVal;
843                     }
844
845                     if ($scope.record_undo_stack.length != $scope.save_stack_depth) {
846                         $scope.dirtyFlag = true;
847                     } else {
848                         $scope.dirtyFlag = false;
849                     }
850
851                     if ($scope.record_undo_stack.length > $scope.max_undo)
852                         $scope.record_undo_stack.shift();
853
854                     console.log('undo stack is ' + $scope.record_undo_stack.length + ' deep');
855                     $scope.in_redo = false;
856                     $scope.in_undo = false;
857                 });
858
859                 $scope.processUndo = function () {
860                     if ($scope.record_undo_stack.length) {
861                         $scope.in_undo = true;
862
863                         var undo_item = $scope.record_undo_stack.pop();
864                         $scope.record_redo_stack.push(undo_item);
865
866                         $scope.record = new MARC21.Record({ marcbreaker : undo_item.breaker });
867                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
868                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
869
870                         $scope.current_event_target = undo_item.target;
871                         $scope.current_event_target_cursor_pos = undo_item.pos;
872                         console.log('Undo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
873
874                         $timeout(function(){$scope.$digest()}).then(setCaret);
875                         return false;
876                     }
877
878                     return true;
879                 };
880
881                 $scope.processRedo = function () {
882                     if ($scope.record_redo_stack.length) {
883                         $scope.in_redo = true;
884
885                         var redo_item = $scope.record_redo_stack.pop();
886                         $scope.record_undo_stack.push(redo_item);
887
888                         $scope.record = new MARC21.Record({ marcbreaker : redo_item.breaker });
889                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
890                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
891
892                         $scope.current_event_target = redo_item.target;
893                         $scope.current_event_target_cursor_pos = redo_item.pos;
894                         console.log('Redo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
895
896                         $timeout(function(){$scope.$digest()}).then(setCaret);
897                         return false;
898                     }
899
900                     return true;
901                 };
902
903                 $scope.saveRecord = function () {
904                     $scope.mangle_005();
905                     $scope[$scope.record_type].marc($scope.record.toXmlString());
906                     return egCore.pcrud.update(
907                         $scope[$scope.record_type]
908                     ).then(loadRecord);
909                 };
910
911                 $scope.seeBreaker = function () {
912                     alert($scope.record.toBreaker());
913                 };
914
915                 $scope.$watch('recordId',
916                     function(newVal, oldVal) {
917                         if (newVal && newVal !== oldVal) {
918                             loadRecord();
919                         }
920                     }
921                 );
922
923                 if ($scope.recordId)
924                     loadRecord();
925
926                 $scope.mangle_005 = function () {
927                     var now = new Date();
928                     var y = now.getUTCFullYear();
929                 
930                     var m = now.getUTCMonth() + 1;
931                     if (m < 10) m = '0' + m;
932                 
933                     var d = now.getUTCDate();
934                     if (d < 10) d = '0' + d;
935                 
936                     var H = now.getUTCHours();
937                     if (H < 10) H = '0' + H;
938                 
939                     var M = now.getUTCMinutes();
940                     if (M < 10) M = '0' + M;
941                 
942                     var S = now.getUTCSeconds();
943                     if (S < 10) S = '0' + S;
944                 
945                     var stamp = '' + y + m + d + H + M + S + '.0';
946                     var f = $scope.record.field('005',true)[0];
947                     if (f) {
948                         f.data = stamp;
949                     } else {
950                         $scope.record.insertOrderedFields(
951                             new MARC21.Field({
952                                 tag : '005',
953                                 data: stamp
954                             })
955                         );
956                     }
957                 
958                 }
959
960             }
961         ]          
962     }
963 })
964
965 .directive("egMarcEditBibsource", ['$timeout',function ($timeout) {
966     return {
967         restrict: 'E',
968         replace: true,
969         template: '<span class="nullable">'+
970                     '<select class="form-control" ng-model="bib_source" ng-options="s.id() as s.source() for s in bib_sources">'+
971                       '<option value="">Select a Source</option>'+
972                     '</select>'+
973                   '</span>',
974         controller: ['$scope','egCore',
975             function ($scope , egCore) {
976
977                 egCore.pcrud.retrieveAll('cbs', {}, {atomic : true})
978                     .then(function(list) { $scope.bib_sources = list; });
979
980                 $scope.$watch('bib_source',
981                     function(newVal, oldVal) {
982                         if (newVal !== oldVal) {
983                             $scope.bre.source(newVal);
984                         }
985                     }
986                 );
987
988             }
989         ]
990     }
991 }])
992
993 ;