]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/opac/skin/default/js/rdetail.js
Addressing https://bugs.launchpad.net/evergreen/+bug/520632
[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++) {
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 = 0; i < arr.length; i++ ) {
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             var kids = globalOrgTree.children();
720             if (kids) {
721                         for( var i = 0; i < kids.length; i++ ) {
722                                 var org = findOrgUnit(kids[i]);
723                                 if( orgIsMine(org, loc) ) {
724                                         node = org;
725                                         break;
726                                 }
727                 }
728                         }
729                 } 
730         }
731
732         if(!node && findOrgType(globalOrgTree.ou_type()).can_have_vols())
733                 node = globalOrgTree;
734
735
736         /* don't show hidden orgs */
737
738         if(node) {
739
740                 if(!isXUL() && !isTrue(node.opac_visible())) return;
741
742                 var row = copyRow.cloneNode(true);
743                 row.id = "cp_info_" + node.id();
744
745                 var libtd = findNodeByName( row, config.names.rdetail.lib_cell );
746                 var cntd  = findNodeByName( row, config.names.rdetail.cn_cell );
747                 var cpctd = findNodeByName( row, config.names.rdetail.cp_count_cell );
748                 var actions = $n(row, 'rdetail_actions_cell');
749
750                 var p = libtd.getElementsByTagName('a')[0];
751                 libtd.insertBefore(text(node.name()), p);
752                 libtd.setAttribute("style", "padding-left: " + ((findOrgDepth(node) - 1)  * 9) + "px;");
753
754                 if(!findOrgType(node.ou_type()).can_have_vols()) {
755
756                         row.removeChild(cntd);
757                         row.removeChild(cpctd);
758                         row.removeChild(actions);
759                         row.setAttribute('novols', '1');
760
761                         libtd.setAttribute("colspan", numStatuses + 3 );
762                         libtd.colSpan = numStatuses + 3;
763                         addCSSClass(row, 'copy_info_region_row');
764                 } 
765
766                 copyRowParent.appendChild(row);
767
768         } else { node = globalOrgTree; }
769
770     var kids = node.children();
771     if (kids) {
772         for( var c = 0; c < kids.length; c++ ) 
773                 _rdetailRows(kids[c]);
774     }
775 }
776
777 function rdetailCNPrint(orgid, cn) {
778         var div = cpdBuildPrintWindow( record, orgid);
779         var template = div.removeChild($n(div, 'cnrow'));
780         var rowNode = $("cp_info_" + orgid);
781         cpdStylePopupWindow(div);
782         openWindow(div.innerHTML);
783 }
784
785 var localCNFound = false;
786 var ctr = 0;
787 function _rdetailBuildInfoRows(r) {
788
789         if (rdetailShowCopyLocation)
790                 unHideMe( $n( $('rdetail_copy_info_table'), 'rdetail_copylocation_header' ) );
791
792         removeChildren(copyRowParent);
793
794         _rdetailRows();
795
796         var summary = r.getResultObject();
797         if(!summary) return;
798
799         var found = false;
800         for( var i = 0; i < summary.length; i++ ) {
801
802                 var arr = summary[i];
803                 globalCNCache[arr[1]] = 1;
804                 var thisOrg = findOrgUnit(arr[0]);
805                 var rowNode = $("cp_info_" + thisOrg.id());
806                 if(!rowNode) continue;
807
808                 if(rowNode.getAttribute("used")) {
809
810                         if( rowNode.nextSibling ) {
811                                 sib = rowNode.nextSibling;
812                                 o ='cp_info_'+thisOrg.id()+'_';
813                                 /* push the new row on as the last row for this org unit */
814                                 while( sib && sib.id.match(o) ) {
815                                         sib = sib.nextSibling;
816                                 }
817                                 if(sib)
818                                         rowNode = copyRowParent.insertBefore(copyRow.cloneNode(true), sib);
819                                 else
820                                         rowNode = copyRowParent.appendChild(copyRow.cloneNode(true));
821                         } else {
822                                 rowNode = copyRowParent.appendChild(copyRow.cloneNode(true));
823                         }
824
825                         var n = findNodeByName( rowNode, config.names.rdetail.lib_cell );
826                         n.appendChild(text(thisOrg.name()));
827                         n.setAttribute("style", "padding-left: " + ((findOrgDepth(thisOrg) - 1)  * 9) + "px;");
828                         rowNode.id = "cp_info_" + thisOrg.id() + '_' + (++ctr); 
829
830                 } else {
831                         rowNode.setAttribute("used", "1");
832                 }
833
834                 var cpc_temp = rowNode.removeChild(
835                                 findNodeByName(rowNode, config.names.rdetail.cp_count_cell));
836
837                 var statuses = arr[2];
838                 var cl = '';
839                 if (rdetailShowCopyLocation) {
840                         cl = arr[2];
841                         statuses = arr[3];
842                 }
843
844
845                 rdetailApplyStatuses(rowNode, cpc_temp, statuses);
846
847                 var isLocal = false;
848                 if( orgIsMine( findOrgUnit(getLocation()), thisOrg ) ) { 
849                         found = true; 
850                         isLocal = true; 
851                         if(!localCNFound) {
852                                 localCNFound = true;
853                                 defaultCN = arr[1];
854                         }
855                 }
856
857                 //if(isLocal) unHideMe(rowNode);
858                 unHideMe(rowNode);
859
860                 rdetailSetPath( thisOrg, isLocal );
861                 rdetailBuildBrowseInfo( rowNode, arr[1], isLocal, thisOrg, cl );
862
863                 if( i == summary.length - 1 && !defaultCN) defaultCN = arr[1];
864         }
865
866         if(!found) unHideMe(G.ui.rdetail.cp_info_none);
867 }
868
869 function rdetailBuildBrowseInfo(row, cn, local, orgNode, cl) {
870
871         if(local) {
872                 var cache = callnumberCache[cn];
873                 if( cache ) cache.count++;
874                 else callnumberCache[cn] = { count : 1 };
875         }
876
877         var depth = getDepth();
878         if( !local ) depth = findOrgDepth(globalOrgTree);
879
880         $n(row, 'rdetail_callnumber_cell').appendChild(text(cn));
881
882         if (rdetailShowCopyLocation) {
883                 var cl_cell = $n(row, 'rdetail_copylocation_cell');
884                 cl_cell.appendChild(text(cl));
885                 unHideMe(cl_cell);
886         }
887
888         _debug('setting action clicks for cn ' + cn);
889
890         var dHref = 'javascript:rdetailVolumeDetails('+
891                         '{copy_location : "'+cl+'", rowid : "'+row.id+'", cn :"'+cn+'", depth:"'+depth+'", org:"'+orgNode.id()+'", local: '+local+'});';
892
893         var bHref = 'javascript:rdetailShowCNBrowse("' + cn + '", '+orgNode.id()+', "'+depth+'");'; 
894
895         unHideMe( $n(row, 'details') )
896                 $n(row, 'details').setAttribute('href', dHref);
897         unHideMe( $n(row, 'browse') )
898                 $n(row, 'browse').setAttribute('href', bHref);
899
900         if(isXUL()) {
901                 unHideMe($n(row, 'hold_div'));
902                 $n(row, 'hold').onclick = function() {
903                         var req = new Request(FETCH_VOLUME_BY_INFO, cn, record.doc_id(), orgNode.id());
904                         req.callback(
905                                         function(r) {
906                                         var vol = r.getResultObject();
907                                         holdsDrawEditor({type: 'V', volumeObject : vol});
908                                         }
909                                     );
910                         req.send();
911                 };
912         }
913 }
914
915 // sets the path to org as 'active' and displays the path if it's local 
916 function rdetailSetPath(org, local) {
917         if( findOrgDepth(org) == 0 ) return;
918         var row = $("cp_info_" + org.id());
919         row.setAttribute("hasinfo", "1");
920         unHideMe(row);
921         rdetailSetPath(findOrgUnit(org.parent_ou()), local);
922 }
923
924 //Append all the statuses for a given summary to the 
925 //copy summary table 
926 function rdetailApplyStatuses( row, template, statuses ) {
927         for( var j in _statusPositions ) {
928                 var stat = _statusPositions[j];
929                 var val = statuses[stat.id()];
930                 var nn = template.cloneNode(true);
931                 if(val) nn.appendChild(text(val));
932                 else nn.appendChild(text(0));
933                 row.appendChild(nn);
934         }
935 }
936
937 //Add one td (creating a new column) to the copy summary
938 //table for each opac_visible copy status
939 function rdetailBuildStatusColumns() {
940
941         rdetailGrabCopyStatuses();
942         var parent = statusRow;
943         var template = parent.removeChild(G.ui.rdetail.cp_status);
944
945         var i = 0;
946         for( i = 0; i < cp_statuses.length; i++ ) {
947
948                 var c = cp_statuses[i];
949                 if( c && isTrue(c.opac_visible()) ) {
950                         var name = c.name();
951                         _statusPositions[i] = c;
952                         var node = template.cloneNode(true);
953                         var data = findNodeByName( node, config.names.rdetail.cp_status);
954
955                         data.appendChild(text(name));
956                         parent.appendChild(node);
957                 }
958         }       
959
960         numStatuses = 0;
961         for(x in _statusPositions) numStatuses++; 
962 }
963
964 function rdetailGrabCopyStatuses() {
965         if(cp_statuses) return cp_statuses;
966         var req = new Request(FETCH_COPY_STATUSES);
967         req.send(true);
968         cp_statuses = req.result();
969         cp_statuses = cp_statuses.sort(_rdetailSortStatuses);
970 }
971
972 function _rdetailSortStatuses(a, b) {
973         return parseInt(a.id()) - parseInt(b.id());
974 }
975
976 /**
977  * Check for a Google Book preview after the main page loads
978  */
979 function rdetailCheckForGBPreview() {
980         if (!rdetailGoogleBookPreview) return;
981         dojo.addOnLoad(function() {
982                 searchForGBPreview( cleanISBN(record.isbn()) );
983         });
984 }
985
986 /**
987  *
988  * @param {DOM object} isbn The form element containing the input parameters "isbns"
989  */
990 function searchForGBPreview( isbn ) {
991         dojo.require("dojo.io.script");
992         dojo.io.script.get({"url": "https://www.google.com/jsapi"});
993         dojo.io.script.get({"url": "http://books.google.com/books/api.js", "content": {"key": "notsupplied", "callback": "google.loader.callbacks.books"}});
994         dojo.io.script.get({"url": "http://books.google.com/books", "content": { "bibkeys": isbn, "jscmd": "viewapi", "callback": "GBPreviewCallback"}});
995 }
996
997 /**
998  * This function is the call-back function for the JSON scripts which 
999  * executes a Google book search response.
1000  *
1001  * XXX I18N of text needed
1002  *
1003  * @param {JSON} GBPBookInfo is the JSON object pulled from the Google books service.
1004  */
1005 function GBPreviewCallback(GBPBookInfo) {
1006         var GBPreviewDiv = document.getElementById("rdetail_preview_div");
1007         var GBPBook;
1008
1009         for ( i in GBPBookInfo ) {
1010                 GBPBook = GBPBookInfo[i];
1011         }
1012
1013         if ( !GBPBook ) {
1014                 return;
1015         }
1016
1017         if ( GBPBook.preview != "noview" ) {
1018                 if ( GBPBook.preview == 'full' ) {
1019                         setText( $('rdetail_preview_link'), $('rdetail_preview_full_text').innerHTML );
1020                         $('rdetail_preview_link_a').title = $('rdetail_preview_title').innerHTML;      
1021                 }
1022
1023                 // Add a button below the book cover image to load the preview.
1024                 GBPBadge = document.createElement( 'img' );
1025                 GBPBadge.src = 'http://books.google.com/intl/en/googlebooks/images/gbs_preview_button1.gif';
1026                 GBPBadge.title = $('rdetail_preview_badge').innerHTML;
1027                 GBPBadge.style.border = 0;
1028                 GBPBadgelink = document.createElement( 'a' );
1029                 GBPBadgelink.href = 'javascript:rdetailShowExtra("preview");';
1030                 GBPBadgelink.appendChild( GBPBadge );
1031                 $('rdetail_image_cell').appendChild( GBPBadgelink );
1032                 $('rdetail_preview_div').style.height = 600;
1033
1034                 /* Display the "Preview" tab in the Extras section */
1035                 unHideMe( $('rdetail_preview_link' ) );
1036         }
1037 }
1038
1039 /**
1040  *  This is called when the user clicks on the 'Preview' link.  We assume
1041  *  a preview is available from Google if this link was made visible.
1042  *
1043  * XXX I18N of Google Book Preview language attribute needed
1044  */
1045 function rdetailDisplayGBPreview() {
1046         unHideMe($('rdetail_extras_loading'));
1047         GBPreviewPane = $('rdetail_preview_div');
1048         if ( GBPreviewPane.getAttribute('loaded') == null ||
1049                 GBPreviewPane.getAttribute('loaded') == "false" ) {
1050                 google.load("books", "0", {"callback" : rdetailGBPViewerLoadCallback, "language": "en"} );
1051                 GBPreviewPane.setAttribute('loaded', 'true');
1052         }
1053 }
1054
1055 function rdetailGBPViewerLoadCallback() {
1056         hideMe($('rdetail_extras_loading'));
1057         var GBPViewer = new google.books.DefaultViewer(document.getElementById('rdetail_preview_div'));
1058         GBPViewer.load('ISBN:' + cleanISBN(record.isbn()) );
1059
1060 }