]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/services/marcedit.js
webstaff: force MARC editor context menus to have a high z-index
[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             recordType : '@',
433             maxUndo : '@'
434         },
435         link: function (scope, element, attrs) {
436
437             element.bind('click', function(e) {;
438                 scope.current_event_target = $(e.target).attr('id');
439                 if (scope.current_event_target) {
440                     console.log('Recording click event on ' + scope.current_event_target);
441                     scope.current_event_target_cursor_pos =
442                         e.target.selectionDirection=='backward' ?
443                             e.target.selectionStart :
444                             e.target.selectionEnd;
445                 }
446             });
447
448         },
449         controller : ['$timeout','$scope','$q','egCore', 'egTagTable',
450             function ( $timeout , $scope , $q,  egCore ,  egTagTable ) {
451
452                 MARC21.Record.delimiter = '$';
453
454                 $scope.flatEditor = false;
455                 $scope.brandNewRecord = false;
456                 $scope.bib_source = null;
457                 $scope.record_type = $scope.recordType || 'bre';
458                 $scope.max_undo = $scope.maxUndo || 100;
459                 $scope.record_undo_stack = [];
460                 $scope.record_redo_stack = [];
461                 $scope.in_undo = false;
462                 $scope.in_redo = false;
463                 $scope.record = new MARC21.Record();
464                 $scope.save_stack_depth = 0;
465                 $scope.controlfields = [];
466                 $scope.datafields = [];
467
468                 egTagTable.loadTagTable();
469
470                 $scope.saveFlatTextMARC = function () {
471                     $scope.record = new MARC21.Record({ marcbreaker : $scope.flat_text_marc });
472                 };
473
474                 $scope.refreshVisual = function () {
475                     if (!$scope.flatEditor) {
476                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
477                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
478                     }
479                 };
480
481                 $scope.onKeydown = function (event) {
482                     var event_return = true;
483
484                     console.log(
485                         'keydown: which='+event.which+
486                         ', ctrlKey='+event.ctrlKey+
487                         ', shiftKey='+event.shiftKey+
488                         ', altKey='+event.altKey+
489                         ', metaKey='+event.altKey
490                     );
491
492                     if (event.which == 89 && event.ctrlKey) { // ctrl+y, redo
493                         event_return = $scope.processRedo();
494                     } else if (event.which == 90 && event.ctrlKey) { // ctrl+z, undo
495                         event_return = $scope.processUndo();
496                     } else if ((event.which == 68 || event.which == 73) && event.ctrlKey) { // ctrl+d or ctrl+i, insert subfield
497
498                         var element = $(event.target);
499                         var new_sf, index_sf, move_data;
500
501                         if (element.hasClass('marcsfvalue')) {
502                             index_sf = event.data.scope.subfield[2];
503                             new_sf = index_sf + 1;
504
505                             var start = event.target.selectionStart;
506                             var end = event.target.selectionEnd - event.target.selectionStart ?
507                                     event.target.selectionEnd :
508                                     event.target.value.length;
509
510                             move_data = event.target.value.substring(start,end);
511
512                         } else if (element.hasClass('marcsfcode')) {
513                             index_sf = event.data.scope.subfield[2];
514                             new_sf = index_sf + 1;
515                         } else if (element.hasClass('marctag') || element.hasClass('marcind')) {
516                             index_sf = 0;
517                             new_sf = index_sf;
518                         }
519
520                         $scope.current_event_target = 'r' + $scope.recordId +
521                                                       'f' + event.data.scope.field.position + 
522                                                       's' + new_sf + 'code';
523
524                         event.data.scope.field.subfields.forEach(function(sf) {
525                             if (sf[2] >= new_sf) sf[2]++;
526                             if (sf[2] == index_sf) sf[1] = event.target.value.substring(0,start) + event.target.value.substring(end);
527                         });
528                         event.data.scope.field.subfields.splice(
529                             new_sf,
530                             0,
531                             [' ', move_data, new_sf ]
532                         );
533
534                         $scope.current_event_target_cursor_pos = 0;
535                         $scope.current_event_target_cursor_pos_end = 1;
536
537                         $timeout(function(){$scope.$digest()}).then(setCaret);
538
539                         event_return = false;
540
541                     } else if (event.which == 117 && event.shiftKey) { // shift + F6, insert 006
542                         event.data.scope.field.record.insertOrderedFields(
543                             new MARC21.Field({
544                                 tag : '006',
545                                 data : '                                        '
546                             })
547                         );
548
549                         $scope.force_render = true;
550                         $timeout(function(){$scope.$digest()}).then(setCaret);
551
552                         event_return = false;
553
554                     } else if (event.which == 118 && event.shiftKey) { // shift + F7, insert 007
555                         event.data.scope.field.record.insertOrderedFields(
556                             new MARC21.Field({
557                                 tag : '007',
558                                 data : '                                        '
559                             })
560                         );
561
562                         $scope.force_render = true;
563                         $timeout(function(){$scope.$digest()}).then(setCaret);
564
565                         event_return = false;
566
567                     } else if (event.which == 119 && event.shiftKey) { // shift + F8, insert/replace 008
568                         var new_008_data = event.data.scope.field.record.generate008();
569
570
571                         var old_008s = event.data.scope.field.record.field('008',true);
572                         old_008s.forEach(function(o) {
573                             var domnode = $('#r'+o.record.subfield('901','c')[1] + 'f' + o.position);
574                             domnode.scope().$destroy();
575                             domnode.remove();
576                             event.data.scope.field.record.deleteFields(o);
577                         });
578
579                         event.data.scope.field.record.insertOrderedFields(
580                             new MARC21.Field({
581                                 tag : '008',
582                                 data : new_008_data
583                             })
584                         );
585
586                         $scope.force_render = true;
587                         $timeout(function(){$scope.$digest()}).then(setCaret);
588
589                         event_return = false;
590
591                     } else if (event.which == 13 && event.ctrlKey) { // ctrl+enter, insert datafield
592
593                         var element = $(event.target);
594
595                         var index_field = event.data.scope.field.position;
596                         var new_field = index_field + 1;
597
598                         event.data.scope.field.record.insertFieldsAfter(
599                             event.data.scope.field,
600                             new MARC21.Field({
601                                 tag : '999',
602                                 subfields : [[' ','',0]]
603                             })
604                         );
605
606                         $scope.current_event_target = 'r' + $scope.recordId +
607                                                       'f' + new_field + 'tag';
608
609                         $scope.current_event_target_cursor_pos = 0;
610                         $scope.current_event_target_cursor_pos_end = 3;
611                         $scope.force_render = true;
612
613                         $timeout(function(){$scope.$digest()}).then(setCaret);
614
615                         event_return = false;
616
617                     } else if (event.which == 46 && event.ctrlKey) { // ctrl+del, remove field
618
619                         var del_field = event.data.scope.field.position;
620
621                         var domnode = $('#r'+event.data.scope.field.record.subfield('901','c')[1] + 'f' + del_field);
622
623                         event.data.scope.field.record.deleteFields(
624                             event.data.scope.field
625                         );
626
627                         domnode.scope().$destroy();
628                         domnode.remove();
629
630                         $scope.current_event_target = 'r' + $scope.recordId +
631                                                       'f' + del_field + 'tag';
632
633                         $scope.current_event_target_cursor_pos = 0;
634                         $scope.current_event_target_cursor_pos_end = 0
635                         $scope.force_render = true;
636
637                         $timeout(function(){$scope.$digest()}).then(setCaret);
638
639                         event_return = false;
640
641                     } else if (event.which == 46 && event.shiftKey && $(event.target).hasClass('marcsf')) { // shift+del, remove subfield
642
643                         var sf = event.data.scope.subfield[2] - 1;
644                         if (sf == -1) sf = 0;
645
646                         event.data.scope.field.deleteExactSubfields(
647                             event.data.scope.subfield
648                         );
649
650                         if (!event.data.scope.field.subfields[sf]) {
651                             $scope.current_event_target = 'r' + $scope.recordId +
652                                                           'f' + event.data.scope.field.position + 
653                                                           'tag';
654                         } else {
655                             $scope.current_event_target = 'r' + $scope.recordId +
656                                                           'f' + event.data.scope.field.position + 
657                                                           's' + sf + 'value';
658                         }
659
660                         $scope.current_event_target_cursor_pos = 0;
661                         $scope.current_event_target_cursor_pos_end = 0;
662                         $scope.force_render = true;
663
664                         $timeout(function(){$scope.$digest()}).then(setCaret);
665
666                         event_return = false;
667
668                     } else if (event.keyCode == 38) {
669                         if (event.ctrlKey) { // copy the field up
670                             var index_field = event.data.scope.field.position;
671
672                             var field_obj;
673                             if (event.data.scope.field.isControlfield()) {
674                                 field_obj = new MARC21.Field({
675                                     tag : event.data.scope.field.tag,
676                                     data : event.data.scope.field.data
677                                 });
678                             } else {
679                                 var sf_clone = [];
680                                 for (var i in event.data.scope.field.subfields) {
681                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
682                                 }
683                                 field_obj = new MARC21.Field({
684                                     tag : event.data.scope.field.tag,
685                                     ind1 : event.data.scope.field.ind1,
686                                     ind2 : event.data.scope.field.ind2,
687                                     subfields : sf_clone
688                                 });
689                             }
690
691
692                             event.data.scope.field.record.insertFieldsBefore(
693                                 event.data.scope.field,
694                                 field_obj
695                             );
696
697                             $scope.current_event_target = 'r' + $scope.recordId +
698                                                           'f' + index_field + 'tag';
699
700                             $scope.current_event_target_cursor_pos = 0;
701                             $scope.current_event_target_cursor_pos_end = 3;
702                             $scope.force_render = true;
703
704                             $timeout(function(){$scope.$digest()}).then(setCaret);
705
706                         } else { // jump to prev field
707                             if (event.data.scope.field.position > 0) {
708                                 $timeout(function(){
709                                     $scope.current_event_target_cursor_pos = 0;
710                                     $scope.current_event_target_cursor_pos_end = 0;
711                                     $scope.current_event_target = 'r' + $scope.recordId +
712                                                                   'f' + (event.data.scope.field.position - 1) +
713                                                                   'tag';
714                                 }).then(setCaret);
715                             }
716                         }
717
718                         event_return = false;
719
720                     } else if (event.keyCode == 40) { // down arrow...
721                         if (event.ctrlKey) { // copy the field down
722
723                             var index_field = event.data.scope.field.position;
724                             var new_field = index_field + 1;
725
726                             var field_obj;
727                             if (event.data.scope.field.isControlfield()) {
728                                 field_obj = new MARC21.Field({
729                                     tag : event.data.scope.field.tag,
730                                     data : event.data.scope.field.data
731                                 });
732                             } else {
733                                 var sf_clone = [];
734                                 for (var i in event.data.scope.field.subfields) {
735                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
736                                 }
737                                 field_obj = new MARC21.Field({
738                                     tag : event.data.scope.field.tag,
739                                     ind1 : event.data.scope.field.ind1,
740                                     ind2 : event.data.scope.field.ind2,
741                                     subfields : sf_clone
742                                 });
743                             }
744
745                             event.data.scope.field.record.insertFieldsAfter(
746                                 event.data.scope.field,
747                                 field_obj
748                             );
749
750                             $scope.current_event_target = 'r' + $scope.recordId +
751                                                           'f' + new_field + 'tag';
752
753                             $scope.current_event_target_cursor_pos = 0;
754                             $scope.current_event_target_cursor_pos_end = 3;
755                             $scope.force_render = true;
756
757                             $timeout(function(){$scope.$digest()}).then(setCaret);
758
759                         } else { // jump to next field
760                             if (event.data.scope.field.record.fields[event.data.scope.field.position + 1]) {
761                                 $timeout(function(){
762                                     $scope.current_event_target_cursor_pos = 0;
763                                     $scope.current_event_target_cursor_pos_end = 0;
764                                     $scope.current_event_target = 'r' + $scope.recordId +
765                                                                   'f' + (event.data.scope.field.position + 1) +
766                                                                   'tag';
767                                 }).then(setCaret);
768                             }
769                         }
770
771                         event_return = false;
772
773                     } else { // Assumes only marc editor elements have IDs that can trigger this event handler.
774                         $scope.current_event_target = $(event.target).attr('id');
775                         if ($scope.current_event_target) {
776                             $scope.current_event_target_cursor_pos =
777                                 event.target.selectionDirection=='backward' ?
778                                     event.target.selectionStart :
779                                     event.target.selectionEnd;
780                         }
781                     }
782
783                     return event_return;
784                 };
785
786                 function setCaret() {
787                     if ($scope.current_event_target) {
788                         console.log("Putting caret in " + $scope.current_event_target);
789                         if (!$scope.current_event_target_cursor_pos_end)
790                             $scope.current_event_target_cursor_pos_end = $scope.current_event_target_cursor_pos
791
792                         var element = $('#'+$scope.current_event_target).get(0);
793                         if (element) {
794                             element.focus();
795                             if (element.setSelectionRange) {
796                                 element.setSelectionRange(
797                                     $scope.current_event_target_cursor_pos,
798                                     $scope.current_event_target_cursor_pos_end
799                                 );
800                             }
801                             $scope.current_event_cursor_pos_end = null;
802                             $scope.current_event_target = null;
803                         }
804                     }
805                 }
806
807                 function loadRecord() {
808                     return (function() {
809                         var deferred = $q.defer();
810                         if ($scope.recordId) {
811                             egCore.pcrud.retrieve(
812                                 $scope.record_type, $scope.recordId
813                             ).then(function(rec) {
814                                 deferred.resolve(rec);
815                             });
816                         } else {
817                             var bre = new egCore.idl.bre();
818                             bre.marc($scope.marcXml);
819                             deferred.resolve(bre);
820                             $scope.brandNewRecord = true;
821                         }
822                         return deferred.promise;
823                     })().then(function(rec) {
824                         $scope.in_redo = true;
825                         $scope[$scope.record_type] = rec;
826                         $scope.record = new MARC21.Record({ marcxml : $scope.Record().marc() });
827                         $scope.calculated_record_type = $scope.record.recordType();
828                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
829                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
830                         $scope.save_stack_depth = $scope.record_undo_stack.length;
831                         $scope.flat_text_marc = $scope.record.toBreaker();
832
833                         if ($scope.record_type == 'bre') {
834                             $scope.bib_source = $scope.Record().source();
835                         }
836
837                     }).then(function(){
838                         return egTagTable.fetchFFPosTable($scope.calculated_record_type)
839                     }).then(function(){
840                         return egTagTable.fetchFFValueTable($scope.calculated_record_type)
841                     }).then(setCaret);
842                 }
843
844                 $scope.$watch('record.toBreaker()', function (newVal, oldVal) {
845                     if (!$scope.in_undo && !$scope.in_redo && oldVal != newVal) {
846                         $scope.record_undo_stack.push({
847                             breaker: oldVal,
848                             target: $scope.current_event_target,
849                             pos: $scope.current_event_target_cursor_pos
850                         });
851
852                         if ($scope.force_render) {
853                             $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
854                             $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
855                             $scope.force_render = false;
856                         }
857
858                         $scope.flat_text_marc = newVal;
859                     }
860
861                     if ($scope.record_undo_stack.length != $scope.save_stack_depth) {
862                         $scope.dirtyFlag = true;
863                     } else {
864                         $scope.dirtyFlag = false;
865                     }
866
867                     if ($scope.record_undo_stack.length > $scope.max_undo)
868                         $scope.record_undo_stack.shift();
869
870                     console.log('undo stack is ' + $scope.record_undo_stack.length + ' deep');
871                     $scope.in_redo = false;
872                     $scope.in_undo = false;
873                 });
874
875                 $scope.processUndo = function () {
876                     if ($scope.record_undo_stack.length) {
877                         $scope.in_undo = true;
878
879                         var undo_item = $scope.record_undo_stack.pop();
880                         $scope.record_redo_stack.push(undo_item);
881
882                         $scope.record = new MARC21.Record({ marcbreaker : undo_item.breaker });
883                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
884                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
885
886                         $scope.current_event_target = undo_item.target;
887                         $scope.current_event_target_cursor_pos = undo_item.pos;
888                         console.log('Undo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
889
890                         $timeout(function(){$scope.$digest()}).then(setCaret);
891                         return false;
892                     }
893
894                     return true;
895                 };
896
897                 $scope.processRedo = function () {
898                     if ($scope.record_redo_stack.length) {
899                         $scope.in_redo = true;
900
901                         var redo_item = $scope.record_redo_stack.pop();
902                         $scope.record_undo_stack.push(redo_item);
903
904                         $scope.record = new MARC21.Record({ marcbreaker : redo_item.breaker });
905                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
906                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
907
908                         $scope.current_event_target = redo_item.target;
909                         $scope.current_event_target_cursor_pos = redo_item.pos;
910                         console.log('Redo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
911
912                         $timeout(function(){$scope.$digest()}).then(setCaret);
913                         return false;
914                     }
915
916                     return true;
917                 };
918
919                 $scope.Record = function () {
920                     return $scope[$scope.record_type];
921                 };
922
923                 $scope.deleteRecord = function () {
924                     $scope.Record().deleted(true);
925                     return $scope.saveRecord();
926                 };
927
928                 $scope.undeleteRecord = function () {
929                     $scope.Record().deleted(false);
930                     return $scope.saveRecord();
931                 };
932
933                 $scope.saveRecord = function () {
934                     $scope.mangle_005();
935                     $scope.Record().editor(egCore.auth.user().id());
936                     $scope.Record().edit_date('now');
937                     $scope.Record().marc($scope.record.toXmlString());
938                     if ($scope.recordId) {
939                         return egCore.pcrud.update(
940                             $scope.Record()
941                         ).then(loadRecord);
942                     } else {
943                         $scope.Record().creator(egCore.auth.user().id());
944                         $scope.Record().create_date('now');
945                         return egCore.pcrud.create(
946                             $scope.Record()
947                         ).then(function(bre) {
948                             $scope.recordId = bre.id(); 
949                         }).then(loadRecord);
950                     }
951                 };
952
953                 $scope.seeBreaker = function () {
954                     alert($scope.record.toBreaker());
955                 };
956
957                 $scope.$watch('recordId',
958                     function(newVal, oldVal) {
959                         if (newVal && newVal !== oldVal) {
960                             loadRecord();
961                         }
962                     }
963                 );
964
965                 if ($scope.recordId || $scope.marcXml) {
966                     loadRecord();
967                 }
968
969                 $scope.mangle_005 = function () {
970                     var now = new Date();
971                     var y = now.getUTCFullYear();
972                 
973                     var m = now.getUTCMonth() + 1;
974                     if (m < 10) m = '0' + m;
975                 
976                     var d = now.getUTCDate();
977                     if (d < 10) d = '0' + d;
978                 
979                     var H = now.getUTCHours();
980                     if (H < 10) H = '0' + H;
981                 
982                     var M = now.getUTCMinutes();
983                     if (M < 10) M = '0' + M;
984                 
985                     var S = now.getUTCSeconds();
986                     if (S < 10) S = '0' + S;
987                 
988                     var stamp = '' + y + m + d + H + M + S + '.0';
989                     var f = $scope.record.field('005',true)[0];
990                     if (f) {
991                         f.data = stamp;
992                     } else {
993                         $scope.record.insertOrderedFields(
994                             new MARC21.Field({
995                                 tag : '005',
996                                 data: stamp
997                             })
998                         );
999                     }
1000                 
1001                 }
1002
1003             }
1004         ]          
1005     }
1006 })
1007
1008 .directive("egMarcEditBibsource", ['$timeout',function ($timeout) {
1009     return {
1010         restrict: 'E',
1011         replace: true,
1012         template: '<span class="nullable">'+
1013                     '<select class="form-control" ng-model="bib_source" ng-options="s.id() as s.source() for s in bib_sources">'+
1014                       '<option value="">Select a Source</option>'+
1015                     '</select>'+
1016                   '</span>',
1017         controller: ['$scope','egCore',
1018             function ($scope , egCore) {
1019
1020                 egCore.pcrud.retrieveAll('cbs', {}, {atomic : true})
1021                     .then(function(list) { $scope.bib_sources = list; });
1022
1023                 $scope.$watch('bib_source',
1024                     function(newVal, oldVal) {
1025                         if (newVal !== oldVal) {
1026                             $scope.bre.source(newVal);
1027                         }
1028                     }
1029                 );
1030
1031             }
1032         ]
1033     }
1034 }])
1035
1036 ;