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