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