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