]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/catalog/app.js
lp1362743 holdings view duplicate barcodes
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / catalog / app.js
1 /**
2  * TPAC Frame App
3  *
4  * currently, this app doesn't use routes for each sub-ui, because 
5  * reloading the catalog each time is sloooow.  better so far to 
6  * swap out divs w/ ng-if / ng-show / ng-hide as needed.
7  *
8  */
9
10 angular.module('egCatalogApp', ['ui.bootstrap','ngRoute','ngLocationUpdate','egCoreMod','egGridMod', 'egMarcMod', 'egUserMod', 'egHoldingsMod', 'ngToast','egPatronSearchMod',
11 'egSerialsMod','egSerialsAppDep'])
12
13 .config(['ngToastProvider', function(ngToastProvider) {
14   ngToastProvider.configure({
15     verticalPosition: 'bottom',
16     animation: 'fade'
17   });
18 }])
19
20 .config(function($routeProvider, $locationProvider, $compileProvider) {
21     $locationProvider.html5Mode(true);
22     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); // grid export
23         
24     var resolver = {delay : ['egCore','egStartup','egUser', function(egCore, egStartup, egUser) {
25         egCore.env.classLoaders.aous = function() {
26             return egCore.org.settings([
27                 'cat.marc_control_number_identifier'
28             ]).then(function(settings) {
29                 // local settings are cached within egOrg.  Caching them
30                 // again in egEnv just simplifies the syntax for access.
31                 egCore.env.aous = settings;
32             });
33         }
34         egCore.env.loadClasses.push('aous');
35         return egStartup.go()
36     }]};
37
38     $routeProvider.when('/cat/catalog/index', {
39         templateUrl: './cat/catalog/t_catalog',
40         controller: 'CatalogCtrl',
41         resolve : resolver
42     });
43
44     // Jump directly to the results page.  Any URL parameter 
45     // supported by the embedded catalog is supported here.
46     $routeProvider.when('/cat/catalog/results', {
47         templateUrl: './cat/catalog/t_catalog',
48         controller: 'CatalogCtrl',
49         resolve : resolver
50     });
51
52     $routeProvider.when('/cat/catalog/retrieve_by_id', {
53         templateUrl: './cat/catalog/t_retrieve_by_id',
54         controller: 'CatalogRecordRetrieve',
55         resolve : resolver
56     });
57
58     $routeProvider.when('/cat/catalog/retrieve_by_tcn', {
59         templateUrl: './cat/catalog/t_retrieve_by_tcn',
60         controller: 'CatalogRecordRetrieve',
61         resolve : resolver
62     });
63
64     $routeProvider.when('/cat/catalog/retrieve_by_authority_id', {
65         templateUrl: './cat/catalog/t_retrieve_by_authority_id',
66         controller: 'CatalogRecordRetrieve',
67         resolve : resolver
68     });
69
70     $routeProvider.when('/cat/catalog/new_bib', {
71         templateUrl: './cat/catalog/t_new_bib',
72         controller: 'NewBibCtrl',
73         resolve : resolver
74     });
75
76     // create some catalog page-specific mappings
77     $routeProvider.when('/cat/catalog/record/:record_id', {
78         templateUrl: './cat/catalog/t_catalog',
79         controller: 'CatalogCtrl',
80         resolve : resolver
81     });
82
83     // create some catalog page-specific mappings
84     $routeProvider.when('/cat/catalog/record/:record_id/:record_tab', {
85         templateUrl: './cat/catalog/t_catalog',
86         controller: 'CatalogCtrl',
87         resolve : resolver
88     });
89
90     $routeProvider.when('/cat/catalog/batchEdit', {
91         templateUrl: './cat/catalog/t_batchedit',
92         controller: 'BatchEditCtrl',
93         resolve : resolver
94     });
95
96     $routeProvider.when('/cat/catalog/batchEdit/:container_type/:container_id', {
97         templateUrl: './cat/catalog/t_batchedit',
98         controller: 'BatchEditCtrl',
99         resolve : resolver
100     });
101
102     $routeProvider.when('/cat/catalog/vandelay', {
103         templateUrl: './cat/catalog/t_vandelay',
104         controller: 'VandelayCtrl',
105         resolve : resolver
106     });
107
108     $routeProvider.when('/cat/catalog/verifyURLs', {
109         templateUrl: './cat/catalog/t_verifyurls',
110         controller: 'URLVerifyCtrl',
111         resolve : resolver
112     });
113
114     $routeProvider.when('/cat/catalog/manageAuthorities', {
115         templateUrl: './cat/catalog/t_manageauthorities',
116         controller: 'ManageAuthoritiesCtrl',
117         resolve : resolver
118     });
119
120     $routeProvider.when('/cat/catalog/authority/:authority_id/marc_edit', {
121         templateUrl: './cat/catalog/t_authority',
122         controller: 'AuthorityCtrl',
123         resolve : resolver
124     });
125
126     $routeProvider.otherwise({redirectTo : '/cat/catalog/index'});
127 })
128
129
130 /**
131  * */
132 .controller('CatalogRecordRetrieve',
133        ['$scope','$routeParams','$location','$q','egCore',
134 function($scope , $routeParams , $location , $q , egCore ) {
135
136     $scope.focusMe = true;
137
138     // jump to the patron checkout UI
139     function loadRecord(record_id) {
140         $location
141         .path('/cat/catalog/record/' + record_id);
142     }
143
144     function loadAuthorityRecord(record_id) {
145         $location
146         .path('/cat/catalog/authority/' + record_id + '/marc_edit');
147     }
148
149     $scope.submitId = function(args) {
150         $scope.recordNotFound = null;
151         if (!args.record_id) return;
152
153         // blur so next time it's set to true it will re-apply select()
154         $scope.selectMe = false;
155
156         return loadRecord(args.record_id);
157     }
158
159     $scope.submitAuthorityId = function(args) {
160         if (!args.record_id) return;
161
162         // blur so next time it's set to true it will re-apply select()
163         $scope.selectMe = false;
164
165         return loadAuthorityRecord(args.record_id);
166     }
167
168     $scope.submitTCN = function(args) {
169         $scope.recordNotFound = null;
170         $scope.moreRecordsFound = null;
171         if (!args.record_tcn) return;
172
173         // blur so next time it's set to true it will re-apply select()
174         $scope.selectMe = false;
175
176         // lookup TCN
177         egCore.net.request(
178             'open-ils.search',
179             'open-ils.search.biblio.tcn',
180             args.record_tcn)
181
182         .then(function(resp) { // get_barcodes
183
184             if (resp.count) {
185                 return $q.when(resp);
186             } else {
187                 // Search again including deleted records
188                 return egCore.net.request('open-ils.search', 
189                     'open-ils.search.biblio.tcn', args.record_tcn, true);
190             }
191
192         }).then(function(resp2) {
193
194             if (!resp2.count) {
195                 $scope.recordNotFound = args.record_tcn;
196                 $scope.selectMe = true;
197                 return;
198             }
199
200             if (resp2.count > 1) {
201                 $scope.moreRecordsFound = args.record_tcn;
202                 $scope.selectMe = true;
203                 return;
204             }
205
206             var record_id = resp2.ids[0];
207             return loadRecord(record_id);
208         });
209     }
210
211 }])
212
213 .controller('NewBibCtrl',
214        ['$scope','$routeParams','$location','$window','$q','egCore',
215         'egGridDataProvider','egHoldGridActions','$timeout','holdingsSvc',
216 function($scope , $routeParams , $location , $window , $q , egCore) {
217
218     $scope.have_template = false;
219     $scope.marc_template = '';
220     $scope.stop_unload = false;
221     $scope.template_list = [];
222     $scope.template_name = '';
223     $scope.new_bib_id = 0;
224
225     egCore.net.request(
226         'open-ils.cat',
227         'open-ils.cat.marc_template.types.retrieve'
228     ).then(function(resp) {
229         angular.forEach(resp, function(name) {
230             $scope.template_list.push(name);
231         });
232         $scope.template_list.sort();
233     });
234     $scope.template_name = egCore.hatch.getSessionItem('eg.cat.last_bib_marc_template');
235     if (!$scope.template_name) {
236         egCore.hatch.getItem('cat.default_bib_marc_template').then(function(template) {
237             $scope.template_name = template;
238         });
239     }
240
241     $scope.loadTemplate = function() {
242         if ($scope.template_name) {
243             egCore.net.request(
244                 'open-ils.cat',
245                 'open-ils.cat.biblio.marc_template.retrieve',
246                 $scope.template_name
247             ).then(function(template) {
248                 $scope.marc_template = template;
249                 $scope.have_template = true;
250                 egCore.hatch.setSessionItem('eg.cat.last_bib_marc_template', $scope.template_name);
251             });
252         }
253     }
254
255     $scope.setDefaultTemplate = function() {
256         var hatch_key = "cat.default_bib_marc_template";
257         if ($scope.template_name) {
258             egCore.hatch.setItem(hatch_key, $scope.template_name);
259         } else {
260             egCore.hatch.removeItem(hatch_key);
261         }
262     }
263
264     $scope.$watch('new_bib_id', function(newVal, oldVal) {
265         if (newVal) {
266             $location.path('/cat/catalog/record/' + $scope.new_bib_id);
267         }
268     });
269     
270
271 }])
272 .controller('CatalogCtrl',
273        ['$scope','$routeParams','$location','$window','$q','egCore','egHolds','egCirc','egConfirmDialog','ngToast',
274         'egGridDataProvider','egHoldGridActions','egProgressDialog','$timeout','$uibModal','holdingsSvc','egUser','conjoinedSvc',
275         '$cookies','egSerialsCoreSvc',
276 function($scope , $routeParams , $location , $window , $q , egCore , egHolds , egCirc , egConfirmDialog , ngToast ,
277          egGridDataProvider , egHoldGridActions , egProgressDialog , $timeout , $uibModal , holdingsSvc , egUser , conjoinedSvc,
278          $cookies , egSerialsCoreSvc
279 ) {
280
281     var holdingsSvcInst = new holdingsSvc();
282
283     // set record ID on page load if available...
284     $scope.record_id = $routeParams.record_id;
285     $scope.summary_pane_record;
286
287     if ($scope.record_id) {
288         // TODO: Apply tab-specific title contexts
289         egCore.strings.setPageTitle(
290             egCore.strings.PAGE_TITLE_BIB_DETAIL,
291             egCore.strings.PAGE_TITLE_CATALOG_CONTEXT,
292             {record_id : $scope.record_id}
293         );
294     } else {
295         // Default to title = Catalog
296         egCore.strings.setPageTitle(
297             egCore.strings.PAGE_TITLE_CATALOG_CONTEXT);
298     }
299
300     if ($routeParams.record_id) $scope.from_route = true;
301     else $scope.from_route = false;
302
303     // set search and preferred library cookies
304     egCore.hatch.getItem('eg.search.search_lib').then(function(val) {
305         $cookies.put('eg_search_lib', val, { path : '/' });
306     });
307     egCore.hatch.getItem('eg.search.pref_lib').then(function(val) {
308         $cookies.put('eg_pref_lib', val, { path : '/' });
309     });
310
311     // will hold a ref to the opac iframe
312     $scope.opac_iframe = null;
313     $scope.parts_iframe = null;
314
315     $scope.search_result_index = 1;
316     $scope.search_result_hit_count = 1;
317
318     $scope.$watch(
319         'opac_iframe.dom.contentWindow.search_result_index',
320         function (n,o) {
321             if (!isNaN(parseInt(n)))
322                 $scope.search_result_index = n + 1;
323         }
324     );
325
326     $scope.$watch(
327         'opac_iframe.dom.contentWindow.search_result_hit_count',
328         function (n,o) {
329             if (!isNaN(parseInt(n)))
330                 $scope.search_result_hit_count = n;
331         }
332     );
333
334     $scope.in_opac_call = false;
335     $scope.opac_call = function (opac_frame_function, force_opac_tab) {
336         if ($scope.opac_iframe) {
337             if (force_opac_tab) $scope.record_tab = 'catalog';
338             $scope.in_opac_call = true;
339             $scope.opac_iframe.dom.contentWindow[opac_frame_function]();
340             if (opac_frame_function == 'rdetailBackToResults') {
341                 $location.update_path('/cat/catalog/index');
342             }
343         }
344     }
345
346     $scope.add_cart_to_record_bucket = function() {
347         var cartkey = $cookies.get('cartcache');
348         if (!cartkey) return;
349         egCore.net.request(
350             'open-ils.actor',
351             'open-ils.actor.anon_cache.get_value',
352             cartkey,
353             'mylist'
354         ).then(function(list) {
355             list = list.map(function(x) {
356                 return parseInt(x);
357             });
358             $scope.add_to_record_bucket(list);
359         });
360     }
361
362     $scope.add_to_record_bucket = function(recs) {
363         if (!angular.isArray(recs)) {
364             recs = [ $scope.record_id ];
365         }
366         return $uibModal.open({
367             templateUrl: './cat/catalog/t_add_to_bucket',
368             backdrop: 'static',
369             animation: true,
370             size: 'md',
371             controller:
372                    ['$scope','$uibModalInstance',
373             function($scope , $uibModalInstance) {
374
375                 $scope.bucket_id = 0;
376                 $scope.newBucketName = '';
377                 $scope.allBuckets = [];
378                 egCore.net.request(
379                     'open-ils.actor',
380                     'open-ils.actor.container.retrieve_by_class.authoritative',
381                     egCore.auth.token(), egCore.auth.user().id(),
382                     'biblio', 'staff_client'
383                 ).then(function(buckets) { $scope.allBuckets = buckets; });
384
385                 $scope.add_to_bucket = function() {
386                     var promises = [];
387                     angular.forEach(recs, function(recId) {
388                         var item = new egCore.idl.cbrebi();
389                         item.bucket($scope.bucket_id);
390                         item.target_biblio_record_entry(recId);
391                         promises.push(egCore.net.request(
392                             'open-ils.actor',
393                             'open-ils.actor.container.item.create',
394                             egCore.auth.token(), 'biblio', item
395                         ));
396                     });
397                     $q.all(promises).then(function(resp) {
398                         $uibModalInstance.close();
399                     });
400                 }
401
402                 $scope.add_to_new_bucket = function() {
403                     var bucket = new egCore.idl.cbreb();
404                     bucket.owner(egCore.auth.user().id());
405                     bucket.name($scope.newBucketName);
406                     bucket.description('');
407                     bucket.btype('staff_client');
408
409                     egCore.net.request(
410                         'open-ils.actor',
411                         'open-ils.actor.container.create',
412                         egCore.auth.token(), 'biblio', bucket
413                     ).then(function(bucket) {
414                         $scope.bucket_id = bucket;
415                         $scope.add_to_bucket();
416                     });
417                 }
418
419                 $scope.cancel = function() {
420                     $uibModalInstance.dismiss();
421                 }
422             }]
423         });
424     }
425
426     $scope.carousels_available = false;
427     egCore.net.request(
428         'open-ils.actor',
429         'open-ils.actor.carousel.retrieve_manual_by_staff',
430         egCore.auth.token()
431     ).then(function(carousels) { $scope.carousels_available = true; });
432
433     $scope.add_to_carousel = function(recs) {
434         if (!angular.isArray(recs)) {
435             recs = [ $scope.record_id ];
436         }
437         return $uibModal.open({
438             templateUrl: './cat/catalog/t_add_to_carousel',
439             backdrop: 'static',
440             animation: true,
441             size: 'md',
442             controller:
443                    ['$scope','$uibModalInstance',
444             function($scope , $uibModalInstance) {
445                 $scope.bucket_id = 0;
446                 $scope.allCarousels = [];
447                 egCore.net.request(
448                     'open-ils.actor',
449                     'open-ils.actor.carousel.retrieve_manual_by_staff',
450                     egCore.auth.token()
451                 ).then(function(carousels) { $scope.allCarousels = carousels; });
452
453                 $scope.add_to_carousel = function() {
454                     // or more precisely, the carousel's bucket
455                     var promises = [];
456                     angular.forEach(recs, function(recId) {
457                         var item = new egCore.idl.cbrebi();
458                         item.bucket($scope.bucket_id);
459                         item.target_biblio_record_entry(recId);
460                         promises.push(egCore.net.request(
461                             'open-ils.actor',
462                             'open-ils.actor.container.item.create',
463                             egCore.auth.token(), 'biblio', item
464                         ));
465                     });
466                     $q.all(promises).then(function(resp) {
467                         $uibModalInstance.close();
468                     });
469                 }
470
471                 $scope.cancel = function() {
472                     $uibModalInstance.dismiss();
473                 }
474             }]
475         });
476     }
477
478     $scope.current_overlay_target     = egCore.hatch.getLocalItem('eg.cat.marked_overlay_record');
479     $scope.current_transfer_target    = egCore.hatch.getLocalItem('eg.cat.transfer_target_record');
480     $scope.current_conjoined_target   = egCore.hatch.getLocalItem('eg.cat.marked_conjoined_record');
481
482     $scope.quickReceive = function () {
483         var list = [];
484         var next_per_stream = {};
485
486         var recId = $scope.record_id;
487         return $uibModal.open({
488             templateUrl: './share/t_subscription_select_dialog',
489             backdrop: 'static',
490             controller: ['$scope', '$uibModalInstance',
491                 function($scope, $uibModalInstance) {
492
493                     $scope.focus = true;
494                     $scope.rememberMe = 'eg.serials.quickreceive.last_org';
495                     $scope.record_id = recId;
496                     $scope.ssubId = null;
497
498                     $scope.ok = function() { $uibModalInstance.close($scope.ssubId) }
499                     $scope.cancel = function() { $uibModalInstance.dismiss(); }
500                 }
501             ]
502         }).result.then(function(ssubId) {
503             if (ssubId) {
504                 var promises = [];
505                 promises.push(egSerialsCoreSvc.fetchItemsForSub(ssubId,{status:'Expected'}).then(function(){
506                     angular.forEach(egSerialsCoreSvc.itemTree, function (item) {
507                         if (next_per_stream[item.stream().id()]) return;
508                         if (item.status() == 'Expected') {
509                             next_per_stream[item.stream().id()] = item;
510                             list.push(egCore.idl.Clone(item));
511                         }
512                     });
513                 }));
514
515                 return $q.all(promises).then(function() {
516
517                     if (!list.length) {
518                         ngToast.warning(egCore.strings.SERIALS_NO_ITEMS);
519                         return $q.reject();
520                     }
521
522                     return egSerialsCoreSvc.process_items(
523                         'receive',
524                         $scope.record_id,
525                         list,
526                         true, // barcode
527                         false,// bind
528                         false, // print by default
529                         function() { $scope.holdings_record_id_changed($scope.record_id) }
530                     );
531                 });
532             } else {
533                 ngToast.warning(egCore.strings.SERIALS_NO_SUBS);
534                 return $q.reject();
535             }
536         });
537     }
538
539     $scope.markConjoined = function () {
540         $scope.current_conjoined_target = $scope.record_id;
541         egCore.hatch.setLocalItem('eg.cat.marked_conjoined_record',$scope.record_id);
542         ngToast.create(egCore.strings.MARK_CONJ_TARGET);
543     };
544
545     $scope.markHoldingsTransfer = function () {
546         $scope.current_transfer_target = $scope.record_id;
547         egCore.hatch.setLocalItem('eg.cat.transfer_target_record',$scope.record_id);
548         egCore.hatch.removeLocalItem('eg.cat.transfer_target_lib');
549         egCore.hatch.removeLocalItem('eg.cat.transfer_target_vol');
550         ngToast.create(egCore.strings.MARK_HOLDINGS_TARGET);
551     };
552
553     $scope.markOverlay = function () {
554         $scope.current_overlay_target = $scope.record_id;
555         egCore.hatch.setLocalItem('eg.cat.marked_overlay_record',$scope.record_id);
556         ngToast.create(egCore.strings.MARK_OVERLAY_TARGET);
557     };
558
559     $scope.clearRecordMarks = function () {
560         $scope.current_overlay_target     = null;
561         $scope.current_transfer_target    = null;
562         $scope.current_conjoined_target   = null;
563         $scope.current_hold_transfer_dest = null;
564         egCore.hatch.removeLocalItem('eg.cat.transfer_target_record');
565         egCore.hatch.removeLocalItem('eg.cat.marked_conjoined_record');
566         egCore.hatch.removeLocalItem('eg.cat.marked_overlay_record');
567         egCore.hatch.removeLocalItem('eg.circ.hold.title_transfer_target');
568     }
569
570     $scope.stop_unload = false;
571     $scope.$watch('stop_unload',
572         function(newVal, oldVal) {
573             if (newVal && newVal != oldVal && $scope.opac_iframe) {
574                 $($scope.opac_iframe.dom.contentWindow).on('beforeunload', function(){
575                     return 'There is unsaved data in this record.'
576                 });
577             } else {
578                 if ($scope.opac_iframe)
579                     $($scope.opac_iframe.dom.contentWindow).off('beforeunload');
580             }
581         }
582     );
583
584     // Set the "last bib" cookie, if we have that
585     if ($scope.record_id)
586         egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
587
588     $scope.refresh_record_callback = function (record_id) {
589         egCore.pcrud.retrieve('bre', record_id, {
590             flesh : 1,
591             flesh_fields : {
592                 bre : ['simple_record','creator','editor']
593             }
594         }).then(function(rec) {
595             rec.owner(egCore.org.get(rec.owner()));
596             $scope.summary_pane_record = rec;
597         });
598
599         return record_id;
600     }
601
602     patron_search_dialog = function() {
603         return $uibModal.open({
604             templateUrl: './share/t_patron_selector',
605             backdrop: 'static',
606             size: 'lg',
607             animation: true,
608             controller:
609                    ['$scope','$uibModalInstance','$controller',
610             function($scope , $uibModalInstance , $controller) {
611                 angular.extend(this, $controller('BasePatronSearchCtrl', {$scope : $scope}));
612                 $scope.clearForm();
613                 $scope.need_one_selected = function() {
614                     var items = $scope.gridControls.selectedItems();
615                     return (items.length == 1) ? false : true
616                 }
617                 $scope.ok = function() {
618                     var items = $scope.gridControls.selectedItems();
619                     if (items.length == 1) {
620                         $uibModalInstance.close(items[0].card().barcode());
621                     } else {
622                         $uibModalInstance.close()
623                     }
624                 }
625                 $scope.cancel = function($event) {
626                     $uibModalInstance.dismiss();
627                     $event.preventDefault();
628                 }
629             }]
630         });
631     }
632
633     // Map the Angular catalog-only 'item_table' tab to the AngJS
634     // 'catalog' tab.
635     function get_default_record_tab() {
636         var tab = egCore.hatch.getLocalItem('eg.cat.default_record_tab');
637         if (!tab || tab === 'item_table') { return 'catalog'; }
638         return tab;
639     }
640
641     // also set it when the iframe changes to a new record
642     $scope.handle_page = function(url) {
643
644         if (!url || url == 'about:blank') {
645             // nothing loaded.  If we already have a record ID, leave it.
646             return;
647         }
648
649         var prev_record_id = $scope.record_id;
650         var match = url.match(/\/+opac\/+record\/+(\d+)/);
651         if (match) {
652             $scope.record_id = match[1];
653             egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
654             $scope.holdings_record_id_changed($scope.record_id);
655             conjoinedSvc.fetch($scope.record_id).then(function(){
656                 $scope.conjoinedGridDataProvider.refresh();
657             });
658             init_parts_url();
659             $scope.grid_actions.refresh();
660             $location.update_path('/cat/catalog/record/' + $scope.record_id);
661             // update_path() bypasses the controller for path 
662             // /cat/catalog/record/:record_id. Manually set title here too.
663             egCore.strings.setPageTitle(
664                 egCore.strings.PAGE_TITLE_BIB_DETAIL,
665                 egCore.strings.PAGE_TITLE_CATALOG_CONTEXT,
666                 {record_id : $scope.record_id}
667             );
668         } else {
669             delete $scope.record_id;
670             $scope.from_route = false;
671         }
672
673         // child scope is executing this function, so our digest doesn't fire ... thus,
674         $scope.$apply();
675
676         // don't change tabs if we are using the OPAC nav buttons,
677         // or we didn't change records on the OPAC load
678         if (!$scope.in_opac_call && ($scope.record_id != prev_record_id)) {
679             if ($scope.record_id) {
680                 $scope.default_tab = get_default_record_tab();
681                 tab = $routeParams.record_tab || $scope.default_tab;
682             } else {
683                 tab = $routeParams.record_tab || 'catalog';
684             }
685             $scope.set_record_tab(tab);
686         } else {
687             $scope.in_opac_call = false;
688         }
689
690         if ($scope.opac_iframe && $location.path().match(/cat\/catalog/)) {
691             var doc = $scope.opac_iframe.dom.contentWindow.document;
692             $(doc).find('#hold_usr_search').show();
693             $(doc).find('#hold_usr_search').on('click', function() {
694                 patron_search_dialog().result.then(function(barc) {
695                     $(doc).find('#hold_usr_input').val(barc);
696                     $(doc).find('#hold_usr_input').trigger($.Event('keydown', {which: 13}));
697                 });
698             });
699             $(doc).find('#select_basket_action').on('change', function() {
700                 if (this.options[this.selectedIndex].value && this.options[this.selectedIndex].value == "add_cart_to_bucket") {
701                     $scope.add_cart_to_record_bucket();
702                 }
703             });
704         }
705
706     }
707
708     // xulG catalog handlers
709     $scope.handlers = { }
710
711     // ------------------------------------------------------------------
712     // Conjoined items
713
714     $scope.conjoinedGridControls = {};
715     $scope.conjoinedGridDataProvider = egGridDataProvider.instance({
716         get : function(offset, count) {
717             return this.arrayNotifier(conjoinedSvc.items, offset, count);
718         }
719     });
720
721     $scope.changeConjoinedType = function () {
722         var peers = egCore.idl.Clone($scope.conjoinedGridControls.selectedItems());
723         angular.forEach(peers, function (p) {
724             p.target_copy(p.target_copy().id());
725             p.peer_type(p.peer_type().id());
726         });
727
728         var conjoinedGridDataProviderRef = $scope.conjoinedGridDataProvider;
729
730         return $uibModal.open({
731             templateUrl: './cat/catalog/t_conjoined_selector',
732             backdrop: 'static',
733             animation: true,
734             controller:
735                    ['$scope','$uibModalInstance',
736             function($scope , $uibModalInstance) {
737                 $scope.update = true;
738
739                 $scope.peer_type = null;
740                 $scope.peer_type_list = [];
741                 conjoinedSvc.get_peer_types().then(function(list){
742                     $scope.peer_type_list = list;
743                 });
744     
745                 $scope.ok = function(type) {
746                     var promises = [];
747     
748                     angular.forEach(peers, function (p) {
749                         p.ischanged(1);
750                         p.peer_type(type);
751                         promises.push(egCore.pcrud.update(p));
752                     });
753     
754                     return $q.all(promises)
755                         .then(function(){$uibModalInstance.close()})
756                         .then(function(){return conjoinedSvc.fetch()})
757                         .then(function(){conjoinedGridDataProviderRef.refresh()});
758                 }
759     
760                 $scope.cancel = function($event) {
761                     $uibModalInstance.dismiss();
762                     $event.preventDefault();
763                 }
764             }]
765         });
766         
767     }
768
769     $scope.refreshConjoined = function () {
770         conjoinedSvc.fetch($scope.record_id)
771         .then(function(){$scope.conjoinedGridDataProvider.refresh();});
772     }
773
774     $scope.deleteSelectedConjoined = function () {
775         var peers = $scope.conjoinedGridControls.selectedItems();
776
777         if (peers.length > 0) {
778             egConfirmDialog.open(
779                 egCore.strings.CONFIRM_DELETE_PEERS,
780                 egCore.strings.CONFIRM_DELETE_PEERS_MESSAGE,
781                 {peers : peers.length}
782             ).result.then(function() {
783                 angular.forEach(peers, function (p) {
784                     p.isdeleted(1);
785                 });
786
787                 egCore.pcrud.remove(peers).then(function() {
788                     return conjoinedSvc.fetch();
789                 }).then(function() {
790                     $scope.conjoinedGridDataProvider.refresh();
791                 });
792             });
793         }
794     }
795     if ($scope.record_id)
796         conjoinedSvc.fetch($scope.record_id);
797
798     // ------------------------------------------------------------------
799     // Holdings
800
801     $scope.holdingsGridControls = {
802         activateItem : function (item) {
803             $scope.selectedHoldingsVolCopyEdit();
804         }
805     };
806     $scope.holdingsGridDataProvider = egGridDataProvider.instance({
807         get : function(offset, count) {
808             return this.arrayNotifier(holdingsSvcInst.copies, offset, count);
809         }
810     });
811
812     $scope.add_copies_to_bucket = function() {
813         var copy_list = gatherSelectedHoldingsIds();
814         if (copy_list.length == 0) return;
815
816         return $uibModal.open({
817             templateUrl: './cat/catalog/t_add_to_bucket',
818             backdrop: 'static',
819             animation: true,
820             size: 'md',
821             controller:
822                    ['$scope','$uibModalInstance',
823             function($scope , $uibModalInstance) {
824
825                 $scope.bucket_id = 0;
826                 $scope.newBucketName = '';
827                 $scope.allBuckets = [];
828
829                 egCore.net.request(
830                     'open-ils.actor',
831                     'open-ils.actor.container.retrieve_by_class.authoritative',
832                     egCore.auth.token(), egCore.auth.user().id(),
833                     'copy', 'staff_client'
834                 ).then(function(buckets) { $scope.allBuckets = buckets; });
835
836                 $scope.add_to_bucket = function() {
837                     var promises = [];
838                     angular.forEach(copy_list, function (cp) {
839                         var item = new egCore.idl.ccbi()
840                         item.bucket($scope.bucket_id);
841                         item.target_copy(cp);
842                         promises.push(
843                             egCore.net.request(
844                                 'open-ils.actor',
845                                 'open-ils.actor.container.item.create',
846                                 egCore.auth.token(), 'copy', item
847                             )
848                         );
849
850                         return $q.all(promises).then(function() {
851                             $uibModalInstance.close();
852                         });
853                     });
854                 }
855
856                 $scope.add_to_new_bucket = function() {
857                     var bucket = new egCore.idl.ccb();
858                     bucket.owner(egCore.auth.user().id());
859                     bucket.name($scope.newBucketName);
860                     bucket.description('');
861                     bucket.btype('staff_client');
862
863                     return egCore.net.request(
864                         'open-ils.actor',
865                         'open-ils.actor.container.create',
866                         egCore.auth.token(), 'copy', bucket
867                     ).then(function(bucket) {
868                         $scope.bucket_id = bucket;
869                         $scope.add_to_bucket();
870                     });
871                 }
872
873                 $scope.cancel = function() {
874                     $uibModalInstance.dismiss();
875                 }
876             }]
877         });
878     }
879
880     // TODO: refactor common code between cat/catalog/app.js and cat/item/app.js 
881
882     $scope.need_one_selected = function() {
883         var items = $scope.holdingsGridControls.selectedItems();
884         if (items.length == 1) return false;
885         return true;
886     };
887
888     $scope.make_copies_bookable = function() {
889
890         var copies_by_record = {};
891         var record_list = [];
892         angular.forEach(
893             $scope.holdingsGridControls.selectedItems(),
894             function (item) {
895                 var record_id = item['call_number.record.id'];
896                 if (typeof copies_by_record[ record_id ] == 'undefined') {
897                     copies_by_record[ record_id ] = [];
898                     record_list.push( record_id );
899                 }
900                 copies_by_record[ record_id ].push(item.id);
901             }
902         );
903
904         var promises = [];
905         var combined_results = [];
906         angular.forEach(record_list, function(record_id) {
907             promises.push(
908                 egCore.net.request(
909                     'open-ils.booking',
910                     'open-ils.booking.resources.create_from_copies',
911                     egCore.auth.token(),
912                     copies_by_record[record_id]
913                 ).then(function(results) {
914                     if (results && results['brsrc']) {
915                         combined_results = combined_results.concat(results['brsrc']);
916                     }
917                 })
918             );
919         });
920
921         $q.all(promises).then(function() {
922             if (combined_results.length > 0) {
923                 $uibModal.open({
924                     template: '<eg-embed-frame url="booking_admin_url" handlers="funcs"></eg-embed-frame>',
925                     backdrop: 'static',
926                     animation: true,
927                     size: 'md',
928                     controller:
929                            ['$scope','$location','egCore','$uibModalInstance',
930                     function($scope , $location , egCore , $uibModalInstance) {
931
932                         $scope.funcs = {
933                             ses : egCore.auth.token(),
934                             resultant_brsrc : combined_results.map(function(o) { return o[0]; })
935                         }
936
937                         var booking_path = '/eg/conify/global/booking/resource';
938
939                         $scope.booking_admin_url =
940                             $location.absUrl().replace(/\/eg\/staff.*/, booking_path);
941                     }]
942                 });
943             }
944         });
945     }
946
947     $scope.book_copies_now = function(items) {
948         location.href = "/eg2/staff/booking/create_reservation/for_resource/" + items[0]['barcode'];
949     }
950
951     $scope.requestItems = function() {
952         var copy_list = gatherSelectedHoldingsIds();
953         if (copy_list.length == 0) return;
954
955         return $uibModal.open({
956             templateUrl: './cat/catalog/t_request_items',
957             animation: true,
958             controller:
959                    ['$scope','$uibModalInstance',
960             function($scope , $uibModalInstance) {
961                 $scope.user = null;
962                 $scope.first_user_fetch = true;
963
964                 $scope.hold_data = {
965                     hold_type : 'C',
966                     copy_list : copy_list,
967                     pickup_lib: egCore.org.get(egCore.auth.user().ws_ou()),
968                     user      : egCore.auth.user().id()
969                 };
970
971                 egUser.get( $scope.hold_data.user ).then(function(u) {
972                     $scope.user = u;
973                     $scope.barcode = u.card().barcode();
974                     $scope.user_name = egUser.format_name(u);
975                     $scope.hold_data.user = u.id();
976                 });
977
978                 $scope.user_name = '';
979                 $scope.barcode = '';
980                 $scope.$watch('barcode', function (n) {
981                     if (!$scope.first_user_fetch) {
982                         egUser.getByBarcode(n).then(function(u) {
983                             $scope.user = u;
984                             $scope.user_name = egUser.format_name(u);
985                             $scope.hold_data.user = u.id();
986                         }, function() {
987                             $scope.user = null;
988                             $scope.user_name = '';
989                             delete $scope.hold_data.user;
990                         });
991                     }
992                     $scope.first_user_fetch = false;
993                 });
994
995                 $scope.ok = function(h) {
996                     var args = {
997                         patronid  : h.user,
998                         hold_type : h.hold_type,
999                         pickup_lib: h.pickup_lib.id(),
1000                         depth     : 0
1001                     };
1002
1003                     egCore.net.request(
1004                         'open-ils.circ',
1005                         'open-ils.circ.holds.test_and_create.batch.override',
1006                         egCore.auth.token(), args, h.copy_list
1007                     ).then(function() {
1008                         holds = []; // force the holds grid to refetch data.
1009                         $uibModalInstance.close();
1010                     });
1011                 }
1012
1013                 $scope.cancel = function($event) {
1014                     $uibModalInstance.dismiss();
1015                     $event.preventDefault();
1016                 }
1017             }]
1018         });
1019     }
1020
1021     $scope.manage_reservations = function() {
1022         var item = $scope.holdingsGridControls.selectedItems()[0];
1023         if (item)
1024             location.href = "/eg2/staff/booking/manage_reservations/by_resource/" + item.barcode;
1025     }
1026
1027
1028     $scope.view_place_orders = function() {
1029         if (!$scope.record_id) return;
1030         var url = egCore.env.basePath + 'acq/legacy/lineitem/related/' + $scope.record_id + '?target=bib';
1031         $timeout(function() { $window.open(url, '_blank') });
1032     }
1033
1034     $scope.replaceBarcodes = function() {
1035         var copy_list = gatherSelectedRawCopies();
1036         if (copy_list.length == 0) return;
1037
1038         var holdingsGridDataProviderRef = $scope.holdingsGridDataProvider;
1039
1040         angular.forEach(copy_list, function (cp) {
1041             $uibModal.open({
1042                 templateUrl: './cat/share/t_replace_barcode',
1043                 backdrop: 'static',
1044                 animation: true,
1045                 controller:
1046                            ['$scope','$uibModalInstance',
1047                     function($scope , $uibModalInstance) {
1048                         $scope.duplicate_barcode = false;
1049                         $scope.isModal = true;
1050                         $scope.focusBarcode = false;
1051                         $scope.focusBarcode2 = true;
1052                         $scope.barcode1 = cp.barcode();
1053
1054                         // check input to see if it's a duplicate barcode
1055                         $scope.checkCurrentBarcode = function() {
1056                             if (!$scope.duplicate_barcode_string) {
1057                                 $scope.duplicate_barcode_string = window.duplicate_barcode_string;
1058                             }
1059                             var searchParams = {
1060                                 deleted : 'f',
1061                                 'barcode' : $scope.barcode2,
1062                                 id : { '!=' : $scope.copyId }
1063                             };
1064                             egCore.pcrud.search('acp', searchParams).then(function (res) {
1065                                 $scope.duplicate_barcode = res;
1066                             });
1067                         }
1068
1069                         $scope.updateBarcode = function() {
1070                             $scope.copyNotFound = false;
1071                             $scope.updateOK = false;
1072                 
1073                             egCore.pcrud.search('acp',
1074                                 {deleted : 'f', barcode : $scope.barcode1})
1075                             .then(function(copy) {
1076                 
1077                                 if (!copy) {
1078                                     $scope.focusBarcode = true;
1079                                     $scope.copyNotFound = true;
1080                                     return;
1081                                 }
1082                 
1083                                 $scope.copyId = copy.id();
1084                                 copy.barcode($scope.barcode2);
1085                 
1086                                 egCore.pcrud.update(copy).then(function(stat) {
1087                                     $scope.updateOK = stat;
1088                                     $scope.focusBarcode = true;
1089                                     holdingsSvc.fetchAgain().then(function (){
1090                                         holdingsGridDataProviderRef.refresh();
1091                                     });
1092                                 });
1093
1094                             });
1095                             $uibModalInstance.close();
1096                         }
1097
1098                         $scope.cancel = function($event) {
1099                             $uibModalInstance.dismiss();
1100                             $event.preventDefault();
1101                         }
1102                     }
1103                 ]
1104             });
1105         });
1106     }
1107
1108     var holdings_bChannel = null;
1109     // subscribe to BroadcastChannel for any child VolCopy tabs
1110     // refresh grid if needed to show new updates
1111     // if ($scope.record_tab === 'holdings'){
1112     $scope.$watch('record_tab', function(n){
1113     
1114         if (n === 'holdings'){
1115             if (typeof BroadcastChannel != 'undefined') {
1116                 // we're in holdings tab, connect 2 bChannel
1117                 holdings_bChannel = new BroadcastChannel('eg.holdings.update');
1118                 holdings_bChannel.onmessage = function(e){
1119                     if (e.data
1120                         && e.data.records
1121                         && e.data.records.length
1122                         && e.data.records.includes(Number($scope.record_id))
1123                     ){ // it's for us, refresh grid!
1124                         console.log("Got broadcast from channel eg.holdings.update for records " + e.data.records);
1125                         $scope.holdings_record_id_changed($scope.record_id);
1126                     }
1127                 }
1128             };
1129
1130         } else if (holdings_bChannel){ // we're leaving holding tab, close bChannel
1131             holdings_bChannel.close();
1132         }
1133     
1134     });
1135
1136     // refresh the list of holdings when the record_id is changed.
1137     $scope.holdings_record_id_changed = function(id) {
1138         if ($scope.record_id != id) $scope.record_id = id;
1139         console.log('record id changed to ' + id + ', loading new holdings');
1140         holdingsSvcInst.fetch({
1141             rid : $scope.record_id,
1142             org : $scope.holdings_ou,
1143             copy: $scope.holdings_show_vols ? $scope.holdings_show_copies : false,
1144             vol : $scope.holdings_show_vols,
1145             empty: $scope.holdings_show_empty,
1146             empty_org: $scope.holdings_show_empty_org
1147         }).then(function() {
1148             $scope.holdingsGridDataProvider.refresh();
1149         });
1150     }
1151
1152     // refresh the list of holdings when the filter lib is changed.
1153     $scope.holdings_ou = egCore.org.get(egCore.auth.user().ws_ou());
1154     $scope.holdings_ou_changed = function(org) {
1155         $scope.holdings_ou = org;
1156         holdingsSvcInst.fetch({
1157             rid : $scope.record_id,
1158             org : $scope.holdings_ou,
1159             copy: $scope.holdings_show_vols ? $scope.holdings_show_copies : false,
1160             vol : $scope.holdings_show_vols,
1161             empty: $scope.holdings_show_empty,
1162             empty_org: $scope.holdings_show_empty_org
1163         }).then(function() {
1164             $scope.holdingsGridDataProvider.refresh();
1165         });
1166     }
1167
1168     $scope.holdings_cb_changed = function(cb,newVal,norefresh) {
1169         $scope[cb] = newVal;
1170         var x = $scope.holdings_show_vols ? $scope.holdings_show_copies : false;
1171         $('#holdings_show_copies').prop('checked', x);
1172         egCore.hatch.setItem('cat.' + cb, newVal);
1173         if (!norefresh) holdingsSvcInst.fetch({
1174             rid : $scope.record_id,
1175             org : $scope.holdings_ou,
1176             copy: $scope.holdings_show_vols ? $scope.holdings_show_copies : false,
1177             vol : $scope.holdings_show_vols,
1178             empty: $scope.holdings_show_empty,
1179             empty_org: $scope.holdings_show_empty_org
1180         }).then(function() {
1181             $scope.holdingsGridDataProvider.refresh();
1182         });
1183     }
1184
1185     egCore.hatch.getItem('cat.holdings_show_vols').then(function(x){
1186         if (typeof x ==  'undefined') x = true;
1187         $scope.holdings_cb_changed('holdings_show_vols',x,true);
1188         $('#holdings_show_vols').prop('checked', x);
1189     }).then(function(){
1190         egCore.hatch.getItem('cat.holdings_show_copies').then(function(x){
1191             if (typeof x ==  'undefined') x = true;
1192             $scope.holdings_cb_changed('holdings_show_copies',x,true);
1193             x = $scope.holdings_show_vols ? x : false;
1194             $('#holdings_show_copies').prop('checked', x);
1195         }).then(function(){
1196             egCore.hatch.getItem('cat.holdings_show_empty').then(function(x){
1197                 if (typeof x ==  'undefined') x = true;
1198                 $scope.holdings_cb_changed('holdings_show_empty',x);
1199                 $('#holdings_show_empty').prop('checked', x);
1200             }).then(function(){
1201                 egCore.hatch.getItem('cat.holdings_show_empty_org').then(function(x){
1202                     if (typeof x ==  'undefined') x = true;
1203                     $scope.holdings_cb_changed('holdings_show_empty_org',x);
1204                     $('#holdings_show_empty_org').prop('checked', x);
1205                 })
1206             })
1207         })
1208     });
1209
1210     $scope.vols_not_shown = function () {
1211         return !$scope.holdings_show_vols;
1212     }
1213
1214     $scope.copies_not_shown = function () {
1215         return !$scope.holdings_show_copies;
1216     }
1217
1218     $scope.empty_org_not_shown = function () {
1219         return !$scope.holdings_show_empty_org;
1220     }
1221
1222     $scope.holdings_checkbox_handler = function (item) {
1223         $scope.holdings_cb_changed(item.checkbox,item.checked);
1224     }
1225
1226     function gatherSelectedHoldingsIds () {
1227         var cp_id_list = [];
1228         angular.forEach(
1229             $scope.holdingsGridControls.selectedItems(),
1230             function (item) { cp_id_list = cp_id_list.concat(item.id_list) }
1231         );
1232         return cp_id_list;
1233     }
1234
1235     function gatherSelectedRawCopies () {
1236         var cp_list = [];
1237         angular.forEach(
1238             $scope.holdingsGridControls.selectedItems(),
1239             function (item) { if (item.raw) cp_list = cp_list.concat(item.raw) }
1240         );
1241         return cp_list;
1242     }
1243
1244     function gatherSelectedEmptyVolumeIds () {
1245         var cn_id_list = [];
1246         angular.forEach(
1247             $scope.holdingsGridControls.selectedItems(),
1248             function (item) {
1249                 if (item.copy_count == 0 || (!item.id && item.call_number))
1250                     // we are in a compressed row with no copies, or we are in a single
1251                     // call number row with no copy (testing for presence of 'id')
1252                     // In either case, the call number is 'empty'
1253                     cn_id_list.push(item.call_number.id)
1254             }
1255         );
1256         return cn_id_list;
1257     }
1258
1259     function gatherSelectedVolumeIds () {
1260         var cn_id_list = [];
1261         angular.forEach(
1262             $scope.holdingsGridControls.selectedItems(),
1263             function (item) {
1264                 if (cn_id_list.indexOf(item.call_number.id) == -1)
1265                     cn_id_list.push(item.call_number.id)
1266             }
1267         );
1268         return cn_id_list;
1269     }
1270
1271     $scope.selectedHoldingsDelete = function (vols, copies) {
1272
1273         var cnHash = {};
1274         var perCnCopies = {};
1275
1276         var cn_count = 0;
1277         var cp_count = 0;
1278
1279         angular.forEach(
1280             $scope.holdingsGridControls.selectedItems(),
1281             function (item) {
1282                 if (vols && item.raw_call_number) {
1283                     cnHash[item.call_number.id] = egCore.idl.Clone(item.raw_call_number);
1284                     cnHash[item.call_number.id].isdeleted(1);
1285                     cn_count++;
1286                 } else if (copies) {
1287                     angular.forEach(egCore.idl.Clone(item.raw), function (cp) {
1288                         cp.isdeleted(1);
1289                         cp_count++;
1290                         var cn_id = cp.call_number().id();
1291                         if (!cnHash[cn_id]) {
1292                             cnHash[cn_id] = cp.call_number();
1293                             perCnCopies[cn_id] = [cp];
1294                         } else {
1295                             perCnCopies[cn_id].push(cp);
1296                         }
1297                         cp.call_number(cn_id); // prevent loops in JSON-ification
1298                     });
1299
1300                 }
1301             }
1302         );
1303
1304         angular.forEach(perCnCopies, function (v, k) {
1305             if (vols) {
1306                 cnHash[k].isdeleted(1);
1307                 cn_count++;
1308             }
1309             cnHash[k].copies(v);
1310         });
1311
1312         cnList = [];
1313         angular.forEach(cnHash, function (v, k) {
1314             cnList.push(v);
1315         });
1316
1317         if (cnList.length == 0) return;
1318
1319         var flags = {};
1320         if (vols && copies) flags.force_delete_copies = 1;
1321
1322         egConfirmDialog.open(
1323             egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES,
1324             egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES_MESSAGE,
1325             {copies : cp_count, volumes : cn_count}
1326         ).result.then(function() {
1327             egCore.net.request(
1328                 'open-ils.cat',
1329                 'open-ils.cat.asset.volume.fleshed.batch.update',
1330                 egCore.auth.token(), cnList, 1, flags
1331             ).then(function(resp) {
1332                 var evt = egCore.evt.parse(resp);
1333                 if (evt) {
1334                     egConfirmDialog.open(
1335                         egCore.strings.OVERRIDE_DELETE_ITEMS_FROM_CATALOG_TITLE,
1336                         egCore.strings.OVERRIDE_DELETE_ITEMS_FROM_CATALOG_BODY,
1337                         {'evt_desc': evt.desc}
1338                     ).result.then(function() {
1339                         egCore.net.request(
1340                             'open-ils.cat',
1341                             'open-ils.cat.asset.volume.fleshed.batch.update.override',
1342                             egCore.auth.token(), cnList, 1,
1343                             { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
1344                         ).then(function() {
1345                             holdingsSvcInst.fetchAgain().then(function() {
1346                                 $scope.holdingsGridDataProvider.refresh();
1347                             });
1348                         });
1349                     });
1350                 } else {
1351                     holdingsSvcInst.fetchAgain().then(function() {
1352                         $scope.holdingsGridDataProvider.refresh();
1353                     });
1354                 }
1355             });
1356         });
1357     }
1358     $scope.selectedHoldingsCopyDelete = function () { $scope.selectedHoldingsDelete(false,true) }
1359     $scope.selectedHoldingsVolCopyDelete = function () { $scope.selectedHoldingsDelete(true,true) }
1360     $scope.selectedHoldingsEmptyVolCopyDelete = function () { $scope.selectedHoldingsDelete(true,false) }
1361
1362     spawnHoldingsAdd = function (add_vols,add_copies){
1363         var raw = [];
1364         if (!add_vols && add_copies) { // just a copy on existing volumes
1365             angular.forEach(gatherSelectedVolumeIds(), function (v) {
1366                 raw.push( {callnumber : v} );
1367             });
1368         } else if (add_vols) {
1369             if (typeof $scope.holdingsGridControls.selectedItems == "function" &&
1370                 $scope.holdingsGridControls.selectedItems().length > 0) {
1371                 angular.forEach($scope.holdingsGridControls.selectedItems(),
1372                     function (item) {
1373                         raw.push({
1374                             owner : item.owner_id,
1375                             label : ((item.call_number) ? item.call_number.label : null)
1376                         });
1377                     });
1378             } else {
1379                 raw.push({
1380                     owner : egCore.auth.user().ws_ou()
1381                 });
1382             }
1383         }
1384
1385         if (raw.length == 0) raw.push({});
1386
1387         egCore.net.request(
1388             'open-ils.actor',
1389             'open-ils.actor.anon_cache.set_value',
1390             null, 'edit-these-copies', {
1391                 record_id: $scope.record_id,
1392                 raw: raw,
1393                 hide_vols : false,
1394                 hide_copies : !add_copies
1395             }
1396         ).then(function(key) {
1397             if (key) {
1398                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
1399                 $timeout(function() { $window.open(url, '_blank') });
1400             } else {
1401                 alert('Could not create anonymous cache key!');
1402             }
1403         });
1404     }
1405     $scope.selectedHoldingsVolCopyAdd = function () { spawnHoldingsAdd(true,true) }
1406     $scope.selectedHoldingsCopyAdd = function () { spawnHoldingsAdd(false,true) }
1407     $scope.selectedHoldingsVolAdd = function () { spawnHoldingsAdd(true,false) }
1408
1409     spawnHoldingsEdit = function (hide_vols,hide_copies){
1410         egCore.net.request(
1411             'open-ils.actor',
1412             'open-ils.actor.anon_cache.set_value',
1413             null, 'edit-these-copies', {
1414                 record_id: $scope.record_id,
1415                 copies: gatherSelectedHoldingsIds(),
1416                 raw: gatherSelectedEmptyVolumeIds().map(
1417                     function(v){ return { callnumber : v } }
1418                 ),
1419                 hide_vols : hide_vols,
1420                 hide_copies : hide_copies
1421             }
1422         ).then(function(key) {
1423             if (key) {
1424                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
1425                 $timeout(function() { $window.open(url, '_blank') });
1426             } else {
1427                 alert('Could not create anonymous cache key!');
1428             }
1429         });
1430     }
1431     $scope.selectedHoldingsVolCopyEdit = function () { spawnHoldingsEdit(false,false) }
1432     $scope.selectedHoldingsVolEdit = function () { spawnHoldingsEdit(false,true) }
1433     $scope.selectedHoldingsCopyEdit = function () { spawnHoldingsEdit(true,false) }
1434
1435     $scope.selectedHoldingsItemStatus = function (){
1436         var url = egCore.env.basePath + 'cat/item/search/' + gatherSelectedHoldingsIds().join(',')
1437         $timeout(function() { $window.open(url, '_blank') });
1438     }
1439
1440     $scope.markFromSelectedAsHoldingsTarget = function() {
1441         egCore.hatch.setLocalItem(
1442             'eg.cat.transfer_target_lib',
1443             $scope.holdingsGridControls.selectedItems()[0].owner_id
1444         );
1445         egCore.hatch.setLocalItem(
1446             'eg.cat.transfer_target_record',
1447             $scope.record_id
1448         );
1449         if ($scope.holdingsGridControls.selectedItems()[0].call_number.id) { // cn.id missing when vols are collapsed, or we are on an empty lib
1450             egCore.hatch.setLocalItem(
1451                 'eg.cat.transfer_target_vol',
1452                 $scope.holdingsGridControls.selectedItems()[0].call_number.id
1453             );
1454         } else {
1455             // clear out the stale value if we're on a lib-only
1456             // or vol-collapsed row
1457             egCore.hatch.removeLocalItem('eg.cat.transfer_target_vol');
1458         }
1459         ngToast.create(egCore.strings.MARK_HOLDINGS_TARGET);
1460     }
1461
1462     $scope.selectedHoldingsItemStatusDetail = function (){
1463         angular.forEach(
1464             gatherSelectedHoldingsIds(),
1465             function (cid) {
1466                 var url = egCore.env.basePath +
1467                           'cat/item/' + cid;
1468                 $timeout(function() { $window.open(url, '_blank') });
1469             }
1470         );
1471     }
1472
1473     $scope.transferVolumes = function (){
1474         var target_record = egCore.hatch.getLocalItem('eg.cat.transfer_target_record');
1475         var target_lib = egCore.hatch.getLocalItem('eg.cat.transfer_target_lib');
1476         if (!target_lib
1477             && (!target_record || ($scope.record_id == target_record) )
1478         ) return;
1479
1480         var vols_to_move = {};
1481         if (target_lib) {
1482             // we're moving volumes to a different library
1483             var vol_ids = gatherSelectedVolumeIds();
1484             if (vol_ids.length) {
1485                 vols_to_move[target_lib] = vol_ids;
1486
1487                 // if we're *only* switching libs,
1488                 // grab the current record as the target
1489                 target_record = target_record || $scope.record_id;
1490             }
1491         } else {
1492             // we're moving volumes to the same library they exist in
1493             // currently, but on a different record
1494             var items = $scope.holdingsGridControls.selectedItems();
1495             angular.forEach(items, function(item) {
1496                 if (!(item.call_number.owning_lib in vols_to_move)) {
1497                     vols_to_move[item.call_number.owning_lib] = new Array;
1498                 }
1499                 vols_to_move[item.call_number.owning_lib].push(item.call_number.id);
1500             });
1501         }
1502
1503         var promises = [];        
1504         angular.forEach(vols_to_move, function(vols, owning_lib) {
1505             promises.push(egCore.net.request(
1506                 'open-ils.cat',
1507                 'open-ils.cat.asset.volume.batch.transfer.override',
1508                 egCore.auth.token(), {
1509                     docid   : target_record,
1510                     lib     : owning_lib,
1511                     volumes : vols
1512                 }
1513             ));
1514         });
1515         $q.all(promises).then(function(success) {
1516             if (success) {
1517                 ngToast.create(egCore.strings.VOLS_TRANSFERED);
1518                 holdingsSvcInst.fetchAgain().then(function() {
1519                     $scope.holdingsGridDataProvider.refresh();
1520                 });
1521             } else {
1522                 alert('Could not transfer volumes!');
1523             }
1524         });
1525     }
1526
1527     // this "transfers" selected copies to a new owning library,
1528     // auto-creating volumes as required
1529     $scope.transferItemsAutoFill = function() {
1530         var target_record = egCore.hatch.getLocalItem('eg.cat.transfer_target_record');
1531         var target_lib = egCore.hatch.getLocalItem('eg.cat.transfer_target_lib');
1532         if (!target_lib
1533             && (!target_record || ($scope.record_id == target_record) )
1534         ) return;
1535
1536         var items = $scope.holdingsGridControls.selectedItems();
1537         if (!items.length) {
1538             return;
1539         }
1540
1541         var vols_to_move   = {};
1542         var copies_to_move = {};
1543         angular.forEach(items, function(item) {
1544             var needs_move = false;
1545             if (target_lib
1546                 && (item.call_number.owning_lib != target_lib)) {
1547                     item.call_number.owning_lib = target_lib;
1548                     needs_move = true;
1549             }
1550             if (target_record
1551                 && (item.call_number.record != target_record)) {
1552                     item.call_number.record = target_record;
1553                     needs_move = true;
1554             }
1555             if (needs_move) {
1556                 if (item.call_number.id in vols_to_move) {
1557                     copies_to_move[item.call_number.id].push(item.id);
1558                 } else {
1559                     vols_to_move[item.call_number.id] = item.call_number;
1560                     copies_to_move[item.call_number.id] = new Array;
1561                     copies_to_move[item.call_number.id].push(item.id);
1562                 }
1563             }
1564         });
1565
1566         var promises = [];
1567         angular.forEach(vols_to_move, function(vol) {
1568             promises.push(egCore.net.request(
1569                 'open-ils.cat',
1570                 'open-ils.cat.call_number.find_or_create',
1571                 egCore.auth.token(),
1572                 vol.label,
1573                 vol.record, // may be new
1574                 vol.owning_lib, // may be new
1575                 vol.prefix.id,
1576                 vol.suffix.id,
1577                 vol.label_class
1578             ).then(function(resp) {
1579                 var evt = egCore.evt.parse(resp);
1580                 if (evt) return;
1581                 return egCore.net.request(
1582                     'open-ils.cat',
1583                     'open-ils.cat.transfer_copies_to_volume',
1584                     egCore.auth.token(),
1585                     resp.acn_id,
1586                     copies_to_move[vol.id]
1587                 );
1588             }));
1589         });
1590         $q.all(promises).then(function() {
1591             ngToast.create(egCore.strings.ITEMS_TRANSFERED);
1592             holdingsSvcInst.fetchAgain().then(function() {
1593                 $scope.holdingsGridDataProvider.refresh();
1594             });
1595         });
1596     }
1597
1598     $scope.gridCellHandlers = {};
1599     $scope.gridCellHandlers.copyAlertsEdit = function(id) {
1600         egCirc.manage_copy_alerts([id]).then(function() {
1601             // update grid items?
1602         });
1603     };
1604
1605     $scope.transferItems = function (){
1606         var xfer_target = egCore.hatch.getLocalItem('eg.cat.transfer_target_vol');
1607
1608         if (!xfer_target) {
1609             // we have no specific volume, let's try to fill in the
1610             // blanks instead
1611             return $scope.transferItemsAutoFill();
1612         }
1613
1614         var copy_ids = gatherSelectedHoldingsIds();
1615         if (copy_ids.length > 0) {
1616             egCore.net.request(
1617                 'open-ils.cat',
1618                 'open-ils.cat.transfer_copies_to_volume',
1619                 egCore.auth.token(),
1620                 xfer_target,
1621                 copy_ids
1622             ).then(
1623                 function(resp) { // oncomplete
1624                     var evt = egCore.evt.parse(resp);
1625                     if (evt) {
1626                         egConfirmDialog.open(
1627                             egCore.strings.OVERRIDE_TRANSFER_COPIES_TO_MARKED_VOLUME_TITLE,
1628                             egCore.strings.OVERRIDE_TRANSFER_COPIES_TO_MARKED_VOLUME_BODY,
1629                             {'evt_desc': evt.desc}
1630                         ).result.then(function() {
1631                             egCore.net.request(
1632                                 'open-ils.cat',
1633                                 'open-ils.cat.transfer_copies_to_volume.override',
1634                                 egCore.auth.token(),
1635                                 xfer_target,
1636                                 copy_ids,
1637                                 { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
1638                             ).then(function(resp) {
1639                                 holdingsSvcInst.fetchAgain().then(function() {
1640                                     $scope.holdingsGridDataProvider.refresh();
1641                                 });
1642                             });
1643                         });
1644                     } else {
1645                         ngToast.create(egCore.strings.ITEMS_TRANSFERED);
1646                         holdingsSvcInst.fetchAgain().then(function() {
1647                             $scope.holdingsGridDataProvider.refresh();
1648                         });
1649                     }
1650                 },
1651                 null, // onerror
1652                 null // onprogress
1653             )
1654         }
1655     }
1656
1657     $scope.selectedHoldingsItemStatusTgrEvt = function (){
1658         angular.forEach(
1659             gatherSelectedHoldingsIds(),
1660             function (cid) {
1661                 var url = egCore.env.basePath +
1662                           'cat/item/' + cid + '/triggered_events';
1663                 $timeout(function() { $window.open(url, '_blank') });
1664             }
1665         );
1666     }
1667
1668     $scope.selectedHoldingsItemStatusHolds = function (){
1669         angular.forEach(
1670             gatherSelectedHoldingsIds(),
1671             function (cid) {
1672                 var url = egCore.env.basePath +
1673                           'cat/item/' + cid + '/holds';
1674                 $timeout(function() { $window.open(url, '_blank') });
1675             }
1676         );
1677     }
1678
1679     $scope.selectedHoldingsPrintLabels = function() {
1680         egCore.net.request(
1681             'open-ils.actor',
1682             'open-ils.actor.anon_cache.set_value',
1683             null, 'print-labels-these-copies', {
1684                 copies : gatherSelectedHoldingsIds()
1685             }
1686         ).then(function(key) {
1687             if (key) {
1688                 var url = egCore.env.basePath + 'cat/printlabels/' + key;
1689                 $timeout(function() { $window.open(url, '_blank') });
1690             } else {
1691                 alert('Could not create anonymous cache key!');
1692             }
1693         });
1694     }
1695
1696     $scope.selectedHoldingsDamaged = function () {
1697         var copy_list = gatherSelectedRawCopies();
1698         if (copy_list.length == 0) return;
1699
1700         angular.forEach(copy_list, function(cp) {
1701             egCirc.mark_damaged({
1702                 id: cp.id(),
1703                 barcode: cp.barcode(),
1704                 circ_lib: cp.circ_lib().id()
1705             }).then(function() {
1706                 holdingsSvcInst.fetchAgain().then(function() {
1707                     $scope.holdingsGridDataProvider.refresh();
1708                 });
1709             });
1710         });
1711     }
1712
1713     $scope.selectedHoldingsDiscard = function () {
1714         var copy_list = gatherSelectedRawCopies();
1715         if (copy_list.length == 0) return;
1716         egCirc.mark_discard(copy_list.map(function(cp) {
1717             return {id: cp.id(), barcode: cp.barcode()};})).then(function() {
1718                 holdingsSvcInst.fetchAgain().then(function() {
1719                     $scope.holdingsGridDataProvider.refresh();
1720                 });
1721             });
1722     }
1723
1724     $scope.selectedHoldingsMissing = function () {
1725         var copy_list = gatherSelectedRawCopies();
1726         if (copy_list.length == 0) return;
1727         egCirc.mark_missing(copy_list.map(function(cp) {
1728             return {id: cp.id(), barcode: cp.barcode()};})).then(function() {
1729                 holdingsSvcInst.fetchAgain().then(function() {
1730                     $scope.holdingsGridDataProvider.refresh();
1731                 });
1732             });
1733     }
1734
1735     $scope.selectedHoldingsCopyAlertsAdd = function() {
1736         egCirc.add_copy_alerts(gatherSelectedHoldingsIds()).then(function() {
1737             // no need to refresh grid
1738         });
1739     }
1740     $scope.selectedHoldingsCopyAlertsManage = function() {
1741         egCirc.manage_copy_alerts(gatherSelectedHoldingsIds()).then(function() {
1742             // no need to refresh grid
1743         });
1744     }
1745
1746     $scope.attach_to_peer_bib = function() {
1747         var copy_list = gatherSelectedHoldingsIds();
1748         if (copy_list.length == 0) return;
1749
1750         egCore.hatch.getItem('eg.cat.marked_conjoined_record').then(function(target_record) {
1751             if (!target_record) return;
1752
1753             return $uibModal.open({
1754                 templateUrl: './cat/catalog/t_conjoined_selector',
1755                 backdrop: 'static',
1756                 animation: true,
1757                 controller:
1758                        ['$scope','$uibModalInstance',
1759                 function($scope , $uibModalInstance) {
1760                     $scope.update = false;
1761
1762                     $scope.peer_type = null;
1763                     $scope.peer_type_list = [];
1764                     conjoinedSvc.get_peer_types().then(function(list){
1765                         $scope.peer_type_list = list;
1766                     });
1767     
1768                     $scope.ok = function(type) {
1769                         var promises = [];
1770     
1771                         angular.forEach(copy_list, function (cp) {
1772                             var n = new egCore.idl.bpbcm();
1773                             n.isnew(true);
1774                             n.peer_record(target_record);
1775                             n.target_copy(cp);
1776                             n.peer_type(type);
1777                             promises.push(egCore.pcrud.create(n));
1778                         });
1779     
1780                         return $q.all(promises).then(function(){$uibModalInstance.close()});
1781                     }
1782     
1783                     $scope.cancel = function($event) {
1784                         $uibModalInstance.dismiss();
1785                         $event.preventDefault();
1786                     }
1787                 }]
1788             });
1789         });
1790     }
1791
1792
1793     // ------------------------------------------------------------------
1794     // Holds 
1795     var provider = egGridDataProvider.instance({});
1796     var holds = []; // current list of holds
1797     var hold_count = 0;
1798     var hold_grid_load_promise;
1799
1800     $scope.hold_grid_data_provider = provider;
1801     $scope.grid_actions = egHoldGridActions;
1802     $scope.grid_actions.refresh = function () { holds = []; hold_count = 0; provider.refresh() };
1803     $scope.hold_grid_controls = {};
1804
1805     provider.get = function(offset, count) {
1806         if ($scope.record_tab != 'holds') return $q.when();
1807
1808         if (hold_grid_load_promise) {
1809             // Active load in progress.
1810             console.debug('Exiting concurrent hold fetch');
1811             return hold_grid_load_promise;
1812         }
1813
1814         // see if we have the requested range cached
1815         if (holds[offset]) {
1816             console.debug(
1817                 'Serving holds from cache with pickup lib', $scope.pickup_ou.id());
1818             return provider.arrayNotifier(holds, offset, count);
1819         }
1820
1821         hold_count = 0;
1822         holds = [];
1823         var restrictions = {
1824                 is_staff_request : 'true',
1825                 fulfillment_time : null,
1826                 cancel_time      : null,
1827                 record_id        : $scope.record_id,
1828                 pickup_lib       : egCore.org.descendants($scope.pickup_ou.id(), true)
1829         };
1830
1831         var order_by = [{ request_time : null }];
1832         // NOTE: Server sort is disabled for now.  See the comment on
1833         // similar code in circ/holds/app.js for details.
1834         if (false && provider.sort && provider.sort.length) {
1835             order_by = [];
1836             angular.forEach(provider.sort, function (c) {
1837                 if (!angular.isObject(c)) {
1838                     if (c.match(/^hold\./)) {
1839                         var i = c.replace('hold.','');
1840                         var ob = {};
1841                         ob[i] = null;
1842                         order_by.push(ob);
1843                     }
1844                 } else {
1845                     var i = Object.keys(c)[0];
1846                     var direction = c[i];
1847                     if (i.match(/^hold\./)) {
1848                         i = i.replace('hold.','');
1849                         var ob = {}
1850                         ob[i] = {dir:direction};
1851                         order_by.push(ob);
1852                     }
1853                 }
1854             });
1855         }
1856
1857         console.debug(
1858             'Fetching holds from network with PU lib', $scope.pickup_ou.id());
1859
1860         egProgressDialog.open({max : 1, value : 0});
1861         var first = true;
1862         hold_grid_load_promise = egHolds.fetch_wide_holds(
1863             restrictions,
1864             order_by
1865         ).then(function () {
1866                 hold_grid_load_promise = null;
1867                 return provider.arrayNotifier(holds, offset, count);
1868             },
1869             null,
1870             function(hold_data) {
1871                 if (first) {
1872                     hold_count = hold_data;
1873                     first = false;
1874                     egProgressDialog.update({max:hold_count});
1875                 } else {
1876                     egProgressDialog.increment();
1877                     var new_item = { id : hold_data.id, hold : hold_data };
1878                     new_item.status_string =
1879                         egCore.strings['HOLD_STATUS_' + hold_data.hold_status]
1880                         || hold_data.hold_status;
1881
1882                     holds.push(new_item);
1883                 }
1884             }
1885         ).finally(function() {
1886             hold_grid_load_promise = null;
1887             egProgressDialog.close();
1888         });
1889
1890         return hold_grid_load_promise;
1891     }
1892
1893     $scope.detail_view = function(action, user_data, items) {
1894         if (h = items[0]) {
1895             $scope.detail_hold_id = h.hold.id;
1896         }
1897     }
1898
1899     $scope.list_view = function(items) {
1900          $scope.detail_hold_id = null;
1901     }
1902
1903     // refresh the list of record holds when the pickup lib is changed.
1904     $scope.pickup_ou = egCore.org.get(egCore.auth.user().ws_ou());
1905     $scope.pickup_ou_changed = function(org) {
1906         if ($scope.pickup_ou && $scope.pickup_ou.id() == org.id()) {
1907             // This fires on every component render, even though the
1908             // value we already have may match.  Avoid duplicate lookups.
1909             return;
1910         }
1911
1912         var promise = hold_grid_load_promise || $q.when();
1913
1914         // Avoid refreshing the grid if it's currently loading data.
1915         promise.finally(function() {
1916
1917             // Previous grid data load complete.  Timeout gives the
1918             // grid a chance to mark itself as load-completed, which
1919             // happens after the data load promise is done.
1920             setTimeout(function() {
1921                 console.debug('Refreshing holds after PU lib change to ', org.id());
1922                 $scope.pickup_ou = org;
1923                 holds = []
1924                 hold_count = 0;
1925                 provider.refresh();
1926             });
1927         })
1928     }
1929
1930     function map_prefix_to_subhash (h,pf) {
1931         var newhash = {};
1932         angular.forEach(Object.keys(h), function (k) {
1933             if (k.startsWith(pf)) {
1934                 var nk = k.substr(pf.length);
1935                 newhash[nk] = h[k];
1936             }
1937         });
1938         return newhash;
1939     }
1940
1941     $scope.print_holds = function() {
1942         var pholds = [];
1943         angular.forEach(holds, function(item) {
1944             pholds.push({
1945                 hold : item.hold,
1946                 status_string : item.status_string,
1947                 patron_first : item.hold.usr_first_given_name,
1948                 patron_last : item.hold.usr_family_name,
1949                 patron_alias : item.hold.usr_alias,
1950                 patron_barcode : item.hold.ucard_barcode,
1951                 copy : map_prefix_to_subhash(item.hold,'cp_'),
1952                 volume : map_prefix_to_subhash(item.hold,'cn_'),
1953                 title : item.hold.title,
1954                 author : item.hold.author
1955             });
1956         });
1957
1958         egCore.print.print({
1959             context : 'receipt', 
1960             template : 'holds_for_bib', 
1961             scope : {holds : pholds}
1962         });
1963     }
1964
1965     $scope.current_hold_transfer_dest = egCore.hatch.getLocalItem ('eg.circ.hold.title_transfer_target');
1966
1967     $scope.mark_hold_transfer_dest = function() {
1968         $scope.current_hold_transfer_dest = $scope.record_id;
1969         egCore.hatch.setLocalItem(
1970             'eg.circ.hold.title_transfer_target', $scope.record_id);
1971         ngToast.create(egCore.strings.HOLD_TRANSFER_DEST_MARKED);
1972     }
1973
1974     // UI presents this option as "all holds"
1975     $scope.transfer_holds_to_marked = function() {
1976         var hold_ids = $scope.hold_grid_controls.allItems().map(
1977             function(hold_data) {return hold_data.hold.id});
1978         egHolds.transfer_to_marked_title(hold_ids);
1979     }
1980
1981     // ------------------------------------------------------------------
1982     // Initialize the selected tab
1983
1984     // we explicitly initialize catalog_url because otherwise Firefox
1985     // ends up setting it to $BASE_URL/{{url}}, which then messes
1986     // things up. See LP#1708951
1987     $scope.catalog_url = '';
1988
1989     function init_cat_url() {
1990         // Set the initial catalog URL.  This only happens once.
1991         // The URL is otherwise generated through user navigation.
1992         if ($scope.catalog_url) return;
1993
1994         var url = $location.absUrl().replace(/\/staff.*/, '/opac/advanced');
1995
1996         // A record ID in the path indicates a request for the record-
1997         // specific page.
1998         if ($routeParams.record_id) {
1999             url = url.replace(/\/advanced/, '/record/' + $scope.record_id);
2000         }
2001
2002         // Jumping directly to the results page by passing a search
2003         // query via the URL.  Copy all URL params to the iframe url.
2004         if ($location.path().match(/catalog\/results/)) {
2005             url = url.replace(/\/advanced/, '/results?');
2006             var first = true;
2007             angular.forEach($location.search(), function(val, key) {
2008                 if (!first) url += '&';
2009                 first = false;
2010                 url += encodeURIComponent(key) 
2011                     + '=' + encodeURIComponent(val);
2012             });
2013         }
2014
2015         // if we're displaying the advanced search form, select
2016         // whatever default pane the user has chosen via workstation
2017         // preference
2018         if (url.match(/\/opac\/advanced$/)) {
2019             egCore.hatch.getItem('eg.search.adv_pane').then(function(adv_pane_val){
2020                 if (adv_pane_val) {
2021                     url += '?pane=' + encodeURIComponent(adv_pane_val);
2022                 }
2023
2024                 $scope.catalog_url = url;
2025             });
2026         } else {
2027             $scope.catalog_url = url;
2028         }
2029
2030     }
2031
2032     function init_parts_url() {
2033         $scope.parts_url = $location
2034             .absUrl()
2035             .replace(
2036                 /\/staff.*/,
2037                 '/conify/global/biblio/monograph_part?r='+$scope.record_id
2038             );
2039     }
2040
2041     $scope.set_record_tab = function(tab) {
2042         $scope.record_tab = tab;
2043
2044         switch(tab) {
2045
2046             case 'monoparts':
2047                 init_parts_url();
2048                 break;
2049
2050             case 'catalog':
2051                 init_cat_url();
2052                 break;
2053
2054             case 'holds':
2055                 $scope.detail_hold_record_id = $scope.record_id; 
2056                 // refresh the holds grid
2057                 provider.refresh();
2058
2059                 break;
2060         }
2061     }
2062
2063     $scope.set_default_record_tab = function() {
2064         egCore.hatch.setLocalItem(
2065             'eg.cat.default_record_tab', $scope.record_tab);
2066         $timeout(function(){$scope.default_tab = $scope.record_tab});
2067     }
2068
2069     var tab;
2070     if ($scope.record_id) {
2071         $scope.default_tab = get_default_record_tab();
2072         tab = $routeParams.record_tab || $scope.default_tab;
2073
2074     } else {
2075         tab = $routeParams.record_tab || 'catalog';
2076     }
2077     $scope.set_record_tab(tab);
2078
2079 }])
2080
2081 .controller('AuthorityCtrl',
2082        ['$scope','$routeParams','$location','$window','$q','egCore',
2083 function($scope , $routeParams , $location , $window , $q , egCore) {
2084
2085     // set record ID on page load if available...
2086     $scope.authority_id = $routeParams.authority_id;
2087
2088     if ($routeParams.authority_id) $scope.from_route = true;
2089     else $scope.from_route = false;
2090
2091     $scope.stop_unload = false;
2092 }])
2093
2094 .controller('URLVerifyCtrl',
2095        ['$scope','$location',
2096 function($scope , $location) {
2097     $scope.verifyurls_url = $location.absUrl().replace(/\/staff.*/, '/url_verify/sessions');
2098 }])
2099
2100 .controller('VandelayCtrl',
2101        ['$scope','$location', 'egCore', '$uibModal',
2102 function($scope , $location, egCore, $uibModal) {
2103     $scope.vandelay_url = $location.absUrl().replace(/\/staff\/cat\/catalog\/vandelay/, '/vandelay/vandelay');
2104     $scope.funcs = {};
2105     $scope.funcs.edit_marc_modal = function(bre, callback){
2106         var marcArgs = { 'marc_xml': bre.marc() };
2107         var vqbibrecId = bre.id();
2108         $uibModal.open({
2109             templateUrl: './cat/catalog/t_edit_marc_modal',
2110             backdrop: 'static',
2111             size: 'lg',
2112             controller: ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
2113                 $scope.focusMe = true;
2114                 $scope.recordId = vqbibrecId;
2115                 $scope.args = marcArgs;
2116                 $scope.dirty_flag = false;
2117                 $scope.ok = function(marg){
2118                     $uibModalInstance.close(marg);
2119                 };
2120                 $scope.cancel = function(){ $uibModalInstance.dismiss() }
2121             }]
2122         }).result.then(function(res){
2123             var new_xml = res.marc_xml;
2124             egCore.pcrud.retrieve('vqbr', vqbibrecId).then(function(vqbib){
2125                 vqbib.marc(new_xml);
2126                 egCore.pcrud.update(vqbib).then( function(){ callback(vqbibrecId); });
2127             });
2128         });
2129     };
2130 }])
2131
2132 .controller('ManageAuthoritiesCtrl',
2133        ['$scope','$location',
2134 function($scope , $location) {
2135     $scope.manageauthorities_url = $location.absUrl().replace(/\/staff.*/, '/cat/authority/list');
2136 }])
2137
2138 .controller('BatchEditCtrl',
2139        ['$scope','$location','$routeParams',
2140 function($scope , $location , $routeParams) {
2141     $scope.batchedit_url = $location.absUrl().replace(/\/eg.*/, '/opac/extras/merge_template');
2142     if ($routeParams.container_type) {
2143         switch ($routeParams.container_type) {
2144             case 'bucket':
2145                 $scope.batchedit_url += '?recordSource=b&containerid=' + $routeParams.container_id;
2146                 break;
2147             case 'record':
2148                 $scope.batchedit_url += '?recordSource=r&recid=' + $routeParams.container_id;
2149                 break;
2150         };
2151     }
2152 }])
2153
2154  
2155 .filter('boolText', function(){
2156     return function (v) {
2157         return v == 't';
2158     }
2159 })
2160
2161 .factory('conjoinedSvc', 
2162        ['egCore','$q',
2163 function(egCore , $q) {
2164
2165     var service = {
2166         items : [], // record search results
2167         index : 0, // search grid index
2168         rid : null
2169     };
2170
2171     service.flesh = {   
2172         flesh : 4, 
2173         flesh_fields : {
2174             bpbcm : ['target_copy','peer_type'],
2175             acp : ['call_number'],
2176             acn : ['record'],
2177             bre : ['simple_record']
2178         },
2179         // avoid fetching the MARC blob by specifying which
2180         // fields on the bre to select.  More may be needed.
2181         // note that fleshed fields are explicitly selected.
2182         select : { bre : ['id'] },
2183         order_by : { bpbcm : ['id'] },
2184     }
2185
2186     // resolved with the last received copy
2187     service.fetch = function(rid) {
2188         if (!rid && !service.rid) return $q.when();
2189
2190         if (rid) service.rid = rid;
2191         service.items = [];
2192         service.index = 0;
2193
2194         return egCore.pcrud.search(
2195             'bpbcm',
2196             {peer_record : service.rid},
2197             service.flesh,
2198             {atomic : true}
2199         ).then( function(list) { // finished
2200             service.items = list;
2201             return service.items;
2202         });
2203     }
2204
2205     // returns a promise resolved with the list of peer bib types
2206     service.get_peer_types = function() {
2207         if (egCore.env.bpt)
2208             return $q.when(egCore.env.bpt.list);
2209
2210         return egCore.pcrud.retrieveAll('bpt', null, {atomic : true})
2211         .then(function(list) {
2212             egCore.env.absorbList(list, 'bpt');
2213             return list;
2214         });
2215     };
2216
2217     return service;
2218 }])
2219
2220