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