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