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