]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/opac/skin/default/js/rdetail.js
Add a basic UI for creating and deleting MFHD records to the record display in the...
[working/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 req = new Request(DELETE_MFHD_RECORD, G.user.session, holdings.id());
308                         var res = req.send();
309                         alert(dojo.string.substitute(opac_strings.DELETED_MFHD_RECORD, [holdings.id()]));
310                 }, label:"Delete"}).placeAt(mfhd_edit, "last");
311                 // new dijit.MenuItem({onClick:function(){alert("Edit properties " + holdings.id());}, label:opac_strings.EDIT_PROPERTIES}).placeAt(mfhd_edit, "last");
312                 var mfhd_mb = new dijit.form.DropDownButton({dropDown: mfhd_edit, label:opac_strings.EDIT_MFHD_MENU, style:"float:right"});
313                 mfhd_mb.placeAt("mfhdHoldingsCaption" + entryNum, "last");
314                 mfhd_edit.startup();
315         }
316 }
317
318 function _holdingsDrawMFHDEntry(entryNum, entryName, entry) {
319         var flatEntry = entry.toString().replace(/,/g, ', ');
320         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");
321 }
322
323 function _rdetailDraw(r) {
324         record = r.getResultObject();
325
326         runEvt('rdetail', 'recordRetrieved', record.doc_id());
327
328         G.ui.rdetail.title.appendChild(text(record.title()));
329         buildSearchLink(STYPE_AUTHOR, record.author(), G.ui.rdetail.author);
330         G.ui.rdetail.isbn.appendChild(text(cleanISBN(record.isbn())));
331         G.ui.rdetail.edition.appendChild(text(record.edition()));
332         G.ui.rdetail.pubdate.appendChild(text(record.pubdate()));
333         G.ui.rdetail.publisher.appendChild(text(record.publisher()));
334         $('rdetail_physical_desc').appendChild(text(record.physical_description()));
335         r = record.types_of_resource();
336         if(r) {
337                 G.ui.rdetail.tor.appendChild(text(r[0]));
338                 setResourcePic( G.ui.rdetail.tor_pic, r[0]);
339         }
340         G.ui.rdetail.abstr.appendChild(text(record.synopsis()));
341
342         try{
343                 if(record.isbn()) {
344                         if(ENABLE_ADDED_CONTENT_ATTRIB_LINKS) {
345                                 unHideMe($('rdetail.jacket_attrib_div'));
346                                 var href = $('rdetail.jacket_attrib_link').getAttribute('href') +cleanISBN(record.isbn());
347                                 $('rdetail.jacket_attrib_link').setAttribute('href', href);
348                         }
349                         rdetailCheckForGBPreview();
350
351                 } else {
352                         hideMe($("rdetail.jacket_attrib_div"));
353                         hideMe($("rdetail_img_link"));
354                 }
355         } catch(E) {}
356
357
358         // see if the record has any external links 
359         var links = record.online_loc();
360         for( var i = 0; links && links.length > 0 && i < links.length; i = i + 3 ) {
361                 var href = links[i];
362                 // avoid matching "HTTP: The Complete Reference"
363                 if( href.match(/https?:\/|ftps?:\/|mailto:/i) ) {
364                         unHideMe($('rdetail_online_row'));
365                         // MODS can contain a display label (used for the text of the link)
366                         // as well as a note about the URL; many legacy systems conflate the
367                         // two and generate MARC records that expect the note to be used as
368                         // the text of the link, with no display label; here's the canonical
369                         // format:
370                         //
371                         // 856 40 $uhttp://localhost$yDisplay label$zPublic note
372                         //
373                         // Note that the MARC21slim2MODS XSL concatenates $3 and $y together
374                         // (as $y was defined later in MARC21's life as the display label)
375                         var displayLabel = '' + links[i+1];
376                         var note = '' + links[i+2];
377                         if(!displayLabel || displayLabel.match(/https?:\/|ftps?:\/|mailto:/i)) {
378                                 if(!note || note.match(/https?:\/|ftps?:\/|mailto:/i)) {
379                                         displayLabel = href;
380                                 } else {
381                                         displayLabel = note;
382                                 }
383                         }
384                         $('rdetail_online').appendChild(elem('a', {href:href,'class':'classic_link'}, displayLabel));
385                         if (note && note != displayLabel) {
386                                 $('rdetail_online').appendChild(elem('span', {'class':'url_note'}, ' - ' + note));
387                         }
388                         $('rdetail_online').appendChild(elem('br'));
389                 }
390         }
391
392         // Fill in our unAPI ID, if anyone cares
393         var abbrs = document.getElementsByTagName('abbr');
394         var span;
395         for (var i = 0; i < abbrs.length; i = i + 1) {
396                 if (abbrs[i].getAttribute('name') == 'unapi') {
397                         span = abbrs[i];
398                         break;
399                 }
400         }
401         buildunAPISpan( span, 'biblio-record_entry', record.doc_id() );
402
403         $('rdetail_place_hold').setAttribute(
404                         'href','javascript:holdsDrawEditor({record:"'+record.doc_id()+'",type:"T"});');
405
406         var RW = $('rdetail_exp_refworks');
407         if (RW && rdetailEnableRefWorks) {
408
409                 var here = (findOrgUnit(getLocation())).name();
410                 var org_name = here.replace(" ", "+");
411                 var cgi = new CGI();
412
413                 RW.setAttribute(
414                         'href',
415                         rdetailRefWorksHost + '/express/expressimport.asp?vendor='
416                         + org_name
417                         + '&filter=MARC+Format&database=All+MARC+Formats&encoding=65001&url=http%3A%2F%2F'
418                         + cgi.server_name + '/opac/extras/supercat/marctxt/record/'
419                         + record.doc_id()
420                );
421
422                 RW.setAttribute('target', 'RefWorksMain');
423
424                 unHideMe($('rdetail_exp_refworks_span'));
425         }
426
427         $('rdetail_img_link').setAttribute('href', buildISBNSrc(cleanISBN(record.isbn()), 'large'));
428         G.ui.rdetail.image.setAttribute("src", buildISBNSrc(cleanISBN(record.isbn())));
429         runEvt("rdetail", "recordDrawn");
430         recordsCache.push(record);
431
432         rdetailSetExtrasSelector();
433
434         var breq = new Request(FETCH_BRE, [getRid()]);
435         breq.callback( rdetailCheckDeleted );
436         breq.send();
437
438         resultBuildCaches( [ record ] );
439         resultDrawSubjects();
440         resultDrawSeries();
441
442         // grab added content 
443         acCollectData(cleanISBN(record.isbn()), rdetailhandleAC);
444 }
445
446
447
448 function rdetailCheckDeleted(r) {
449         var br = r.getResultObject()[0];
450         if( isTrue(br.deleted()) ) {
451                 hideMe($('rdetail_place_hold'));
452                 $('rdetail_more_actions_selector').disabled = true;
453                 unHideMe($('rdetail_deleted_exp'));
454         }
455 }
456
457 function rdetailSetExtrasSelector() {
458         if(!grabUser()) return;
459         unHideMe($('rdetail_more_actions'));
460
461         var req = new Request( 
462                         FETCH_CONTAINERS, G.user.session, G.user.id(), 'biblio', 'bookbag' );
463         req.callback(rdetailAddBookbags);
464         req.send();
465 }
466
467 function rdetailAddBookbags(r) {
468
469         var containers = r.getResultObject();
470         var selector = $('rdetail_more_actions_selector');
471         var found = false;
472         var index = 3;
473         doSelectorActions(selector);
474
475         for( var i = 0; i != containers.length; i++ ) {
476                 found = true;
477                 var container = containers[i];
478                 insertSelectorVal( selector, index++, container.name(), 
479                                 "container_" + container.id(), rdetailAddToBookbag,  1 );
480         }
481
482         nextContainerIndex = index;
483 }
484
485 var _actions = {};
486 function rdetailNewBookbag() {
487         var name = prompt($('rdetail_bb_new').innerHTML,"");
488         if(!name) return;
489
490         var id;
491         if( id = containerCreate( name ) ) {
492                 alert($('rdetail_bb_success').innerHTML);
493                 var selector = $('rdetail_more_actions_selector');
494                 insertSelectorVal( selector, nextContainerIndex++, name, 
495                                 "container_" + id, rdetailAddToBookbag, 1 );
496                 setSelector( selector, 'start' );
497         }
498 }
499
500
501 function rdetailAddToBookbag() {
502         var selector = $('rdetail_more_actions_selector');
503         var id = selector.options[selector.selectedIndex].value;
504         setSelector( selector, 'start' );
505
506         if( containerCreateItem( id.substring(10), record.doc_id() )) {
507                 alert($('rdetail_bb_item_success').innerHTML);
508         }
509 }
510
511
512 var rdetailMarcFetched = false;
513 function rdetailShowExtra(type, args) {
514
515         hideMe($('rdetail_copy_info_div'));
516         hideMe($('rdetail_reviews_div'));
517         hideMe($('rdetail_toc_div'));
518         hideMe($('rdetail_anotes_div'));
519         hideMe($('rdetail_excerpt_div'));
520         hideMe($('rdetail_preview_div'));
521         hideMe($('rdetail_marc_div'));
522         hideMe($('cn_browse'));
523         hideMe($('rdetail_cn_browse_div'));
524         hideMe($('rdetail_notes_div'));
525
526         removeCSSClass($('rdetail_copy_info_link'), 'rdetail_extras_selected');
527         removeCSSClass($('rdetail_viewcn_link'), 'rdetail_extras_selected');
528         removeCSSClass($('rdetail_reviews_link'), 'rdetail_extras_selected');
529         removeCSSClass($('rdetail_toc_link'), 'rdetail_extras_selected');
530         removeCSSClass($('rdetail_excerpt_link'), 'rdetail_extras_selected');
531         removeCSSClass($('rdetail_preview_link'), 'rdetail_extras_selected');
532         removeCSSClass($('rdetail_anotes_link'), 'rdetail_extras_selected');
533         removeCSSClass($('rdetail_annotation_link'), 'rdetail_extras_selected');
534         removeCSSClass($('rdetail_viewmarc_link'), 'rdetail_extras_selected');
535
536         switch(type) {
537
538                 case "copyinfo": 
539                         unHideMe($('rdetail_copy_info_div')); 
540                         addCSSClass($('rdetail_copy_info_link'), 'rdetail_extras_selected');
541                         break;
542
543                 case "reviews": 
544                         addCSSClass($('rdetail_reviews_link'), 'rdetail_extras_selected');
545                         unHideMe($('rdetail_reviews_div')); 
546                         break;
547
548                 case "excerpt": 
549                         addCSSClass($('rdetail_excerpt_link'), 'rdetail_extras_selected');
550                         unHideMe($('rdetail_excerpt_div'));
551                         break;
552
553                 case "preview": 
554                         addCSSClass($('rdetail_preview_link'), 'rdetail_extras_selected');
555                         unHideMe($('rdetail_preview_div'));
556                         rdetailDisplayGBPreview();
557                         break;
558
559                 case "anotes": 
560                         addCSSClass($('rdetail_anotes_link'), 'rdetail_extras_selected');
561                         unHideMe($('rdetail_anotes_div'));
562                         break;
563
564                 case "toc": 
565                         addCSSClass($('rdetail_toc_link'), 'rdetail_extras_selected');
566                         unHideMe($('rdetail_toc_div'));
567                         break;
568
569                 case "marc": 
570                         addCSSClass($('rdetail_viewmarc_link'), 'rdetail_extras_selected');
571                         unHideMe($('rdetail_marc_div')); 
572                         if(rdetailMarcFetched) return;
573                         unHideMe($('rdetail_extras_loading'));
574                         rdetailMarcFetched = true;
575                         var req = new Request( FETCH_MARC_HTML, record.doc_id() );
576                         req.callback(rdetailViewMarc); 
577                         req.send();
578                         break;
579
580                 case 'cn':
581                         addCSSClass($('rdetail_viewcn_link'), 'rdetail_extras_selected');
582                         unHideMe($('rdetail_cn_browse_div'));
583                         rdetailShowCNBrowse(defaultCN, getLocation(), null, true);
584                         break;
585
586         }
587 }
588
589 function rdetailVolumeDetails(args) {
590         var row = $(args.rowid);
591         var tbody = row.parentNode;
592         cpdBuild( tbody, row, record, args.cn, args.org, args.depth, args.copy_location );
593         return;
594 }
595
596 function rdetailBuildCNList() {
597
598         var select = $('cn_browse_selector');
599         var index = 0;
600         var arr = [];
601         for( var cn in callnumberCache ) arr.push( cn );
602         arr.sort();
603
604         if( arr.length == 0 ) {
605                 hideMe($('rdetail_cn_browse_select_div'));
606                 return;
607         }
608
609         for( var i in arr ) {
610                 var cn = arr[i];
611                 var opt = new Option(cn);
612                 select.options[index++] = opt;
613         }
614         select.onchange = rdetailGatherCN;
615 }
616
617 function rdetailGatherCN() {
618         var cn = getSelectorVal($('cn_browse_selector'));
619         rdetailShowCNBrowse( cn, getLocation(), getDepth(), true );
620         setSelector( $('cn_browse_selector'), cn );
621 }
622
623
624 function rdetailShowCNBrowse( cn, loc, depth, fromOnclick ) {
625
626         if(!cn) {
627                 unHideMe($('cn_browse_none'));
628                 hideMe($('rdetail_cn_browse_select_div'));
629                 return;
630         }
631
632         unHideMe($('rdetail_cn_browse_select_div'));
633         rdetailBuildCNList();
634         setSelector( $('cn_browse_selector'), cn );
635         hideMe($('rdetail_copy_info_div'));
636         hideMe($('rdetail_reviews_div'));
637         hideMe($('rdetail_toc_div'));
638         hideMe($('rdetail_marc_div'));
639         unHideMe($('rdetail_cn_browse_div'));
640         unHideMe($('cn_browse'));
641         if( !rdetailLocalOnly && ! fromOnclick ) depth = findOrgDepth(globalOrgTree);
642         cnBrowseGo(cn, loc, depth);
643 }
644
645 function rdetailhandleAC(data) {
646
647         if( data.reviews.html ) {
648                 $('rdetail_review_container').innerHTML = data.reviews.html;
649                 unHideMe($('rdetail_reviews_link'));
650         }
651
652         if( data.toc.html ) {
653                 $('rdetail_toc_div').innerHTML = data.toc.html;
654                 unHideMe($('rdetail_toc_link'));
655         }
656
657         if( data.excerpt.html ) {
658                 $('rdetail_excerpt_div').innerHTML = data.excerpt.html;
659                 unHideMe($('rdetail_excerpt_link'));
660         }
661
662         if( data.anotes.html ) {
663                 $('rdetail_anotes_div').innerHTML = data.anotes.html;
664                 unHideMe($('rdetail_anotes_link'));
665         }
666 }
667
668 function rdetailShowReviews(r) {
669         hideMe($('rdetail_extras_loading'));
670         var res = r.getResultObject();
671         var par = $('rdetail_reviews_div');
672         var template = par.removeChild($('rdetail_review_template'));
673         if( res && res.length > 0 ) {
674                 unHideMe($('rdetail_reviews_link'));
675                 for( var i = 0; i != res.length; i++ ) {
676                         var rev = res[i];       
677                         if( rev.text && rev.info ) {
678                                 var node = template.cloneNode(true);
679                                 $n(node, 'review_header').appendChild(text(rev.info));
680                                 $n(node, 'review_text').appendChild(text(rev.text));
681                                 par.appendChild(node);
682                         }
683                 }
684         }
685 }
686
687
688 function rdetailShowTOC(r) {
689         hideMe($('rdetail_extras_loading'));
690         var resp = r.getResultObject();
691         if(resp) {
692                 unHideMe($('rdetail_toc_link'));
693                 $('rdetail_toc_div').innerHTML = resp;
694         }
695 }
696
697 function rdetailBuildInfoRows() {
698         var req;
699         var method = FETCH_COPY_COUNTS_SUMMARY;
700         if (rdetailShowCopyLocation)
701                 method = FETCH_COPY_LOCATION_COUNTS_SUMMARY;
702
703         if( rdetailShowLocal ) 
704                 req = new Request(method, record.doc_id(), getLocation(), getDepth())
705         else
706                 req = new Request(method, record.doc_id());
707         req.callback(_rdetailBuildInfoRows);
708         req.send();
709 }
710
711 function _rdetailRows(node) {
712
713         if( rdetailShowLocal && getLocation() != globalOrgTree.id() ) {
714                 var loc = findOrgUnit(getLocation());
715                 if( node ) {
716                         if( !orgIsMine(node, loc) && !orgIsMine(loc,node) ) return;
717                 } else {
718                         for( var i = 0; i < globalOrgTree.children().length; i++ ) {
719                                 var org = findOrgUnit(globalOrgTree.children()[i]);
720                                 if( orgIsMine(org, loc) ) {
721                                         node = org;
722                                         break;
723                                 }
724                         }
725                 } 
726         }
727
728         if(!node && findOrgType(globalOrgTree.ou_type()).can_have_vols())
729                 node = globalOrgTree;
730
731
732         /* don't show hidden orgs */
733
734         if(node) {
735
736                 if(!isXUL() && !isTrue(node.opac_visible())) return;
737
738                 var row = copyRow.cloneNode(true);
739                 row.id = "cp_info_" + node.id();
740
741                 var libtd = findNodeByName( row, config.names.rdetail.lib_cell );
742                 var cntd  = findNodeByName( row, config.names.rdetail.cn_cell );
743                 var cpctd = findNodeByName( row, config.names.rdetail.cp_count_cell );
744                 var actions = $n(row, 'rdetail_actions_cell');
745
746                 var p = libtd.getElementsByTagName('a')[0];
747                 libtd.insertBefore(text(node.name()), p);
748                 libtd.setAttribute("style", "padding-left: " + ((findOrgDepth(node) - 1)  * 9) + "px;");
749
750                 if(!findOrgType(node.ou_type()).can_have_vols()) {
751
752                         row.removeChild(cntd);
753                         row.removeChild(cpctd);
754                         row.removeChild(actions);
755                         row.setAttribute('novols', '1');
756
757                         libtd.setAttribute("colspan", numStatuses + 3 );
758                         libtd.colSpan = numStatuses + 3;
759                         addCSSClass(row, 'copy_info_region_row');
760                 } 
761
762                 copyRowParent.appendChild(row);
763
764         } else { node = globalOrgTree; }
765
766         for( var c in node.children() ) 
767                 _rdetailRows(node.children()[c]);
768 }
769
770 function rdetailCNPrint(orgid, cn) {
771         var div = cpdBuildPrintWindow( record, orgid);
772         var template = div.removeChild($n(div, 'cnrow'));
773         var rowNode = $("cp_info_" + orgid);
774         cpdStylePopupWindow(div);
775         openWindow(div.innerHTML);
776 }
777
778 var localCNFound = false;
779 var ctr = 0;
780 function _rdetailBuildInfoRows(r) {
781
782         if (rdetailShowCopyLocation)
783                 unHideMe( $n( $('rdetail_copy_info_table'), 'rdetail_copylocation_header' ) );
784
785         removeChildren(copyRowParent);
786
787         _rdetailRows();
788
789         var summary = r.getResultObject();
790         if(!summary) return;
791
792         var found = false;
793         for( var i = 0; i < summary.length; i++ ) {
794
795                 var arr = summary[i];
796                 globalCNCache[arr[1]] = 1;
797                 var thisOrg = findOrgUnit(arr[0]);
798                 var rowNode = $("cp_info_" + thisOrg.id());
799                 if(!rowNode) continue;
800
801                 if(rowNode.getAttribute("used")) {
802
803                         if( rowNode.nextSibling ) {
804                                 sib = rowNode.nextSibling;
805                                 o ='cp_info_'+thisOrg.id()+'_';
806                                 /* push the new row on as the last row for this org unit */
807                                 while( sib && sib.id.match(o) ) {
808                                         sib = sib.nextSibling;
809                                 }
810                                 if(sib)
811                                         rowNode = copyRowParent.insertBefore(copyRow.cloneNode(true), sib);
812                                 else
813                                         rowNode = copyRowParent.appendChild(copyRow.cloneNode(true));
814                         } else {
815                                 rowNode = copyRowParent.appendChild(copyRow.cloneNode(true));
816                         }
817
818                         var n = findNodeByName( rowNode, config.names.rdetail.lib_cell );
819                         n.appendChild(text(thisOrg.name()));
820                         n.setAttribute("style", "padding-left: " + ((findOrgDepth(thisOrg) - 1)  * 9) + "px;");
821                         rowNode.id = "cp_info_" + thisOrg.id() + '_' + (++ctr); 
822
823                 } else {
824                         rowNode.setAttribute("used", "1");
825                 }
826
827                 var cpc_temp = rowNode.removeChild(
828                                 findNodeByName(rowNode, config.names.rdetail.cp_count_cell));
829
830                 var statuses = arr[2];
831                 var cl = '';
832                 if (rdetailShowCopyLocation) {
833                         cl = arr[2];
834                         statuses = arr[3];
835                 }
836
837
838                 rdetailApplyStatuses(rowNode, cpc_temp, statuses);
839
840                 var isLocal = false;
841                 if( orgIsMine( findOrgUnit(getLocation()), thisOrg ) ) { 
842                         found = true; 
843                         isLocal = true; 
844                         if(!localCNFound) {
845                                 localCNFound = true;
846                                 defaultCN = arr[1];
847                         }
848                 }
849
850                 //if(isLocal) unHideMe(rowNode);
851                 unHideMe(rowNode);
852
853                 rdetailSetPath( thisOrg, isLocal );
854                 rdetailBuildBrowseInfo( rowNode, arr[1], isLocal, thisOrg, cl );
855
856                 if( i == summary.length - 1 && !defaultCN) defaultCN = arr[1];
857         }
858
859         if(!found) unHideMe(G.ui.rdetail.cp_info_none);
860 }
861
862 function rdetailBuildBrowseInfo(row, cn, local, orgNode, cl) {
863
864         if(local) {
865                 var cache = callnumberCache[cn];
866                 if( cache ) cache.count++;
867                 else callnumberCache[cn] = { count : 1 };
868         }
869
870         var depth = getDepth();
871         if( !local ) depth = findOrgDepth(globalOrgTree);
872
873         $n(row, 'rdetail_callnumber_cell').appendChild(text(cn));
874
875         if (rdetailShowCopyLocation) {
876                 var cl_cell = $n(row, 'rdetail_copylocation_cell');
877                 cl_cell.appendChild(text(cl));
878                 unHideMe(cl_cell);
879         }
880
881         _debug('setting action clicks for cn ' + cn);
882
883         var dHref = 'javascript:rdetailVolumeDetails('+
884                         '{copy_location : "'+cl+'", rowid : "'+row.id+'", cn :"'+cn+'", depth:"'+depth+'", org:"'+orgNode.id()+'", local: '+local+'});';
885
886         var bHref = 'javascript:rdetailShowCNBrowse("' + cn + '", '+orgNode.id()+', "'+depth+'");'; 
887
888         unHideMe( $n(row, 'details') )
889                 $n(row, 'details').setAttribute('href', dHref);
890         unHideMe( $n(row, 'browse') )
891                 $n(row, 'browse').setAttribute('href', bHref);
892
893         if(isXUL()) {
894                 unHideMe($n(row, 'hold_div'));
895                 $n(row, 'hold').onclick = function() {
896                         var req = new Request(FETCH_VOLUME_BY_INFO, cn, record.doc_id(), orgNode.id());
897                         req.callback(
898                                         function(r) {
899                                         var vol = r.getResultObject();
900                                         holdsDrawEditor({type: 'V', volumeObject : vol});
901                                         }
902                                     );
903                         req.send();
904                 };
905         }
906 }
907
908 // sets the path to org as 'active' and displays the path if it's local 
909 function rdetailSetPath(org, local) {
910         if( findOrgDepth(org) == 0 ) return;
911         var row = $("cp_info_" + org.id());
912         row.setAttribute("hasinfo", "1");
913         unHideMe(row);
914         rdetailSetPath(findOrgUnit(org.parent_ou()), local);
915 }
916
917 //Append all the statuses for a given summary to the 
918 //copy summary table 
919 function rdetailApplyStatuses( row, template, statuses ) {
920         for( var j in _statusPositions ) {
921                 var stat = _statusPositions[j];
922                 var val = statuses[stat.id()];
923                 var nn = template.cloneNode(true);
924                 if(val) nn.appendChild(text(val));
925                 else nn.appendChild(text(0));
926                 row.appendChild(nn);
927         }
928 }
929
930 //Add one td (creating a new column) to the copy summary
931 //table for each opac_visible copy status
932 function rdetailBuildStatusColumns() {
933
934         rdetailGrabCopyStatuses();
935         var parent = statusRow;
936         var template = parent.removeChild(G.ui.rdetail.cp_status);
937
938         var i = 0;
939         for( i = 0; i < cp_statuses.length; i++ ) {
940
941                 var c = cp_statuses[i];
942                 if( c && isTrue(c.opac_visible()) ) {
943                         var name = c.name();
944                         _statusPositions[i] = c;
945                         var node = template.cloneNode(true);
946                         var data = findNodeByName( node, config.names.rdetail.cp_status);
947
948                         data.appendChild(text(name));
949                         parent.appendChild(node);
950                 }
951         }       
952
953         numStatuses = 0;
954         for(x in _statusPositions) numStatuses++; 
955 }
956
957 function rdetailGrabCopyStatuses() {
958         if(cp_statuses) return cp_statuses;
959         var req = new Request(FETCH_COPY_STATUSES);
960         req.send(true);
961         cp_statuses = req.result();
962         cp_statuses = cp_statuses.sort(_rdetailSortStatuses);
963 }
964
965 function _rdetailSortStatuses(a, b) {
966         return parseInt(a.id()) - parseInt(b.id());
967 }
968
969 /**
970  * Check for a Google Book preview 
971  */
972 function rdetailCheckForGBPreview() {
973         if (!rdetailGoogleBookPreview) return;
974         searchForGBPreview( cleanISBN(record.isbn()) );
975 }
976
977 /**
978  *
979  * @param {DOM object} query The form element containing the
980  *                     input parameters "isbns"
981  */
982 function searchForGBPreview( isbn ) {
983
984         // Delete any previous Google Booksearch JSON queries.
985         var GBPJsonScript = document.getElementById("GBPJsonScript");
986         if (GBPJsonScript) {
987                 GBPJsonScript.parentNode.removeChild(GBPJsonScript);
988         }
989
990         // Add a script element with the src as the user's Google Booksearch query. 
991         // JSON output is specified by including the alt=json-in-script argument
992         // and the callback function is also specified as a URI argument.
993         var GBPScriptElement = document.createElement("script");
994
995         GBPScriptElement.setAttribute("id", "GBPJsonScript");
996         GBPScriptElement.setAttribute("src",
997                         "http://books.google.com/books?bibkeys=" + 
998                         isbn + "&jscmd=viewapi&callback=GBPreviewCallback");
999         GBPScriptElement.setAttribute("type", "text/javascript");
1000
1001         // make the request to Google booksearch
1002         document.documentElement.firstChild.appendChild(GBPScriptElement);
1003 }
1004
1005 /**
1006  * This function is the call-back function for the JSON scripts which 
1007  * executes a Google book search response.
1008  *
1009  * XXX I18N of text needed
1010  *
1011  * @param {JSON} booksInfo is the JSON object pulled from the Google books service.
1012  */
1013 function GBPreviewCallback(GBPBookInfo) {
1014         var GBPreviewDiv = document.getElementById("rdetail_preview_div");
1015         var GBPBook;
1016
1017         for ( i in GBPBookInfo ) {
1018                 GBPBook = GBPBookInfo[i];
1019         }
1020
1021         if ( !GBPBook ) {
1022                 return;
1023         }
1024
1025         if ( GBPBook.preview != "noview" ) {
1026                 if ( GBPBook.preview == 'full' ) {
1027                         setText( $('rdetail_preview_link'), $('rdetail_preview_full_text').innerHTML );
1028                         $('rdetail_preview_link_a').title = $('rdetail_preview_title').innerHTML;      
1029                 }
1030
1031                 // Add a button below the book cover image to load the preview.
1032                 GBPBadge = document.createElement( 'img' );
1033                 GBPBadge.src = 'http://books.google.com/intl/en/googlebooks/images/gbs_preview_button1.gif';
1034                 GBPBadge.title = $('rdetail_preview_badge').innerHTML;
1035                 GBPBadge.style.border = 0;
1036                 GBPBadgelink = document.createElement( 'a' );
1037                 GBPBadgelink.href = 'javascript:rdetailShowExtra("preview");';
1038                 GBPBadgelink.appendChild( GBPBadge );
1039                 $('rdetail_image_cell').appendChild( GBPBadgelink );
1040                 $('rdetail_preview_div').style.height = 600;
1041
1042                 /* Display the "Preview" tab in the Extras section */
1043                 unHideMe( $('rdetail_preview_link' ) );
1044         }
1045 }
1046
1047 /**
1048  *  This is called when the user clicks on the 'Preview' link.  We assume
1049  *  a preview is available from Google if this link was made visible.
1050  *
1051  * XXX I18N of Google Book Preview language attribute needed
1052  */
1053 function rdetailDisplayGBPreview() {
1054         unHideMe($('rdetail_extras_loading'));
1055         GBPreviewPane = $('rdetail_preview_div');
1056         if ( GBPreviewPane.getAttribute('loaded') == null ||
1057                 GBPreviewPane.getAttribute('loaded') == "false" ) {
1058                 google.load("books", "0", {"callback" : rdetailGBPViewerLoadCallback, "language": "en"} );
1059                 GBPreviewPane.setAttribute('loaded', 'true');
1060         }
1061 }
1062
1063 function rdetailGBPViewerLoadCallback() {
1064         hideMe($('rdetail_extras_loading'));
1065         var GBPViewer = new google.books.DefaultViewer(document.getElementById('rdetail_preview_div'));
1066         GBPViewer.load('ISBN:' + cleanISBN(record.isbn()) );
1067
1068 }