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