]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/services/marcedit.js
LP#1745462: avoid trying to validate empty fields
[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: '=', contextMenuEvent: '=' },
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.css('borderTop','solid 1px');
18                 }
19
20                 $scope.setContent = function (v, a) {
21                     var replace_with = v;
22
23                     if (a) {
24                         replace_with = a(
25                             $scope,
26                             $element,
27                             $scope.item.value,
28                             $scope.$parent.$parent.content,
29                             $scope.contextMenuEvent
30                         );
31                     }
32
33                     if (typeof replace_with !== 'undefined') {
34                         $timeout(function(){
35                             $scope.$parent.$parent.$apply(function(){
36                                 $scope.$parent.$parent.content = replace_with
37                             })
38                         }, 0);
39                     }
40                     $($element).parent().css({display: 'none'});
41                 }
42             }
43         ]
44     }
45 }])
46
47 .directive("contenteditable", function() {
48     return {
49         restrict: "A",
50         require: "ngModel",
51         link: function(scope,element,attrs,ngModel){
52
53             function read(){
54                 // save new text into model
55                 var elhtml = element.text();
56                 ngModel.$setViewValue(elhtml);
57             }
58
59             ngModel.$render = function(){
60                 element.text(ngModel.$viewValue || "");
61             };
62
63             element.bind("blur.c_e keyup.c_e change.c_e", function(){
64                 scope.$apply(read);
65             });
66         }
67     };
68 })
69
70 .directive("egMarcEditEditable", ['$timeout', '$compile', '$document', function ($timeout, $compile, $document) {
71     return {
72         restrict: 'E',
73         replace: true,
74         templateUrl: './cat/share/t_marcedit_editable',
75         scope: {
76             field: '=',
77             onKeydown: '=',
78             subfield: '=',
79             content: '=',
80             contextItemContainer: '@',
81             contextItemGenerator: '=',
82             max: '@',
83             itype: '@',
84             selectOnFocus: '=',
85             advanceFocusAfterInput: '=',
86             isDisabled: "="
87         },
88         controller : ['$scope',
89             function ( $scope ) {
90                 $scope.isInputDisabled = $scope.isDisabled == 'disabled';
91                 if ($scope.contextItemContainer && angular.isArray($scope.$parent[$scope.contextItemContainer]))
92                     $scope.item_container = $scope.$parent[$scope.contextItemContainer];
93                 else if ($scope.contextItemGenerator)
94                     $scope.item_generator = $scope.contextItemGenerator;
95
96                 $scope.showContext = function (event) {
97                     $scope.item_list = [];
98                     if ($scope.item_container) {
99                         $scope.item_list = $scope.item_container;
100                     } else if ($scope.item_generator) {
101                         // always recalculate; tag and/or subfield
102                         // codes may have changed
103
104                         var generator = $scope.item_generator;
105                         if (!angular.isArray(generator)) generator = [generator];
106
107                         var is_first = true;
108                         angular.forEach(generator, function (g) {
109                             var sub_list = g();
110
111                             if (is_first)
112                                 is_first = false;
113                             else if (Boolean(sub_list[0]))
114                                 sub_list[0].divider = true;
115
116                             $scope.item_list = $scope.item_list.concat(sub_list);
117                         });
118
119                     } else {
120                         return true;
121                     }
122
123                     if (angular.isArray($scope.item_list) && $scope.item_list.length > 0) { // we have a list of values or transforms
124                         console.log('Showing context menu...');
125                         $('body').trigger('click');
126
127                         $scope.contextMenuEvent = event;
128                         var tmpl = 
129                             '<ul class="dropdown-menu scrollable-menu" role="menu" style="z-index: 2000;">'+
130                                 '<eg-context-menu-item context-menu-event="contextMenuEvent" ng-repeat="item in item_list" item="item" content="content"/>'+
131                             '</ul>';
132             
133                         var tnode = angular.element(tmpl);
134                         $document.find('body').append(tnode);
135
136                         $(tnode).css({
137                             display: 'block',
138                             top: event.pageY,
139                             left: event.pageX
140                         });
141
142                         $timeout(function() {
143                             var e = $compile(tnode)($scope);
144                         }, 0);
145
146
147                         $('body').on('click.context_menu',function() {
148                             $(tnode).css('display','none');
149                             $('body').off('click.context_menu');
150                         });
151
152                         return false;
153                     }
154             
155                     return true;
156                 }
157
158             }
159         ],
160         link: function (scope, element, attrs) {
161
162             if (scope.onKeydown) element.bind('keydown', {scope : scope}, scope.onKeydown);
163
164             if (Boolean(scope.selectOnFocus)) {
165                 element.addClass('noSelection');
166                 element.bind('focus', function (e) {
167                     var el = $(e.target).children('input').first();
168                     if (el.select) { el.select(); }
169                 });
170             }
171
172             element.children("div[contenteditable]").each(function() {
173                 $(this).focus(function(e) {
174                     var tNode = e.target.firstChild;
175                     var range = document.createRange();
176                     range.setStart(tNode, 0);
177                     range.setEnd(tNode, tNode.length);
178                     var sel = window.getSelection();
179                     sel.removeAllRanges();
180                     sel.addRange(range);
181                 });
182             });
183
184             function findCaretTarget(id, itype) {
185                 var tgt = null;
186                 if (itype == 'tag') {
187                     tgt = id.replace(/tag$/, 'i1');
188                 } else if (itype == 'ind') {
189                     if (id.match(/i1$/)) {
190                         tgt = id.replace(/i1$/, 'i2');
191                     } else if (id.match(/i2$/)) {
192                         tgt = id.replace(/i2$/, 's0code');
193                     }
194                 } else if (itype == 'sfc') {
195                     tgt = id.replace(/code$/, 'value');
196                 }
197                 return tgt;
198             }
199             if (Boolean(scope.advanceFocusAfterInput)) {
200                 element.bind('input', function (e) {
201                     if (scope.content.length == scope.max) {
202                         var tgt = findCaretTarget(e.currentTarget.id, scope.itype);
203                         if (tgt) {
204                             var element = $('#' + tgt).get(0);
205                             if (element) {
206                                 element.focus();
207                             }
208                         }
209                     }
210                 });
211             }
212
213             element.bind('change', function (e) { element.size = scope.max || parseInt(scope.content.length * 1.1) });
214
215             element.bind('contextmenu', {scope : scope}, scope.showContext);
216         }
217     }
218 }])
219
220 .directive("egMarcEditFixedField", ['$timeout', '$compile', '$document', function ($timeout, $compile, $document) {
221     return {
222         transclude: true,
223         restrict: 'E',
224         template: '<div class="col-md-2">'+
225                     '<div class="col-md-1"><label name="{{fixedField}}" for="{{fixedField}}_ff_input">{{fixedFieldLabel}}</label></div>'+
226                     '<div class="col-md-1"><input type="text" style="padding-left: 5px; margin-left: 1em" size="4" id="{{fixedField}}_ff_input"/></div>'+
227                   '</div>',
228         scope: { record: "=", fixedField: "@", fixedFieldLabel: "@" },
229         replace: true,
230         controller : ['$scope', '$element', 'egTagTable',
231             function ( $scope ,  $element ,  egTagTable) {
232                 $($element).removeClass('fixed-field-box');
233                 $($element).children().css({ display : 'none' });
234                 $scope.fixedFieldLabel = $scope.fixedFieldLabel || $scope.fixedField;
235                 $scope.me = null;
236                 $scope.content = null; // this is where context menus dump their values
237                 $scope.item_container = [];
238                 $scope.in_handler = false;
239                 $scope.ready = false;
240                 $element.find('input').bind('focus', function (e) { e.target.select() });
241                 $element.find('input').bind('mouseup', function(e) {
242                     e.preventDefault()
243                     return false;
244                 });
245
246                 $scope.$watch('content', function (newVal, oldVal) {
247                     var input = $($element).find('input');
248                     input.val(newVal);
249                     input.trigger('keyup'); // cascade the update
250                 });
251
252                 $scope.$watch('record.ready', function (newVal, oldVal) { // wait for the record to be loaded
253                     if (newVal && !$scope.ready) {
254                         $scope.rtype = $scope.record.recordType();
255
256                         egTagTable.fetchFFPosTable( $scope.rtype ).then(function (ff_list) {
257                             angular.forEach(ff_list, function (ff) {
258                                 if (!$scope.me) {
259                                     if (ff.fixed_field == $scope.fixedField && ff.rec_type == $scope.rtype) {
260                                         $scope.me = ff;
261                                         $scope.ready = true;
262                                         $($element).addClass('fixed-field-box');
263                                         $($element).children().css({ display : 'inline' });
264
265                                         var input = $($element).find('input');
266                                         input.attr('maxlength', $scope.me.length);
267                                         input.val($scope.record.extractFixedField($scope.me.fixed_field));
268                                         input.on('keyup', function(e) {
269                                             $scope.in_handler = true;
270                                             $scope.record.setFixedField($scope.me.fixed_field, input.val());
271                                             try { $scope.$parent.$digest(); } catch(e) {};
272                                         });
273                                     }
274                                 }
275                             });
276                             return $scope.me;
277                         }).then(function (me) {
278                             if (me) {
279                                 $scope.$watch(
280                                     function() {
281                                         return $scope.record.extractFixedField($scope.fixedField);
282                                     },
283                                     function (newVal, oldVal) {
284                                         if ($scope.in_handler) {
285                                             $scope.in_handler = false;
286                                         } else if (oldVal != newVal) {
287                                             $($element).find('input').val(newVal);
288                                         }
289                                     }
290                                 );
291                             }
292                         }).then(function () {
293                             return egTagTable.fetchFFValueTable( $scope.rtype );
294                         }).then(function (vlist) {
295                             if (vlist[$scope.fixedField]) {
296                                 vlist[$scope.fixedField].forEach(function (v) {
297                                     if (v[0].length <= v[2]) {
298                                         $scope.item_container.push({ value : v[0], label : v[0] + ': ' + v[1] });
299                                     }
300                                 });
301                             }
302                         }).then(function () {
303                             if ($scope.item_container && $scope.item_container.length)
304                                 $($element).bind('contextmenu', $scope.showContext);
305                         });
306
307                     }
308                 });
309
310                 $scope.showContext = function (event) {
311                     if ($scope.context_menu_element) {
312                         console.log('Reshowing context menu...');
313                         $('body').trigger('click');
314                         $($scope.context_menu_element).css({ display: 'block', top: event.pageY, left: event.pageX });
315                         $('body').on('click.context_menu',function() {
316                             $($scope.context_menu_element).css('display','none');
317                             $('body').off('click.context_menu');
318                         });
319                         return false;
320                     }
321
322                     if (angular.isArray($scope.item_container)) { // we have a list of values or transforms
323                         console.log('Showing context menu...');
324                         $('body').trigger('click');
325
326                         var tmpl = 
327                             '<ul class="dropdown-menu scrollable-menu" role="menu" style="z-index: 2000;">'+
328                                 '<eg-context-menu-item ng-repeat="item in item_container" item="item" content="content"/>'+
329                             '</ul>';
330             
331                         var tnode = angular.element(tmpl);
332                         $document.find('body').append(tnode);
333
334                         $(tnode).css({
335                             display: 'block',
336                             top: event.pageY,
337                             left: event.pageX
338                         });
339
340                         $scope.context_menu_element = tnode;
341
342                         $timeout(function() {
343                             var e = $compile(tnode)($scope);
344                         }, 0);
345
346
347                         $('body').on('click.context_menu',function() {
348                             $(tnode).css('display','none');
349                             $('body').off('click.context_menu');
350                         });
351
352                         return false;
353                     }
354             
355                     return true;
356                 }
357
358             }
359         ]
360     }
361 }])
362
363 .directive("egMarcEditSubfield", function () {
364     return {
365         transclude: true,
366         restrict: 'E',
367         template: '<span>'+
368                     '<span><label class="marcedit marcsfcodedelimiter"'+
369                         'for="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}s{{subfield[2]}}code" '+
370                         '>‡</label><eg-marc-edit-editable '+
371                         'itype="sfc" '+
372                         'select-on-focus="true" '+
373                         'advance-focus-after-input="true" '+
374                         'class="marcedit marcsf marcsfcode" '+
375                         'field="field" '+
376                         'subfield="subfield" '+
377                         'content="subfield[0]" '+
378                         'max="1" '+
379                         'on-keydown="onKeydown" '+
380                         'context-item-generator="sf_code_options" '+
381                         'id="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}s{{subfield[2]}}code" '+
382                     '/></span>'+
383                     '<span><eg-marc-edit-editable '+
384                         'itype="sfv" '+
385                         'select-on-focus="true" '+
386                         'class="marcedit marcsf marcsfvalue" '+
387                         'field="field" '+
388                         'subfield="subfield" '+
389                         'content="subfield[1]" '+
390                         'on-keydown="onKeydown" '+
391                         'context-item-generator="sf_val_options" '+
392                         'id="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}s{{subfield[2]}}value" '+
393                     '/></span>'+
394                   '</span>',
395         scope: { field: "=", subfield: "=", onKeydown: '=' },
396         replace: true,
397         controller : ['$scope', 'egTagTable',
398             function ( $scope ,  egTagTable) {
399
400                 $scope.sf_code_options = function () {
401                     return egTagTable.getSubfieldCodes($scope.field.tag);
402                 }
403                 $scope.sf_val_options = function () {
404                     return egTagTable.getSubfieldValues($scope.field.tag, $scope.subfield[0]);
405                 }
406             }
407         ]
408     }
409 })
410
411 .directive("egMarcEditInd", function () {
412     return {
413         transclude: true,
414         restrict: 'E',
415         template: '<span><eg-marc-edit-editable '+
416                       'itype="ind" '+
417                       'class="marcedit marcind" '+
418                       'select-on-focus="true" '+
419                       'advance-focus-after-input="true" '+
420                       'field="field" '+
421                       'content="ind" '+
422                       'max="1" '+
423                       'on-keydown="onKeydown" '+
424                       'context-item-generator="ind_val_options" '+
425                       'id="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}i{{indNumber}}"'+
426                       '/></span>',
427         scope: { ind : '=', field: '=', onKeydown: '=', indNumber: '@' },
428         replace: true,
429         controller : ['$scope', 'egTagTable',
430             function ( $scope ,  egTagTable) {
431
432                 $scope.ind_val_options = function () {
433                     return egTagTable.getIndicatorValues($scope.field.tag, $scope.indNumber);
434                 }
435             }
436         ]
437     }
438 })
439
440 .directive("egMarcEditTag", function () {
441     return {
442         transclude: true,
443         restrict: 'E',
444         template: '<span><eg-marc-edit-editable '+
445                       'itype="tag" '+
446                       'class="marcedit marctag" '+
447                       'select-on-focus="true" '+
448                       'advance-focus-after-input="true" '+
449                       'field="field" '+
450                       'content="tag" '+
451                       'max="3" '+
452                       'on-keydown="onKeydown" '+
453                       'context-item-generator="tag_options" '+
454                       'id="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}tag"'+
455                       '/></span>',
456         scope: { tag : '=', field: '=', onKeydown: '=', contextFunctions: '=' },
457         replace: true,
458         controller : ['$scope', 'egTagTable', 'egCore',
459             function ( $scope ,  egTagTable,   egCore) {
460
461                 $scope.tag_options = [
462                     function () {
463                         var options = [
464                             { label : egCore.strings.ADD_006, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.add006(e) } },
465                             { label : egCore.strings.ADD_007, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.add007(e) } },
466                             { label : egCore.strings.ADD_REPLACE_008, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.reify008(e) } },
467                         ];
468
469                         if (!$scope.field.isControlfield()) {
470                             options = options.concat([
471                                 { label : egCore.strings.INSERT_FIELD_AFTER, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.addDatafield(e) } },
472                                 { label : egCore.strings.INSERT_FIELD_BEFORE, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.addDatafield(e,true) } },
473                             ]);
474                         }
475
476                         options.push({ label : egCore.strings.DELETE_FIELD, action : function(j1,j2,j3,j4,e) { $scope.contextFunctions.deleteDatafield(e) } });
477                         return options;
478                     },
479                     function () { return egTagTable.getFieldTags() }
480                 ];
481
482             }
483         ]
484     }
485 })
486
487 .directive("egMarcEditDatafield", function () {
488     return {
489         transclude: true,
490         restrict: 'E',
491         template: '<div>'+
492                     '<span><eg-marc-edit-tag context-functions="contextFunctions" field="field" tag="field.tag" on-keydown="onKeydown"/></span>'+
493                     '<span><eg-marc-edit-ind field="field" ind="field.ind1" on-keydown="onKeydown" ind-number="1"/></span>'+
494                     '<span><eg-marc-edit-ind field="field" ind="field.ind2" on-keydown="onKeydown" ind-number="2"/></span>'+
495                     '<span><eg-marc-edit-subfield ng-class="{ \'unvalidatedheading\' : field.heading_checked && !field.heading_valid, \'marcedit_stacked_subfield\' : stackSubfields.enabled }" ng-repeat="subfield in field.subfields" subfield="subfield" field="field" on-keydown="onKeydown"/></span>'+
496                     // FIXME: template should probably be moved to file to improve
497                     // translatibility
498                     '<span  ng-class="{ \'marcedit_stacked_subfield\' : stackSubfields.enabled }">' +
499                     '<button class="btn btn-info btn-xs" '+
500                     'aria-label="Manage authority record links" '+
501                     'ng-show="isAuthorityControlled(field)"'+
502                     'ng-click="spawnAuthorityLinker()"'+
503                     '>'+
504                     '<span class="glyphicon glyphicon-link"></span>'+
505                     '</button>'+
506                     '<span ng-show="field.heading_checked && field.heading_valid" class="glyphicon glyphicon-ok-sign"></span>'+
507                     '<span ng-show="field.heading_checked && !field.heading_valid" class="glyphicon glyphicon-question-sign"></span>'+
508                     '</span>'+
509                   '</div>',
510         scope: { field: "=", onKeydown: '=', contextFunctions: '=' },
511         replace: true,
512         controller : ['$scope','$uibModal',
513             function ( $scope,  $uibModal ) {
514                 $scope.stackSubfields = $scope.$parent.$parent.stackSubfields;
515                 $scope.isAuthorityControlled = function () {
516                     return ($scope.$parent.$parent.record_type == 'bre') &&
517                            $scope.$parent.$parent.controlSet.bibFieldByTag($scope.field.tag);
518                 }
519                 $scope.spawnAuthorityLinker = function() {
520                     // intentionally making a clone in case
521                     // user decides to abandon the linking
522                     var fieldCopy = new MARC21.Field({
523                         tag       : $scope.field.tag,
524                         ind1      : $scope.field.ind1,
525                         ind2      : $scope.field.ind2
526                     });
527                     angular.forEach($scope.field.subfields, function(sf) {
528                         fieldCopy.subfields.push(sf.slice(0));
529                     });
530                     var cs = $scope.$parent.$parent.controlSet;
531                     var args = { changed : false };
532                     $uibModal.open({
533                         templateUrl: './cat/share/t_authority_link_dialog',
534                         backdrop: 'static',
535                         size: 'lg',
536                         controller: ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
537                             $scope.controlSet = cs;
538                             $scope.bibField = fieldCopy;
539                             $scope.focusMe = true;
540                             $scope.args = args;
541                             $scope.ok = function(args) { $uibModalInstance.close(args) };
542                             $scope.cancel = function () { $uibModalInstance.dismiss() };
543                         }]
544                     }).result.then(function (args) {
545                         if (args.changed) {
546                             $scope.field.subfields.length = 0;
547                             angular.forEach(fieldCopy.subfields, function(sf) {
548                                 $scope.field.addSubfields(sf[0], sf[1]);
549                             });
550                         }
551                     });
552                 }
553             }
554         ]
555     }
556 })
557
558 .directive("egMarcEditControlfield", function () {
559     return {
560         transclude: true,
561         restrict: 'E',
562         template: '<div>'+
563                     '<span><eg-marc-edit-tag context-functions="contextFunctions" field="field" tag="field.tag" on-keydown="onKeydown"/></span>'+
564                     '<span><eg-marc-edit-editable '+
565                       'itype="cfld" '+
566                       'field="field" '+
567                       'class="marcedit marcdata" '+
568                       'content="field.data" '+
569                       'on-keydown="onKeydown" '+
570                       'id="r{{field.record.subfield(\'901\',\'c\')[1] || 0}}f{{field.position}}data"'+
571                       '/></span>'+
572                       // TODO: move to TT2 template
573                       '<button class="btn btn-info btn-xs" '+
574                       'aria-label="Physical Characteristics Wizard" '+
575                       'ng-show="showPhysCharLink()"'+
576                       'ng-click="spawnPhysCharWizard()"'+
577                       '>'+
578                       '<span class="glyphicon glyphicon-link"></span>'+
579                       '</button>'+
580                   '</div>',
581         scope: { field: "=", onKeydown: '=', contextFunctions: '=' },
582         controller : ['$scope','$uibModal',
583             function ( $scope,  $uibModal) {
584                 $scope.showPhysCharLink = function () {
585                     return ($scope.$parent.$parent.record_type == 'bre') 
586                         && $scope.field.tag == '007';
587                 }
588                 $scope.spawnPhysCharWizard = function() {
589                     var args = {
590                         changed : false,
591                         field : $scope.field,
592                         orig_value : $scope.field.data
593                     };
594                     $uibModal.open({
595                         templateUrl: './cat/share/t_physchar_dialog',
596                         controller: ['$scope','$uibModalInstance',
597                             function( $scope , $uibModalInstance) {
598                             $scope.focusMe = true;
599                             $scope.args = args;
600                             $scope.ok = function(args) { $uibModalInstance.close(args) };
601                             $scope.cancel = function () { 
602                                 $uibModalInstance.dismiss();
603                                 args.field.data = args.orig_value;
604                             };
605                         }],
606                     }).result.then(function (args) {
607                         // $scope.field.data is changed within the 
608                         // wizard.  Nothing left to do on submit.
609                     });
610
611                 }
612             }
613         ]
614     }
615 })
616
617 .directive("egMarcEditLeader", function () {
618     return {
619         transclude: true,
620         restrict: 'E',
621         template: '<div>'+
622                     '<span><eg-marc-edit-editable '+
623                       'class="marcedit marctag" '+
624                       'content="tag" '+
625                       'on-keydown="onKeydown" '+
626                       'id="leadertag" '+
627                       'is-disabled="disabled"'+
628                       '/></span>'+
629                     '<span><eg-marc-edit-editable '+
630                       'class="marcedit marcdata" '+
631                       'itype="ldr" '+
632                       'max="{{record.leader.length}}" '+
633                       'content="record.leader" '+
634                       'id="r{{record.subfield(\'901\',\'c\')[1] || 0}}leaderdata" '+
635                       'on-keydown="onKeydown"'+
636                       '/></span>'+
637                   '</div>',
638         controller : ['$scope',
639             function ( $scope ) {
640                 $scope.tag = 'LDR';
641             }
642         ],
643         scope: { record: "=", onKeydown: '=' }
644     }
645 })
646
647 /// TODO: fixed field editor and such
648 .directive("egMarcEditRecord", function () {
649     return {
650         templateUrl : './cat/share/t_marcedit',
651         restrict: 'E',
652         replace: true,
653         scope: {
654             dirtyFlag : '=',
655             recordId : '=',
656             marcXml : '=',
657             onSave : '=',
658             // in-place mode means that the editor is being
659             // used just to munge some MARCXML client-side, rather
660             // than to (immediately) update the database
661             //
662             // In short, we can use inPlaceMode as a way to skip
663             // "normal" bre saving and then process the MARC ourselves
664             // via a callback
665             //
666             // inPlaceMode is r/w to allow our Z39.50 import editor to be
667             // switched back into a normal editor after the initial import
668             inPlaceMode : '=',
669             fastAdd : '@',
670             flatOnly : '@',
671             embedded : '@',
672             recordType : '@',
673             maxUndo : '@',
674             saveLabel : '@'
675         },
676         link: function (scope, element, attrs) {
677
678             element.bind('mouseup', function(e) {;
679                 scope.current_event_target = $(e.target).attr('id');
680                 if (scope.current_event_target && $(e.target).hasClass('noSelection')) {
681                     e.preventDefault()
682                     return false;
683                 }
684             });
685
686             element.bind('click', function(e) {;
687                 scope.current_event_target = $(e.target).attr('id');
688                 if (scope.current_event_target) {
689                     console.log('Recording click event on ' + scope.current_event_target);
690                     scope.current_event_target_cursor_pos =
691                         e.target.selectionDirection=='backward' ?
692                             e.target.selectionStart :
693                             e.target.selectionEnd;
694                 }
695             });
696
697         },
698         controller : ['$timeout','$scope','$q','$window','egCore', 'egTagTable','egConfirmDialog','egAlertDialog',
699             function ( $timeout , $scope , $q,  $window , egCore ,  egTagTable , egConfirmDialog , egAlertDialog ) {
700
701
702                 $scope.onSaveCallback = $scope.onSave;
703                 if (typeof $scope.onSaveCallback !== 'undefined' && !angular.isArray($scope.onSaveCallback))
704                     $scope.onSaveCallback = [ $scope.onSaveCallback ];
705
706                 MARC21.Record.delimiter = '$';
707
708                 $scope.enable_fast_add = false;
709                 $scope.fast_item_callnumber = '';
710                 $scope.fast_item_barcode = '';
711                 
712                 $scope.flatEditor = { isEnabled : $scope.flatOnly ? true : false };
713                 
714                 egCore.hatch.getItem('cat.marcedit.flateditor').then(function(val) {
715                     $scope.flatEditor.isEnabled = val;
716                 });
717                 
718                 $scope.$watch('flatEditor.isEnabled', function (newVal, oldVal) {
719                     if (newVal != oldVal) egCore.hatch.setItem('cat.marcedit.flateditor', newVal);
720                 });
721
722                 $scope.brandNewRecord = false;
723                 $scope.bib_source = null;
724                 $scope.record_type = $scope.recordType || 'bre';
725                 $scope.max_undo = $scope.maxUndo || 100;
726                 $scope.record_undo_stack = [];
727                 $scope.record_redo_stack = [];
728                 $scope.in_undo = false;
729                 $scope.in_redo = false;
730                 $scope.record = new MARC21.Record();
731                 $scope.save_stack_depth = 0;
732                 $scope.controlfields = [];
733                 $scope.datafields = [];
734                 $scope.controlSet = egTagTable.getAuthorityControlSet();
735                 $scope.showHelp = false;
736                 $scope.stackSubfields = { enabled : false };
737                 egCore.hatch.getItem('cat.marcedit.stack_subfields').then(function(val) {
738                     $scope.stackSubfields.enabled = val;
739                 });
740                 $scope.$watch('stackSubfields.enabled', function (newVal, oldVal) {
741                     if (newVal != oldVal) egCore.hatch.setItem('cat.marcedit.stack_subfields', newVal);
742                 });
743                 $scope.caretRecId = $scope.recordId;
744
745                 egTagTable.loadTagTable({ marcRecordType : $scope.record_type });
746
747                 $scope.saveFlatTextMARC = function () {
748                     $scope.record = new MARC21.Record({ marcbreaker : $scope.flat_text_marc });
749                 };
750
751                 $scope.refreshVisual = function () {
752                     if (!$scope.flatEditor.isEnabled) {
753                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
754                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
755                     }
756                 };
757
758                 var addDatafield = function (e,before) {
759                     var element = $(e.target);
760
761                     var index_field = e.data.scope.field.position;
762                     var new_field_index = index_field;
763
764                     var new_field = new MARC21.Field({
765                         tag : '999',
766                         subfields : [[' ','',0]]
767                     });
768
769                     if (Boolean(before)) {
770                         e.data.scope.field.record.insertFieldsBefore(
771                             e.data.scope.field,
772                             new_field
773                         );
774                     } else {
775                         e.data.scope.field.record.insertFieldsAfter(
776                             e.data.scope.field,
777                             new_field
778                         );
779                         new_field_index++;
780                     }
781
782                     $scope.current_event_target = 'r' + $scope.caretRecId +
783                                                   'f' + new_field_index + 'tag';
784
785                     $scope.current_event_target_cursor_pos = 0;
786                     $scope.current_event_target_cursor_pos_end = 3;
787                     $scope.force_render = true;
788
789                     $timeout(function(){$scope.$digest()}).then(setCaret);
790                 };
791
792                 var deleteDatafield = function (e) {
793                     var del_field = e.data.scope.field.position;
794
795                     var sf901c = e.data.scope.field.record.subfield('901','c');
796                     var recId = (sf901c === null) ? '' : sf901c[1];
797                     var domnode = $('#r' + recId + 'f' + del_field);
798
799                     e.data.scope.field.record.deleteFields(
800                         e.data.scope.field
801                     );
802
803                     domnode.scope().$destroy();
804                     domnode.remove();
805
806                     $scope.current_event_target = 'r' + $scope.caretRecId +
807                                                   'f' + del_field + 'tag';
808
809                     $scope.current_event_target_cursor_pos = 0;
810                     $scope.current_event_target_cursor_pos_end = 0
811                     $scope.force_render = true;
812
813                     $timeout(function(){$scope.$digest()}).then(setCaret);
814                 };
815
816                 var add006 = function (e) {
817                     e.data.scope.field.record.insertOrderedFields(
818                         new MARC21.Field({
819                             tag : '006',
820                             data : '                                        '
821                         })
822                     );
823
824                     $scope.force_render = true;
825                     $timeout(function(){$scope.$digest()}).then(setCaret);
826                 };
827
828                 var add007 = function (e) {
829                     e.data.scope.field.record.insertOrderedFields(
830                         new MARC21.Field({
831                             tag : '007',
832                             data : '                                        '
833                         })
834                     );
835
836                     $scope.force_render = true;
837                     $timeout(function(){$scope.$digest()}).then(setCaret);
838                 };
839
840                 var reify008 = function (e) {
841                     var new_008_data = e.data.scope.field.record.generate008();
842
843
844                     var old_008s = e.data.scope.field.record.field('008',true);
845                     old_008s.forEach(function(o) {
846                         var domnode = $('#r'+o.record.subfield('901','c')[1] + 'f' + o.position);
847                         domnode.scope().$destroy();
848                         domnode.remove();
849                         e.data.scope.field.record.deleteFields(o);
850                     });
851
852                     e.data.scope.field.record.insertOrderedFields(
853                         new MARC21.Field({
854                             tag : '008',
855                             data : new_008_data
856                         })
857                     );
858
859                     $scope.force_render = true;
860                     $timeout(function(){$scope.$digest()}).then(setCaret);
861                 };
862
863                 $scope.context_functions = {
864                     addDatafield : addDatafield,
865                     deleteDatafield : deleteDatafield,
866                     add006 : add006,
867                     add007 : add007,
868                     reify008 : reify008
869                 };
870
871                 $scope.onKeydown = function (event) {
872                     var event_return = true;
873
874                     console.log(
875                         'keydown: which='+event.which+
876                         ', ctrlKey='+event.ctrlKey+
877                         ', shiftKey='+event.shiftKey+
878                         ', altKey='+event.altKey+
879                         ', metaKey='+event.altKey
880                     );
881
882                     if (event.which == 89 && event.ctrlKey) { // ctrl+y, redo
883                         event_return = $scope.processRedo();
884                     } else if (event.which == 90 && event.ctrlKey) { // ctrl+z, undo
885                         event_return = $scope.processUndo();
886                     } else if ((event.which == 68 || event.which == 73) && event.ctrlKey) { // ctrl+d or ctrl+i, insert subfield
887
888                         var element = $(event.target);
889                         var new_sf, index_sf, move_data;
890
891                         if (element.hasClass('marcsfvalue')) {
892                             index_sf = event.data.scope.subfield[2];
893                             new_sf = index_sf + 1;
894
895                             var start = event.target.selectionStart || getCaretPosEditableDiv(element);
896                             var end;
897                             if (event.target.value){
898                                 end = event.target.selectionEnd - event.target.selectionStart ?
899                                         event.target.selectionEnd :
900                                         event.target.value.length;
901                             } else {
902                                 end = element.text().length;
903                             }
904
905                             move_data = element.value ?
906                                 element.value.substring(start,end) :
907                                 element.text().substring(start, end);
908
909                         } else if (element.hasClass('marcsfcode')) {
910                             index_sf = event.data.scope.subfield[2];
911                             new_sf = index_sf + 1;
912                         } else if (element.hasClass('marctag') || element.hasClass('marcind')) {
913                             index_sf = 0;
914                             new_sf = index_sf;
915                         }
916
917                         $scope.current_event_target = 'r' + $scope.caretRecId +
918                                                       'f' + event.data.scope.field.position + 
919                                                       's' + new_sf + 'code';
920
921                         event.data.scope.field.subfields.forEach(function(sf) {
922                             if (sf[2] >= new_sf) sf[2]++;
923                             if (sf[2] == index_sf) {
924                                 sf[1] = event.target.value ?
925                                     event.target.value.substring(0,start) + event.target.value.substring(end) :
926                                     element.text().substring(0, start);
927                             }
928                         });
929                         event.data.scope.field.subfields.splice(
930                             new_sf,
931                             0,
932                             [' ', move_data, new_sf ]
933                         );
934
935                         $scope.current_event_target_cursor_pos = 0;
936                         $scope.current_event_target_cursor_pos_end = 1;
937
938                         $timeout(function(){$scope.$digest()}).then(setCaret);
939
940                         event_return = false;
941
942                     } else if (event.which == 117 && event.shiftKey) { // shift + F6, insert 006
943                         add006(event);
944                         event_return = false;
945
946                     } else if (event.which == 118 && event.shiftKey) { // shift + F7, insert 007
947                         add007(event);
948                         event_return = false;
949
950                     } else if (event.which == 119 && event.shiftKey) { // shift + F8, insert/replace 008
951                         reify008(event);
952                         event_return = false;
953
954                     } else if (event.which == 13 && event.ctrlKey) { // ctrl+enter, insert datafield
955                         addDatafield(event, event.shiftKey); // shift key inserts before
956                         event_return = false;
957
958                     } else if (event.which == 13 &&
959                               ($(event.target).hasClass('marcsf') || $(event.target.parentNode).hasClass('marcsf'))
960                               ) {
961                         // bare return; don't allow it
962                         event_return = false;
963
964                     } else if (event.which == 46 && event.ctrlKey) { // ctrl+del, remove field
965                         deleteDatafield(event);
966                         event_return = false;
967
968                     } else if (event.which == 46 && event.shiftKey && ($(event.target).hasClass('marcsf') || $(event.target.parentNode).hasClass('marcsf'))) { 
969                         // shift+del, remove subfield
970
971                         var sf = event.data.scope.subfield[2] - 1;
972                         if (sf == -1) sf = 0;
973
974                         event.data.scope.field.deleteExactSubfields(
975                             event.data.scope.subfield
976                         );
977
978                         if (!event.data.scope.field.subfields[sf]) {
979                             $scope.current_event_target = 'r' + $scope.caretRecId +
980                                                           'f' + event.data.scope.field.position + 
981                                                           'tag';
982                         } else {
983                             $scope.current_event_target = 'r' + $scope.caretRecId +
984                                                           'f' + event.data.scope.field.position + 
985                                                           's' + sf + 'value';
986                         }
987
988                         $scope.current_event_target_cursor_pos = 0;
989                         $scope.current_event_target_cursor_pos_end = 0;
990                         $scope.force_render = true;
991
992                         $timeout(function(){$scope.$digest()}).then(setCaret);
993
994                         event_return = false;
995
996                     } else if (event.keyCode == 38) {
997                         if (event.ctrlKey) { // copy the field up
998                             var index_field = event.data.scope.field.position;
999
1000                             var field_obj;
1001                             if (event.data.scope.field.isControlfield()) {
1002                                 field_obj = new MARC21.Field({
1003                                     tag : event.data.scope.field.tag,
1004                                     data : event.data.scope.field.data
1005                                 });
1006                             } else {
1007                                 var sf_clone = [];
1008                                 for (var i in event.data.scope.field.subfields) {
1009                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
1010                                 }
1011                                 field_obj = new MARC21.Field({
1012                                     tag : event.data.scope.field.tag,
1013                                     ind1 : event.data.scope.field.ind1,
1014                                     ind2 : event.data.scope.field.ind2,
1015                                     subfields : sf_clone
1016                                 });
1017                             }
1018
1019
1020                             event.data.scope.field.record.insertFieldsBefore(
1021                                 event.data.scope.field,
1022                                 field_obj
1023                             );
1024
1025                             $scope.current_event_target = 'r' + $scope.caretRecId +
1026                                                           'f' + index_field + 'tag';
1027
1028                             $scope.current_event_target_cursor_pos = 0;
1029                             $scope.current_event_target_cursor_pos_end = 3;
1030                             $scope.force_render = true;
1031
1032                             $timeout(function(){$scope.$digest()}).then(setCaret);
1033
1034                         } else { // jump to prev field
1035                             if (event.data.scope.field.position > 0) {
1036                                 $timeout(function(){
1037                                     $scope.current_event_target_cursor_pos = 0;
1038                                     $scope.current_event_target_cursor_pos_end = 0;
1039                                     $scope.current_event_target = 'r' + $scope.caretRecId +
1040                                                                   'f' + (event.data.scope.field.position - 1) +
1041                                                                   'tag';
1042                                 }).then(setCaret);
1043                             }
1044                         }
1045
1046                         event_return = false;
1047
1048                     } else if (event.keyCode == 40) { // down arrow...
1049                         if (event.ctrlKey) { // copy the field down
1050
1051                             var index_field = event.data.scope.field.position;
1052                             var new_field = index_field + 1;
1053
1054                             var field_obj;
1055                             if (event.data.scope.field.isControlfield()) {
1056                                 field_obj = new MARC21.Field({
1057                                     tag : event.data.scope.field.tag,
1058                                     data : event.data.scope.field.data
1059                                 });
1060                             } else {
1061                                 var sf_clone = [];
1062                                 for (var i in event.data.scope.field.subfields) {
1063                                     sf_clone.push(event.data.scope.field.subfields[i].slice());
1064                                 }
1065                                 field_obj = new MARC21.Field({
1066                                     tag : event.data.scope.field.tag,
1067                                     ind1 : event.data.scope.field.ind1,
1068                                     ind2 : event.data.scope.field.ind2,
1069                                     subfields : sf_clone
1070                                 });
1071                             }
1072
1073                             event.data.scope.field.record.insertFieldsAfter(
1074                                 event.data.scope.field,
1075                                 field_obj
1076                             );
1077
1078                             $scope.current_event_target = 'r' + $scope.caretRecId +
1079                                                           'f' + new_field + 'tag';
1080
1081                             $scope.current_event_target_cursor_pos = 0;
1082                             $scope.current_event_target_cursor_pos_end = 3;
1083                             $scope.force_render = true;
1084
1085                             $timeout(function(){$scope.$digest()}).then(setCaret);
1086
1087                         } else { // jump to next field
1088                             if (event.data.scope.field.record.fields[event.data.scope.field.position + 1]) {
1089                                 $timeout(function(){
1090                                     $scope.current_event_target_cursor_pos = 0;
1091                                     $scope.current_event_target_cursor_pos_end = 0;
1092                                     $scope.current_event_target = 'r' + $scope.caretRecId +
1093                                                                   'f' + (event.data.scope.field.position + 1) +
1094                                                                   'tag';
1095                                 }).then(setCaret);
1096                             }
1097                         }
1098
1099                         event_return = false;
1100
1101                     } else { // Assumes only marc editor elements have IDs that can trigger this event handler.
1102                         $scope.current_event_target = $(event.target).hasClass('focusable') ? $(event.target) : null;//.attr('id');
1103                         if ($scope.current_event_target) {
1104                             $scope.current_event_target_cursor_pos =
1105                                 event.target.selectionDirection=='backward' ?
1106                                     event.target.selectionStart :
1107                                     event.target.selectionEnd;
1108                         }
1109                     }
1110
1111                     return event_return;
1112                 };
1113
1114                 function setCaret() {
1115                     if ($scope.current_event_target) {
1116                         console.log("Putting caret in " + $scope.current_event_target);
1117                         if (!$scope.current_event_target_cursor_pos_end)
1118                             $scope.current_event_target_cursor_pos_end = $scope.current_event_target_cursor_pos
1119
1120                         var element = $('#'+$scope.current_event_target + " .focusable").get(0);
1121                         if (element) {
1122                             element.focus();
1123                             if (element.setSelectionRange) {
1124                                 element.setSelectionRange(
1125                                     $scope.current_event_target_cursor_pos,
1126                                     $scope.current_event_target_cursor_pos_end
1127                                 );
1128                             }
1129                         }
1130                         $scope.current_event_cursor_pos_end = null;
1131                         $scope.current_event_target = null;
1132                     }
1133                 }
1134
1135                 function getCaretPosEditableDiv(editableDiv){
1136                     var caretPos = 0, sel, range;
1137                     if (window.getSelection) {
1138                         sel = window.getSelection();
1139                         if (sel.rangeCount) {
1140                             range = sel.getRangeAt(0);
1141                             if (range.commonAncestorContainer.parentNode == editableDiv[0]) {
1142                                 caretPos = range.endOffset;
1143                             }
1144                         }
1145                     }
1146                     return caretPos;
1147                 }
1148
1149                 function loadRecord() {
1150                     return (function() {
1151                         var deferred = $q.defer();
1152                         if ($scope.recordId) {
1153                             egCore.pcrud.retrieve(
1154                                 $scope.record_type, $scope.recordId
1155                             ).then(function(rec) {
1156                                 deferred.resolve(rec);
1157                             });
1158                         } else {
1159                             if ($scope.recordType == 'bre') {
1160                                 var bre = new egCore.idl.bre();
1161                                 bre.marc($scope.marcXml);
1162                                 deferred.resolve(bre);
1163                             } else if ($scope.recordType == 'are') {
1164                                 var are = new egCore.idl.are();
1165                                 are.marc($scope.marcXml);
1166                                 deferred.resolve(are);
1167                             } else if ($scope.recordType == 'sre') {
1168                                 var sre = new egCore.idl.sre();
1169                                 sre.marc($scope.marcXml);
1170                                 deferred.resolve(sre);
1171                             }
1172                             $scope.brandNewRecord = true;
1173                         }
1174                         return deferred.promise;
1175                     })().then(function(rec) {
1176                         $scope.in_redo = true;
1177                         $scope[$scope.record_type] = rec;
1178                         $scope.record = new MARC21.Record({ marcxml : $scope.Record().marc() });
1179                         if (!$scope.recordId) {
1180                             var sf901c = $scope.record.subfield('901', 'c');
1181                             if (sf901c !== null) {
1182                                 $scope.caretRecId = sf901c[1];
1183                             }
1184                         }
1185                         $scope.calculated_record_type = $scope.record.recordType();
1186                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1187                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1188                         $scope.save_stack_depth = $scope.record_undo_stack.length;
1189                         $scope.dirtyFlag = false;
1190                         $scope.flat_text_marc = $scope.record.toBreaker();
1191
1192                         if ($scope.record_type == 'bre') {
1193                             $scope.bib_source = $scope.Record().source();
1194                         }
1195
1196                     }).then(function(){
1197                         return egTagTable.fetchFFPosTable($scope.calculated_record_type)
1198                     }).then(function(){
1199                         return egTagTable.fetchFFValueTable($scope.calculated_record_type)
1200                     }).then(setCaret);
1201                 }
1202
1203                 $scope.$watch('record.toBreaker()', function (newVal, oldVal) {
1204                     if (!$scope.in_undo && !$scope.in_redo && oldVal != newVal) {
1205                         $scope.record_undo_stack.push({
1206                             breaker: oldVal,
1207                             target: $scope.current_event_target,
1208                             pos: $scope.current_event_target_cursor_pos
1209                         });
1210
1211                         if ($scope.force_render) {
1212                             $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1213                             $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1214                             $scope.force_render = false;
1215                         }
1216
1217                         $scope.flat_text_marc = newVal;
1218                     }
1219
1220                     if ($scope.record_undo_stack.length != $scope.save_stack_depth) {
1221                         $scope.dirtyFlag = true;
1222                     } else {
1223                         $scope.dirtyFlag = false;
1224                     }
1225
1226                     if ($scope.record_undo_stack.length > $scope.max_undo)
1227                         $scope.record_undo_stack.shift();
1228
1229                     console.log('undo stack is ' + $scope.record_undo_stack.length + ' deep');
1230                     $scope.in_redo = false;
1231                     $scope.in_undo = false;
1232                 });
1233
1234                 $scope.processUndo = function () {
1235                     if ($scope.record_undo_stack.length) {
1236                         $scope.in_undo = true;
1237
1238                         var undo_item = $scope.record_undo_stack.pop();
1239                         $scope.record_redo_stack.push(undo_item);
1240
1241                         $scope.record = new MARC21.Record({ marcbreaker : undo_item.breaker });
1242                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1243                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1244
1245                         $scope.current_event_target = undo_item.target;
1246                         $scope.current_event_target_cursor_pos = undo_item.pos;
1247                         console.log('Undo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
1248
1249                         $timeout(function(){$scope.$digest()}).then(setCaret);
1250                         return false;
1251                     }
1252
1253                     return true;
1254                 };
1255
1256                 $scope.processRedo = function () {
1257                     if ($scope.record_redo_stack.length) {
1258                         $scope.in_redo = true;
1259
1260                         var redo_item = $scope.record_redo_stack.pop();
1261                         $scope.record_undo_stack.push(redo_item);
1262
1263                         $scope.record = new MARC21.Record({ marcbreaker : redo_item.breaker });
1264                         $scope.controlfields = $scope.record.fields.filter(function(f){ return f.isControlfield() });
1265                         $scope.datafields = $scope.record.fields.filter(function(f){ return !f.isControlfield() });
1266
1267                         $scope.current_event_target = redo_item.target;
1268                         $scope.current_event_target_cursor_pos = redo_item.pos;
1269                         console.log('Redo targeting ' + $scope.current_event_target + ' position ' + $scope.current_event_target_cursor_pos);
1270
1271                         $timeout(function(){$scope.$digest()}).then(setCaret);
1272                         return false;
1273                     }
1274
1275                     return true;
1276                 };
1277
1278                 $scope.Record = function () {
1279                     return $scope[$scope.record_type];
1280                 };
1281
1282                 $scope.deleteRecord = function () {
1283                     egConfirmDialog.open(
1284                         egCore.strings.CONFIRM_DELETE_RECORD,
1285                         (($scope.record_type == 'bre') ?
1286                             egCore.strings.CONFIRM_DELETE_BRE_MSG :
1287                             egCore.strings.CONFIRM_DELETE_ARE_MSG),
1288                         { id : $scope.recordId }
1289                     ).result.then(function() {
1290                         if ($scope.record_type == 'bre') {
1291                             egCore.net.request(
1292                                 'open-ils.cat',
1293                                 'open-ils.cat.biblio.record_entry.delete',
1294                                 egCore.auth.token(), $scope.recordId
1295                             ).then(function(resp) {
1296                                 var evt = egCore.evt.parse(resp);
1297                                 if (evt) {
1298                                     return egAlertDialog.open(
1299                                         egCore.strings.ALERT_DELETE_FAILED,
1300                                         { id : $scope.recordId, desc : evt.desc }
1301                                     );
1302                                 } else {
1303                                     loadRecord().then(processOnSaveCallbacks);
1304                                 }
1305                             });
1306                         } else {
1307                             $scope.Record().deleted(true);
1308                             return $scope.saveRecord();
1309                         }
1310                     });
1311                 };
1312
1313                 $scope.undeleteRecord = function () {
1314                     $scope.Record().deleted(false);
1315                     return $scope.saveRecord();
1316                 };
1317
1318                 $scope.validateHeadings = function () {
1319                     if ($scope.record_type != 'bre') return;
1320                     var chain = $q.when();
1321                     angular.forEach($scope.record.fields, function(f) {
1322                         if (!$scope.controlSet.bibFieldByTag(f.tag)) return;
1323                         // if heading already has a $0, assume it's good
1324                         if (f.subfield('0', true).length) {
1325                             f.heading_checked = true;
1326                             f.heading_valid = true;
1327                             return;
1328                         }
1329                         var auth_match = $scope.controlSet.bibToAuthorities(f);
1330                         if (auth_match.length == 0) return;
1331                         chain = chain.then(function() {
1332                             var promise = egCore.net.request(
1333                                 'open-ils.search',
1334                                 'open-ils.search.authority.simple_heading.from_xml.batch.atomic',
1335                                 auth_match[0]
1336                             ).then(function (matches) {
1337                                 f.heading_valid = false;
1338                                 if (matches[0]) { // probably set
1339                                     for (var cset in matches[0]) {
1340                                         var arr = matches[0][cset];
1341                                         if (arr.length) {
1342                                             // protect against errant empty string values
1343                                             if (arr.length == 1 && arr[0] == '')
1344                                                 continue;
1345                                             f.heading_valid = true;
1346                                             break;
1347                                         }
1348                                     }
1349                                 }
1350                                 f.heading_checked = true;
1351                             });
1352                             return promise;
1353                         });
1354                     });
1355                 }
1356
1357                 processOnSaveCallbacks = function() {
1358                     var deferred = $q.defer();
1359                     if (typeof $scope.onSaveCallback !== 'undefined') {
1360                         var promise = deferred.promise;
1361
1362                         angular.forEach($scope.onSaveCallback, function (f) {
1363                             if (angular.isFunction(f)) promise = promise.then(f);
1364                         });
1365
1366                     }
1367                     return deferred.resolve($scope.recordId)
1368                 };
1369
1370                 $scope.saveRecord = function () {
1371                     if ($scope.inPlaceMode) {
1372                         $scope.marcXml = $scope.record.toXmlString();
1373                         return $timeout(processOnSaveCallbacks);
1374                     }
1375                     $scope.mangle_005();
1376                     $scope.Record().editor(egCore.auth.user().id());
1377                     $scope.Record().edit_date('now');
1378                     $scope.record.pruneEmptyFieldsAndSubfields();
1379                     $scope.Record().marc($scope.record.toXmlString());
1380                     if ($scope.recordId) {
1381                         return egCore.pcrud.update(
1382                             $scope.Record()
1383                         ).then(function() { // success
1384                             $scope.save_stack_depth = $scope.record_undo_stack.length;
1385                             $scope.dirtyFlag = false;
1386                             if ($scope.enable_fast_add) {
1387                                 egCore.net.request(
1388                                     'open-ils.actor',
1389                                     'open-ils.actor.anon_cache.set_value',
1390                                     null, 'edit-these-copies', {
1391                                         record_id: $scope.recordId,
1392                                         raw: [{
1393                                             label : $scope.fast_item_callnumber,
1394                                             barcode : $scope.fast_item_barcode,
1395                                             fast_add : true
1396                                         }],
1397                                         hide_vols : false,
1398                                         hide_copies : false
1399                                     }
1400                                 ).then(function(key) {
1401                                     if (key) {
1402                                         var url = egCore.env.basePath + 'cat/volcopy/' + key;
1403                                         $timeout(function() { $window.open(url, '_blank') });
1404                                     } else {
1405                                         alert('Could not create anonymous cache key!');
1406                                     }
1407                                 });
1408                             }
1409                         }, function() { // failure
1410                             alert('Could not save the record!');
1411                         }).then(loadRecord).then(processOnSaveCallbacks);
1412                     } else {
1413                         $scope.Record().creator(egCore.auth.user().id());
1414                         $scope.Record().create_date('now');
1415                         return egCore.pcrud.create(
1416                             $scope.Record()
1417                         ).then(function(bre) {
1418                             $scope.recordId = bre.id(); 
1419                             $scope.caretRecId = $scope.recordId;
1420                             if ($scope.enable_fast_add) {
1421                                 egCore.net.request(
1422                                     'open-ils.actor',
1423                                     'open-ils.actor.anon_cache.set_value',
1424                                     null, 'edit-these-copies', {
1425                                         record_id: $scope.recordId,
1426                                         raw: [{
1427                                             label : $scope.fast_item_callnumber,
1428                                             barcode : $scope.fast_item_barcode,
1429                                         }],
1430                                         hide_vols : false,
1431                                         hide_copies : false
1432                                     }
1433                                 ).then(function(key) {
1434                                     if (key) {
1435                                         var url = egCore.env.basePath + 'cat/volcopy/' + key;
1436                                         $timeout(function() { $window.open(url, '_blank') });
1437                                     } else {
1438                                         alert('Could not create anonymous cache key!');
1439                                     }
1440                                 });
1441                             }
1442                         }).then(loadRecord).then(processOnSaveCallbacks);
1443                     }
1444
1445
1446                 };
1447
1448                 $scope.seeBreaker = function () {
1449                     alert($scope.record.toBreaker());
1450                 };
1451
1452                 $scope.$watch('recordId',
1453                     function(newVal, oldVal) {
1454                         if (newVal && newVal !== oldVal) {
1455                             loadRecord();
1456                         }
1457                     }
1458                 );
1459                 $scope.$watch('marcXml',
1460                     function(newVal, oldVal) {
1461                         if (newVal && newVal !== oldVal) {
1462                             loadRecord();
1463                         }
1464                     }
1465                 );
1466
1467                 var unregister = $scope.$watch(function() {
1468                     return egTagTable.initialized();
1469                 }, function(val) {
1470                     if (val) {
1471                         unregister();
1472                         if ($scope.recordId || $scope.marcXml) {
1473                             loadRecord();
1474                         }
1475                     }
1476                 });
1477
1478                 $scope.mangle_005 = function () {
1479                     var now = new Date();
1480                     var y = now.getUTCFullYear();
1481                 
1482                     var m = now.getUTCMonth() + 1;
1483                     if (m < 10) m = '0' + m;
1484                 
1485                     var d = now.getUTCDate();
1486                     if (d < 10) d = '0' + d;
1487                 
1488                     var H = now.getUTCHours();
1489                     if (H < 10) H = '0' + H;
1490                 
1491                     var M = now.getUTCMinutes();
1492                     if (M < 10) M = '0' + M;
1493                 
1494                     var S = now.getUTCSeconds();
1495                     if (S < 10) S = '0' + S;
1496                 
1497                     var stamp = '' + y + m + d + H + M + S + '.0';
1498                     var f = $scope.record.field('005',true)[0];
1499                     if (f) {
1500                         f.data = stamp;
1501                     } else {
1502                         $scope.record.insertOrderedFields(
1503                             new MARC21.Field({
1504                                 tag : '005',
1505                                 data: stamp
1506                             })
1507                         );
1508                     }
1509                 
1510                 }
1511
1512             }
1513         ]          
1514     }
1515 })
1516
1517 .directive("egMarcEditBibsource", ['$timeout',function ($timeout) {
1518     return {
1519         restrict: 'E',
1520         replace: true,
1521         template: '<span class="nullable">'+
1522                     '<select class="form-control" ng-model="bib_source" ng-options="s.id() as s.source() for s in bib_sources | orderBy: \'source()\'">'+
1523                       '<option value="">Select a Source</option>'+
1524                     '</select>'+
1525                   '</span>',
1526         controller: ['$scope','egCore',
1527             function ($scope , egCore) {
1528
1529                 egCore.pcrud.retrieveAll('cbs', {}, {atomic : true})
1530                     .then(function(list) { $scope.bib_sources = list; });
1531
1532                 $scope.$watch('bib_source',
1533                     function(newVal, oldVal) {
1534                         if (newVal !== oldVal) {
1535                             $scope.bre.source(newVal);
1536                         }
1537                     }
1538                 );
1539
1540             }
1541         ]
1542     }
1543 }])
1544
1545 .directive("egMarcEditAuthorityLinker", function () {
1546     return {
1547         restrict: 'E',
1548         replace: true,
1549         templateUrl: './cat/share/t_authority_linker',
1550         scope : {
1551             bibField : '=',
1552             controlSet : '=',
1553             changed : '='
1554         },
1555         controller: ['$scope','$uibModal','egCore','egAuth',
1556             function ($scope , $uibModal,  egCore,  egAuth) {
1557
1558                 $scope.searchStr = '';
1559                 var cni = egCore.env.aous['cat.marc_control_number_identifier'] ||
1560                   'Set cat.marc_control_number_identifier in Library Settings';
1561
1562                 var axis_list = $scope.controlSet.bibFieldBrowseAxes($scope.bibField.tag);
1563                 $scope.axis = axis_list[0];
1564
1565                 $scope._controlled_sf_list = {};
1566                 $scope._controlled_auth_sf_list = {};
1567                 var found_acs = [];
1568                 angular.forEach($scope.controlSet.controlSetList(), function(acs_id) {
1569                     if ($scope.controlSet.controlSet(acs_id).control_map[$scope.bibField.tag])
1570                         found_acs.push(acs_id);
1571                 });
1572                 if (found_acs.length) {
1573                      angular.forEach($scope.controlSet.controlSet(found_acs[0]).control_map[$scope.bibField.tag],
1574                         function(value, sf_label) {
1575                             $scope._controlled_sf_list[ sf_label ] = 1;
1576                             angular.forEach($scope.controlSet.controlSet(found_acs[0]).control_map[$scope.bibField.tag][sf_label],
1577                                 function(auth_sf, auth_tag) {
1578                                     if (!$scope._controlled_auth_sf_list[auth_tag]) {
1579                                         $scope._controlled_auth_sf_list[auth_tag] = { };
1580                                     }
1581                                     $scope._controlled_auth_sf_list[auth_tag][auth_sf] = 1;
1582                                 }
1583                             );
1584                         }
1585                     )
1586                 }
1587
1588                 $scope.bibField.subfields.forEach(function (sf) {
1589                     if (sf[0] in $scope._controlled_sf_list) {
1590                         sf.selected = true;
1591                         sf.selectable = true;
1592                     } else {
1593                         sf.selectable = false;
1594                     }
1595                 });
1596                 $scope.summarizeField = function() {
1597                     var source_f = {
1598                         'tag': $scope.bibField.tag,
1599                         'ind1': $scope.bibField.ind1,
1600                         'ind2': $scope.bibField.ind2,
1601                         'subfields': []
1602                     };
1603                     $scope.bibField.subfields.forEach(function(sf) {
1604                         if (sf.selected) {
1605                             source_f.subfields.push([ sf[0], sf[1] ]);
1606                         }
1607                     });
1608                     return source_f;
1609                 }
1610                 $scope.getSearchString = function() {
1611                     var source_f = $scope.summarizeField();
1612                     var values = [];
1613                     angular.forEach(source_f.subfields, function(val) {
1614                         values.push(val[1]);
1615                     });
1616                     return values.join(' ');
1617                 }
1618                 $scope.searchStr = $scope.getSearchString();
1619                 $scope.$watch(function() {
1620                     var ct = 0;
1621                     angular.forEach($scope.bibField.subfields, function(sf) {
1622                         if (sf.selected) ct++
1623                         });
1624                     return ct;
1625                 },
1626                 function(newVal, oldVal) {
1627                     $scope.searchStr = $scope.getSearchString();
1628                 });
1629
1630                 $scope.updateSubfieldZero = function(value) {
1631                     $scope.changed = true;
1632                     $scope.bibField.deleteSubfield({ code : ['0'] });
1633                     $scope.bibField.subfields.push([
1634                         '0', '(' + cni + ')' + value
1635                     ]);
1636                 };
1637
1638                 $scope.applyHeading = function(headingField) {
1639                     // TODO: move the MARC21 rules for copying indicators
1640                     // out of here
1641                     if (headingField.tag == '130' && $scope.bibField.tag == '130') {
1642                         $scope.bibField.ind1 = headingField.ind2;
1643                     } else {
1644                         $scope.bibField.ind1 = headingField.ind1;
1645                     }
1646                     // deal with 4xx and 5xx
1647                     var authFallbackTag = '1' + headingField.tag.substr(1, 2);
1648                     var _valid_auth_sfs = (headingField.tag in $scope._controlled_auth_sf_list) ?
1649                                           $scope._controlled_auth_sf_list[headingField.tag] :
1650                                           (authFallbackTag in $scope._controlled_auth_sf_list) ?
1651                                           $scope._controlled_auth_sf_list[authFallbackTag] :
1652                                           [];
1653                     // save the $0 for later use
1654                     var sfZero = '';
1655                     if (headingField.subfield('0')) {
1656                         sfZero = headingField.subfield('0')[1];
1657                     }
1658                     // grab any bib subfields not under authority control
1659                     // TODO do something about uncontrolled subdivisions
1660                     var uncontrolledBibSf = [];
1661                     angular.forEach($scope.bibField.subfields, function(sf) {
1662                         if (!(sf[0] in $scope._controlled_sf_list) && (sf[0] != '0')) {
1663                             uncontrolledBibSf.push([ sf[0], sf[1] ]);
1664                         }
1665                     });
1666                     // grab the authority subfields
1667                     var authoritySf = [];
1668                     angular.forEach(headingField.subfields, function(sf) {
1669                         if (sf[0] in _valid_auth_sfs) {
1670                             authoritySf.push([ sf[0], sf[1] ]);
1671                         }
1672                     });
1673                     $scope.bibField.subfields.length = 0;
1674                     angular.forEach(authoritySf, function(sf) {
1675                         $scope.bibField.addSubfields(sf[0], sf[1]);
1676                     });
1677                     angular.forEach(uncontrolledBibSf, function(sf) {
1678                         $scope.bibField.addSubfields(sf[0], sf[1]);
1679                     });
1680                     if (sfZero) {
1681                         $scope.bibField.addSubfields('0', sfZero);
1682                     }
1683                     $scope.bibField.subfields.forEach(function (sf) {
1684                     if (sf[0] in $scope._controlled_sf_list) {
1685                             // intentionally not selecting any subfields
1686                             // after we've applied an authority heading
1687                             sf.selected = false;
1688                             sf.selectable = true;
1689                         } else {
1690                             sf.selectable = false;
1691                         }
1692                     });
1693                     $scope.changed = true;
1694                 }
1695
1696                 $scope.createAuthorityFromBib = function(spawn_editor) {
1697                     var source_f = $scope.summarizeField();
1698
1699                     var args = { authority_id : 0 };
1700                     var method = (spawn_editor) ?
1701                         'open-ils.cat.authority.record.create_from_bib.readonly' :
1702                         'open-ils.cat.authority.record.create_from_bib';
1703                     egCore.net.request(
1704                         'open-ils.cat',
1705                         method,
1706                         source_f,
1707                         cni,
1708                         egAuth.token()
1709                     ).then(function(newAuthority) {
1710                         if (spawn_editor) {
1711                             $uibModal.open({
1712                                 templateUrl: './cat/share/t_edit_new_authority',
1713                                 size: 'lg',
1714                                 controller:
1715                                     ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
1716                                     $scope.focusMe = true;
1717                                     $scope.args = args;
1718                                     $scope.dirty_flag = false;
1719                                     $scope.marc_xml = newAuthority,
1720                                     $scope.ok = function(args) { $uibModalInstance.close(args) }
1721                                     $scope.cancel = function () { $uibModalInstance.dismiss() }
1722                                 }]
1723                             }).result.then(function (args) {
1724                                 if (!args || !args.authority_id) return;
1725                                 $scope.updateSubfieldZero(args.authority_id);
1726                             });
1727                         } else {
1728                             $scope.updateSubfieldZero(newAuthority.id());
1729                         }
1730                     });
1731                 }
1732
1733             }
1734         ]
1735     }
1736 })
1737
1738 .directive("egPhyscharWizard", ['$sce', function ($sce) {
1739     return {
1740         restrict: 'E',
1741         replace: true,
1742         templateUrl: './cat/share/t_physchar_wizard',
1743         scope : {
1744             field : '='
1745         },
1746         controller: ['$scope','$q','egTagTable',
1747             function ($scope , $q , egTagTable) {
1748
1749                 // $scope.step is the 1-based position in the list of 
1750                 // subfields for the currently selected type.
1751                 // step==0 means we are currently selecting the type
1752                 $scope.step = 0;
1753
1754                 // position and offset of the "subfields" we're
1755                 // currently editing; this is maintained as a convenience
1756                 // for the highlighting of the currently active position
1757                 $scope.offset = 0;
1758                 $scope.len = 1;
1759
1760                 if (!$scope.field.data) 
1761                     $scope.field.data = '';
1762
1763                 // currently selected subfield value selector option
1764                 $scope.selected_option = null;
1765
1766                 function current_ptype() {
1767                     return $scope.field.data.substr(0, 1);   
1768                 }
1769
1770                 function current_subfield() {
1771                     return egTagTable.getPhysCharSubfieldMap(current_ptype())
1772                     .then(function(sf_list) {return sf_list[$scope.step-1]});
1773                 }
1774
1775                 $scope.values_for_step = [];
1776                 function set_values_for_step() {
1777                     var promise;
1778
1779                     if ($scope.step == 0) {
1780                         $scope.offset = 0;
1781                         $scope.len    = 1;
1782                         promise = egTagTable.getPhysCharTypeMap();
1783                     } else {
1784                         promise = current_subfield().then(
1785                             function(subfield) {
1786                                 return egTagTable
1787                                     .getPhysCharValueMap(subfield.id());
1788                             }
1789                         );
1790                     }
1791
1792                     return promise.then(function(list) { 
1793                         $scope.values_for_step = list;
1794                         set_selected_option_from_field();
1795                         set_label_for_step();
1796                     });
1797                 }
1798
1799                 $scope.change_ptype = function(option) {
1800                     $scope.selected_option = option;
1801                     var new_val = option.ptype_key();
1802                     if (current_ptype() != new_val) {
1803                         $scope.field.data = new_val; // total reset
1804                     }
1805                 }
1806
1807                 $scope.change_option = function(option) {
1808                     $scope.selected_option = option;
1809                     var new_val = option.value();
1810                     get_step_slot().then(function(slot) {
1811                         var value = $scope.field.data;
1812                         while (value.length < (slot[0] + slot[1])) 
1813                             value += ' ';
1814                         var before = value.substr(0, slot[0]);
1815                         var after = value.substr(slot[0] + slot[1]);
1816                         $scope.field.data = 
1817                             before + new_val.substr(0, slot[1]) + after;
1818                         $scope.offset = slot[0];
1819                         $scope.len    = slot[1];
1820                     });
1821                 }
1822
1823                 function get_step_slot() {
1824                     if ($scope.step == 0) return $q.when([0, 1]);
1825                     return current_subfield().then(function(sf) {
1826                         return [sf.start_pos(), sf.length()]
1827                     });
1828                 }
1829
1830                 $scope.is_last_step = function() {
1831                     // This one is called w/ every digest, so avoid async
1832                     // calls.  Wait until we have loaded the current ptype
1833                     // subfields to determine if this is the last step.
1834                     return (
1835                         current_ptype() && 
1836                         egTagTable.phys_char_sf_map[current_ptype()] &&
1837                         egTagTable.phys_char_sf_map[current_ptype()].length 
1838                             == $scope.step
1839                     );
1840                 }
1841
1842                 $scope.label_for_step = '';
1843                 function set_label_for_step() {
1844                     if ($scope.step > 0) {
1845                         current_subfield().then(function(sf) {
1846                             $scope.label_for_step = sf.label();
1847                         });
1848                     }
1849                 }
1850                 
1851                 $scope.next_step = function() {
1852                     $scope.step++;
1853                     set_values_for_step();
1854                 }
1855
1856                 $scope.prev_step = function() {
1857                     $scope.step--;
1858                     set_values_for_step();
1859                 }
1860
1861                 function set_selected_option_from_field() {
1862                     if ($scope.step == 0) {
1863                         $scope.selected_option = $scope.values_for_step
1864                         .filter(function(opt) {
1865                             return (opt.ptype_key() == current_ptype())})[0];
1866                     } else {
1867                         get_step_slot().then(function(slot) {
1868                             $scope.offset = slot[0];
1869                             $scope.len    = slot[1];
1870                             var val = String.prototype.substr.apply(                      
1871                                 $scope.field.data, slot);
1872                             if (val) {
1873                                 $scope.selected_option = $scope.values_for_step
1874                                 .filter(function(opt) { 
1875                                     return (opt.value() == val)})[0];
1876                             } else {
1877                                 $scope.selected_option = null;
1878                             }
1879                         })
1880                     }
1881                 }
1882
1883                 $scope.highlightedFieldData = function() {
1884                     if (
1885                             $scope.len && $scope.field.data &&
1886                             $scope.field.data.length > 0 &&
1887                             $scope.field.data.length >= $scope.offset
1888                         ) {
1889                         return $sce.trustAsHtml(
1890                             $scope.field.data.substring(0, $scope.offset) + 
1891                             '<span class="active-physchar">' +
1892                             $scope.field.data.substr($scope.offset, $scope.len) +
1893                             '</span>' +
1894                             $scope.field.data.substr($scope.offset + $scope.len)
1895                         );
1896                     } else {
1897                         return $scope.field.data;
1898                     }
1899                 };
1900
1901                 set_values_for_step();
1902             }
1903         ]
1904     }
1905 }])
1906
1907
1908 .directive("egMarcEditAuthorityBrowser", function () {
1909     return {
1910         restrict: 'E',
1911         replace: true,
1912         templateUrl: './cat/share/t_authority_browser',
1913         scope : {
1914             searchString : '=',
1915             controlSet : '=',
1916             axis : '=',
1917             applyHeading : '&'
1918         },
1919         controller: ['$scope','$http',
1920             function ($scope , $http) {
1921
1922                 $scope.page = 0;
1923                 $scope.limit = 5;
1924                 $scope.main_headings = [];
1925
1926                 function getHeadingString(headingField) {
1927                     var heading = '';
1928                     angular.forEach(headingField.subfields, function (sf) {
1929                         if (['x', 'y', 'z'].indexOf(sf[0]) > -1) {
1930                             heading += ' --';
1931                         }
1932                         if (heading) {
1933                             heading += ' ';
1934                         }
1935                         heading += sf[1];
1936                     });
1937                     return heading;
1938                 }
1939
1940                 $scope.doBrowse = function() {
1941                     $scope.main_headings.length = 0;
1942                     if ($scope.searchString.length == 0) return;
1943                     var type = 'authority.'
1944                     var url = '/opac/extras/browse/marcxml/'
1945                             + 'authority.' + $scope.axis + '.refs'
1946                             + '/1' // OU - currently unscoped
1947                             + '/' + $scope.searchString
1948                             + '/' + $scope.page
1949                             + '/' + $scope.limit;
1950                     $http({
1951                         url : url,
1952                         method : 'GET',
1953                         transformResponse : function(data) {
1954                             // use a bit of jQuery to deal with the XML
1955                             var $xml = $( $.parseXML(data) );
1956                             var marc = [];
1957                             $xml.find('record').each(function() {
1958                                 var rec = new MARC21.Record();
1959                                 rec.fromXmlDocument($(this)[0].outerHTML);
1960                                 marc.push(rec);
1961                             });
1962                             return marc;
1963                         }
1964                     }).then(function(response) {
1965                         angular.forEach(response.data, function(rec) {
1966                             var authId = rec.subfield('901', 'c')[1];
1967                             var auth_org = '';
1968                             if (rec.field('003')) {
1969                                 auth_org = rec.field('003').data;
1970                             }
1971                             var headingField = rec.field('1..');
1972                             var seeFroms = rec.field('4..', true);
1973                             var seeAlsos = rec.field('5..', true);
1974
1975                             var main_heading = {
1976                                 authority_id : authId,
1977                                 heading : getHeadingString(headingField),
1978                                 seealso_headings : [ ],
1979                                 seefrom_headings : [ ],
1980                             };
1981
1982                             var sfZero = '';
1983                             if (auth_org) {
1984                                 sfZero = '(' + auth_org + ')';
1985                             }
1986                             sfZero += authId;
1987                             headingField.addSubfields('0', sfZero);
1988
1989                             main_heading['headingField'] = headingField;
1990                             angular.forEach(seeAlsos, function(headingField) {
1991                                 main_heading.seealso_headings.push({
1992                                     heading : getHeadingString(headingField),
1993                                     headingField : headingField
1994                                 });
1995                             });
1996                             angular.forEach(seeFroms, function(headingField) {
1997                                 main_heading.seefrom_headings.push({
1998                                     heading : getHeadingString(headingField),
1999                                     headingField : headingField
2000                                 });
2001                             });
2002                             $scope.main_headings.push(main_heading);
2003                         });
2004                     });
2005                 }
2006
2007                 $scope.$watch('searchString',
2008                     function(newVal, oldVal) {
2009                         if (newVal !== oldVal) {
2010                             $scope.doBrowse();
2011                         }
2012                     }
2013                 );
2014                 $scope.$watch('page',
2015                     function(newVal, oldVal) {
2016                         if (newVal !== oldVal) {
2017                             $scope.doBrowse();
2018                         }
2019                     }
2020                 );
2021
2022                 $scope.doBrowse();
2023             }
2024         ]
2025     }
2026 })
2027
2028 ;