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