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