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