]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/opac/skin/default/js/rdetail.js
Close LP bug 613551 - JS error in Internet Explorer from google.loader.callbacks...
[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
473     // Proxied through Evergreen AddedContent module
474         acCollectData(cleanISBN(record.isbn()), rdetailhandleAC);
475
476     var currentISBN = cleanISBN(record.isbn());
477
478     // Not proxied, cross-site javascript
479
480     // ChiliFresh
481     if (chilifresh && chilifresh != '(none)' && currentISBN) {
482         $('chilifreshReviewLink').setAttribute('id','isbn_'+currentISBN);
483         $('chilifreshReviewResult').setAttribute('id','chili_review_'+currentISBN);
484         unHideMe($('rdetail_reviews_link'));
485         unHideMe($('rdetail_chilifresh_reviews'));
486         try {
487             chili_init();
488         } catch(E) {
489             dump(E + '\n');
490             hideMe($('rdetail_reviews_link'));
491             hideMe($('rdetail_chilifresh_reviews'));
492         }
493     }
494
495     // Novelist
496     if (novelist && currentISBN) {
497         unHideMe($('rdetail_novelist_link'));
498     }
499 }
500
501
502
503 function rdetailCheckDeleted(r) {
504         var br = r.getResultObject()[0];
505         if( isTrue(br.deleted()) ) {
506                 hideMe($('rdetail_place_hold'));
507                 $('rdetail_more_actions_selector').disabled = true;
508                 unHideMe($('rdetail_deleted_exp'));
509         }
510 }
511
512 function rdetailSetExtrasSelector() {
513         if(!grabUser()) return;
514         unHideMe($('rdetail_more_actions'));
515
516         var req = new Request( 
517                         FETCH_CONTAINERS, G.user.session, G.user.id(), 'biblio', 'bookbag' );
518         req.callback(rdetailAddBookbags);
519         req.send();
520 }
521
522 function rdetailAddBookbags(r) {
523
524         var containers = r.getResultObject();
525         var selector = $('rdetail_more_actions_selector');
526         var found = false;
527         var index = 3;
528         doSelectorActions(selector);
529
530         for( var i = 0; i < containers.length; i++ ) {
531                 found = true;
532                 var container = containers[i];
533                 insertSelectorVal( selector, index++, container.name(), 
534                                 "container_" + container.id(), rdetailAddToBookbag,  1 );
535         }
536
537         nextContainerIndex = index;
538 }
539
540 var _actions = {};
541 function rdetailNewBookbag() {
542         var name = prompt($('rdetail_bb_new').innerHTML,"");
543         if(!name) return;
544
545         var id;
546         if( id = containerCreate( name ) ) {
547                 alert($('rdetail_bb_success').innerHTML);
548                 var selector = $('rdetail_more_actions_selector');
549                 insertSelectorVal( selector, nextContainerIndex++, name, 
550                                 "container_" + id, rdetailAddToBookbag, 1 );
551                 setSelector( selector, 'start' );
552         }
553 }
554
555
556 function rdetailAddToBookbag() {
557         var selector = $('rdetail_more_actions_selector');
558         var id = selector.options[selector.selectedIndex].value;
559         setSelector( selector, 'start' );
560
561         if( containerCreateItem( id.substring(10), record.doc_id() )) {
562                 alert($('rdetail_bb_item_success').innerHTML);
563         }
564 }
565
566
567 var rdetailMarcFetched = false;
568 function rdetailShowExtra(type, args) {
569
570         hideMe($('rdetail_copy_info_div'));
571         hideMe($('rdetail_summary_div'));
572         hideMe($('rdetail_reviews_div'));
573         hideMe($('rdetail_toc_div'));
574         hideMe($('rdetail_anotes_div'));
575         hideMe($('rdetail_excerpt_div'));
576         hideMe($('rdetail_preview_div'));
577         hideMe($('rdetail_marc_div'));
578         hideMe($('cn_browse'));
579         hideMe($('rdetail_cn_browse_div'));
580         hideMe($('rdetail_novelist_div'));
581         hideMe($('rdetail_notes_div'));
582
583         removeCSSClass($('rdetail_copy_info_link'), 'rdetail_extras_selected');
584         removeCSSClass($('rdetail_viewcn_link'), 'rdetail_extras_selected');
585         removeCSSClass($('rdetail_summary_link'), 'rdetail_extras_selected');
586         removeCSSClass($('rdetail_reviews_link'), 'rdetail_extras_selected');
587         removeCSSClass($('rdetail_toc_link'), 'rdetail_extras_selected');
588         removeCSSClass($('rdetail_excerpt_link'), 'rdetail_extras_selected');
589         removeCSSClass($('rdetail_preview_link'), 'rdetail_extras_selected');
590         removeCSSClass($('rdetail_anotes_link'), 'rdetail_extras_selected');
591         removeCSSClass($('rdetail_annotation_link'), 'rdetail_extras_selected');
592         removeCSSClass($('rdetail_viewmarc_link'), 'rdetail_extras_selected');
593         removeCSSClass($('rdetail_novelist_link'), 'rdetail_extras_selected');
594
595         switch(type) {
596
597                 case "copyinfo": 
598                         unHideMe($('rdetail_copy_info_div')); 
599                         addCSSClass($('rdetail_copy_info_link'), 'rdetail_extras_selected');
600                         break;
601
602         case "summary":
603             addCSSClass($('rdetail_summary_link'), 'rdetail_extras_selected');
604             unHideMe($('rdetail_summary_div'));
605             break;
606
607                 case "reviews": 
608                         addCSSClass($('rdetail_reviews_link'), 'rdetail_extras_selected');
609                         unHideMe($('rdetail_reviews_div')); 
610                         break;
611
612                 case "excerpt": 
613                         addCSSClass($('rdetail_excerpt_link'), 'rdetail_extras_selected');
614                         unHideMe($('rdetail_excerpt_div'));
615                         break;
616
617                 case "preview": 
618                         addCSSClass($('rdetail_preview_link'), 'rdetail_extras_selected');
619                         unHideMe($('rdetail_preview_div'));
620                         rdetailDisplayGBPreview();
621                         break;
622
623                 case "anotes": 
624                         addCSSClass($('rdetail_anotes_link'), 'rdetail_extras_selected');
625                         unHideMe($('rdetail_anotes_div'));
626                         break;
627
628                 case "toc": 
629                         addCSSClass($('rdetail_toc_link'), 'rdetail_extras_selected');
630                         unHideMe($('rdetail_toc_div'));
631                         break;
632
633                 case "marc": 
634                         addCSSClass($('rdetail_viewmarc_link'), 'rdetail_extras_selected');
635                         unHideMe($('rdetail_marc_div')); 
636                         if(rdetailMarcFetched) return;
637                         unHideMe($('rdetail_extras_loading'));
638                         rdetailMarcFetched = true;
639                         var req = new Request( FETCH_MARC_HTML, record.doc_id() );
640                         req.callback(rdetailViewMarc); 
641                         req.send();
642                         break;
643
644                 case "novelist": 
645                         addCSSClass($('rdetail_novelist_link'), 'rdetail_extras_selected');
646                         unHideMe($('rdetail_novelist_div')); 
647                         break;
648
649                 case 'cn':
650                         addCSSClass($('rdetail_viewcn_link'), 'rdetail_extras_selected');
651                         unHideMe($('rdetail_cn_browse_div'));
652                         rdetailShowCNBrowse(defaultCN, getLocation(), null, true);
653                         break;
654
655         }
656 }
657
658 function rdetailVolumeDetails(args) {
659         var row = $(args.rowid);
660         var tbody = row.parentNode;
661         cpdBuild( tbody, row, record, args.cn, args.org, args.depth, args.copy_location );
662         return;
663 }
664
665 function rdetailBuildCNList() {
666
667         var select = $('cn_browse_selector');
668         var index = 0;
669         var arr = [];
670         for( var cn in callnumberCache ) arr.push( cn );
671         arr.sort();
672
673         if( arr.length == 0 ) {
674                 hideMe($('rdetail_cn_browse_select_div'));
675                 return;
676         }
677
678         for( var i = 0; i < arr.length; i++ ) {
679                 var cn = arr[i];
680                 var opt = new Option(cn);
681                 select.options[index++] = opt;
682         }
683         select.onchange = rdetailGatherCN;
684 }
685
686 function rdetailGatherCN() {
687         var cn = getSelectorVal($('cn_browse_selector'));
688         rdetailShowCNBrowse( cn, getLocation(), getDepth(), true );
689         setSelector( $('cn_browse_selector'), cn );
690 }
691
692
693 function rdetailShowCNBrowse( cn, loc, depth, fromOnclick ) {
694
695         if(!cn) {
696                 unHideMe($('cn_browse_none'));
697                 hideMe($('rdetail_cn_browse_select_div'));
698                 return;
699         }
700
701         unHideMe($('rdetail_cn_browse_select_div'));
702         rdetailBuildCNList();
703         setSelector( $('cn_browse_selector'), cn );
704         hideMe($('rdetail_copy_info_div'));
705         hideMe($('rdetail_reviews_div'));
706         hideMe($('rdetail_summary_div'));
707         hideMe($('rdetail_toc_div'));
708         hideMe($('rdetail_marc_div'));
709         unHideMe($('rdetail_cn_browse_div'));
710         unHideMe($('cn_browse'));
711         if( !rdetailLocalOnly && ! fromOnclick ) depth = findOrgDepth(globalOrgTree);
712         cnBrowseGo(cn, loc, depth);
713 }
714
715 function rdetailhandleAC(data) {
716
717         if( data.summary.html ) {
718                 $('rdetail_summary_div').innerHTML = data.summary.html;
719                 unHideMe($('rdetail_summary_link'));
720         }
721
722         if( data.reviews.html ) {
723                 $('rdetail_review_container').innerHTML = data.reviews.html;
724                 unHideMe($('rdetail_reviews_link'));
725         }
726
727         if( data.toc.html ) {
728                 $('rdetail_toc_div').innerHTML = data.toc.html;
729                 unHideMe($('rdetail_toc_link'));
730         }
731
732         if( data.excerpt.html ) {
733                 $('rdetail_excerpt_div').innerHTML = data.excerpt.html;
734                 unHideMe($('rdetail_excerpt_link'));
735         }
736
737         if( data.anotes.html ) {
738                 $('rdetail_anotes_div').innerHTML = data.anotes.html;
739                 unHideMe($('rdetail_anotes_link'));
740         }
741 }
742
743 function rdetailShowReviews(r) {
744         hideMe($('rdetail_extras_loading'));
745         var res = r.getResultObject();
746         var par = $('rdetail_reviews_div');
747         var template = par.removeChild($('rdetail_review_template'));
748         if( res && res.length > 0 ) {
749                 unHideMe($('rdetail_reviews_link'));
750                 for( var i = 0; i < res.length; i++ ) {
751                         var rev = res[i];       
752                         if( rev.text && rev.info ) {
753                                 var node = template.cloneNode(true);
754                                 $n(node, 'review_header').appendChild(text(rev.info));
755                                 $n(node, 'review_text').appendChild(text(rev.text));
756                                 par.appendChild(node);
757                         }
758                 }
759         }
760 }
761
762
763 function rdetailShowTOC(r) {
764         hideMe($('rdetail_extras_loading'));
765         var resp = r.getResultObject();
766         if(resp) {
767                 unHideMe($('rdetail_toc_link'));
768                 $('rdetail_toc_div').innerHTML = resp;
769         }
770 }
771
772 function rdetailBuildInfoRows() {
773         var req;
774         var method = FETCH_COPY_COUNTS_SUMMARY;
775         if (rdetailShowCopyLocation)
776                 method = FETCH_COPY_LOCATION_COUNTS_SUMMARY;
777
778         if( rdetailShowLocal ) 
779                 req = new Request(method, record.doc_id(), getLocation(), getDepth())
780         else
781                 req = new Request(method, record.doc_id());
782         req.callback(_rdetailBuildInfoRows);
783         req.send();
784 }
785
786 function _rdetailRows(node) {
787
788         if( rdetailShowLocal && getLocation() != globalOrgTree.id() ) {
789                 var loc = findOrgUnit(getLocation());
790                 if( node ) {
791                         if( !orgIsMine(node, loc) && !orgIsMine(loc,node) ) return;
792                 } else {
793             var kids = globalOrgTree.children();
794             if (kids) {
795                         for( var i = 0; i < kids.length; i++ ) {
796                                 var org = findOrgUnit(kids[i]);
797                                 if( orgIsMine(org, loc) ) {
798                                         node = org;
799                                         break;
800                                 }
801                 }
802                         }
803                 } 
804         }
805
806         if(!node && findOrgType(globalOrgTree.ou_type()).can_have_vols())
807                 node = globalOrgTree;
808
809
810         /* don't show hidden orgs */
811
812         if(node) {
813
814                 if(!isXUL() && !isTrue(node.opac_visible())) return;
815
816                 var row = copyRow.cloneNode(true);
817                 row.id = "cp_info_" + node.id();
818
819                 var libtd = findNodeByName( row, config.names.rdetail.lib_cell );
820                 var cntd  = findNodeByName( row, config.names.rdetail.cn_cell );
821                 var cpctd = findNodeByName( row, config.names.rdetail.cp_count_cell );
822                 var actions = $n(row, 'rdetail_actions_cell');
823
824                 var p = libtd.getElementsByTagName('a')[0];
825                 libtd.insertBefore(text(node.name()), p);
826                 libtd.setAttribute("style", "padding-left: " + ((findOrgDepth(node) - 1)  * 9) + "px;");
827
828                 if(!findOrgType(node.ou_type()).can_have_vols()) {
829
830                         row.removeChild(cntd);
831                         row.removeChild(cpctd);
832                         row.removeChild(actions);
833                         row.setAttribute('novols', '1');
834
835                         libtd.setAttribute("colspan", numStatuses + 3 );
836                         libtd.colSpan = numStatuses + 3;
837                         addCSSClass(row, 'copy_info_region_row');
838                 } 
839
840                 copyRowParent.appendChild(row);
841
842         } else { node = globalOrgTree; }
843
844     var kids = node.children();
845     if (kids) {
846         for( var c = 0; c < kids.length; c++ ) 
847                 _rdetailRows(kids[c]);
848     }
849 }
850
851 function rdetailCNPrint(orgid, cn) {
852         var div = cpdBuildPrintWindow( record, orgid);
853         var template = div.removeChild($n(div, 'cnrow'));
854         var rowNode = $("cp_info_" + orgid);
855         cpdStylePopupWindow(div);
856         openWindow(div.innerHTML);
857 }
858
859 var localCNFound = false;
860 var ctr = 0;
861 function _rdetailBuildInfoRows(r) {
862
863         if (rdetailShowCopyLocation)
864                 unHideMe( $n( $('rdetail_copy_info_table'), 'rdetail_copylocation_header' ) );
865
866         removeChildren(copyRowParent);
867
868         _rdetailRows();
869
870         var summary = r.getResultObject();
871         if(!summary) return;
872
873         var found = false;
874         for( var i = 0; i < summary.length; i++ ) {
875
876                 var arr = summary[i];
877                 globalCNCache[arr[1]] = 1;
878                 var thisOrg = findOrgUnit(arr[0]);
879                 var rowNode = $("cp_info_" + thisOrg.id());
880                 if(!rowNode) continue;
881
882                 if(rowNode.getAttribute("used")) {
883
884                         if( rowNode.nextSibling ) {
885                                 sib = rowNode.nextSibling;
886                                 o ='cp_info_'+thisOrg.id()+'_';
887                                 /* push the new row on as the last row for this org unit */
888                                 while( sib && sib.id.match(o) ) {
889                                         sib = sib.nextSibling;
890                                 }
891                                 if(sib)
892                                         rowNode = copyRowParent.insertBefore(copyRow.cloneNode(true), sib);
893                                 else
894                                         rowNode = copyRowParent.appendChild(copyRow.cloneNode(true));
895                         } else {
896                                 rowNode = copyRowParent.appendChild(copyRow.cloneNode(true));
897                         }
898
899                         var n = findNodeByName( rowNode, config.names.rdetail.lib_cell );
900                         n.appendChild(text(thisOrg.name()));
901                         n.setAttribute("style", "padding-left: " + ((findOrgDepth(thisOrg) - 1)  * 9) + "px;");
902                         rowNode.id = "cp_info_" + thisOrg.id() + '_' + (++ctr); 
903
904                 } else {
905                         rowNode.setAttribute("used", "1");
906                 }
907
908                 var cpc_temp = rowNode.removeChild(
909                                 findNodeByName(rowNode, config.names.rdetail.cp_count_cell));
910
911                 var statuses = arr[2];
912                 var cl = '';
913                 if (rdetailShowCopyLocation) {
914                         cl = arr[2];
915                         statuses = arr[3];
916                 }
917
918
919                 rdetailApplyStatuses(rowNode, cpc_temp, statuses);
920
921                 var isLocal = false;
922                 if( orgIsMine( findOrgUnit(getLocation()), thisOrg ) ) { 
923                         found = true; 
924                         isLocal = true; 
925                         if(!localCNFound) {
926                                 localCNFound = true;
927                                 defaultCN = arr[1];
928                         }
929                 }
930
931                 //if(isLocal) unHideMe(rowNode);
932                 unHideMe(rowNode);
933
934                 rdetailSetPath( thisOrg, isLocal );
935                 rdetailBuildBrowseInfo( rowNode, arr[1], isLocal, thisOrg, cl );
936
937                 if( i == summary.length - 1 && !defaultCN) defaultCN = arr[1];
938         }
939
940         if(!found) unHideMe(G.ui.rdetail.cp_info_none);
941 }
942
943 function rdetailBuildBrowseInfo(row, cn, local, orgNode, cl) {
944
945         if(local) {
946                 var cache = callnumberCache[cn];
947                 if( cache ) cache.count++;
948                 else callnumberCache[cn] = { count : 1 };
949         }
950
951         var depth = getDepth();
952         if( !local ) depth = findOrgDepth(globalOrgTree);
953
954         $n(row, 'rdetail_callnumber_cell').appendChild(text(cn));
955
956         if (rdetailShowCopyLocation) {
957                 var cl_cell = $n(row, 'rdetail_copylocation_cell');
958                 cl_cell.appendChild(text(cl));
959                 unHideMe(cl_cell);
960         }
961
962         _debug('setting action clicks for cn ' + cn);
963
964         var dHref = 'javascript:rdetailVolumeDetails('+
965                         '{copy_location : "'+cl.replace(/\"/g, '\\"')+'", rowid : "'+row.id+'", cn :"'+cn.replace(/\"/g, '\\"')+'", depth:"'+depth+'", org:"'+orgNode.id()+'", local: '+local+'});';
966
967         var bHref = 'javascript:rdetailShowCNBrowse("' + cn.replace(/\"/g, '\\"') + '", '+orgNode.id()+', "'+depth+'");'; 
968
969         unHideMe( $n(row, 'details') )
970                 $n(row, 'details').setAttribute('href', dHref);
971         unHideMe( $n(row, 'browse') )
972                 $n(row, 'browse').setAttribute('href', bHref);
973
974         if(isXUL()) {
975                 unHideMe($n(row, 'hold_div'));
976                 $n(row, 'hold').onclick = function() {
977                         var req = new Request(FETCH_VOLUME_BY_INFO, cn, record.doc_id(), orgNode.id());
978                         req.callback(
979                                         function(r) {
980                                         var vol = r.getResultObject();
981                                         holdsDrawEditor({type: 'V', volumeObject : vol});
982                                         }
983                                     );
984                         req.send();
985                 };
986         }
987 }
988
989 // sets the path to org as 'active' and displays the path if it's local 
990 function rdetailSetPath(org, local) {
991         if( findOrgDepth(org) == 0 ) return;
992         var row = $("cp_info_" + org.id());
993         row.setAttribute("hasinfo", "1");
994         unHideMe(row);
995         rdetailSetPath(findOrgUnit(org.parent_ou()), local);
996 }
997
998 //Append all the statuses for a given summary to the 
999 //copy summary table 
1000 function rdetailApplyStatuses( row, template, statuses ) {
1001         for( var j in _statusPositions ) {
1002                 var stat = _statusPositions[j];
1003                 var val = statuses[stat.id()];
1004                 var nn = template.cloneNode(true);
1005                 if(val) nn.appendChild(text(val));
1006                 else nn.appendChild(text(0));
1007                 row.appendChild(nn);
1008         }
1009 }
1010
1011 //Add one td (creating a new column) to the copy summary
1012 //table for each opac_visible copy status
1013 function rdetailBuildStatusColumns() {
1014
1015         rdetailGrabCopyStatuses();
1016         var parent = statusRow;
1017         var template = parent.removeChild(G.ui.rdetail.cp_status);
1018
1019         var i = 0;
1020         for( i = 0; i < cp_statuses.length; i++ ) {
1021
1022                 var c = cp_statuses[i];
1023                 if( c && isTrue(c.opac_visible()) ) {
1024                         var name = c.name();
1025                         _statusPositions[i] = c;
1026                         var node = template.cloneNode(true);
1027                         var data = findNodeByName( node, config.names.rdetail.cp_status);
1028
1029                         data.appendChild(text(name));
1030                         parent.appendChild(node);
1031                 }
1032         }       
1033
1034         numStatuses = 0;
1035         for(x in _statusPositions) numStatuses++; 
1036 }
1037
1038 function rdetailGrabCopyStatuses() {
1039         if(cp_statuses) return cp_statuses;
1040         var req = new Request(FETCH_COPY_STATUSES);
1041         req.send(true);
1042         cp_statuses = req.result();
1043         cp_statuses = cp_statuses.sort(_rdetailSortStatuses);
1044 }
1045
1046 function _rdetailSortStatuses(a, b) {
1047         return parseInt(a.id()) - parseInt(b.id());
1048 }
1049
1050 /**
1051  * Check for a Google Book preview after the main page loads
1052  */
1053 function rdetailCheckForGBPreview() {
1054         if (!rdetailGoogleBookPreview) return;
1055         dojo.addOnLoad(function() {
1056                 searchForGBPreview( cleanISBN(record.isbn()) );
1057         });
1058 }
1059
1060 /**
1061  *
1062  * @param {DOM object} isbn The form element containing the input parameters "isbns"
1063  */
1064 function searchForGBPreview( isbn ) {
1065         dojo.require("dojo.io.script");
1066         dojo.io.script.get({"url": "https://www.google.com/jsapi"});
1067         dojo.io.script.get({"url": "http://books.google.com/books", "content": { "bibkeys": isbn, "jscmd": "viewapi", "callback": "GBPreviewCallback"}});
1068 }
1069
1070 /**
1071  * This function is the call-back function for the JSON scripts which 
1072  * executes a Google book search response.
1073  *
1074  * XXX I18N of text needed
1075  *
1076  * @param {JSON} GBPBookInfo is the JSON object pulled from the Google books service.
1077  */
1078 function GBPreviewCallback(GBPBookInfo) {
1079         var GBPreviewDiv = document.getElementById("rdetail_preview_div");
1080         var GBPBook;
1081
1082         for ( i in GBPBookInfo ) {
1083                 GBPBook = GBPBookInfo[i];
1084         }
1085
1086         if ( !GBPBook ) {
1087                 return;
1088         }
1089
1090         if ( GBPBook.preview != "noview" ) {
1091                 if ( GBPBook.preview == 'full' ) {
1092                         setText( $('rdetail_preview_link'), $('rdetail_preview_full_text').innerHTML );
1093                         $('rdetail_preview_link_a').title = $('rdetail_preview_title').innerHTML;      
1094                 }
1095
1096                 // Add a button below the book cover image to load the preview.
1097                 GBPBadge = document.createElement( 'img' );
1098                 GBPBadge.src = 'http://books.google.com/intl/en/googlebooks/images/gbs_preview_button1.gif';
1099                 GBPBadge.title = $('rdetail_preview_badge').innerHTML;
1100                 GBPBadge.style.border = 0;
1101                 GBPBadgelink = document.createElement( 'a' );
1102                 GBPBadgelink.href = 'javascript:rdetailShowExtra("preview");';
1103                 GBPBadgelink.appendChild( GBPBadge );
1104                 $('rdetail_image_cell').appendChild( GBPBadgelink );
1105                 $('rdetail_preview_div').style.height = 600;
1106
1107                 /* Display the "Preview" tab in the Extras section */
1108                 unHideMe( $('rdetail_preview_link' ) );
1109         }
1110 }
1111
1112 /**
1113  *  This is called when the user clicks on the 'Preview' link.  We assume
1114  *  a preview is available from Google if this link was made visible.
1115  *
1116  * XXX I18N of Google Book Preview language attribute needed
1117  */
1118 function rdetailDisplayGBPreview() {
1119         unHideMe($('rdetail_extras_loading'));
1120         GBPreviewPane = $('rdetail_preview_div');
1121         if ( GBPreviewPane.getAttribute('loaded') == null ||
1122                 GBPreviewPane.getAttribute('loaded') == "false" ) {
1123                 google.load("books", "0", {"callback" : rdetailGBPViewerLoadCallback, "language": "en"} );
1124                 GBPreviewPane.setAttribute('loaded', 'true');
1125         }
1126 }
1127
1128 function rdetailGBPViewerLoadCallback() {
1129         hideMe($('rdetail_extras_loading'));
1130         var GBPViewer = new google.books.DefaultViewer(document.getElementById('rdetail_preview_div'));
1131         GBPViewer.load('ISBN:' + cleanISBN(record.isbn()) );
1132
1133 }
1134