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