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