f05c363295639347a3b7666add8b4c4b4e50ac52
[working/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     // also set it when the iframe changes to a new record
634     $scope.handle_page = function(url) {
635
636         if (!url || url == 'about:blank') {
637             // nothing loaded.  If we already have a record ID, leave it.
638             return;
639         }
640
641         var prev_record_id = $scope.record_id;
642         var match = url.match(/\/+opac\/+record\/+(\d+)/);
643         if (match) {
644             $scope.record_id = match[1];
645             egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
646             $scope.holdings_record_id_changed($scope.record_id);
647             conjoinedSvc.fetch($scope.record_id).then(function(){
648                 $scope.conjoinedGridDataProvider.refresh();
649             });
650             init_parts_url();
651             $scope.grid_actions.refresh();
652             $location.update_path('/cat/catalog/record/' + $scope.record_id);
653             // update_path() bypasses the controller for path 
654             // /cat/catalog/record/:record_id. Manually set title here too.
655             egCore.strings.setPageTitle(
656                 egCore.strings.PAGE_TITLE_BIB_DETAIL,
657                 egCore.strings.PAGE_TITLE_CATALOG_CONTEXT,
658                 {record_id : $scope.record_id}
659             );
660         } else {
661             delete $scope.record_id;
662             $scope.from_route = false;
663         }
664
665         // child scope is executing this function, so our digest doesn't fire ... thus,
666         $scope.$apply();
667
668         // don't change tabs if we are using the OPAC nav buttons,
669         // or we didn't change records on the OPAC load
670         if (!$scope.in_opac_call && ($scope.record_id != prev_record_id)) {
671             if ($scope.record_id) {
672                 $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
673                 tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
674             } else {
675                 tab = $routeParams.record_tab || 'catalog';
676             }
677             $scope.set_record_tab(tab);
678         } else {
679             $scope.in_opac_call = false;
680         }
681
682         if ($scope.opac_iframe && $location.path().match(/cat\/catalog/)) {
683             var doc = $scope.opac_iframe.dom.contentWindow.document;
684             $(doc).find('#hold_usr_search').show();
685             $(doc).find('#hold_usr_search').on('click', function() {
686                 patron_search_dialog().result.then(function(barc) {
687                     $(doc).find('#hold_usr_input').val(barc);
688                     $(doc).find('#hold_usr_input').trigger($.Event('keydown', {which: 13}));
689                 });
690             });
691             $(doc).find('#select_basket_action').on('change', function() {
692                 if (this.options[this.selectedIndex].value && this.options[this.selectedIndex].value == "add_cart_to_bucket") {
693                     $scope.add_cart_to_record_bucket();
694                 }
695             });
696         }
697
698     }
699
700     // xulG catalog handlers
701     $scope.handlers = { }
702
703     // ------------------------------------------------------------------
704     // Conjoined items
705
706     $scope.conjoinedGridControls = {};
707     $scope.conjoinedGridDataProvider = egGridDataProvider.instance({
708         get : function(offset, count) {
709             return this.arrayNotifier(conjoinedSvc.items, offset, count);
710         }
711     });
712
713     $scope.changeConjoinedType = function () {
714         var peers = egCore.idl.Clone($scope.conjoinedGridControls.selectedItems());
715         angular.forEach(peers, function (p) {
716             p.target_copy(p.target_copy().id());
717             p.peer_type(p.peer_type().id());
718         });
719
720         var conjoinedGridDataProviderRef = $scope.conjoinedGridDataProvider;
721
722         return $uibModal.open({
723             templateUrl: './cat/catalog/t_conjoined_selector',
724             backdrop: 'static',
725             animation: true,
726             controller:
727                    ['$scope','$uibModalInstance',
728             function($scope , $uibModalInstance) {
729                 $scope.update = true;
730
731                 $scope.peer_type = null;
732                 $scope.peer_type_list = [];
733                 conjoinedSvc.get_peer_types().then(function(list){
734                     $scope.peer_type_list = list;
735                 });
736     
737                 $scope.ok = function(type) {
738                     var promises = [];
739     
740                     angular.forEach(peers, function (p) {
741                         p.ischanged(1);
742                         p.peer_type(type);
743                         promises.push(egCore.pcrud.update(p));
744                     });
745     
746                     return $q.all(promises)
747                         .then(function(){$uibModalInstance.close()})
748                         .then(function(){return conjoinedSvc.fetch()})
749                         .then(function(){conjoinedGridDataProviderRef.refresh()});
750                 }
751     
752                 $scope.cancel = function($event) {
753                     $uibModalInstance.dismiss();
754                     $event.preventDefault();
755                 }
756             }]
757         });
758         
759     }
760
761     $scope.refreshConjoined = function () {
762         conjoinedSvc.fetch($scope.record_id)
763         .then(function(){$scope.conjoinedGridDataProvider.refresh();});
764     }
765
766     $scope.deleteSelectedConjoined = function () {
767         var peers = $scope.conjoinedGridControls.selectedItems();
768
769         if (peers.length > 0) {
770             egConfirmDialog.open(
771                 egCore.strings.CONFIRM_DELETE_PEERS,
772                 egCore.strings.CONFIRM_DELETE_PEERS_MESSAGE,
773                 {peers : peers.length}
774             ).result.then(function() {
775                 angular.forEach(peers, function (p) {
776                     p.isdeleted(1);
777                 });
778
779                 egCore.pcrud.remove(peers).then(function() {
780                     return conjoinedSvc.fetch();
781                 }).then(function() {
782                     $scope.conjoinedGridDataProvider.refresh();
783                 });
784             });
785         }
786     }
787     if ($scope.record_id)
788         conjoinedSvc.fetch($scope.record_id);
789
790     // ------------------------------------------------------------------
791     // Holdings
792
793     $scope.holdingsGridControls = {
794         activateItem : function (item) {
795             $scope.selectedHoldingsVolCopyEdit();
796         }
797     };
798     $scope.holdingsGridDataProvider = egGridDataProvider.instance({
799         get : function(offset, count) {
800             return this.arrayNotifier(holdingsSvcInst.copies, offset, count);
801         }
802     });
803
804     $scope.add_copies_to_bucket = function() {
805         var copy_list = gatherSelectedHoldingsIds();
806         if (copy_list.length == 0) return;
807
808         return $uibModal.open({
809             templateUrl: './cat/catalog/t_add_to_bucket',
810             backdrop: 'static',
811             animation: true,
812             size: 'md',
813             controller:
814                    ['$scope','$uibModalInstance',
815             function($scope , $uibModalInstance) {
816
817                 $scope.bucket_id = 0;
818                 $scope.newBucketName = '';
819                 $scope.allBuckets = [];
820
821                 egCore.net.request(
822                     'open-ils.actor',
823                     'open-ils.actor.container.retrieve_by_class.authoritative',
824                     egCore.auth.token(), egCore.auth.user().id(),
825                     'copy', 'staff_client'
826                 ).then(function(buckets) { $scope.allBuckets = buckets; });
827
828                 $scope.add_to_bucket = function() {
829                     var promises = [];
830                     angular.forEach(copy_list, function (cp) {
831                         var item = new egCore.idl.ccbi()
832                         item.bucket($scope.bucket_id);
833                         item.target_copy(cp);
834                         promises.push(
835                             egCore.net.request(
836                                 'open-ils.actor',
837                                 'open-ils.actor.container.item.create',
838                                 egCore.auth.token(), 'copy', item
839                             )
840                         );
841
842                         return $q.all(promises).then(function() {
843                             $uibModalInstance.close();
844                         });
845                     });
846                 }
847
848                 $scope.add_to_new_bucket = function() {
849                     var bucket = new egCore.idl.ccb();
850                     bucket.owner(egCore.auth.user().id());
851                     bucket.name($scope.newBucketName);
852                     bucket.description('');
853                     bucket.btype('staff_client');
854
855                     return egCore.net.request(
856                         'open-ils.actor',
857                         'open-ils.actor.container.create',
858                         egCore.auth.token(), 'copy', bucket
859                     ).then(function(bucket) {
860                         $scope.bucket_id = bucket;
861                         $scope.add_to_bucket();
862                     });
863                 }
864
865                 $scope.cancel = function() {
866                     $uibModalInstance.dismiss();
867                 }
868             }]
869         });
870     }
871
872     // TODO: refactor common code between cat/catalog/app.js and cat/item/app.js 
873
874     $scope.need_one_selected = function() {
875         var items = $scope.holdingsGridControls.selectedItems();
876         if (items.length == 1) return false;
877         return true;
878     };
879
880     $scope.make_copies_bookable = function() {
881
882         var copies_by_record = {};
883         var record_list = [];
884         angular.forEach(
885             $scope.holdingsGridControls.selectedItems(),
886             function (item) {
887                 var record_id = item['call_number.record.id'];
888                 if (typeof copies_by_record[ record_id ] == 'undefined') {
889                     copies_by_record[ record_id ] = [];
890                     record_list.push( record_id );
891                 }
892                 copies_by_record[ record_id ].push(item.id);
893             }
894         );
895
896         var promises = [];
897         var combined_results = [];
898         angular.forEach(record_list, function(record_id) {
899             promises.push(
900                 egCore.net.request(
901                     'open-ils.booking',
902                     'open-ils.booking.resources.create_from_copies',
903                     egCore.auth.token(),
904                     copies_by_record[record_id]
905                 ).then(function(results) {
906                     if (results && results['brsrc']) {
907                         combined_results = combined_results.concat(results['brsrc']);
908                     }
909                 })
910             );
911         });
912
913         $q.all(promises).then(function() {
914             if (combined_results.length > 0) {
915                 $uibModal.open({
916                     template: '<eg-embed-frame url="booking_admin_url" handlers="funcs"></eg-embed-frame>',
917                     backdrop: 'static',
918                     animation: true,
919                     size: 'md',
920                     controller:
921                            ['$scope','$location','egCore','$uibModalInstance',
922                     function($scope , $location , egCore , $uibModalInstance) {
923
924                         $scope.funcs = {
925                             ses : egCore.auth.token(),
926                             resultant_brsrc : combined_results.map(function(o) { return o[0]; })
927                         }
928
929                         var booking_path = '/eg/conify/global/booking/resource';
930
931                         $scope.booking_admin_url =
932                             $location.absUrl().replace(/\/eg\/staff.*/, booking_path);
933                     }]
934                 });
935             }
936         });
937     }
938
939     $scope.book_copies_now = function(items) {
940         location.href = "/eg2/staff/booking/create_reservation/for_resource/" + items[0]['barcode'];
941     }
942
943     $scope.requestItems = function() {
944         var copy_list = gatherSelectedHoldingsIds();
945         if (copy_list.length == 0) return;
946
947         return $uibModal.open({
948             templateUrl: './cat/catalog/t_request_items',
949             animation: true,
950             controller:
951                    ['$scope','$uibModalInstance',
952             function($scope , $uibModalInstance) {
953                 $scope.user = null;
954                 $scope.first_user_fetch = true;
955
956                 $scope.hold_data = {
957                     hold_type : 'C',
958                     copy_list : copy_list,
959                     pickup_lib: egCore.org.get(egCore.auth.user().ws_ou()),
960                     user      : egCore.auth.user().id()
961                 };
962
963                 egUser.get( $scope.hold_data.user ).then(function(u) {
964                     $scope.user = u;
965                     $scope.barcode = u.card().barcode();
966                     $scope.user_name = egUser.format_name(u);
967                     $scope.hold_data.user = u.id();
968                 });
969
970                 $scope.user_name = '';
971                 $scope.barcode = '';
972                 $scope.$watch('barcode', function (n) {
973                     if (!$scope.first_user_fetch) {
974                         egUser.getByBarcode(n).then(function(u) {
975                             $scope.user = u;
976                             $scope.user_name = egUser.format_name(u);
977                             $scope.hold_data.user = u.id();
978                         }, function() {
979                             $scope.user = null;
980                             $scope.user_name = '';
981                             delete $scope.hold_data.user;
982                         });
983                     }
984                     $scope.first_user_fetch = false;
985                 });
986
987                 $scope.ok = function(h) {
988                     var args = {
989                         patronid  : h.user,
990                         hold_type : h.hold_type,
991                         pickup_lib: h.pickup_lib.id(),
992                         depth     : 0
993                     };
994
995                     egCore.net.request(
996                         'open-ils.circ',
997                         'open-ils.circ.holds.test_and_create.batch.override',
998                         egCore.auth.token(), args, h.copy_list
999                     );
1000
1001                     $uibModalInstance.close();
1002                 }
1003
1004                 $scope.cancel = function($event) {
1005                     $uibModalInstance.dismiss();
1006                     $event.preventDefault();
1007                 }
1008             }]
1009         });
1010     }
1011
1012     $scope.manage_reservations = function() {
1013         var item = $scope.holdingsGridControls.selectedItems()[0];
1014         if (item)
1015             location.href = "/eg2/staff/booking/manage_reservations/by_resource/" + item.barcode;
1016     }
1017
1018
1019     $scope.view_place_orders = function() {
1020         if (!$scope.record_id) return;
1021         var url = egCore.env.basePath + 'acq/legacy/lineitem/related/' + $scope.record_id + '?target=bib';
1022         $timeout(function() { $window.open(url, '_blank') });
1023     }
1024
1025     $scope.replaceBarcodes = function() {
1026         var copy_list = gatherSelectedRawCopies();
1027         if (copy_list.length == 0) return;
1028
1029         var holdingsGridDataProviderRef = $scope.holdingsGridDataProvider;
1030
1031         angular.forEach(copy_list, function (cp) {
1032             $uibModal.open({
1033                 templateUrl: './cat/share/t_replace_barcode',
1034                 backdrop: 'static',
1035                 animation: true,
1036                 controller:
1037                            ['$scope','$uibModalInstance',
1038                     function($scope , $uibModalInstance) {
1039                         $scope.isModal = true;
1040                         $scope.focusBarcode = false;
1041                         $scope.focusBarcode2 = true;
1042                         $scope.barcode1 = cp.barcode();
1043
1044                         $scope.updateBarcode = function() {
1045                             $scope.copyNotFound = false;
1046                             $scope.updateOK = false;
1047                 
1048                             egCore.pcrud.search('acp',
1049                                 {deleted : 'f', barcode : $scope.barcode1})
1050                             .then(function(copy) {
1051                 
1052                                 if (!copy) {
1053                                     $scope.focusBarcode = true;
1054                                     $scope.copyNotFound = true;
1055                                     return;
1056                                 }
1057                 
1058                                 $scope.copyId = copy.id();
1059                                 copy.barcode($scope.barcode2);
1060                 
1061                                 egCore.pcrud.update(copy).then(function(stat) {
1062                                     $scope.updateOK = stat;
1063                                     $scope.focusBarcode = true;
1064                                     holdingsSvc.fetchAgain().then(function (){
1065                                         holdingsGridDataProviderRef.refresh();
1066                                     });
1067                                 });
1068
1069                             });
1070                             $uibModalInstance.close();
1071                         }
1072
1073                         $scope.cancel = function($event) {
1074                             $uibModalInstance.dismiss();
1075                             $event.preventDefault();
1076                         }
1077                     }
1078                 ]
1079             });
1080         });
1081     }
1082
1083     var holdings_bChannel = null;
1084     // subscribe to BroadcastChannel for any child VolCopy tabs
1085     // refresh grid if needed to show new updates
1086     // if ($scope.record_tab === 'holdings'){
1087     $scope.$watch('record_tab', function(n){
1088     
1089         if (n === 'holdings'){
1090             if (typeof BroadcastChannel != 'undefined') {
1091                 // we're in holdings tab, connect 2 bChannel
1092                 holdings_bChannel = new BroadcastChannel('eg.holdings.update');
1093                 holdings_bChannel.onmessage = function(e){
1094                     if (e.data
1095                         && e.data.records
1096                         && e.data.records.length
1097                         && e.data.records.includes(Number($scope.record_id))
1098                     ){ // it's for us, refresh grid!
1099                         console.log("Got broadcast from channel eg.holdings.update for records " + e.data.records);
1100                         $scope.holdings_record_id_changed($scope.record_id);
1101                     }
1102                 }
1103             };
1104
1105         } else if (holdings_bChannel){ // we're leaving holding tab, close bChannel
1106             holdings_bChannel.close();
1107         }
1108     
1109     });
1110
1111     // refresh the list of holdings when the record_id is changed.
1112     $scope.holdings_record_id_changed = function(id) {
1113         if ($scope.record_id != id) $scope.record_id = id;
1114         console.log('record id changed to ' + id + ', loading new holdings');
1115         holdingsSvcInst.fetch({
1116             rid : $scope.record_id,
1117             org : $scope.holdings_ou,
1118             copy: $scope.holdings_show_vols ? $scope.holdings_show_copies : false,
1119             vol : $scope.holdings_show_vols,
1120             empty: $scope.holdings_show_empty,
1121             empty_org: $scope.holdings_show_empty_org
1122         }).then(function() {
1123             $scope.holdingsGridDataProvider.refresh();
1124         });
1125     }
1126
1127     // refresh the list of holdings when the filter lib is changed.
1128     $scope.holdings_ou = egCore.org.get(egCore.auth.user().ws_ou());
1129     $scope.holdings_ou_changed = function(org) {
1130         $scope.holdings_ou = org;
1131         holdingsSvcInst.fetch({
1132             rid : $scope.record_id,
1133             org : $scope.holdings_ou,
1134             copy: $scope.holdings_show_vols ? $scope.holdings_show_copies : false,
1135             vol : $scope.holdings_show_vols,
1136             empty: $scope.holdings_show_empty,
1137             empty_org: $scope.holdings_show_empty_org
1138         }).then(function() {
1139             $scope.holdingsGridDataProvider.refresh();
1140         });
1141     }
1142
1143     $scope.holdings_cb_changed = function(cb,newVal,norefresh) {
1144         $scope[cb] = newVal;
1145         var x = $scope.holdings_show_vols ? $scope.holdings_show_copies : false;
1146         $('#holdings_show_copies').prop('checked', x);
1147         egCore.hatch.setItem('cat.' + cb, newVal);
1148         if (!norefresh) holdingsSvcInst.fetch({
1149             rid : $scope.record_id,
1150             org : $scope.holdings_ou,
1151             copy: $scope.holdings_show_vols ? $scope.holdings_show_copies : false,
1152             vol : $scope.holdings_show_vols,
1153             empty: $scope.holdings_show_empty,
1154             empty_org: $scope.holdings_show_empty_org
1155         }).then(function() {
1156             $scope.holdingsGridDataProvider.refresh();
1157         });
1158     }
1159
1160     egCore.hatch.getItem('cat.holdings_show_vols').then(function(x){
1161         if (typeof x ==  'undefined') x = true;
1162         $scope.holdings_cb_changed('holdings_show_vols',x,true);
1163         $('#holdings_show_vols').prop('checked', x);
1164     }).then(function(){
1165         egCore.hatch.getItem('cat.holdings_show_copies').then(function(x){
1166             if (typeof x ==  'undefined') x = true;
1167             $scope.holdings_cb_changed('holdings_show_copies',x,true);
1168             x = $scope.holdings_show_vols ? x : false;
1169             $('#holdings_show_copies').prop('checked', x);
1170         }).then(function(){
1171             egCore.hatch.getItem('cat.holdings_show_empty').then(function(x){
1172                 if (typeof x ==  'undefined') x = true;
1173                 $scope.holdings_cb_changed('holdings_show_empty',x);
1174                 $('#holdings_show_empty').prop('checked', x);
1175             }).then(function(){
1176                 egCore.hatch.getItem('cat.holdings_show_empty_org').then(function(x){
1177                     if (typeof x ==  'undefined') x = true;
1178                     $scope.holdings_cb_changed('holdings_show_empty_org',x);
1179                     $('#holdings_show_empty_org').prop('checked', x);
1180                 })
1181             })
1182         })
1183     });
1184
1185     $scope.vols_not_shown = function () {
1186         return !$scope.holdings_show_vols;
1187     }
1188
1189     $scope.copies_not_shown = function () {
1190         return !$scope.holdings_show_copies;
1191     }
1192
1193     $scope.empty_org_not_shown = function () {
1194         return !$scope.holdings_show_empty_org;
1195     }
1196
1197     $scope.holdings_checkbox_handler = function (item) {
1198         $scope.holdings_cb_changed(item.checkbox,item.checked);
1199     }
1200
1201     function gatherSelectedHoldingsIds () {
1202         var cp_id_list = [];
1203         angular.forEach(
1204             $scope.holdingsGridControls.selectedItems(),
1205             function (item) { cp_id_list = cp_id_list.concat(item.id_list) }
1206         );
1207         return cp_id_list;
1208     }
1209
1210     function gatherSelectedRawCopies () {
1211         var cp_list = [];
1212         angular.forEach(
1213             $scope.holdingsGridControls.selectedItems(),
1214             function (item) { if (item.raw) cp_list = cp_list.concat(item.raw) }
1215         );
1216         return cp_list;
1217     }
1218
1219     function gatherSelectedEmptyVolumeIds () {
1220         var cn_id_list = [];
1221         angular.forEach(
1222             $scope.holdingsGridControls.selectedItems(),
1223             function (item) {
1224                 if (item.copy_count == 0 || (!item.id && item.call_number))
1225                     // we are in a compressed row with no copies, or we are in a single
1226                     // call number row with no copy (testing for presence of 'id')
1227                     // In either case, the call number is 'empty'
1228                     cn_id_list.push(item.call_number.id)
1229             }
1230         );
1231         return cn_id_list;
1232     }
1233
1234     function gatherSelectedVolumeIds () {
1235         var cn_id_list = [];
1236         angular.forEach(
1237             $scope.holdingsGridControls.selectedItems(),
1238             function (item) {
1239                 if (cn_id_list.indexOf(item.call_number.id) == -1)
1240                     cn_id_list.push(item.call_number.id)
1241             }
1242         );
1243         return cn_id_list;
1244     }
1245
1246     $scope.selectedHoldingsDelete = function (vols, copies) {
1247
1248         var cnHash = {};
1249         var perCnCopies = {};
1250
1251         var cn_count = 0;
1252         var cp_count = 0;
1253
1254         angular.forEach(
1255             $scope.holdingsGridControls.selectedItems(),
1256             function (item) {
1257                 if (vols && item.raw_call_number) {
1258                     cnHash[item.call_number.id] = egCore.idl.Clone(item.raw_call_number);
1259                     cnHash[item.call_number.id].isdeleted(1);
1260                     cn_count++;
1261                 } else if (copies) {
1262                     angular.forEach(egCore.idl.Clone(item.raw), function (cp) {
1263                         cp.isdeleted(1);
1264                         cp_count++;
1265                         var cn_id = cp.call_number().id();
1266                         if (!cnHash[cn_id]) {
1267                             cnHash[cn_id] = cp.call_number();
1268                             perCnCopies[cn_id] = [cp];
1269                         } else {
1270                             perCnCopies[cn_id].push(cp);
1271                         }
1272                         cp.call_number(cn_id); // prevent loops in JSON-ification
1273                     });
1274
1275                 }
1276             }
1277         );
1278
1279         angular.forEach(perCnCopies, function (v, k) {
1280             if (vols) {
1281                 cnHash[k].isdeleted(1);
1282                 cn_count++;
1283             }
1284             cnHash[k].copies(v);
1285         });
1286
1287         cnList = [];
1288         angular.forEach(cnHash, function (v, k) {
1289             cnList.push(v);
1290         });
1291
1292         if (cnList.length == 0) return;
1293
1294         var flags = {};
1295         if (vols && copies) flags.force_delete_copies = 1;
1296
1297         egConfirmDialog.open(
1298             egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES,
1299             egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES_MESSAGE,
1300             {copies : cp_count, volumes : cn_count}
1301         ).result.then(function() {
1302             egCore.net.request(
1303                 'open-ils.cat',
1304                 'open-ils.cat.asset.volume.fleshed.batch.update',
1305                 egCore.auth.token(), cnList, 1, flags
1306             ).then(function(resp) {
1307                 var evt = egCore.evt.parse(resp);
1308                 if (evt) {
1309                     egConfirmDialog.open(
1310                         egCore.strings.OVERRIDE_DELETE_ITEMS_FROM_CATALOG_TITLE,
1311                         egCore.strings.OVERRIDE_DELETE_ITEMS_FROM_CATALOG_BODY,
1312                         {'evt_desc': evt.desc}
1313                     ).result.then(function() {
1314                         egCore.net.request(
1315                             'open-ils.cat',
1316                             'open-ils.cat.asset.volume.fleshed.batch.update.override',
1317                             egCore.auth.token(), cnList, 1,
1318                             { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
1319                         ).then(function() {
1320                             holdingsSvcInst.fetchAgain().then(function() {
1321                                 $scope.holdingsGridDataProvider.refresh();
1322                             });
1323                         });
1324                     });
1325                 } else {
1326                     holdingsSvcInst.fetchAgain().then(function() {
1327                         $scope.holdingsGridDataProvider.refresh();
1328                     });
1329                 }
1330             });
1331         });
1332     }
1333     $scope.selectedHoldingsCopyDelete = function () { $scope.selectedHoldingsDelete(false,true) }
1334     $scope.selectedHoldingsVolCopyDelete = function () { $scope.selectedHoldingsDelete(true,true) }
1335     $scope.selectedHoldingsEmptyVolCopyDelete = function () { $scope.selectedHoldingsDelete(true,false) }
1336
1337     spawnHoldingsAdd = function (add_vols,add_copies){
1338         var raw = [];
1339         if (!add_vols && add_copies) { // just a copy on existing volumes
1340             angular.forEach(gatherSelectedVolumeIds(), function (v) {
1341                 raw.push( {callnumber : v} );
1342             });
1343         } else if (add_vols) {
1344             if (typeof $scope.holdingsGridControls.selectedItems == "function" &&
1345                 $scope.holdingsGridControls.selectedItems().length > 0) {
1346                 angular.forEach($scope.holdingsGridControls.selectedItems(),
1347                     function (item) {
1348                         raw.push({
1349                             owner : item.owner_id,
1350                             label : ((item.call_number) ? item.call_number.label : null)
1351                         });
1352                     });
1353             } else {
1354                 raw.push({
1355                     owner : egCore.auth.user().ws_ou()
1356                 });
1357             }
1358         }
1359
1360         if (raw.length == 0) raw.push({});
1361
1362         egCore.net.request(
1363             'open-ils.actor',
1364             'open-ils.actor.anon_cache.set_value',
1365             null, 'edit-these-copies', {
1366                 record_id: $scope.record_id,
1367                 raw: raw,
1368                 hide_vols : false,
1369                 hide_copies : !add_copies
1370             }
1371         ).then(function(key) {
1372             if (key) {
1373                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
1374                 $timeout(function() { $window.open(url, '_blank') });
1375             } else {
1376                 alert('Could not create anonymous cache key!');
1377             }
1378         });
1379     }
1380     $scope.selectedHoldingsVolCopyAdd = function () { spawnHoldingsAdd(true,true) }
1381     $scope.selectedHoldingsCopyAdd = function () { spawnHoldingsAdd(false,true) }
1382     $scope.selectedHoldingsVolAdd = function () { spawnHoldingsAdd(true,false) }
1383
1384     spawnHoldingsEdit = function (hide_vols,hide_copies){
1385         egCore.net.request(
1386             'open-ils.actor',
1387             'open-ils.actor.anon_cache.set_value',
1388             null, 'edit-these-copies', {
1389                 record_id: $scope.record_id,
1390                 copies: gatherSelectedHoldingsIds(),
1391                 raw: gatherSelectedEmptyVolumeIds().map(
1392                     function(v){ return { callnumber : v } }
1393                 ),
1394                 hide_vols : hide_vols,
1395                 hide_copies : hide_copies
1396             }
1397         ).then(function(key) {
1398             if (key) {
1399                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
1400                 $timeout(function() { $window.open(url, '_blank') });
1401             } else {
1402                 alert('Could not create anonymous cache key!');
1403             }
1404         });
1405     }
1406     $scope.selectedHoldingsVolCopyEdit = function () { spawnHoldingsEdit(false,false) }
1407     $scope.selectedHoldingsVolEdit = function () { spawnHoldingsEdit(false,true) }
1408     $scope.selectedHoldingsCopyEdit = function () { spawnHoldingsEdit(true,false) }
1409
1410     $scope.selectedHoldingsItemStatus = function (){
1411         var url = egCore.env.basePath + 'cat/item/search/' + gatherSelectedHoldingsIds().join(',')
1412         $timeout(function() { $window.open(url, '_blank') });
1413     }
1414
1415     $scope.markFromSelectedAsHoldingsTarget = function() {
1416         egCore.hatch.setLocalItem(
1417             'eg.cat.transfer_target_lib',
1418             $scope.holdingsGridControls.selectedItems()[0].owner_id
1419         );
1420         egCore.hatch.setLocalItem(
1421             'eg.cat.transfer_target_record',
1422             $scope.record_id
1423         );
1424         if ($scope.holdingsGridControls.selectedItems()[0].call_number.id) { // cn.id missing when vols are collapsed, or we are on an empty lib
1425             egCore.hatch.setLocalItem(
1426                 'eg.cat.transfer_target_vol',
1427                 $scope.holdingsGridControls.selectedItems()[0].call_number.id
1428             );
1429         } else {
1430             // clear out the stale value if we're on a lib-only
1431             // or vol-collapsed row
1432             egCore.hatch.removeLocalItem('eg.cat.transfer_target_vol');
1433         }
1434         ngToast.create(egCore.strings.MARK_HOLDINGS_TARGET);
1435     }
1436
1437     $scope.selectedHoldingsItemStatusDetail = function (){
1438         angular.forEach(
1439             gatherSelectedHoldingsIds(),
1440             function (cid) {
1441                 var url = egCore.env.basePath +
1442                           'cat/item/' + cid;
1443                 $timeout(function() { $window.open(url, '_blank') });
1444             }
1445         );
1446     }
1447
1448     $scope.transferVolumes = function (){
1449         var target_record = egCore.hatch.getLocalItem('eg.cat.transfer_target_record');
1450         var target_lib = egCore.hatch.getLocalItem('eg.cat.transfer_target_lib');
1451         if (!target_lib
1452             && (!target_record || ($scope.record_id == target_record) )
1453         ) return;
1454
1455         var vols_to_move = {};
1456         if (target_lib) {
1457             // we're moving volumes to a different library
1458             var vol_ids = gatherSelectedVolumeIds();
1459             if (vol_ids.length) {
1460                 vols_to_move[target_lib] = vol_ids;
1461
1462                 // if we're *only* switching libs,
1463                 // grab the current record as the target
1464                 target_record = target_record || $scope.record_id;
1465             }
1466         } else {
1467             // we're moving volumes to the same library they exist in
1468             // currently, but on a different record
1469             var items = $scope.holdingsGridControls.selectedItems();
1470             angular.forEach(items, function(item) {
1471                 if (!(item.call_number.owning_lib in vols_to_move)) {
1472                     vols_to_move[item.call_number.owning_lib] = new Array;
1473                 }
1474                 vols_to_move[item.call_number.owning_lib].push(item.call_number.id);
1475             });
1476         }
1477
1478         var promises = [];        
1479         angular.forEach(vols_to_move, function(vols, owning_lib) {
1480             promises.push(egCore.net.request(
1481                 'open-ils.cat',
1482                 'open-ils.cat.asset.volume.batch.transfer.override',
1483                 egCore.auth.token(), {
1484                     docid   : target_record,
1485                     lib     : owning_lib,
1486                     volumes : vols
1487                 }
1488             ));
1489         });
1490         $q.all(promises).then(function(success) {
1491             if (success) {
1492                 ngToast.create(egCore.strings.VOLS_TRANSFERED);
1493                 holdingsSvcInst.fetchAgain().then(function() {
1494                     $scope.holdingsGridDataProvider.refresh();
1495                 });
1496             } else {
1497                 alert('Could not transfer volumes!');
1498             }
1499         });
1500     }
1501
1502     // this "transfers" selected copies to a new owning library,
1503     // auto-creating volumes as required
1504     $scope.transferItemsAutoFill = function() {
1505         var target_record = egCore.hatch.getLocalItem('eg.cat.transfer_target_record');
1506         var target_lib = egCore.hatch.getLocalItem('eg.cat.transfer_target_lib');
1507         if (!target_lib
1508             && (!target_record || ($scope.record_id == target_record) )
1509         ) return;
1510
1511         var items = $scope.holdingsGridControls.selectedItems();
1512         if (!items.length) {
1513             return;
1514         }
1515
1516         var vols_to_move   = {};
1517         var copies_to_move = {};
1518         angular.forEach(items, function(item) {
1519             var needs_move = false;
1520             if (target_lib
1521                 && (item.call_number.owning_lib != target_lib)) {
1522                     item.call_number.owning_lib = target_lib;
1523                     needs_move = true;
1524             }
1525             if (target_record
1526                 && (item.call_number.record != target_record)) {
1527                     item.call_number.record = target_record;
1528                     needs_move = true;
1529             }
1530             if (needs_move) {
1531                 if (item.call_number.id in vols_to_move) {
1532                     copies_to_move[item.call_number.id].push(item.id);
1533                 } else {
1534                     vols_to_move[item.call_number.id] = item.call_number;
1535                     copies_to_move[item.call_number.id] = new Array;
1536                     copies_to_move[item.call_number.id].push(item.id);
1537                 }
1538             }
1539         });
1540
1541         var promises = [];
1542         angular.forEach(vols_to_move, function(vol) {
1543             promises.push(egCore.net.request(
1544                 'open-ils.cat',
1545                 'open-ils.cat.call_number.find_or_create',
1546                 egCore.auth.token(),
1547                 vol.label,
1548                 vol.record, // may be new
1549                 vol.owning_lib, // may be new
1550                 vol.prefix.id,
1551                 vol.suffix.id,
1552                 vol.label_class
1553             ).then(function(resp) {
1554                 var evt = egCore.evt.parse(resp);
1555                 if (evt) return;
1556                 return egCore.net.request(
1557                     'open-ils.cat',
1558                     'open-ils.cat.transfer_copies_to_volume',
1559                     egCore.auth.token(),
1560                     resp.acn_id,
1561                     copies_to_move[vol.id]
1562                 );
1563             }));
1564         });
1565         $q.all(promises).then(function() {
1566             ngToast.create(egCore.strings.ITEMS_TRANSFERED);
1567             holdingsSvcInst.fetchAgain().then(function() {
1568                 $scope.holdingsGridDataProvider.refresh();
1569             });
1570         });
1571     }
1572
1573     $scope.gridCellHandlers = {};
1574     $scope.gridCellHandlers.copyAlertsEdit = function(id) {
1575         egCirc.manage_copy_alerts([id]).then(function() {
1576             // update grid items?
1577         });
1578     };
1579
1580     $scope.transferItems = function (){
1581         var xfer_target = egCore.hatch.getLocalItem('eg.cat.transfer_target_vol');
1582
1583         if (!xfer_target) {
1584             // we have no specific volume, let's try to fill in the
1585             // blanks instead
1586             return $scope.transferItemsAutoFill();
1587         }
1588
1589         var copy_ids = gatherSelectedHoldingsIds();
1590         if (copy_ids.length > 0) {
1591             egCore.net.request(
1592                 'open-ils.cat',
1593                 'open-ils.cat.transfer_copies_to_volume',
1594                 egCore.auth.token(),
1595                 xfer_target,
1596                 copy_ids
1597             ).then(
1598                 function(resp) { // oncomplete
1599                     var evt = egCore.evt.parse(resp);
1600                     if (evt) {
1601                         egConfirmDialog.open(
1602                             egCore.strings.OVERRIDE_TRANSFER_COPIES_TO_MARKED_VOLUME_TITLE,
1603                             egCore.strings.OVERRIDE_TRANSFER_COPIES_TO_MARKED_VOLUME_BODY,
1604                             {'evt_desc': evt.desc}
1605                         ).result.then(function() {
1606                             egCore.net.request(
1607                                 'open-ils.cat',
1608                                 'open-ils.cat.transfer_copies_to_volume.override',
1609                                 egCore.auth.token(),
1610                                 xfer_target,
1611                                 copy_ids,
1612                                 { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
1613                             ).then(function(resp) {
1614                                 holdingsSvcInst.fetchAgain().then(function() {
1615                                     $scope.holdingsGridDataProvider.refresh();
1616                                 });
1617                             });
1618                         });
1619                     } else {
1620                         ngToast.create(egCore.strings.ITEMS_TRANSFERED);
1621                         holdingsSvcInst.fetchAgain().then(function() {
1622                             $scope.holdingsGridDataProvider.refresh();
1623                         });
1624                     }
1625                 },
1626                 null, // onerror
1627                 null // onprogress
1628             )
1629         }
1630     }
1631
1632     $scope.selectedHoldingsItemStatusTgrEvt = function (){
1633         angular.forEach(
1634             gatherSelectedHoldingsIds(),
1635             function (cid) {
1636                 var url = egCore.env.basePath +
1637                           'cat/item/' + cid + '/triggered_events';
1638                 $timeout(function() { $window.open(url, '_blank') });
1639             }
1640         );
1641     }
1642
1643     $scope.selectedHoldingsItemStatusHolds = function (){
1644         angular.forEach(
1645             gatherSelectedHoldingsIds(),
1646             function (cid) {
1647                 var url = egCore.env.basePath +
1648                           'cat/item/' + cid + '/holds';
1649                 $timeout(function() { $window.open(url, '_blank') });
1650             }
1651         );
1652     }
1653
1654     $scope.selectedHoldingsPrintLabels = function() {
1655         egCore.net.request(
1656             'open-ils.actor',
1657             'open-ils.actor.anon_cache.set_value',
1658             null, 'print-labels-these-copies', {
1659                 copies : gatherSelectedHoldingsIds()
1660             }
1661         ).then(function(key) {
1662             if (key) {
1663                 var url = egCore.env.basePath + 'cat/printlabels/' + key;
1664                 $timeout(function() { $window.open(url, '_blank') });
1665             } else {
1666                 alert('Could not create anonymous cache key!');
1667             }
1668         });
1669     }
1670
1671     $scope.selectedHoldingsDamaged = function () {
1672         var copy_list = gatherSelectedRawCopies();
1673         if (copy_list.length == 0) return;
1674
1675         angular.forEach(copy_list, function(cp) {
1676             egCirc.mark_damaged({
1677                 id: cp.id(),
1678                 barcode: cp.barcode(),
1679                 circ_lib: cp.circ_lib().id()
1680             }).then(function() {
1681                 holdingsSvcInst.fetchAgain().then(function() {
1682                     $scope.holdingsGridDataProvider.refresh();
1683                 });
1684             });
1685         });
1686     }
1687
1688     $scope.selectedHoldingsDiscard = function () {
1689         var copy_list = gatherSelectedRawCopies();
1690         if (copy_list.length == 0) return;
1691         egCirc.mark_discard(copy_list.map(function(cp) {
1692             return {id: cp.id(), barcode: cp.barcode()};})).then(function() {
1693                 holdingsSvcInst.fetchAgain().then(function() {
1694                     $scope.holdingsGridDataProvider.refresh();
1695                 });
1696             });
1697     }
1698
1699     $scope.selectedHoldingsMissing = function () {
1700         var copy_list = gatherSelectedRawCopies();
1701         if (copy_list.length == 0) return;
1702         egCirc.mark_missing(copy_list.map(function(cp) {
1703             return {id: cp.id(), barcode: cp.barcode()};})).then(function() {
1704                 holdingsSvcInst.fetchAgain().then(function() {
1705                     $scope.holdingsGridDataProvider.refresh();
1706                 });
1707             });
1708     }
1709
1710     $scope.selectedHoldingsCopyAlertsAdd = function() {
1711         egCirc.add_copy_alerts(gatherSelectedHoldingsIds()).then(function() {
1712             // no need to refresh grid
1713         });
1714     }
1715     $scope.selectedHoldingsCopyAlertsManage = function() {
1716         egCirc.manage_copy_alerts(gatherSelectedHoldingsIds()).then(function() {
1717             // no need to refresh grid
1718         });
1719     }
1720
1721     $scope.attach_to_peer_bib = function() {
1722         var copy_list = gatherSelectedHoldingsIds();
1723         if (copy_list.length == 0) return;
1724
1725         egCore.hatch.getItem('eg.cat.marked_conjoined_record').then(function(target_record) {
1726             if (!target_record) return;
1727
1728             return $uibModal.open({
1729                 templateUrl: './cat/catalog/t_conjoined_selector',
1730                 backdrop: 'static',
1731                 animation: true,
1732                 controller:
1733                        ['$scope','$uibModalInstance',
1734                 function($scope , $uibModalInstance) {
1735                     $scope.update = false;
1736
1737                     $scope.peer_type = null;
1738                     $scope.peer_type_list = [];
1739                     conjoinedSvc.get_peer_types().then(function(list){
1740                         $scope.peer_type_list = list;
1741                     });
1742     
1743                     $scope.ok = function(type) {
1744                         var promises = [];
1745     
1746                         angular.forEach(copy_list, function (cp) {
1747                             var n = new egCore.idl.bpbcm();
1748                             n.isnew(true);
1749                             n.peer_record(target_record);
1750                             n.target_copy(cp);
1751                             n.peer_type(type);
1752                             promises.push(egCore.pcrud.create(n));
1753                         });
1754     
1755                         return $q.all(promises).then(function(){$uibModalInstance.close()});
1756                     }
1757     
1758                     $scope.cancel = function($event) {
1759                         $uibModalInstance.dismiss();
1760                         $event.preventDefault();
1761                     }
1762                 }]
1763             });
1764         });
1765     }
1766
1767
1768     // ------------------------------------------------------------------
1769     // Holds 
1770     var provider = egGridDataProvider.instance({});
1771     var holds = []; // current list of holds
1772     var hold_count = 0;
1773
1774     $scope.hold_grid_data_provider = provider;
1775     $scope.grid_actions = egHoldGridActions;
1776     $scope.grid_actions.refresh = function () { holds = []; hold_count = 0; provider.refresh() };
1777     $scope.hold_grid_controls = {};
1778
1779     provider.get = function(offset, count) {
1780         if ($scope.record_tab != 'holds') return $q.when();
1781
1782         // see if we have the requested range cached
1783         if (holds[offset]) {
1784             return provider.arrayNotifier(holds, offset, count);
1785         }
1786
1787         hold_count = 0;
1788         holds = [];
1789         var restrictions = {
1790                 is_staff_request : 'true',
1791                 fulfillment_time : null,
1792                 cancel_time      : null,
1793                 record_id        : $scope.record_id,
1794                 pickup_lib       : egCore.org.descendants($scope.pickup_ou.id(), true)
1795         };
1796
1797         var order_by = [{ request_time : null }];
1798         if (provider.sort && provider.sort.length) {
1799             order_by = [];
1800             angular.forEach(provider.sort, function (c) {
1801                 if (!angular.isObject(c)) {
1802                     if (c.match(/^hold\./)) {
1803                         var i = c.replace('hold.','');
1804                         var ob = {};
1805                         ob[i] = null;
1806                         order_by.push(ob);
1807                     }
1808                 } else {
1809                     var i = Object.keys(c)[0];
1810                     var direction = c[i];
1811                     if (i.match(/^hold\./)) {
1812                         i = i.replace('hold.','');
1813                         var ob = {}
1814                         ob[i] = {dir:direction};
1815                         order_by.push(ob);
1816                     }
1817                 }
1818             });
1819         }
1820
1821         egProgressDialog.open({max : 1, value : 0});
1822         var first = true;
1823         return egHolds.fetch_wide_holds(
1824             restrictions,
1825             order_by
1826         ).then(function () {
1827                 return provider.arrayNotifier(holds, offset, count);
1828             },
1829             null,
1830             function(hold_data) {
1831                 if (first) {
1832                     hold_count = hold_data;
1833                     first = false;
1834                     egProgressDialog.update({max:hold_count});
1835                 } else {
1836                     egProgressDialog.increment();
1837                     var new_item = { id : hold_data.id, hold : hold_data };
1838                     new_item.status_string =
1839                         egCore.strings['HOLD_STATUS_' + hold_data.hold_status]
1840                         || hold_data.hold_status;
1841
1842                     holds.push(new_item);
1843                 }
1844             }
1845         ).finally(egProgressDialog.close);
1846
1847     }
1848
1849     $scope.detail_view = function(action, user_data, items) {
1850         if (h = items[0]) {
1851             $scope.detail_hold_id = h.hold.id;
1852         }
1853     }
1854
1855     $scope.list_view = function(items) {
1856          $scope.detail_hold_id = null;
1857     }
1858
1859     // refresh the list of record holds when the pickup lib is changed.
1860     $scope.pickup_ou = egCore.org.get(egCore.auth.user().ws_ou());
1861     $scope.pickup_ou_changed = function(org) {
1862         $scope.pickup_ou = org;
1863         holds = []
1864         hold_count = 0;
1865         provider.refresh();
1866     }
1867
1868     function map_prefix_to_subhash (h,pf) {
1869         var newhash = {};
1870         angular.forEach(Object.keys(h), function (k) {
1871             if (k.startsWith(pf)) {
1872                 var nk = k.substr(pf.length);
1873                 newhash[nk] = h[k];
1874             }
1875         });
1876         return newhash;
1877     }
1878
1879     $scope.print_holds = function() {
1880         var pholds = [];
1881         angular.forEach(holds, function(item) {
1882             pholds.push({
1883                 hold : item.hold,
1884                 status_string : item.status_string,
1885                 patron_first : item.hold.usr_first_given_name,
1886                 patron_last : item.hold.usr_family_name,
1887                 patron_alias : item.hold.usr_alias,
1888                 patron_barcode : item.hold.ucard_barcode,
1889                 copy : map_prefix_to_subhash(item.hold,'cp_'),
1890                 volume : map_prefix_to_subhash(item.hold,'cn_'),
1891                 title : item.hold.title,
1892                 author : item.hold.author
1893             });
1894         });
1895
1896         egCore.print.print({
1897             context : 'receipt', 
1898             template : 'holds_for_bib', 
1899             scope : {holds : pholds}
1900         });
1901     }
1902
1903     $scope.current_hold_transfer_dest = egCore.hatch.getLocalItem ('eg.circ.hold.title_transfer_target');
1904
1905     $scope.mark_hold_transfer_dest = function() {
1906         $scope.current_hold_transfer_dest = $scope.record_id;
1907         egCore.hatch.setLocalItem(
1908             'eg.circ.hold.title_transfer_target', $scope.record_id);
1909         ngToast.create(egCore.strings.HOLD_TRANSFER_DEST_MARKED);
1910     }
1911
1912     // UI presents this option as "all holds"
1913     $scope.transfer_holds_to_marked = function() {
1914         var hold_ids = $scope.hold_grid_controls.allItems().map(
1915             function(hold_data) {return hold_data.hold.id});
1916         egHolds.transfer_to_marked_title(hold_ids);
1917     }
1918
1919     // ------------------------------------------------------------------
1920     // Initialize the selected tab
1921
1922     // we explicitly initialize catalog_url because otherwise Firefox
1923     // ends up setting it to $BASE_URL/{{url}}, which then messes
1924     // things up. See LP#1708951
1925     $scope.catalog_url = '';
1926
1927     function init_cat_url() {
1928         // Set the initial catalog URL.  This only happens once.
1929         // The URL is otherwise generated through user navigation.
1930         if ($scope.catalog_url) return;
1931
1932         var url = $location.absUrl().replace(/\/staff.*/, '/opac/advanced');
1933
1934         // A record ID in the path indicates a request for the record-
1935         // specific page.
1936         if ($routeParams.record_id) {
1937             url = url.replace(/advanced/, '/record/' + $scope.record_id);
1938         }
1939
1940         // Jumping directly to the results page by passing a search
1941         // query via the URL.  Copy all URL params to the iframe url.
1942         if ($location.path().match(/catalog\/results/)) {
1943             url = url.replace(/advanced/, '/results?');
1944             var first = true;
1945             angular.forEach($location.search(), function(val, key) {
1946                 if (!first) url += '&';
1947                 first = false;
1948                 url += encodeURIComponent(key) 
1949                     + '=' + encodeURIComponent(val);
1950             });
1951         }
1952
1953         // if we're displaying the advanced search form, select
1954         // whatever default pane the user has chosen via workstation
1955         // preference
1956         if (url.match(/\/opac\/advanced$/)) {
1957             egCore.hatch.getItem('eg.search.adv_pane').then(function(adv_pane_val){
1958                 if (adv_pane_val) {
1959                     url += '?pane=' + encodeURIComponent(adv_pane_val);
1960                 }
1961
1962                 $scope.catalog_url = url;
1963             });
1964         } else {
1965             $scope.catalog_url = url;
1966         }
1967
1968     }
1969
1970     function init_parts_url() {
1971         $scope.parts_url = $location
1972             .absUrl()
1973             .replace(
1974                 /\/staff.*/,
1975                 '/conify/global/biblio/monograph_part?r='+$scope.record_id
1976             );
1977     }
1978
1979     $scope.set_record_tab = function(tab) {
1980         $scope.record_tab = tab;
1981
1982         switch(tab) {
1983
1984             case 'monoparts':
1985                 init_parts_url();
1986                 break;
1987
1988             case 'catalog':
1989                 init_cat_url();
1990                 break;
1991
1992             case 'holds':
1993                 $scope.detail_hold_record_id = $scope.record_id; 
1994                 // refresh the holds grid
1995                 provider.refresh();
1996
1997                 break;
1998         }
1999     }
2000
2001     $scope.set_default_record_tab = function() {
2002         egCore.hatch.setLocalItem(
2003             'eg.cat.default_record_tab', $scope.record_tab);
2004         $timeout(function(){$scope.default_tab = $scope.record_tab});
2005     }
2006
2007     var tab;
2008     if ($scope.record_id) {
2009         $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
2010         tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
2011
2012     } else {
2013         tab = $routeParams.record_tab || 'catalog';
2014     }
2015     $scope.set_record_tab(tab);
2016
2017 }])
2018
2019 .controller('AuthorityCtrl',
2020        ['$scope','$routeParams','$location','$window','$q','egCore',
2021 function($scope , $routeParams , $location , $window , $q , egCore) {
2022
2023     // set record ID on page load if available...
2024     $scope.authority_id = $routeParams.authority_id;
2025
2026     if ($routeParams.authority_id) $scope.from_route = true;
2027     else $scope.from_route = false;
2028
2029     $scope.stop_unload = false;
2030 }])
2031
2032 .controller('URLVerifyCtrl',
2033        ['$scope','$location',
2034 function($scope , $location) {
2035     $scope.verifyurls_url = $location.absUrl().replace(/\/staff.*/, '/url_verify/sessions');
2036 }])
2037
2038 .controller('VandelayCtrl',
2039        ['$scope','$location', 'egCore', '$uibModal',
2040 function($scope , $location, egCore, $uibModal) {
2041     $scope.vandelay_url = $location.absUrl().replace(/\/staff\/cat\/catalog\/vandelay/, '/vandelay/vandelay');
2042     $scope.funcs = {};
2043     $scope.funcs.edit_marc_modal = function(bre, callback){
2044         var marcArgs = { 'marc_xml': bre.marc() };
2045         var vqbibrecId = bre.id();
2046         $uibModal.open({
2047             templateUrl: './cat/catalog/t_edit_marc_modal',
2048             backdrop: 'static',
2049             size: 'lg',
2050             controller: ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
2051                 $scope.focusMe = true;
2052                 $scope.recordId = vqbibrecId;
2053                 $scope.args = marcArgs;
2054                 $scope.dirty_flag = false;
2055                 $scope.ok = function(marg){
2056                     $uibModalInstance.close(marg);
2057                 };
2058                 $scope.cancel = function(){ $uibModalInstance.dismiss() }
2059             }]
2060         }).result.then(function(res){
2061             var new_xml = res.marc_xml;
2062             egCore.pcrud.retrieve('vqbr', vqbibrecId).then(function(vqbib){
2063                 vqbib.marc(new_xml);
2064                 egCore.pcrud.update(vqbib).then( function(){ callback(vqbibrecId); });
2065             });
2066         });
2067     };
2068 }])
2069
2070 .controller('ManageAuthoritiesCtrl',
2071        ['$scope','$location',
2072 function($scope , $location) {
2073     $scope.manageauthorities_url = $location.absUrl().replace(/\/staff.*/, '/cat/authority/list');
2074 }])
2075
2076 .controller('BatchEditCtrl',
2077        ['$scope','$location','$routeParams',
2078 function($scope , $location , $routeParams) {
2079     $scope.batchedit_url = $location.absUrl().replace(/\/eg.*/, '/opac/extras/merge_template');
2080     if ($routeParams.container_type) {
2081         switch ($routeParams.container_type) {
2082             case 'bucket':
2083                 $scope.batchedit_url += '?recordSource=b&containerid=' + $routeParams.container_id;
2084                 break;
2085             case 'record':
2086                 $scope.batchedit_url += '?recordSource=r&recid=' + $routeParams.container_id;
2087                 break;
2088         };
2089     }
2090 }])
2091
2092  
2093 .filter('boolText', function(){
2094     return function (v) {
2095         return v == 't';
2096     }
2097 })
2098
2099 .factory('conjoinedSvc', 
2100        ['egCore','$q',
2101 function(egCore , $q) {
2102
2103     var service = {
2104         items : [], // record search results
2105         index : 0, // search grid index
2106         rid : null
2107     };
2108
2109     service.flesh = {   
2110         flesh : 4, 
2111         flesh_fields : {
2112             bpbcm : ['target_copy','peer_type'],
2113             acp : ['call_number'],
2114             acn : ['record'],
2115             bre : ['simple_record']
2116         },
2117         // avoid fetching the MARC blob by specifying which
2118         // fields on the bre to select.  More may be needed.
2119         // note that fleshed fields are explicitly selected.
2120         select : { bre : ['id'] },
2121         order_by : { bpbcm : ['id'] },
2122     }
2123
2124     // resolved with the last received copy
2125     service.fetch = function(rid) {
2126         if (!rid && !service.rid) return $q.when();
2127
2128         if (rid) service.rid = rid;
2129         service.items = [];
2130         service.index = 0;
2131
2132         return egCore.pcrud.search(
2133             'bpbcm',
2134             {peer_record : service.rid},
2135             service.flesh,
2136             {atomic : true}
2137         ).then( function(list) { // finished
2138             service.items = list;
2139             return service.items;
2140         });
2141     }
2142
2143     // returns a promise resolved with the list of peer bib types
2144     service.get_peer_types = function() {
2145         if (egCore.env.bpt)
2146             return $q.when(egCore.env.bpt.list);
2147
2148         return egCore.pcrud.retrieveAll('bpt', null, {atomic : true})
2149         .then(function(list) {
2150             egCore.env.absorbList(list, 'bpt');
2151             return list;
2152         });
2153     };
2154
2155     return service;
2156 }])
2157
2158