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