fd7b94a02dd36cbaf1f007bc7a5e924c7ccac645
[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         if (!holdings) { return null; }
356
357         dojo.forEach(holdings, _holdingsDrawMFHD);
358
359         // Populate XUL menus
360         if (isXUL()) {
361                 runEvt('rdetail','MFHDDrawn');
362         }
363 }
364
365 function _holdingsDrawMFHD(holdings, entryNum) {
366
367         var here = findOrgUnit(getLocation());
368         if (getDepth() > 0 || getDepth === 0 ) {
369                 while (getDepth() < findOrgDepth(here))
370                 here = findOrgUnit( here.parent_ou() );
371                 if (!orgIsMine(findOrgUnit(here), findOrgUnit(holdings.owning_lib()))) {
372                         return null;
373                 }
374         }
375
376         var hb = holdings.basic_holdings();
377         var hba = holdings.basic_holdings_add();
378         var hs = holdings.supplement_holdings();
379         var hsa = holdings.supplement_holdings_add();
380         var hi = holdings.index_holdings();
381         var hia = holdings.index_holdings_add();
382         var ho = holdings.online();
383         var hm = holdings.missing();
384         var hinc = holdings.incomplete();
385         var hloc = holdings.location() || 'MFHD';
386
387         if (    hb.length == 0 && hba.length == 0 && hs.length == 0 &&
388                 hsa.length == 0 && hi.length == 0 && hia.length == 0 &&
389                 ho.length == 0 && hm.length == 0 && hinc.length == 0
390         ) {
391
392                 if (isXUL()) {
393                         /* 
394                          * If we have a record, but nothing to show for it, then the
395                          * record is likely empty or corrupt. This gives cataloguers a
396                          * chance to add holdings or correct the record
397                          */
398                         hb = ['PLACEHOLDER'];
399                 } else {
400                         return null;
401                 }
402         }
403
404         // Show entryNum + 1 in staff client for better menu correlation
405         // Maybe this should be holdings.sre_id() instead? (which could get long after time)
406         var entryNumString = '';
407         if (isXUL()) {
408                 var entryNumInc = entryNum + 1;
409                 entryNumString = ' [Entry #'+entryNumInc+'] ';
410         }
411
412         var refNode;
413         if (entryNum > 0) {
414                 refNode = 'rdetail_holdings_table_' + (entryNum - 1);
415         } else {
416                 refNode = 'rdetail_details_table';
417         }
418
419         dojo.place("<table style='width: 100%;' id='rdetail_holdings_table_"+entryNum+"'><caption id='mfhdHoldingsCaption" + entryNum + "' class='rdetail_header color_1'>" +
420                 dojo.string.substitute(opac_strings.HOLDINGS_TABLE_CAPTION, [hloc]) + entryNumString +
421                 "</caption><tbody id='rdetail_holdings_tbody_" + entryNum +
422                 "'></tbody></table>", refNode, "after"
423         );
424         if (hb.length > 0) { _holdingsDrawMFHDEntry(entryNum, opac_strings.BASIC_HOLDINGS, hb); }
425         if (hba.length > 0) { _holdingsDrawMFHDEntry(entryNum, opac_strings.BASIC_HOLDINGS_ADD, hba); }
426         if (hs.length > 0) { _holdingsDrawMFHDEntry(entryNum, opac_strings.SUPPLEMENT_HOLDINGS, hs); }
427         if (hsa.length > 0) { _holdingsDrawMFHDEntry(entryNum, opac_strings.SUPPLEMENT_HOLDINGS_ADD, hsa); }
428         if (hi.length > 0) { _holdingsDrawMFHDEntry(entryNum, opac_strings.INDEX_HOLDINGS, hi); }
429         if (hia.length > 0) { _holdingsDrawMFHDEntry(entryNum, opac_strings.INDEX_HOLDINGS_ADD, hia); }
430         if (ho.length > 0) { _holdingsDrawMFHDEntry(entryNum, opac_strings.ONLINE_VOLUMES, ho); }
431         if (hm.length > 0) { _holdingsDrawMFHDEntry(entryNum, opac_strings.MISSING_VOLUMES, hm); }
432         if (hinc.length > 0) { _holdingsDrawMFHDEntry(entryNum, opac_strings.INCOMPLETE_VOLUMES, hinc); }
433
434         if (isXUL()) {
435                 mfhdDetails.push({ 'id' : holdings.sre_id(), 'label' : hloc, 'entryNum' : entryNum, 'owning_lib' : holdings.owning_lib() });
436                 dojo.require('openils.Event');
437                 dojo.require('openils.PermaCrud');
438                 var mfhd_edit = new dijit.Menu({});
439                 new dijit.MenuItem({onClick: function(){loadMarcEditor(holdings.sre_id())}, label:opac_strings.EDIT_MFHD_RECORD}).placeAt(mfhd_edit, "first");
440                 new dijit.MenuItem({onClick:function(){
441                         // Avoid accidental deletion of MFHD records
442                         if (!confirm(opac_strings.DELETE_MFHD_CONFIRM)) {
443                                 return;
444                         }
445                         var pcrud = new openils.PermaCrud({"authtoken": G.user.session});
446                         var mfhd_rec = pcrud.retrieve("sre", holdings.sre_id());
447                         if (mfhd_rec) {
448                                 pcrud.eliminate(mfhd_rec);
449                                 alert(dojo.string.substitute(opac_strings.DELETED_MFHD_RECORD, [holdings.sre_id()]));
450                         }
451                 }, label:opac_strings.DELETE_MFHD}).placeAt(mfhd_edit, "last");
452                 // new dijit.MenuItem({onClick:function(){alert("Edit properties " + holdings.sre_id());}, label:opac_strings.EDIT_PROPERTIES}).placeAt(mfhd_edit, "last");
453                 var mfhd_mb = new dijit.form.DropDownButton({dropDown: mfhd_edit, label:opac_strings.EDIT_MFHD_MENU, style:"float:right"});
454                 mfhd_mb.placeAt("mfhdHoldingsCaption" + entryNum, "last");
455                 mfhd_edit.startup();
456         }
457 }
458
459 function _holdingsDrawMFHDEntry(entryNum, entryName, entry) {
460         var flatEntry = entry.toString().replace(/,/g, ', ');
461         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");
462 }
463
464 function _rdetailDraw(r) {
465         record = r.getResultObject();
466
467         runEvt('rdetail', 'recordRetrieved', record.doc_id());
468
469         G.ui.rdetail.title.appendChild(text(record.title()));
470         buildSearchLink(STYPE_AUTHOR, record.author(), G.ui.rdetail.author);
471         G.ui.rdetail.isbn.appendChild(text(cleanISBN(record.isbn())));
472         G.ui.rdetail.edition.appendChild(text(record.edition()));
473         G.ui.rdetail.pubdate.appendChild(text(record.pubdate()));
474         G.ui.rdetail.publisher.appendChild(text(record.publisher()));
475         $('rdetail_physical_desc').appendChild(text(record.physical_description()));
476         r = record.types_of_resource();
477         if(r) {
478                 G.ui.rdetail.tor.appendChild(text(r[0]));
479                 setResourcePic( G.ui.rdetail.tor_pic, r[0]);
480         }
481         G.ui.rdetail.abstr.appendChild(text(record.synopsis()));
482
483         try{
484                 if(record.isbn()) {
485                         if(ENABLE_ADDED_CONTENT_ATTRIB_LINKS) {
486                                 unHideMe($('rdetail.jacket_attrib_div'));
487                                 var href = $('rdetail.jacket_attrib_link').getAttribute('href') +cleanISBN(record.isbn());
488                                 $('rdetail.jacket_attrib_link').setAttribute('href', href);
489                         }
490                         rdetailCheckForGBPreview();
491
492                 } else {
493                         hideMe($("rdetail.jacket_attrib_div"));
494                         hideMe($("rdetail_img_link"));
495                 }
496         } catch(E) {}
497
498
499         // see if the record has any external links 
500         var links = record.online_loc();
501         for( var i = 0; links && links.length > 0 && i < links.length; i = i + 3 ) {
502                 var href = links[i];
503                 // avoid matching "HTTP: The Complete Reference"
504                 if( href.match(/https?:\/|ftps?:\/|mailto:/i) ) {
505                         unHideMe($('rdetail_online_row'));
506                         // MODS can contain a display label (used for the text of the link)
507                         // as well as a note about the URL; many legacy systems conflate the
508                         // two and generate MARC records that expect the note to be used as
509                         // the text of the link, with no display label; here's the canonical
510                         // format:
511                         //
512                         // 856 40 $uhttp://localhost$yDisplay label$zPublic note
513                         //
514                         // Note that the MARC21slim2MODS XSL concatenates $3 and $y together
515                         // (as $y was defined later in MARC21's life as the display label)
516                         var displayLabel = '' + links[i+1];
517                         var note = '' + links[i+2];
518                         if(!displayLabel || displayLabel.match(/https?:\/|ftps?:\/|mailto:/i)) {
519                                 if(!note || note.match(/https?:\/|ftps?:\/|mailto:/i)) {
520                                         displayLabel = href;
521                                 } else {
522                                         displayLabel = note;
523                                 }
524                         }
525                         $('rdetail_online').appendChild(elem('a', {href:href,'class':'classic_link'}, displayLabel));
526                         if (note && note != displayLabel) {
527                                 $('rdetail_online').appendChild(elem('span', {'class':'url_note'}, ' - ' + note));
528                         }
529                         $('rdetail_online').appendChild(elem('br'));
530                 }
531         }
532
533         // Fill in our unAPI ID, if anyone cares
534         var abbrs = document.getElementsByTagName('abbr');
535         var span;
536         for (var i = 0; i < abbrs.length; i++) {
537                 if (abbrs[i].getAttribute('name') == 'unapi') {
538                         span = abbrs[i];
539                         break;
540                 }
541         }
542         buildunAPISpan( span, 'biblio-record_entry', record.doc_id() );
543
544         $('rdetail_place_hold').onclick = function() {
545         var src = location.href;
546
547         if(forceLoginSSL && src.match(/^http:/)) {
548
549             src = src.replace(/^http:/, 'https:');
550
551             if(!src.match(/&place_hold=1/)) {
552                 src += '&place_hold=1';
553             }
554
555             location.href = src;
556
557         } else {
558             holdsDrawEditor({record:record.doc_id(), type:'T'});
559         }
560     }
561
562
563         var RW = $('rdetail_exp_refworks');
564         if (RW && rdetailEnableRefWorks) {
565
566                 var here = (findOrgUnit(getLocation())).name();
567                 var org_name = here.replace(" ", "+");
568                 var cgi = new CGI();
569
570                 RW.setAttribute(
571                         'href',
572                         rdetailRefWorksHost + '/express/expressimport.asp?vendor='
573                         + org_name
574                         + '&filter=MARC+Format&database=All+MARC+Formats&encoding=65001&url=http%3A%2F%2F'
575                         + cgi.server_name + '/opac/extras/supercat/marctxt/record/'
576                         + record.doc_id()
577                );
578
579                 RW.setAttribute('target', 'RefWorksMain');
580
581                 unHideMe($('rdetail_exp_refworks_span'));
582         }
583
584         $('rdetail_img_link').setAttribute('href', buildISBNSrc(cleanISBN(record.isbn()), 'large'));
585         G.ui.rdetail.image.setAttribute("src", buildISBNSrc(cleanISBN(record.isbn())));
586         runEvt("rdetail", "recordDrawn");
587         recordsCache.push(record);
588
589         rdetailSetExtrasSelector();
590
591         var breq = new Request(FETCH_BRE, [getRid()]);
592         breq.callback( rdetailCheckDeleted );
593         breq.send();
594
595         //resultBuildCaches( [ record ] );
596         //resultDrawSubjects();
597         //resultDrawSeries();
598
599         // grab added content 
600
601     // Proxied through Evergreen AddedContent module
602         acCollectData(cleanISBN(record.isbn()), rdetailhandleAC);
603
604     var currentISBN = cleanISBN(record.isbn());
605
606     // Not proxied, cross-site javascript
607
608     // ChiliFresh
609     if (chilifresh && chilifresh != '(none)' && currentISBN) {
610         $('chilifreshReviewLink').setAttribute('id','isbn_'+currentISBN);
611         $('chilifreshReviewResult').setAttribute('id','chili_review_'+currentISBN);
612         unHideMe($('rdetail_reviews_link'));
613         unHideMe($('rdetail_chilifresh_reviews'));
614         try {
615             chili_init();
616         } catch(E) {
617             console.log(E + '\n');
618             hideMe($('rdetail_reviews_link'));
619             hideMe($('rdetail_chilifresh_reviews'));
620         }
621     }
622
623     // Novelist
624     if (novelist && currentISBN) {
625         unHideMe($('rdetail_novelist_link'));
626     }
627
628     // Multi-Home / Foreign Items / Peer Bibs
629     var req = new Request( TEST_PEER_BIBS, record.doc_id() );
630     req.callback(function(r){
631         var test = r.getResultObject();
632         if (test == "1") {
633             unHideMe($('rdetail_foreign_items_link'));
634         }
635     }); 
636     req.send();
637 }
638
639
640
641 function rdetailCheckDeleted(r) {
642         var br = r.getResultObject()[0];
643         if( isTrue(br.deleted()) ) {
644                 hideMe($('rdetail_place_hold'));
645                 $('rdetail_more_actions_selector').disabled = true;
646                 unHideMe($('rdetail_deleted_exp'));
647         }
648 }
649
650 function rdetailSetExtrasSelector() {
651         if(!grabUser()) return;
652         unHideMe($('rdetail_more_actions'));
653
654         var req = new Request( 
655                         FETCH_CONTAINERS, G.user.session, G.user.id(), 'biblio', 'bookbag' );
656         req.callback(rdetailAddBookbags);
657         req.send();
658 }
659
660 function rdetailAddBookbags(r) {
661
662         var containers = r.getResultObject();
663         var selector = $('rdetail_more_actions_selector');
664         var found = false;
665         var index = 3;
666         doSelectorActions(selector);
667
668         for( var i = 0; i < containers.length; i++ ) {
669                 found = true;
670                 var container = containers[i];
671                 insertSelectorVal( selector, index++, container.name(), 
672                                 "container_" + container.id(), rdetailAddToBookbag,  1 );
673         }
674
675         nextContainerIndex = index;
676 }
677
678 var _actions = {};
679 function rdetailNewBookbag() {
680         var name = prompt($('rdetail_bb_new').innerHTML,"");
681         if(!name) return;
682
683         var id;
684         if( id = containerCreate( name ) ) {
685                 alert($('rdetail_bb_success').innerHTML);
686                 var selector = $('rdetail_more_actions_selector');
687                 insertSelectorVal( selector, nextContainerIndex++, name, 
688                                 "container_" + id, rdetailAddToBookbag, 1 );
689                 setSelector( selector, 'start' );
690         }
691 }
692
693
694 function rdetailAddToBookbag() {
695         var selector = $('rdetail_more_actions_selector');
696         var id = selector.options[selector.selectedIndex].value;
697         setSelector( selector, 'start' );
698
699         if( containerCreateItem( id.substring(10), record.doc_id() )) {
700                 alert($('rdetail_bb_item_success').innerHTML);
701         }
702 }
703
704
705 var rdetailMarcFetched = false;
706 var rdetailForeignItemsFetched = false;
707 function rdetailShowExtra(type, args) {
708
709         hideMe($('rdetail_copy_info_div'));
710         hideMe($('rdetail_summary_div'));
711         hideMe($('rdetail_reviews_div'));
712         hideMe($('rdetail_toc_div'));
713         hideMe($('rdetail_anotes_div'));
714         hideMe($('rdetail_excerpt_div'));
715         hideMe($('rdetail_preview_div'));
716         hideMe($('rdetail_marc_div'));
717         hideMe($('cn_browse'));
718         hideMe($('rdetail_cn_browse_div'));
719         hideMe($('rdetail_novelist_div'));
720         hideMe($('rdetail_foreign_items_div'));
721         hideMe($('rdetail_notes_div'));
722
723         removeCSSClass($('rdetail_copy_info_link'), 'rdetail_extras_selected');
724         removeCSSClass($('rdetail_viewcn_link'), 'rdetail_extras_selected');
725         removeCSSClass($('rdetail_summary_link'), 'rdetail_extras_selected');
726         removeCSSClass($('rdetail_reviews_link'), 'rdetail_extras_selected');
727         removeCSSClass($('rdetail_toc_link'), 'rdetail_extras_selected');
728         removeCSSClass($('rdetail_excerpt_link'), 'rdetail_extras_selected');
729         removeCSSClass($('rdetail_preview_link'), 'rdetail_extras_selected');
730         removeCSSClass($('rdetail_anotes_link'), 'rdetail_extras_selected');
731         removeCSSClass($('rdetail_annotation_link'), 'rdetail_extras_selected');
732         removeCSSClass($('rdetail_viewmarc_link'), 'rdetail_extras_selected');
733         removeCSSClass($('rdetail_novelist_link'), 'rdetail_extras_selected');
734         removeCSSClass($('rdetail_foreign_items_link'), 'rdetail_extras_selected');
735
736         switch(type) {
737
738                 case "copyinfo": 
739                         unHideMe($('rdetail_copy_info_div')); 
740                         addCSSClass($('rdetail_copy_info_link'), 'rdetail_extras_selected');
741                         break;
742
743         case "summary":
744             addCSSClass($('rdetail_summary_link'), 'rdetail_extras_selected');
745             unHideMe($('rdetail_summary_div'));
746             break;
747
748                 case "reviews": 
749                         addCSSClass($('rdetail_reviews_link'), 'rdetail_extras_selected');
750                         unHideMe($('rdetail_reviews_div')); 
751                         break;
752
753                 case "excerpt": 
754                         addCSSClass($('rdetail_excerpt_link'), 'rdetail_extras_selected');
755                         unHideMe($('rdetail_excerpt_div'));
756                         break;
757
758                 case "preview": 
759                         addCSSClass($('rdetail_preview_link'), 'rdetail_extras_selected');
760                         unHideMe($('rdetail_preview_div'));
761                         rdetailDisplayGBPreview();
762                         break;
763
764                 case "anotes": 
765                         addCSSClass($('rdetail_anotes_link'), 'rdetail_extras_selected');
766                         unHideMe($('rdetail_anotes_div'));
767                         break;
768
769                 case "toc": 
770                         addCSSClass($('rdetail_toc_link'), 'rdetail_extras_selected');
771                         unHideMe($('rdetail_toc_div'));
772                         break;
773
774                 case "marc": 
775                         addCSSClass($('rdetail_viewmarc_link'), 'rdetail_extras_selected');
776                         unHideMe($('rdetail_marc_div')); 
777                         if(rdetailMarcFetched) return;
778                         unHideMe($('rdetail_extras_loading'));
779                         rdetailMarcFetched = true;
780                         var req = new Request( FETCH_MARC_HTML, record.doc_id() );
781                         req.callback(rdetailViewMarc); 
782                         req.send();
783                         break;
784
785                 case "novelist": 
786                         addCSSClass($('rdetail_novelist_link'), 'rdetail_extras_selected');
787                         unHideMe($('rdetail_novelist_div')); 
788                         break;
789
790                 case "foreign_items": 
791                         addCSSClass($('rdetail_foreign_items_link'), 'rdetail_extras_selected');
792                         unHideMe($('rdetail_foreign_items_div')); 
793             if(rdetailForeignItemsFetched) return;
794                         unHideMe($('rdetail_extras_loading'));
795             rdetailForeignItemsFetched = true;
796                         var req = new Request( FETCH_PEER_BIBS, record.doc_id() );
797                         req.callback(rdetailForeignItems); 
798                         req.send();
799                         break;
800
801                 case 'cn':
802                         addCSSClass($('rdetail_viewcn_link'), 'rdetail_extras_selected');
803                         unHideMe($('rdetail_cn_browse_div'));
804                         rdetailShowCNBrowse(defaultCN, getLocation(), null, true);
805                         break;
806
807         }
808 }
809
810 function rdetailVolumeDetails(args) {
811         var row = $(args.rowid);
812         var tbody = row.parentNode;
813         cpdBuild( tbody, row, record, [args.cn_prefix, args.cn, args.cn_suffix], args.org, args.depth, args.copy_location );
814         return;
815 }
816
817 function rdetailBuildCNList() {
818
819         var select = $('cn_browse_selector');
820         var index = 0;
821         var arr = [];
822         for( var cn_json in callnumberCache ) arr.push( cn_json );
823         arr.sort();
824
825         if( arr.length == 0 ) {
826                 hideMe($('rdetail_cn_browse_select_div'));
827                 return;
828         }
829
830         for( var i = 0; i < arr.length; i++ ) {
831                 var cn_json = arr[i];
832         var cn = JSON2js(cn_json);
833         var whole_cn_text = (cn[0] ? cn[0] + ' ' : '') + cn[1] + (cn[2] ? ' ' + cn[2] : '');
834                 var opt = new Option(whole_cn_text,cn_json);
835                 select.options[index++] = opt;
836         }
837         select.onchange = rdetailGatherCN;
838 }
839
840 function rdetailGatherCN() {
841         var cn = getSelectorVal($('cn_browse_selector'));
842         rdetailShowCNBrowse( JSON2js(cn), getLocation(), getDepth(), true );
843         setSelector( $('cn_browse_selector'), cn );
844 }
845
846
847 function rdetailShowCNBrowse( cn, loc, depth, fromOnclick ) {
848
849         if(!cn) {
850                 unHideMe($('cn_browse_none'));
851                 hideMe($('rdetail_cn_browse_select_div'));
852                 return;
853         }
854
855         unHideMe($('rdetail_cn_browse_select_div'));
856         rdetailBuildCNList();
857         setSelector( $('cn_browse_selector'), js2JSON(cn) );
858         hideMe($('rdetail_copy_info_div'));
859         hideMe($('rdetail_reviews_div'));
860         hideMe($('rdetail_summary_div'));
861         hideMe($('rdetail_toc_div'));
862         hideMe($('rdetail_marc_div'));
863         unHideMe($('rdetail_cn_browse_div'));
864         unHideMe($('cn_browse'));
865         if( !rdetailLocalOnly && ! fromOnclick ) depth = findOrgDepth(globalOrgTree);
866         cnBrowseGo(cn, loc, depth);
867 }
868
869 function rdetailhandleAC(data) {
870
871         if( data.summary.html ) {
872                 $('rdetail_summary_div').innerHTML = data.summary.html;
873                 unHideMe($('rdetail_summary_link'));
874         }
875
876         if( data.reviews.html ) {
877                 $('rdetail_review_container').innerHTML = data.reviews.html;
878                 unHideMe($('rdetail_reviews_link'));
879         }
880
881         if( data.toc.html ) {
882                 $('rdetail_toc_div').innerHTML = data.toc.html;
883                 unHideMe($('rdetail_toc_link'));
884         }
885
886         if( data.excerpt.html ) {
887                 $('rdetail_excerpt_div').innerHTML = data.excerpt.html;
888                 unHideMe($('rdetail_excerpt_link'));
889         }
890
891         if( data.anotes.html ) {
892                 $('rdetail_anotes_div').innerHTML = data.anotes.html;
893                 unHideMe($('rdetail_anotes_link'));
894         }
895 }
896
897 function rdetailShowReviews(r) {
898         hideMe($('rdetail_extras_loading'));
899         var res = r.getResultObject();
900         var par = $('rdetail_reviews_div');
901         var template = par.removeChild($('rdetail_review_template'));
902         if( res && res.length > 0 ) {
903                 unHideMe($('rdetail_reviews_link'));
904                 for( var i = 0; i < res.length; i++ ) {
905                         var rev = res[i];       
906                         if( rev.text && rev.info ) {
907                                 var node = template.cloneNode(true);
908                                 $n(node, 'review_header').appendChild(text(rev.info));
909                                 $n(node, 'review_text').appendChild(text(rev.text));
910                                 par.appendChild(node);
911                         }
912                 }
913         }
914 }
915
916
917 function rdetailShowTOC(r) {
918         hideMe($('rdetail_extras_loading'));
919         var resp = r.getResultObject();
920         if(resp) {
921                 unHideMe($('rdetail_toc_link'));
922                 $('rdetail_toc_div').innerHTML = resp;
923         }
924 }
925
926 function rdetailBuildInfoRows() {
927         var req;
928         var method = FETCH_COPY_COUNTS_SUMMARY;
929         if (rdetailShowCopyLocation)
930                 method = FETCH_COPY_LOCATION_COUNTS_SUMMARY;
931         if( rdetailShowLocal ) 
932                 req = new Request(method, record.doc_id(), getLocation(), getDepth())
933         else
934                 req = new Request(method, record.doc_id());
935         req.callback(_rdetailBuildInfoRows);
936         req.send();
937 }
938
939 function _rdetailRows(node) {
940
941         if( rdetailShowLocal && getLocation() != globalOrgTree.id() ) {
942                 var loc = findOrgUnit(getLocation());
943                 if( node ) {
944                         if( !orgIsMine(node, loc) && !orgIsMine(loc,node) ) return;
945                 } else {
946             var kids = globalOrgTree.children();
947             if (kids) {
948                         for( var i = 0; i < kids.length; i++ ) {
949                                 var org = findOrgUnit(kids[i]);
950                                 if( orgIsMine(org, loc) ) {
951                                         node = org;
952                                         break;
953                                 }
954                 }
955                         }
956                 } 
957         }
958
959         if(!node && findOrgType(globalOrgTree.ou_type()).can_have_vols())
960                 node = globalOrgTree;
961
962
963         /* don't show hidden orgs */
964
965         if(node) {
966
967                 if(!isXUL() && !isTrue(node.opac_visible())) return;
968
969                 if (orgHiding) {
970                         if (isTrue( findOrgType(node.ou_type()).can_have_vols() )) {
971                                 if ( ! orgIsMine( orgHiding.org, node, orgHiding.depth ) ) {
972                                         return;
973                                 }
974                         }
975                 }
976
977                 var row = copyRow.cloneNode(true);
978                 row.id = "cp_info_" + node.id();
979
980                 var libtd = findNodeByName( row, config.names.rdetail.lib_cell );
981                 var cntd  = findNodeByName( row, config.names.rdetail.cn_cell );
982                 var cpctd = findNodeByName( row, config.names.rdetail.cp_count_cell );
983                 var actions = $n(row, 'rdetail_actions_cell');
984
985                 var p = libtd.getElementsByTagName('a')[0];
986                 libtd.insertBefore(text(node.name()), p);
987                 libtd.setAttribute("style", "padding-left: " + ((findOrgDepth(node) - 1)  * 9) + "px;");
988
989                 if(!findOrgType(node.ou_type()).can_have_vols()) {
990
991                         row.removeChild(cntd);
992                         row.removeChild(cpctd);
993                         row.removeChild(actions);
994                         row.setAttribute('novols', '1');
995
996                         libtd.setAttribute("colspan", numStatuses + 3 );
997                         libtd.colSpan = numStatuses + 3;
998                         addCSSClass(row, 'copy_info_region_row');
999                 } 
1000
1001                 copyRowParent.appendChild(row);
1002
1003         } else { node = globalOrgTree; }
1004
1005     var kids = node.children();
1006     if (kids) {
1007         for( var c = 0; c < kids.length; c++ ) 
1008                 _rdetailRows(kids[c]);
1009     }
1010 }
1011
1012 function rdetailCNPrint(orgid, cn) {
1013         var div = cpdBuildPrintWindow( record, orgid);
1014         var template = div.removeChild($n(div, 'cnrow'));
1015         var rowNode = $("cp_info_" + orgid);
1016         cpdStylePopupWindow(div);
1017         openWindow(div.innerHTML);
1018 }
1019
1020 var localCNFound = false;
1021 var ctr = 0;
1022 function _rdetailBuildInfoRows(r) {
1023
1024         if (rdetailShowCopyLocation)
1025                 unHideMe( $n( $('rdetail_copy_info_table'), 'rdetail_copylocation_header' ) );
1026
1027         removeChildren(copyRowParent);
1028
1029         orgHiding = checkOrgHiding();
1030
1031         _rdetailRows();
1032
1033         var summary = r.getResultObject();
1034         if(!summary) return;
1035
1036         var found = false;
1037         for( var i = 0; i < summary.length; i++ ) {
1038
1039                 var arr = summary[i];
1040                 globalCNCache[js2JSON([arr[1],arr[2],arr[3]])] = 1; // prefix, label, suffix.  FIXME - Am I used anywhere?
1041                 var thisOrg = findOrgUnit(arr[0]);
1042                 var rowNode = $("cp_info_" + thisOrg.id());
1043                 if(!rowNode) continue;
1044
1045                 if(rowNode.getAttribute("used")) {
1046
1047                         if( rowNode.nextSibling ) {
1048                                 sib = rowNode.nextSibling;
1049                                 o ='cp_info_'+thisOrg.id()+'_';
1050                                 /* push the new row on as the last row for this org unit */
1051                                 while( sib && sib.id.match(o) ) {
1052                                         sib = sib.nextSibling;
1053                                 }
1054                                 if(sib)
1055                                         rowNode = copyRowParent.insertBefore(copyRow.cloneNode(true), sib);
1056                                 else
1057                                         rowNode = copyRowParent.appendChild(copyRow.cloneNode(true));
1058                         } else {
1059                                 rowNode = copyRowParent.appendChild(copyRow.cloneNode(true));
1060                         }
1061
1062                         var n = findNodeByName( rowNode, config.names.rdetail.lib_cell );
1063                         n.appendChild(text(thisOrg.name()));
1064                         n.setAttribute("style", "padding-left: " + ((findOrgDepth(thisOrg) - 1)  * 9) + "px;");
1065                         rowNode.id = "cp_info_" + thisOrg.id() + '_' + (++ctr); 
1066
1067                 } else {
1068                         rowNode.setAttribute("used", "1");
1069                 }
1070
1071                 var cpc_temp = rowNode.removeChild(
1072                                 findNodeByName(rowNode, config.names.rdetail.cp_count_cell));
1073
1074                 var statuses = arr[4];
1075                 var cl = '';
1076                 if (rdetailShowCopyLocation) {
1077                         cl = arr[4];
1078                         statuses = arr[5];
1079                 }
1080
1081
1082                 rdetailApplyStatuses(rowNode, cpc_temp, statuses);
1083
1084                 var isLocal = false;
1085                 if( orgIsMine( findOrgUnit(getLocation()), thisOrg ) ) { 
1086                         found = true; 
1087                         isLocal = true; 
1088                         if(!localCNFound) {
1089                                 localCNFound = true;
1090                                 defaultCN = [arr[1],arr[2],arr[3]]; // prefix, label, suffix
1091                         }
1092                 }
1093
1094                 //if(isLocal) unHideMe(rowNode);
1095                 unHideMe(rowNode);
1096
1097                 rdetailSetPath( thisOrg, isLocal );
1098                 rdetailBuildBrowseInfo( rowNode, [arr[1],arr[2],arr[3]], isLocal, thisOrg, cl );
1099
1100                 if( i == summary.length - 1 && !defaultCN) defaultCN = [arr[1],arr[2],arr[3]]; // prefix, label, suffix
1101         }
1102
1103         if(!found) unHideMe(G.ui.rdetail.cp_info_none);
1104 }
1105
1106 function rdetailBuildBrowseInfo(row, cn, local, orgNode, cl) {
1107
1108     var whole_cn_json = js2JSON(cn);
1109     var whole_cn_text = (cn[0] ? cn[0] + ' ' : '') + cn[1] + (cn[2] ? ' ' + cn[2] : '');
1110
1111         if(local) {
1112                 var cache = callnumberCache[whole_cn_json];
1113                 if( cache ) cache.count++;
1114                 else callnumberCache[whole_cn_json] = { count : 1 };
1115         }
1116
1117         var depth = getDepth();
1118         if( !local ) depth = findOrgDepth(globalOrgTree);
1119
1120         $n(row, 'rdetail_callnumber_cell').appendChild(text(whole_cn_text));
1121
1122         if (rdetailShowCopyLocation) {
1123                 var cl_cell = $n(row, 'rdetail_copylocation_cell');
1124                 cl_cell.appendChild(text(cl));
1125                 unHideMe(cl_cell);
1126         }
1127
1128         _debug('setting action clicks for cn ' + whole_cn_text);
1129
1130         var dHref = 'javascript:rdetailVolumeDetails('+
1131                         '{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+'});';
1132
1133         var bHref = 'javascript:rdetailShowCNBrowse("'+cn[1].replace(/\"/g, '\\"') + '", '+orgNode.id()+', "'+depth+'");'; 
1134
1135         unHideMe( $n(row, 'details') )
1136                 $n(row, 'details').setAttribute('href', dHref);
1137         unHideMe( $n(row, 'browse') )
1138                 $n(row, 'browse').setAttribute('href', bHref);
1139
1140         if(isXUL()) {
1141                 unHideMe($n(row, 'hold_div'));
1142                 $n(row, 'hold').onclick = function() {
1143                         var req = new Request(FETCH_VOLUME_BY_INFO, cn, record.doc_id(), orgNode.id());
1144                         req.callback(
1145                                         function(r) {
1146                                         var vol = r.getResultObject();
1147                                         holdsDrawEditor({type: 'V', volumeObject : vol});
1148                                         }
1149                                     );
1150                         req.send();
1151                 };
1152         }
1153 }
1154
1155 // sets the path to org as 'active' and displays the path if it's local 
1156 function rdetailSetPath(org, local) {
1157         if( findOrgDepth(org) == 0 ) return;
1158         var row = $("cp_info_" + org.id());
1159         row.setAttribute("hasinfo", "1");
1160         unHideMe(row);
1161         rdetailSetPath(findOrgUnit(org.parent_ou()), local);
1162 }
1163
1164 //Append all the statuses for a given summary to the 
1165 //copy summary table 
1166 function rdetailApplyStatuses( row, template, statuses ) {
1167         for( var j in _statusPositions ) {
1168                 var stat = _statusPositions[j];
1169                 var val = statuses[stat.id()];
1170                 var nn = template.cloneNode(true);
1171                 if(val) nn.appendChild(text(val));
1172                 else nn.appendChild(text(0));
1173                 row.appendChild(nn);
1174         }
1175 }
1176
1177 //Add one td (creating a new column) to the copy summary
1178 //table for each opac_visible copy status
1179 function rdetailBuildStatusColumns() {
1180
1181         rdetailGrabCopyStatuses();
1182         var parent = statusRow;
1183         var template = parent.removeChild(G.ui.rdetail.cp_status);
1184
1185         var i = 0;
1186         for( i = 0; i < cp_statuses.length; i++ ) {
1187
1188                 var c = cp_statuses[i];
1189                 if( c && isTrue(c.opac_visible()) ) {
1190                         var name = c.name();
1191                         _statusPositions[i] = c;
1192                         var node = template.cloneNode(true);
1193                         var data = findNodeByName( node, config.names.rdetail.cp_status);
1194
1195                         data.appendChild(text(name));
1196                         parent.appendChild(node);
1197                 }
1198         }       
1199
1200         numStatuses = 0;
1201         for(x in _statusPositions) numStatuses++; 
1202 }
1203
1204 function rdetailGrabCopyStatuses() {
1205         if(cp_statuses) return cp_statuses;
1206         var req = new Request(FETCH_COPY_STATUSES);
1207         req.send(true);
1208         cp_statuses = req.result();
1209         cp_statuses = cp_statuses.sort(_rdetailSortStatuses);
1210 }
1211
1212 function _rdetailSortStatuses(a, b) {
1213         return parseInt(a.id()) - parseInt(b.id());
1214 }
1215
1216 /**
1217  * Check for a Google Book preview after the main page loads
1218  */
1219 function rdetailCheckForGBPreview() {
1220         if (!rdetailGoogleBookPreview) return;
1221         dojo.addOnLoad(function() {
1222                 searchForGBPreview( cleanISBN(record.isbn()) );
1223         });
1224 }
1225
1226 /**
1227  *
1228  * @param {DOM object} isbn The form element containing the input parameters "isbns"
1229  */
1230 function searchForGBPreview( isbn ) {
1231         dojo.require("dojo.io.script");
1232         dojo.io.script.get({"url": "https://www.google.com/jsapi"});
1233         dojo.io.script.get({"url": "http://books.google.com/books", "content": { "bibkeys": isbn, "jscmd": "viewapi", "callback": "GBPreviewCallback"}});
1234 }
1235
1236 /**
1237  * This function is the call-back function for the JSON scripts which 
1238  * executes a Google book search response.
1239  *
1240  * XXX I18N of text needed
1241  *
1242  * @param {JSON} GBPBookInfo is the JSON object pulled from the Google books service.
1243  */
1244 function GBPreviewCallback(GBPBookInfo) {
1245         var GBPreviewDiv = document.getElementById("rdetail_preview_div");
1246         var GBPBook;
1247
1248         for ( i in GBPBookInfo ) {
1249                 GBPBook = GBPBookInfo[i];
1250         }
1251
1252         if ( !GBPBook ) {
1253                 return;
1254         }
1255
1256         if ( GBPBook.preview != "noview" ) {
1257                 // Add a button below the book cover image to load the preview.
1258                 GBPBadge = document.createElement( 'img' );
1259                 GBPBadge.src = 'http://books.google.com/intl/en/googlebooks/images/gbs_preview_button1.gif';
1260                 GBPBadge.title = $('rdetail_preview_badge').innerHTML;
1261                 GBPBadge.style.border = 0;
1262                 GBPBadgelink = document.createElement( 'a' );
1263                 GBPBadgelink.href = 'javascript:rdetailShowExtra("preview");';
1264                 GBPBadgelink.appendChild( GBPBadge );
1265                 $('rdetail_image_cell').appendChild( GBPBadgelink );
1266                 $('rdetail_preview_div').style.height = 600;
1267
1268                 /* Display the "Preview" tab in the Extras section */
1269                 unHideMe( $('rdetail_preview_link' ) );
1270         }
1271 }
1272
1273 /**
1274  *  This is called when the user clicks on the 'Preview' link.  We assume
1275  *  a preview is available from Google if this link was made visible.
1276  *
1277  * XXX I18N of Google Book Preview language attribute needed
1278  */
1279 function rdetailDisplayGBPreview() {
1280         unHideMe($('rdetail_extras_loading'));
1281         GBPreviewPane = $('rdetail_preview_div');
1282         if ( GBPreviewPane.getAttribute('loaded') == null ||
1283                 GBPreviewPane.getAttribute('loaded') == "false" ) {
1284                 google.load("books", "0", {"callback" : rdetailGBPViewerLoadCallback, "language": "en"} );
1285                 GBPreviewPane.setAttribute('loaded', 'true');
1286         }
1287 }
1288
1289 function rdetailGBPViewerLoadCallback() {
1290         hideMe($('rdetail_extras_loading'));
1291         var GBPViewer = new google.books.DefaultViewer(document.getElementById('rdetail_preview_div'));
1292         GBPViewer.load('ISBN:' + cleanISBN(record.isbn()) );
1293
1294 }
1295
1296 function rdetailDrawExpandedHoldings(anchor, bibid, type) {
1297     var offsets = {"basic": 0, "index": 0, "supplement": 0};
1298     var limit = 10; /* XXX give user control over this? */
1299     var target_id = "holding_type_" + type;
1300     var target = dojo.byId(target_id);
1301
1302     anchor.innerHTML = "[-]";
1303     anchor.oldonclick = anchor.onclick;
1304     anchor.onclick = function() {
1305         anchor.onclick = anchor.oldonclick;
1306         anchor.innerHTML = "[+]";
1307         dojo.empty(target);
1308     };
1309
1310     function _load() {
1311         dojo.empty(target);
1312         fieldmapper.standardRequest(
1313             ["open-ils.serial",
1314                 "open-ils.serial.received_siss.retrieve.by_bib.atomic"], {
1315                 "params": [bibid, {"offset": offsets[type], "limit": limit}],
1316                 "async": true,
1317                 "oncomplete": function(r) {
1318                     try {
1319                         if (msg = r.recv().content()) { /* sic, assignment */
1320                             if (!msg.length) return;
1321                             offsets[type] += msg.length;
1322                             var table = dojo.create("table", null, target);
1323                             dojo.forEach(
1324                                 msg, function(o) {
1325                                     var tr = dojo.create("tr", null, table);
1326                                     dojo.create(
1327                                         "td", {
1328                                             "innerHTML": o.issuance.label(),
1329                                             "style": {"paddingLeft": "3em"}
1330                                         }, tr
1331                                     );
1332
1333                                     if (!o.has_units) return;
1334                                     /* can't place holds if no units */
1335                                     var td = dojo.create("td", null, tr);
1336                                     dojo.create(
1337                                         "a", {
1338                                             "href":"javascript:void(0);",
1339                                             "style": {"marginLeft": "1.5em"},
1340                                             "onclick": function() {
1341                                                 holdsDrawEditor({
1342                                                     "type": "I",
1343                                                     "issuance": o.issuance.id()
1344                                                 });
1345                                             },
1346                                             "innerHTML": "[" +
1347                                                 opac_strings.PLACE_HOLD + "]"
1348                                         }, td
1349                                     );
1350                                 }
1351                             );
1352                             if (msg.length == limit) {
1353                                 dojo.create("br", null, target);
1354                                 dojo.create(
1355                                     "a", {
1356                                         "href": "javascript:void(0);",
1357                                         "innerHTML":
1358                                             "[" + opac_strings.MORE + "]",
1359                                         "onclick": _load
1360                                     }, target
1361                                 );
1362                             }
1363                         }
1364                     } catch (E) {
1365                         void(0);
1366                     }
1367                 }
1368             }
1369         );
1370     }
1371     _load();
1372 }