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