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