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