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