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