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