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