]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/opac/skin/default/js/rdetail.js
Display an array of MFHD records per bib record
[Evergreen.git] / Open-ILS / web / opac / skin / default / js / rdetail.js
1 /* */
2
3
4 detachAllEvt('common', 'run');
5 attachEvt("common", "run", rdetailDraw);
6 attachEvt("rdetail", "recordDrawn", rdetailBuildStatusColumns);
7 attachEvt("rdetail", "recordDrawn", rdetailBuildInfoRows);
8 attachEvt("rdetail", "recordDrawn", rdetailGetPageIds);
9
10 var record = null;
11 var cp_statuses = null;
12 var recordsCache = [];
13
14 var copyRowParent = null;
15 var copyRow = null;
16 var statusRow = null;
17 var numStatuses = null;
18 var defaultCN;
19 var callnumberCache = {};
20 var rdetailLocalOnly = true;
21 var globalCNCache = {};
22 var localTOC;
23 var cachedRecords;
24 var _statusPositions = {};
25
26 var rdetailShowLocal = true;
27 var rdetailShowCopyLocation = true;
28 var googleBookPreview = true;
29 var displaySerialHoldings = true;
30
31
32 var nextContainerIndex;
33
34 function rdetailReload() {
35         var args = {};
36         args[PARAM_LOCATION] = getNewSearchLocation();
37         args[PARAM_DEPTH] = depthSelGetDepth();
38         goTo(buildOPACLink(args));
39 }
40
41 var nextRecord;
42 var prevRecord;
43
44 var rdetailPrev = null;
45 var rdetailNext = null;
46 var rdetailStart = null;
47 var rdetailEnd = null;
48
49
50
51 /* looks to see if we have a next and/or previous record in the
52    record cache, if so, set up the nav links */
53 function rdetailSetPaging(ids) {
54
55         cachedRecords = {};
56         cachedRecords.ids = ids;
57
58         for( var i = 0; i < cachedRecords.ids.length; i++ ) {
59                 var rec = cachedRecords.ids[i];
60                 if( rec == getRid() ) {
61                         if( i > 0 ) prevRecord = cachedRecords.ids[i-1];
62                         if( i < cachedRecords.ids.length - 1 )
63                                 nextRecord = cachedRecords.ids[i+1];
64                         break;
65                 }
66         }
67
68         $('np_offset').appendChild(text(i + 1));
69         $('np_count').appendChild(text(getHitCount()));
70
71         if(prevRecord) {
72                 unHideMe($('np_table'));
73                 unHideMe($('np_prev'));
74                 unHideMe($('np_start'));
75                 rdetailPrev = function() { _rdetailNav(prevRecord); };
76                 rdetailStart = function() { _rdetailNav(cachedRecords.ids[0]); };
77         }
78
79         if(nextRecord) {
80                 unHideMe($('np_table'));
81                 unHideMe($('np_next'));
82                 unHideMe($('np_end'));
83                 rdetailNext = function() { _rdetailNav(nextRecord); };
84                 rdetailEnd = function() { _rdetailNav(cachedRecords.ids[cachedRecords.ids.length-1]); };
85         }
86
87         runEvt('rdetail', 'nextPrevDrawn', i, cachedRecords.ids.length);
88 }
89
90
91 function _rdetailNav(id, offset) {
92         var args = {};
93         args[PARAM_RID] = id;
94         goTo(buildOPACLink(args));
95 }
96
97 function rdetailDraw() {
98
99         detachAllEvt('common','depthChanged');
100         detachAllEvt('common','locationUpdated');
101         attachEvt('common','depthChanged', rdetailReload);
102         attachEvt('common','locationUpdated', rdetailReload);
103         attachEvt('common','holdUpdated', rdetailReload);
104         attachEvt('common','holdUpdateCanceled', rdetailReload);
105
106         copyRowParent = G.ui.rdetail.cp_info_row.parentNode;
107         copyRow = copyRowParent.removeChild(G.ui.rdetail.cp_info_row);
108         statusRow = G.ui.rdetail.cp_status.parentNode;
109         statusRow.id = '__rdsrow';
110
111         G.ui.rdetail.cp_info_local.onclick = rdetailShowLocalCopies;
112         G.ui.rdetail.cp_info_all.onclick = rdetailShowAllCopies;
113
114         if(getLocation() == globalOrgTree.id())
115                 hideMe(G.ui.rdetail.cp_info_all);
116
117         var req = new Request(FETCH_RMODS, getRid());
118         req.callback(_rdetailDraw);
119         req.send();
120
121         if (displaySerialHoldings) {
122                 var req = new Request(FETCH_MFHD_SUMMARY, getRid());
123                 req.callback(_holdingsDraw);
124                 req.send();
125         }
126
127         detachAllEvt("result", "idsReceived");
128         G.evt.result.hitCountReceived = [];
129         G.evt.result.recordReceived = [];
130         G.evt.result.copyCountsReceived = [];
131         G.evt.result.allRecordsReceived = [];
132 }
133
134 function rdetailGetPageIds() {
135         attachEvt("result", "idsReceived", rdetailSetPaging );
136         resultFetchAllRecords = true;
137         rresultCollectIds(true);
138 }
139
140
141 function buildunAPISpan (span, type, id) {
142         var cgi = new CGI();
143         var d = new Date();
144
145         addCSSClass(span,'unapi-id');
146
147         span.setAttribute(
148                         'title', 'tag:' + cgi.server_name + ',' +
149                         d.getFullYear() + ':' + type + '/' + id
150                         );
151 }
152
153 function rdetailViewMarc(r,id) {
154         hideMe($('rdetail_extras_loading'));
155         $('rdetail_view_marc_box').innerHTML = r.getResultObject();
156
157         var div = elem('div', { "class" : 'hide_me' });
158         var span = div.appendChild( elem('abbr') );
159
160         buildunAPISpan( span, 'biblio-record_entry', record.doc_id() );
161
162         $('rdetail_view_marc_box').insertBefore(span, $('rdetail_view_marc_box').firstChild);
163 }
164
165
166 function rdetailShowLocalCopies() {
167         rdetailShowLocal = true;
168         rdetailBuildInfoRows();
169         hideMe(G.ui.rdetail.cp_info_local);
170         unHideMe(G.ui.rdetail.cp_info_all);
171         hideMe(G.ui.rdetail.cp_info_none); 
172 }
173
174 function rdetailShowAllCopies() {
175
176         rdetailShowLocal = false;
177         rdetailBuildInfoRows();
178         hideMe(G.ui.rdetail.cp_info_all);
179         unHideMe(G.ui.rdetail.cp_info_local);
180         hideMe(G.ui.rdetail.cp_info_none); 
181 }
182
183 function OpenMarcEditWindow(pcrud, rec) {
184     /*
185         To run in Firefox directly, must set signed.applets.codebase_principal_support
186         to true in about:config
187     */
188     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
189     win = window.open('/xul/server/cat/marcedit.xul'); // XXX version?
190     dojo.require('openils.PermaCrud');
191
192     win.xulG = {
193         record : {marc : rec.marc()},
194         save : {
195             label: 'Save',
196             func: function(xmlString) {
197                 rec.marc(xmlString);
198                 rec.ischanged(true);
199                 pcrud.update(rec);
200             },
201         }
202     };
203 }
204
205 function loadMarcEditor(recId) {
206         var pcrud = new openils.PermaCrud({"authtoken": G.user.session});
207         var recs = pcrud.search("sre", {"record": recId});
208         OpenMarcEditWindow(pcrud, recs[0]);
209 }
210
211 /*
212  * This function could be written much more intelligently
213  * Limited brain power means that I'm brute-forcing it for now
214  */
215 function _holdingsDraw(h) {
216         holdings = h.getResultObject();
217         if (!holdings) { return null; }
218
219         dojo.forEach(holdings, _holdingsDrawMFHD);
220
221 }
222
223 function _holdingsDrawMFHD(holdings, entryNum) {
224         var hh = holdings.holdings();
225         var hch = holdings.current_holdings();
226         var hs = holdings.supplements();
227         var hcs = holdings.current_supplements();
228         var hi = holdings.indexes();
229         var hci = holdings.current_indexes();
230         var ho = holdings.online();
231         var hm = holdings.missing();
232         var hinc = holdings.incomplete();
233
234         if (    hh.length == 0 && hch.length == 0 && hs.length == 0 &&
235                 hcs.length == 0 && hi.length == 0 && hci.length == 0 &&
236                 ho.length == 0 && hm.length == 0 && hinc.length == 0
237         ) {
238                 return null;
239         }
240
241         dojo.place("<table><caption id='mfhdHoldingsCaption' class='rdetail_header color_1'>Holdings summary</caption><tbody id='rdetail_holdings_tbody_" + entryNum + "'></tbody></table>", "rdetail_details_table", "after");
242         if (hh.length > 0) { _holdingsDrawMFHDEntry(entryNum, 'Holdings', hh); }
243         if (hch.length > 0) { _holdingsDrawMFHDEntry(entryNum, 'Current holdings', hch); }
244         if (hs.length > 0) { _holdingsDrawMFHDEntry(entryNum, 'Supplements', hs); }
245         if (hcs.length > 0) { _holdingsDrawMFHDEntry(entryNum, 'Current supplements', hcs); }
246         if (hi.length > 0) { _holdingsDrawMFHDEntry(entryNum, 'Indexes', hi); }
247         if (hci.length > 0) { _holdingsDrawMFHDEntry(entryNum, 'Current indexes', hci); }
248         if (ho.length > 0) { _holdingsDrawMFHDEntry(entryNum, 'Online', ho); }
249         if (hm.length > 0) { _holdingsDrawMFHDEntry(entryNum, 'Missing volumes', hm); }
250         if (hinc.length > 0) { _holdingsDrawMFHDEntry(entryNum, 'Incomplete volumes', hm); }
251
252         if (isXUL()) {
253                 dojo.require('openils.Event');
254                 dojo.require('openils.PermaCrud');
255                 dojo.place("<span> - </span><a class='classic_link' href='javascript:loadMarcEditor(" + getRid() + ")'> Edit</a>", "mfhdHoldingsCaption", "last");
256         }
257 }
258
259 function _holdingsDrawMFHDEntry(entryNum, entryName, entry) {
260         var commaRegex = /,/;
261         var flatEntry = entry.toString().replace(commaRegex, ', ');
262         dojo.place("<tr><td> </td><td nowrap='nowrap' class='rdetail_desc'>" + entryName + "</td><td class='rdetail_item'>" + flatEntry + "</td></tr>", "rdetail_holdings_tbody_" + entryNum, "last");
263 }
264
265 function _rdetailDraw(r) {
266         record = r.getResultObject();
267
268         runEvt('rdetail', 'recordRetrieved', record.doc_id());
269
270         G.ui.rdetail.title.appendChild(text(record.title()));
271         buildSearchLink(STYPE_AUTHOR, record.author(), G.ui.rdetail.author);
272         G.ui.rdetail.isbn.appendChild(text(cleanISBN(record.isbn())));
273         G.ui.rdetail.edition.appendChild(text(record.edition()));
274         G.ui.rdetail.pubdate.appendChild(text(record.pubdate()));
275         G.ui.rdetail.publisher.appendChild(text(record.publisher()));
276         $('rdetail_physical_desc').appendChild(text(record.physical_description()));
277         r = record.types_of_resource();
278         if(r) {
279                 G.ui.rdetail.tor.appendChild(text(r[0]));
280                 setResourcePic( G.ui.rdetail.tor_pic, r[0]);
281         }
282         G.ui.rdetail.abstr.appendChild(text(record.synopsis()));
283
284         try{
285                 if(record.isbn()) {
286                         if(ENABLE_ADDED_CONTENT_ATTRIB_LINKS) {
287                                 unHideMe($('rdetail.jacket_attrib_div'));
288                                 var href = $('rdetail.jacket_attrib_link').getAttribute('href') +cleanISBN(record.isbn());
289                                 $('rdetail.jacket_attrib_link').setAttribute('href', href);
290                         }
291                         rdetailCheckForGBPreview();
292
293                 } else {
294                         hideMe($("rdetail.jacket_attrib_div"));
295                         hideMe($("rdetail_img_link"));
296                 }
297         } catch(E) {}
298
299
300         // see if the record has any external links 
301         var links = record.online_loc();
302         for( var i = 0; links && links.length > 0 && i < links.length; i = i + 3 ) {
303                 var href = links[i];
304                 // avoid matching "HTTP: The Complete Reference"
305                 if( href.match(/https?:\/|ftps?:\/|mailto:/i) ) {
306                         unHideMe($('rdetail_online_row'));
307                         // MODS can contain a display label (used for the text of the link)
308                         // as well as a note about the URL; many legacy systems conflate the
309                         // two and generate MARC records that expect the note to be used as
310                         // the text of the link, with no display label; here's the canonical
311                         // format:
312                         //
313                         // 856 40 $uhttp://localhost$yDisplay label$zPublic note
314                         //
315                         // Note that the MARC21slim2MODS XSL concatenates $3 and $y together
316                         // (as $y was defined later in MARC21's life as the display label)
317                         var displayLabel = '' + links[i+1];
318                         var note = '' + links[i+2];
319                         if(!displayLabel || displayLabel.match(/https?:\/|ftps?:\/|mailto:/i)) {
320                                 if(!note || note.match(/https?:\/|ftps?:\/|mailto:/i)) {
321                                         displayLabel = href;
322                                 } else {
323                                         displayLabel = note;
324                                 }
325                         }
326                         $('rdetail_online').appendChild(elem('a', {href:href,'class':'classic_link'}, displayLabel));
327                         if (!note && note != displayLabel) {
328                                 $('rdetail_online').appendChild(elem('span', {'class':'url_note'}, ' - ' + note));
329                         }
330                         $('rdetail_online').appendChild(elem('br'));
331                 }
332         }
333
334         // Fill in our unAPI ID, if anyone cares
335         var abbrs = document.getElementsByTagName('abbr');
336         var span;
337         for (var i = 0; i < abbrs.length; i = i + 1) {
338                 if (abbrs[i].getAttribute('name') == 'unapi') {
339                         span = abbrs[i];
340                         break;
341                 }
342         }
343         buildunAPISpan( span, 'biblio-record_entry', record.doc_id() );
344
345         $('rdetail_place_hold').setAttribute(
346                         'href','javascript:holdsDrawEditor({record:"'+record.doc_id()+'",type:"T"});');
347
348         $('rdetail_img_link').setAttribute('href', buildISBNSrc(cleanISBN(record.isbn()), 'large'));
349         G.ui.rdetail.image.setAttribute("src", buildISBNSrc(cleanISBN(record.isbn())));
350         runEvt("rdetail", "recordDrawn");
351         recordsCache.push(record);
352
353         rdetailSetExtrasSelector();
354
355         var breq = new Request(FETCH_BRE, [getRid()]);
356         breq.callback( rdetailCheckDeleted );
357         breq.send();
358
359         resultBuildCaches( [ record ] );
360         resultDrawSubjects();
361         resultDrawSeries();
362
363         // grab added content 
364         acCollectData(cleanISBN(record.isbn()), rdetailhandleAC);
365 }
366
367
368
369 function rdetailCheckDeleted(r) {
370         var br = r.getResultObject()[0];
371         if( isTrue(br.deleted()) ) {
372                 hideMe($('rdetail_place_hold'));
373                 $('rdetail_more_actions_selector').disabled = true;
374                 unHideMe($('rdetail_deleted_exp'));
375         }
376 }
377
378 function rdetailSetExtrasSelector() {
379         if(!grabUser()) return;
380         unHideMe($('rdetail_more_actions'));
381
382         var req = new Request( 
383                         FETCH_CONTAINERS, G.user.session, G.user.id(), 'biblio', 'bookbag' );
384         req.callback(rdetailAddBookbags);
385         req.send();
386 }
387
388 function rdetailAddBookbags(r) {
389
390         var containers = r.getResultObject();
391         var selector = $('rdetail_more_actions_selector');
392         var found = false;
393         var index = 3;
394         doSelectorActions(selector);
395
396         for( var i = 0; i != containers.length; i++ ) {
397                 found = true;
398                 var container = containers[i];
399                 insertSelectorVal( selector, index++, container.name(), 
400                                 "container_" + container.id(), rdetailAddToBookbag,  1 );
401         }
402
403         nextContainerIndex = index;
404 }
405
406 var _actions = {};
407 function rdetailNewBookbag() {
408         var name = prompt($('rdetail_bb_new').innerHTML,"");
409         if(!name) return;
410
411         var id;
412         if( id = containerCreate( name ) ) {
413                 alert($('rdetail_bb_success').innerHTML);
414                 var selector = $('rdetail_more_actions_selector');
415                 insertSelectorVal( selector, nextContainerIndex++, name, 
416                                 "container_" + id, rdetailAddToBookbag, 1 );
417                 setSelector( selector, 'start' );
418         }
419 }
420
421
422 function rdetailAddToBookbag() {
423         var selector = $('rdetail_more_actions_selector');
424         var id = selector.options[selector.selectedIndex].value;
425         setSelector( selector, 'start' );
426
427         if( containerCreateItem( id.substring(10), record.doc_id() )) {
428                 alert($('rdetail_bb_item_success').innerHTML);
429         }
430 }
431
432
433 var rdetailMarcFetched = false;
434 function rdetailShowExtra(type, args) {
435
436         hideMe($('rdetail_copy_info_div'));
437         hideMe($('rdetail_reviews_div'));
438         hideMe($('rdetail_toc_div'));
439         hideMe($('rdetail_anotes_div'));
440         hideMe($('rdetail_excerpt_div'));
441         hideMe($('rdetail_preview_div'));
442         hideMe($('rdetail_marc_div'));
443         hideMe($('cn_browse'));
444         hideMe($('rdetail_cn_browse_div'));
445         hideMe($('rdetail_notes_div'));
446
447         removeCSSClass($('rdetail_copy_info_link'), 'rdetail_extras_selected');
448         removeCSSClass($('rdetail_viewcn_link'), 'rdetail_extras_selected');
449         removeCSSClass($('rdetail_reviews_link'), 'rdetail_extras_selected');
450         removeCSSClass($('rdetail_toc_link'), 'rdetail_extras_selected');
451         removeCSSClass($('rdetail_excerpt_link'), 'rdetail_extras_selected');
452         removeCSSClass($('rdetail_preview_link'), 'rdetail_extras_selected');
453         removeCSSClass($('rdetail_anotes_link'), 'rdetail_extras_selected');
454         removeCSSClass($('rdetail_annotation_link'), 'rdetail_extras_selected');
455         removeCSSClass($('rdetail_viewmarc_link'), 'rdetail_extras_selected');
456
457         switch(type) {
458
459                 case "copyinfo": 
460                         unHideMe($('rdetail_copy_info_div')); 
461                         addCSSClass($('rdetail_copy_info_link'), 'rdetail_extras_selected');
462                         break;
463
464                 case "reviews": 
465                         addCSSClass($('rdetail_reviews_link'), 'rdetail_extras_selected');
466                         unHideMe($('rdetail_reviews_div')); 
467                         break;
468
469                 case "excerpt": 
470                         addCSSClass($('rdetail_excerpt_link'), 'rdetail_extras_selected');
471                         unHideMe($('rdetail_excerpt_div'));
472                         break;
473
474                 case "preview": 
475                         addCSSClass($('rdetail_preview_link'), 'rdetail_extras_selected');
476                         unHideMe($('rdetail_preview_div'));
477                         rdetailDisplayGBPreview();
478                         break;
479
480                 case "anotes": 
481                         addCSSClass($('rdetail_anotes_link'), 'rdetail_extras_selected');
482                         unHideMe($('rdetail_anotes_div'));
483                         break;
484
485                 case "toc": 
486                         addCSSClass($('rdetail_toc_link'), 'rdetail_extras_selected');
487                         unHideMe($('rdetail_toc_div'));
488                         break;
489
490                 case "marc": 
491                         addCSSClass($('rdetail_viewmarc_link'), 'rdetail_extras_selected');
492                         unHideMe($('rdetail_marc_div')); 
493                         if(rdetailMarcFetched) return;
494                         unHideMe($('rdetail_extras_loading'));
495                         rdetailMarcFetched = true;
496                         var req = new Request( FETCH_MARC_HTML, record.doc_id() );
497                         req.callback(rdetailViewMarc); 
498                         req.send();
499                         break;
500
501                 case 'cn':
502                         addCSSClass($('rdetail_viewcn_link'), 'rdetail_extras_selected');
503                         unHideMe($('rdetail_cn_browse_div'));
504                         rdetailShowCNBrowse(defaultCN, getLocation(), null, true);
505                         break;
506
507         }
508 }
509
510 function rdetailVolumeDetails(args) {
511         var row = $(args.rowid);
512         var tbody = row.parentNode;
513         cpdBuild( tbody, row, record, args.cn, args.org, args.depth, args.copy_location );
514         return;
515 }
516
517 function rdetailBuildCNList() {
518
519         var select = $('cn_browse_selector');
520         var index = 0;
521         var arr = [];
522         for( var cn in callnumberCache ) arr.push( cn );
523         arr.sort();
524
525         if( arr.length == 0 ) {
526                 hideMe($('rdetail_cn_browse_select_div'));
527                 return;
528         }
529
530         for( var i in arr ) {
531                 var cn = arr[i];
532                 var opt = new Option(cn);
533                 select.options[index++] = opt;
534         }
535         select.onchange = rdetailGatherCN;
536 }
537
538 function rdetailGatherCN() {
539         var cn = getSelectorVal($('cn_browse_selector'));
540         rdetailShowCNBrowse( cn, getLocation(), getDepth(), true );
541         setSelector( $('cn_browse_selector'), cn );
542 }
543
544
545 function rdetailShowCNBrowse( cn, loc, depth, fromOnclick ) {
546
547         if(!cn) {
548                 unHideMe($('cn_browse_none'));
549                 hideMe($('rdetail_cn_browse_select_div'));
550                 return;
551         }
552
553         unHideMe($('rdetail_cn_browse_select_div'));
554         rdetailBuildCNList();
555         setSelector( $('cn_browse_selector'), cn );
556         hideMe($('rdetail_copy_info_div'));
557         hideMe($('rdetail_reviews_div'));
558         hideMe($('rdetail_toc_div'));
559         hideMe($('rdetail_marc_div'));
560         unHideMe($('rdetail_cn_browse_div'));
561         unHideMe($('cn_browse'));
562         if( !rdetailLocalOnly && ! fromOnclick ) depth = findOrgDepth(globalOrgTree);
563         cnBrowseGo(cn, loc, depth);
564 }
565
566 function rdetailhandleAC(data) {
567
568         if( data.reviews.html ) {
569                 $('rdetail_review_container').innerHTML = data.reviews.html;
570                 unHideMe($('rdetail_reviews_link'));
571         }
572
573         if( data.toc.html ) {
574                 $('rdetail_toc_div').innerHTML = data.toc.html;
575                 unHideMe($('rdetail_toc_link'));
576         }
577
578         if( data.excerpt.html ) {
579                 $('rdetail_excerpt_div').innerHTML = data.excerpt.html;
580                 unHideMe($('rdetail_excerpt_link'));
581         }
582
583         if( data.anotes.html ) {
584                 $('rdetail_anotes_div').innerHTML = data.anotes.html;
585                 unHideMe($('rdetail_anotes_link'));
586         }
587 }
588
589 function rdetailShowReviews(r) {
590         hideMe($('rdetail_extras_loading'));
591         var res = r.getResultObject();
592         var par = $('rdetail_reviews_div');
593         var template = par.removeChild($('rdetail_review_template'));
594         if( res && res.length > 0 ) {
595                 unHideMe($('rdetail_reviews_link'));
596                 for( var i = 0; i != res.length; i++ ) {
597                         var rev = res[i];       
598                         if( rev.text && rev.info ) {
599                                 var node = template.cloneNode(true);
600                                 $n(node, 'review_header').appendChild(text(rev.info));
601                                 $n(node, 'review_text').appendChild(text(rev.text));
602                                 par.appendChild(node);
603                         }
604                 }
605         }
606 }
607
608
609 function rdetailShowTOC(r) {
610         hideMe($('rdetail_extras_loading'));
611         var resp = r.getResultObject();
612         if(resp) {
613                 unHideMe($('rdetail_toc_link'));
614                 $('rdetail_toc_div').innerHTML = resp;
615         }
616 }
617
618 function rdetailBuildInfoRows() {
619         var req;
620         var method = FETCH_COPY_COUNTS_SUMMARY;
621         if (rdetailShowCopyLocation)
622                 method = FETCH_COPY_LOCATION_COUNTS_SUMMARY;
623
624         if( rdetailShowLocal ) 
625                 req = new Request(method, record.doc_id(), getLocation(), getDepth())
626         else
627                 req = new Request(method, record.doc_id());
628         req.callback(_rdetailBuildInfoRows);
629         req.send();
630 }
631
632 function _rdetailRows(node) {
633
634         if( rdetailShowLocal && getLocation() != globalOrgTree.id() ) {
635                 var loc = findOrgUnit(getLocation());
636                 if( node ) {
637                         if( !orgIsMine(node, loc) && !orgIsMine(loc,node) ) return;
638                 } else {
639                         for( var i = 0; i < globalOrgTree.children().length; i++ ) {
640                                 var org = findOrgUnit(globalOrgTree.children()[i]);
641                                 if( orgIsMine(org, loc) ) {
642                                         node = org;
643                                         break;
644                                 }
645                         }
646                 } 
647         }
648
649         if(!node && findOrgType(globalOrgTree.ou_type()).can_have_vols())
650                 node = globalOrgTree;
651
652
653         /* don't show hidden orgs */
654
655         if(node) {
656
657                 if(!isXUL() && !isTrue(node.opac_visible())) return;
658
659                 var row = copyRow.cloneNode(true);
660                 row.id = "cp_info_" + node.id();
661
662                 var libtd = findNodeByName( row, config.names.rdetail.lib_cell );
663                 var cntd  = findNodeByName( row, config.names.rdetail.cn_cell );
664                 var cpctd = findNodeByName( row, config.names.rdetail.cp_count_cell );
665                 var actions = $n(row, 'rdetail_actions_cell');
666
667                 var p = libtd.getElementsByTagName('a')[0];
668                 libtd.insertBefore(text(node.name()), p);
669                 libtd.setAttribute("style", "padding-left: " + ((findOrgDepth(node) - 1)  * 9) + "px;");
670
671                 if(!findOrgType(node.ou_type()).can_have_vols()) {
672
673                         row.removeChild(cntd);
674                         row.removeChild(cpctd);
675                         row.removeChild(actions);
676                         row.setAttribute('novols', '1');
677
678                         libtd.setAttribute("colspan", numStatuses + 3 );
679                         libtd.colSpan = numStatuses + 3;
680                         addCSSClass(row, 'copy_info_region_row');
681                 } 
682
683                 copyRowParent.appendChild(row);
684
685         } else { node = globalOrgTree; }
686
687         for( var c in node.children() ) 
688                 _rdetailRows(node.children()[c]);
689 }
690
691 function rdetailCNPrint(orgid, cn) {
692         var div = cpdBuildPrintWindow( record, orgid);
693         var template = div.removeChild($n(div, 'cnrow'));
694         var rowNode = $("cp_info_" + orgid);
695         cpdStylePopupWindow(div);
696         openWindow(div.innerHTML);
697 }
698
699 var localCNFound = false;
700 var ctr = 0;
701 function _rdetailBuildInfoRows(r) {
702
703         if (rdetailShowCopyLocation)
704                 unHideMe( $n( $('rdetail_copy_info_table'), 'rdetail_copylocation_header' ) );
705
706         removeChildren(copyRowParent);
707
708         _rdetailRows();
709
710         var summary = r.getResultObject();
711         if(!summary) return;
712
713         var found = false;
714         for( var i = 0; i < summary.length; i++ ) {
715
716                 var arr = summary[i];
717                 globalCNCache[arr[1]] = 1;
718                 var thisOrg = findOrgUnit(arr[0]);
719                 var rowNode = $("cp_info_" + thisOrg.id());
720                 if(!rowNode) continue;
721
722                 if(rowNode.getAttribute("used")) {
723
724                         if( rowNode.nextSibling ) {
725                                 sib = rowNode.nextSibling;
726                                 o ='cp_info_'+thisOrg.id()+'_';
727                                 /* push the new row on as the last row for this org unit */
728                                 while( sib && sib.id.match(o) ) {
729                                         sib = sib.nextSibling;
730                                 }
731                                 if(sib)
732                                         rowNode = copyRowParent.insertBefore(copyRow.cloneNode(true), sib);
733                                 else
734                                         rowNode = copyRowParent.appendChild(copyRow.cloneNode(true));
735                         } else {
736                                 rowNode = copyRowParent.appendChild(copyRow.cloneNode(true));
737                         }
738
739                         var n = findNodeByName( rowNode, config.names.rdetail.lib_cell );
740                         n.appendChild(text(thisOrg.name()));
741                         n.setAttribute("style", "padding-left: " + ((findOrgDepth(thisOrg) - 1)  * 9) + "px;");
742                         rowNode.id = "cp_info_" + thisOrg.id() + '_' + (++ctr); 
743
744                 } else {
745                         rowNode.setAttribute("used", "1");
746                 }
747
748                 var cpc_temp = rowNode.removeChild(
749                                 findNodeByName(rowNode, config.names.rdetail.cp_count_cell));
750
751                 var statuses = arr[2];
752                 var cl = '';
753                 if (rdetailShowCopyLocation) {
754                         cl = arr[2];
755                         statuses = arr[3];
756                 }
757
758
759                 rdetailApplyStatuses(rowNode, cpc_temp, statuses);
760
761                 var isLocal = false;
762                 if( orgIsMine( findOrgUnit(getLocation()), thisOrg ) ) { 
763                         found = true; 
764                         isLocal = true; 
765                         if(!localCNFound) {
766                                 localCNFound = true;
767                                 defaultCN = arr[1];
768                         }
769                 }
770
771                 //if(isLocal) unHideMe(rowNode);
772                 unHideMe(rowNode);
773
774                 rdetailSetPath( thisOrg, isLocal );
775                 rdetailBuildBrowseInfo( rowNode, arr[1], isLocal, thisOrg, cl );
776
777                 if( i == summary.length - 1 && !defaultCN) defaultCN = arr[1];
778         }
779
780         if(!found) unHideMe(G.ui.rdetail.cp_info_none);
781 }
782
783 function rdetailBuildBrowseInfo(row, cn, local, orgNode, cl) {
784
785         if(local) {
786                 var cache = callnumberCache[cn];
787                 if( cache ) cache.count++;
788                 else callnumberCache[cn] = { count : 1 };
789         }
790
791         var depth = getDepth();
792         if( !local ) depth = findOrgDepth(globalOrgTree);
793
794         $n(row, 'rdetail_callnumber_cell').appendChild(text(cn));
795
796         if (rdetailShowCopyLocation) {
797                 var cl_cell = $n(row, 'rdetail_copylocation_cell');
798                 cl_cell.appendChild(text(cl));
799                 unHideMe(cl_cell);
800         }
801
802         _debug('setting action clicks for cn ' + cn);
803
804         var dHref = 'javascript:rdetailVolumeDetails('+
805                         '{copy_location : "'+cl+'", rowid : "'+row.id+'", cn :"'+cn+'", depth:"'+depth+'", org:"'+orgNode.id()+'", local: '+local+'});';
806
807         var bHref = 'javascript:rdetailShowCNBrowse("' + cn + '", '+orgNode.id()+', "'+depth+'");'; 
808
809         unHideMe( $n(row, 'details') )
810                 $n(row, 'details').setAttribute('href', dHref);
811         unHideMe( $n(row, 'browse') )
812                 $n(row, 'browse').setAttribute('href', bHref);
813
814         if(isXUL()) {
815                 unHideMe($n(row, 'hold_div'));
816                 $n(row, 'hold').onclick = function() {
817                         var req = new Request(FETCH_VOLUME_BY_INFO, cn, record.doc_id(), orgNode.id());
818                         req.callback(
819                                         function(r) {
820                                         var vol = r.getResultObject();
821                                         holdsDrawEditor({type: 'V', volumeObject : vol});
822                                         }
823                                     );
824                         req.send();
825                 };
826         }
827 }
828
829 // sets the path to org as 'active' and displays the path if it's local 
830 function rdetailSetPath(org, local) {
831         if( findOrgDepth(org) == 0 ) return;
832         var row = $("cp_info_" + org.id());
833         row.setAttribute("hasinfo", "1");
834         unHideMe(row);
835         rdetailSetPath(findOrgUnit(org.parent_ou()), local);
836 }
837
838 //Append all the statuses for a given summary to the 
839 //copy summary table 
840 function rdetailApplyStatuses( row, template, statuses ) {
841         for( var j in _statusPositions ) {
842                 var stat = _statusPositions[j];
843                 var val = statuses[stat.id()];
844                 var nn = template.cloneNode(true);
845                 if(val) nn.appendChild(text(val));
846                 else nn.appendChild(text(0));
847                 row.appendChild(nn);
848         }
849 }
850
851 //Add one td (creating a new column) to the copy summary
852 //table for each opac_visible copy status
853 function rdetailBuildStatusColumns() {
854
855         rdetailGrabCopyStatuses();
856         var parent = statusRow;
857         var template = parent.removeChild(G.ui.rdetail.cp_status);
858
859         var i = 0;
860         for( i = 0; i < cp_statuses.length; i++ ) {
861
862                 var c = cp_statuses[i];
863                 if( c && isTrue(c.opac_visible()) ) {
864                         var name = c.name();
865                         _statusPositions[i] = c;
866                         var node = template.cloneNode(true);
867                         var data = findNodeByName( node, config.names.rdetail.cp_status);
868
869                         data.appendChild(text(name));
870                         parent.appendChild(node);
871                 }
872         }       
873
874         numStatuses = 0;
875         for(x in _statusPositions) numStatuses++; 
876 }
877
878 function rdetailGrabCopyStatuses() {
879         if(cp_statuses) return cp_statuses;
880         var req = new Request(FETCH_COPY_STATUSES);
881         req.send(true);
882         cp_statuses = req.result();
883         cp_statuses = cp_statuses.sort(_rdetailSortStatuses);
884 }
885
886 function _rdetailSortStatuses(a, b) {
887         return parseInt(a.id()) - parseInt(b.id());
888 }
889
890 /**
891  * Check for a Google Book preview 
892  */
893 function rdetailCheckForGBPreview() {
894         if (!googleBookPreview) return;
895         searchForGBPreview( cleanISBN(record.isbn()) );
896 }
897
898 /**
899  *
900  * @param {DOM object} query The form element containing the
901  *                     input parameters "isbns"
902  */
903 function searchForGBPreview( isbn ) {
904
905         // Delete any previous Google Booksearch JSON queries.
906         var GBPJsonScript = document.getElementById("GBPJsonScript");
907         if (GBPJsonScript) {
908                 GBPJsonScript.parentNode.removeChild(GBPJsonScript);
909         }
910
911         // Add a script element with the src as the user's Google Booksearch query. 
912         // JSON output is specified by including the alt=json-in-script argument
913         // and the callback function is also specified as a URI argument.
914         var GBPScriptElement = document.createElement("script");
915
916         GBPScriptElement.setAttribute("id", "GBPJsonScript");
917         GBPScriptElement.setAttribute("src",
918                         "http://books.google.com/books?bibkeys=" + 
919                         isbn + "&jscmd=viewapi&callback=GBPreviewCallback");
920         GBPScriptElement.setAttribute("type", "text/javascript");
921
922         // make the request to Google booksearch
923         document.documentElement.firstChild.appendChild(GBPScriptElement);
924 }
925
926 /**
927  * This function is the call-back function for the JSON scripts which 
928  * executes a Google book search response.
929  *
930  * XXX I18N of text needed
931  *
932  * @param {JSON} booksInfo is the JSON object pulled from the Google books service.
933  */
934 function GBPreviewCallback(GBPBookInfo) {
935         var GBPreviewDiv = document.getElementById("rdetail_preview_div");
936         var GBPBook;
937
938         for ( i in GBPBookInfo ) {
939                 GBPBook = GBPBookInfo[i];
940         }
941
942         if ( !GBPBook ) {
943                 return;
944         }
945
946         if ( GBPBook.preview != "noview" ) {
947                 if ( GBPBook.preview == 'full' ) {
948                         setText( $('rdetail_preview_link'), $('rdetail_preview_full_text').innerHTML );
949                         $('rdetail_preview_link_a').title = $('rdetail_preview_title').innerHTML;      
950                 }
951
952                 // Add a button below the book cover image to load the preview.
953                 GBPBadge = document.createElement( 'img' );
954                 GBPBadge.src = 'http://books.google.com/intl/en/googlebooks/images/gbs_preview_button1.gif';
955                 GBPBadge.title = $('rdetail_preview_badge').innerHTML;
956                 GBPBadge.style.border = 0;
957                 GBPBadgelink = document.createElement( 'a' );
958                 GBPBadgelink.href = 'javascript:rdetailShowExtra("preview");';
959                 GBPBadgelink.appendChild( GBPBadge );
960                 $('rdetail_image_cell').appendChild( GBPBadgelink );
961                 $('rdetail_preview_div').style.height = 600;
962
963                 /* Display the "Preview" tab in the Extras section */
964                 unHideMe( $('rdetail_preview_link' ) );
965         }
966 }
967
968 /**
969  *  This is called when the user clicks on the 'Preview' link.  We assume
970  *  a preview is available from Google if this link was made visible.
971  *
972  * XXX I18N of Google Book Preview language attribute needed
973  */
974 function rdetailDisplayGBPreview() {
975         unHideMe($('rdetail_extras_loading'));
976         GBPreviewPane = $('rdetail_preview_div');
977         if ( GBPreviewPane.getAttribute('loaded') == null ||
978                 GBPreviewPane.getAttribute('loaded') == "false" ) {
979                 google.load("books", "0", {"callback" : rdetailGBPViewerLoadCallback, "language": "en"} );
980                 GBPreviewPane.setAttribute('loaded', 'true');
981         }
982 }
983
984 function rdetailGBPViewerLoadCallback() {
985         hideMe($('rdetail_extras_loading'));
986         var GBPViewer = new google.books.DefaultViewer(document.getElementById('rdetail_preview_div'));
987         GBPViewer.load('ISBN:' + cleanISBN(record.isbn()) );
988
989 }