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