9059a17312ecf3c3f89a1d937b4ce2d31e726b06
[evergreen-equinox.git] / Open-ILS / web / opac / skin / kcls / js / misc.js
1 var anonListCache;
2 var webCacheKey;
3 var userVitalStats;
4
5 function opac_init() {
6         var advLink = getId("home_adv_search_link");
7         if(advLink) advLink.setAttribute("href", buildOPACLink({page:ADVANCED})); 
8         getId("home_myopac_link").setAttribute("href", buildOPACLink({page:MYOPAC}, false, true));
9         getId("myopac_link").setAttribute("href", buildOPACLink({page:MYOPAC}, false, true));
10         getOrgs();
11         
12   var u = grabUser();
13   if(u) {
14         unHideMe($('dash_wrapper'));
15           //alert(fetchOrgSettingDefault(G.user.home_ou(), 'auth.persistent_login_interval'));
16         try {
17           var stats = fieldmapper.standardRequest(['open-ils.actor', 'open-ils.actor.user.opac.vital_stats'], {async:false, params:[u.session]});
18         } catch(e){}
19         userVitalStats = stats;
20         if(!stats) return;
21         
22         var dashfines = $('dash_fines');
23         if(stats.fines.balance_owed > 0) {
24                 dashfines.style.color = "#f41d36";
25                 dashfines.innerHTML = "$"+parseFloat(stats.fines.balance_owed).toFixed(2)
26         } else {
27                 dashfines.style.fontWeight="normal";
28                 dashfines.innerHTML = "No";
29         }
30         $('dash_user').innerHTML = u.first_given_name()+' '+u.family_name();
31         $('dash_checked').innerHTML = stats.checkouts.out+stats.checkouts.overdue;
32         $('dash_holds').innerHTML = stats.holds.total;
33         $('dash_pickup').innerHTML = stats.holds.ready;
34   } else unHideMe($('your-acct-login'));
35 }
36
37 function mySuperInitFunction() {
38         G.ui.common.now_searching = elem('div');
39         webCacheKey = cookieManager.read('sessionID');
40         var list = getCacheValue('anonListCache');
41         anonListCache = isTrue(list)?list:[];
42         if(anonListCache.length) try { unHideMe($('cacheListLink')); } catch(e){}
43         
44         if(G.user && G.user.prefs[PREF_DEF_LOCATION]!="1") {
45           G.user.prefs[PREF_DEF_LOCATION]="1";
46           LOCATION = "1";
47           commitUserPrefs();
48           setSelector($('depth_selector'),      getLocation());
49           _newlocation = getLocation();
50         }
51 }
52
53 function setCacheValue(field, value, timeout) {
54         if(!timeout) timeout = '30m';
55         var key = fieldmapper.standardRequest(['open-ils.actor','open-ils.actor.anon_cache.set_value'],{async:false, params:[webCacheKey, field, value]});
56         if(!isTrue(webCacheKey)) {
57                 webCacheKey = key;
58                 cookieManager.write('sessionID', webCacheKey, timeout);
59         }
60         return key;
61 }
62
63 function getCacheValue(field) {
64         if(!isTrue(webCacheKey)) return null;
65         var val = fieldmapper.standardRequest(['open-ils.actor','open-ils.actor.anon_cache.get_value'], {async:false, params:[webCacheKey, field]});
66         return val;
67 }
68
69 function isInAnonList(id) {
70         for(var i in anonListCache) {
71                 if(anonListCache[i] == id) return true;
72         }       
73         return false;
74 }
75
76 var isCacheListDrawn = false;
77 var anonListParent;
78 var anonListTemp;
79 function showCachedList() {
80         if(grabUser()) goTo(buildOPACLink({page:MYOPAC, 'acctpage':6}, false, true));
81         if(!anonListCache.length) {try { hideResultsPage(); } catch(e) {} hideMe($('anonListTable')); hideMe($('cacheListLink')); return;}
82         try { hideResultsPage(true); } catch(e) {}
83         unHideMe($('anonListTable'));
84         if(!isCacheListDrawn) fieldmapper.standardRequest(["open-ils.search","open-ils.search.biblio.record.mods_slim.retrieve"],{async:true, params:[anonListCache], oncomplete:drawCacheList});       
85 }
86
87 function drawCacheList(r) {
88         isCacheListDrawn = true;
89         var bibs = r.recv().content();
90         if(!anonListParent) anonListParent = $('anonListParent');
91         if(!anonListTemp) anonListTemp = anonListParent.removeChild($('anonListTemp'));
92         removeChildren(anonListParent);
93         $('anon_selector').checked = false;
94         
95         if(grabUser()) {
96                 unHideMe($('holdsCacheSel'));
97                 setSelector($('holdsCacheSel'), grabUser().home_ou());
98         }
99         
100         for(var i in bibs) {
101                 var row = anonListTemp.cloneNode(true);
102                 $n(row, 'anon_selector').doc_id = bibs[i].doc_id();
103                 $n(row, 'curr_row').innerHTML = parseInt(i)+1;
104                 $n(row, 'title').innerHTML = bibs[i].title();
105                 anonListParent.appendChild(row);
106         }
107 }
108
109 function createBibHoldObject(org) {
110         if(!G.user) return null;
111         if(!org) org = G.user.home_ou();
112         
113         var node = findOrgUnit(org);
114         var ntype = findOrgType(node.ou_type());
115         if(!ntype.can_have_users()) return null;
116         
117         var hold = new ahr();
118         var interval = fetchOrgSettingDefault(G.user.home_ou(), 'circ.hold_expire_interval');
119         if(!interval) interval = 0;
120         var secs = interval_to_seconds(interval);
121         var expire = new Date();
122         expire.setTime(expire.getTime() + Number(secs + '000'));
123         var expireDate = holdsVerifyThawDate(dojo.date.stamp.toISOString(expire)); 
124         
125         if(expireDate) hold.expire_time(expireDate);
126         hold.phone_notify("");
127         hold.email_notify(0);
128         hold.pickup_lib(org);
129         hold.usr(G.user.id());
130         hold.hold_type("T");
131         hold.frozen('f');
132         hold.thaw_date(null);
133         
134         return hold;
135 }
136
137 function batchHoldMyList(org, parent) {
138         if(!grabUser()) return;
139         if(!org) G.user.home_ou();
140         if(!parent) parent = $('myopac_bookbag_div');
141         
142         var nodes = dojo.query('input[name=list_action_chbx]', parent).filter(function(node, index){ return node.checked; });
143         if(!nodes.length) return;
144         var arr = [];
145         nodes.forEach(function(node, index){ arr.push(node.getAttribute("recordid")); });
146         var error = {err:""};
147         var resp = placeBatchHold(arr, org, error);
148         if(resp == -1) alert("Unable to place holds"); else alert(resp+" hold"+(resp==1?"":"s")+" placed successfully\n\n"+error.err);
149
150 }
151
152 function placeBatchHold(ids, org, error) { // array of bib IDs, pickup lib (optional), error msgs from holds (optional)
153         if(!grabUser() || !ids.length) return -1;
154         if(!org) org = G.user.home_ou();
155         
156         var holds = [];
157         var chkArr = [];
158         for(var i=0; i<ids.length; i++) {
159                 holds[i] = createBibHoldObject(org);
160                 holds[i].target(ids[i]);
161                 chkArr.push({titleid: ids[i], volume_id: undefined, copy_id: undefined, hold_type: "T", patronid: G.user.id(), depth: 0, pickup_lib: org});
162         }
163         
164         var resp = fieldmapper.standardRequest(['open-ils.circ','open-ils.circ.title_hold.is_possible.batch.atomic'], {async:false, params:[grabUser().session, chkArr]});
165         //if(resp.last_event) alert(resp.last_event.payload.fail_part); else alert('Mulit-hold successful\n'+resp.local_avail);
166         
167         var str = "";
168         var errCount = 0;
169         var flag = false;
170         for(var n in resp) {
171                 if(!resp[n].success) {
172                         flag = true;
173                         str+=ids[n]+": "+(resp[n].last_event.desc==""?resp[n].last_event.textcode:resp[n].last_event.desc)+"\n";
174                         errCount++;
175                 }
176         }
177         
178         if(str != "") error.err+=errCount+" hold"+(errCount==1?"":"s")+" not placed successfully\n"+str;
179         if(flag) return 0;
180         
181         var resp2 = fieldmapper.standardRequest(['open-ils.circ','open-ils.circ.holds.create.batch.atomic'], {async:false, params:[grabUser().session, holds]});
182         var count = -1;
183         for(var t in resp2) {
184                 if(typeof(resp2[t]) != "object") count++; else {
185                         str+=ids[t]+": "+resp2[t][0].desc+"\n";
186                         errCount++;
187                 }
188         }
189         if(str != "") error.err+=errCount+" holds not placed successfully\n"+str;
190         return ++count;
191 }
192
193 function placeHoldOnCache() {
194         //holdsDrawWindow(true);
195         var holdsArr = [];
196         dojo.query('input[name=anon_selector]',$('anonListParent')).filter(function(node, index){
197                 if(node.checked) holdsArr.push(node.doc_id+'');
198         });
199         
200         if(!holdsArr.length) return;
201         setCacheValue('saveAnonCache', holdsArr);
202         goTo(buildOPACLink({page:MYOPAC}, false, true));
203 }
204
205 function delSelCache(parent, name) {
206         if(!parent) parent = $('anonListParent');
207         if(!name) name = 'anon_selector';
208         anonListCache = [];
209         var found = false;
210         var nodes = dojo.query('input[name='+name+']',parent);
211         if(!nodes.length) nodes = dojo.query('.'+name,parent);
212         nodes.forEach(function(node, index){
213                 if(!node.checked) anonListCache.push(node.doc_id); else {
214                         found = true;
215                         var holdsLink = $n($('result_table_template_'+node.doc_id), 'result_my_list_link');
216                         if(holdsLink) {
217                                 removeChildren(holdsLink);
218                                 holdsLink.innerHTML = '';
219                                 holdsLink.appendChild(elem('img', {src:'/opac/skin/kcls/graphics/add_mylist.gif'}, null));
220                                 holdsLink.title = "Add to my list";
221                         }
222                 }
223         });
224         
225         if(found) {
226                 isCacheListDrawn = false;
227                 setCacheValue('anonListCache', anonListCache);
228                 if(name=='anon_selector') showCachedList();
229         }
230 }
231
232 String.prototype.trim = function() {
233         return this.replace(/^\s+|\s+$/g,"");
234 }
235 String.prototype.ltrim = function() {
236         return this.replace(/^\s+/,"");
237 }
238 String.prototype.rtrim = function() {
239         return this.replace(/\s+$/,"");
240 }
241
242
243 //////////////////////
244 //Stephen Chapman
245 document.getElementsByClassName = function(cl) {
246 var retnode = [];
247 var myclass = new RegExp('\\b'+cl+'\\b');
248 var elems = document.getElementsByTagName('*');
249 for (var i = 0; i < elems.length; i++) {
250 var classes = elems[i].className;
251 if (myclass.test(classes)) retnode.push(elems[i]);
252 }
253 return retnode;
254 };
255
256 $c = document.getElementsByClassName;
257 ////////////////////////////////////////////////////////////////////////
258
259 function getOrgs() {
260   var tree = $('depth_selector');
261   buildOrgSel(tree, globalOrgTree, 0);
262   setSelector(tree, getLocation());
263   //setSelector(tree, "1");
264 }
265
266 function swapTabs(el) {
267   if(!el) return;
268   var tabs = dojo.query("a",el.parentNode.id);
269   for(var n=0; n< tabs.length;n++) {
270         var i = tabs[n];
271         if(i==el) {
272           unHideMe($(i.rel));
273           i.style.background="url('/opac/skin/kcls/graphics/"+i.id+"_on.gif') no-repeat bottom";
274         } else {
275           hideMe($(i.rel));
276           i.style.background="url('/opac/skin/kcls/graphics/"+i.id+"_off.gif') no-repeat bottom";
277         }
278   }
279 }
280
281 // walk the marc record dom - returns a concatenated string of the requested marc subfields
282 // depth-first recursive function
283 function walkXML(xml,field,subfield) {
284         if(!xml || !field || !subfield) return "";
285         var nodes = (xml.childNodes)?xml.childNodes:null;
286         if(!nodes) return "";
287         var str = "";
288         
289         for(var i=0; i<nodes.length; i++) {
290                 var obj = nodes[i];
291                 if(obj.hasChildNodes()) {
292                         var tag = (obj.nodeName=="datafield")?obj.getAttribute("tag"):"";
293                         if(tag==field) {
294                           for(var n=0; n<obj.childNodes.length; n++){
295                             var child = obj.childNodes[n];
296                             var code = (child.nodeName=="subfield")?child.getAttribute("code"):"";
297                             if(code==subfield) str += (child.textContent)?child.textContent:child.text; // IE check
298                           }
299                         }
300                         str += walkXML(obj,field,subfield);
301                 }
302         }
303         return str;
304 }
305
306 // returns the requested marc data or passes it to callback if present
307 // callback arg is optional
308 function getMarcData(docid, field, subfield, callback) {
309         if(!docid || !field || !subfield) return "";
310         var cgi = new CGI();
311         var xhr = buildXMLRequest();
312         var proto = (location.href.match(/^[Hh][Tt][Tt][Pp][Ss]:/))?"https://":"http://";
313         
314         if(typeof(callback)=="function") {
315                 xhr.onreadystatechange = function() {
316                                 if(xhr.readyState==4 && xhr.status == 200) callback(walkXML(xhr.responseXML.documentElement,field.toLowerCase(),subfield.toLowerCase()), docid);
317                 }
318         }
319         
320         xhr.open("GET",proto+cgi.server_name+"/opac/extras/supercat/retrieve/marcxml/record/"+docid,((callback)?true:false));
321         xhr.send(null);
322         
323         if(typeof(callback)!="function" && xhr.status == 200) {
324                 return walkXML(xhr.responseXML.documentElement,field.toLowerCase(),subfield.toLowerCase());
325         } else return "";
326 }
327
328 function setFormatIcon(imgEl, type) {
329         if(!imgEl) return false;
330         if(!type) { hideMe(imgEl); return false; }
331         var img = "";
332         
333         switch(type.toLowerCase()) {
334           case "a": img="media_book.png"; break;
335           case "b": img="media_magazines.png"; break;
336           case "c": img="media_printedmusic.jpg"; break;
337           case "d": img="media_microform.jpg"; break;
338           case "e": img="media_equipment.png"; break;
339           case "f": img="media_films.png"; break;
340           case "g": img="media_films.png"; break;
341           case "h": img="media_dvd.jpg"; break;
342           case "i": img="media_bookoncassette.jpg"; break;
343           case "j": img="media_musiccd.png"; break;
344           case "k": img="media_musiccassette.jpg"; break;
345           case "l": img="media_musicrecord.jpg"; break;
346           case "m": img="media_software.jpg"; break;
347           case "n": img="media_bookoncd.png"; break;
348           case "o": img="media_kit.jpg"; break;
349           case "p": img="media_newspaper.jpg"; break;
350           case "q": img="media_largeprint.jpg"; break;
351           case "r": img="media_3dobject.jpg"; break;
352           case "s": img="media_slide.jpg"; break;
353           case "t": img="media_online.jpg"; break;
354           case "u": img="media_eaudio.jpg"; break;
355           case "v": img="media_ebooktext.png"; break;
356           case "w": img="media_eaudio.png"; break;
357           case "x": img="media_downloadmusic.png"; break;
358           case "y": img="media_downloadvideo.jpg"; break;
359           case "z": img="media_map.jpg"; break;
360           case "2": img="media_cassettewithbook.png"; break;
361           case "5": img="media_cdwithbook.png"; break;
362         }
363         
364         if(img) {
365                 imgEl.title = get998dValue(type);
366                 dojo.attr(imgEl, "src","/opac/skin/kcls/graphics/"+img);
367                 dojo.attr(imgEl, "alt", get998dValue(type));
368         } else { hideMe(imgEl); return false; }
369         
370         unHideMe(imgEl);
371         return true;
372 }
373
374 function get998dValue(code) {
375         if(!code) code = "";
376         code = code.toLowerCase();
377         var Label = "";
378         
379         switch(code) {
380                 case "a": Label = "Book"; break;
381                 case "i": Label = "Book on cassette"; break;
382                 case "n": Label = "Book on CD"; break;
383                 case "x": Label = "Download music"; break;
384                 case "y": Label = "Download video"; break;
385                 case "h": Label = "DVD"; break;
386                 case "w": Label = "eBook - Audio"; break;
387                 case "v": Label = "eBook - Text"; break;
388                 case "e": Label = "Equipment"; break;
389                 case "f": Label = "Films"; break;
390                 case "o": Label = "Kit"; break;
391                 case "q": Label = "Large print"; break;
392                 case "b": Label = "Magazine"; break;
393                 case "d": Label = "Microform"; break;
394                 case "k": Label = "Music cassette"; break;
395                 case "j": Label = "Music CD"; break;
396                 case "l": Label = "Music LP"; break;
397                 case "p": Label = "Newspaper"; break;
398                 case "t": Label = "Online"; break;
399                 case "u": Label = "Player"; break;
400                 case "c": Label = "Printed music"; break;
401                 case "2": Label = "Read along with cassette"; break;
402                 case "5": Label = "Read along with CD"; break;
403                 case "c": Label = "Scores"; break;
404                 case "m": Label = "Software"; break;
405                 case "g": Label = "Video"; break;
406                 case "r": Label = "3-D Object"; break;
407                 case "z": Label = "Map"; break;
408                 case "s": Label = "Slide set"; break;
409         }
410         return Label;
411 }
412
413 function mapLibUrl(lib) {
414         var url = "";
415         switch(lib) {
416                 case "1489": url = "http://www.kcls.org/algonapacific/"; break;
417                 case "1490": url = "http://www.kcls.org/auburn/"; break;
418                 case "1492": url = "http://www.kcls.org/bellevue/"; break;
419                 case "1491": url = "http://www.kcls.org/blackdiamond/"; break;
420                 case "1493": url = "http://www.kcls.org/bothell/"; break;
421                 case "1494": url = "http://www.kcls.org/boulevardpark/"; break;
422                 case "1495": url = "http://www.kcls.org/burien/"; break;
423                 case "1496": url = "http://www.kcls.org/carnation/"; break;
424                 case "1497": url = "http://www.kcls.org/covington/"; break;
425                 case "1502": url = "http://www.kcls.org/desmoines/"; break;
426                 case "1503": url = "http://www.kcls.org/duvall/"; break;
427                 case "1508": url = "http://www.kcls.org/fairwood/"; break;
428                 case "1506": url = "http://www.kcls.org/fallcity/"; break;
429                 case "1509": url = "http://www.kcls.org/federalway/"; break;
430                 case "1505": url = "http://www.kcls.org/320th/"; break;
431                 case "1507": url = "http://www.kcls.org/foster/"; break;
432                 case "1513": url = "http://www.kcls.org/issaquah/"; break;
433                 case "1519": url = "http://www.kcls.org/kenmore/"; break;
434                 case "1520": url = "http://www.kcls.org/kent/"; break;
435                 case "1517": url = "http://www.kcls.org/kingsgate/"; break;
436                 case "1518": url = "http://www.kcls.org/kirkland/"; break;
437                 case "1521": url = "http://www.kcls.org/lakeforestpark/"; break;
438                 case "1522": url = "http://www.kcls.org/lakehills/"; break;
439                 case "1499": url = "http://www.kcls.org/crossroads/"; break;
440                 case "1538": url = "http://www.kcls.org/southcenter/"; break;
441                 case "1527": url = "http://www.kcls.org/maplevalley/"; break;
442                 case "1525": url = "http://www.kcls.org/mercerisland/"; break;
443                 case "1526": url = "http://www.kcls.org/muckleshoot/"; break;
444                 case "1529": url = "http://www.kcls.org/newportway/"; break;
445                 case "1528": url = "http://www.kcls.org/northbend/"; break;
446                 case "1533": url = "http://www.kcls.org/redmond/"; break;
447                 case "1532": url = "http://www.kcls.org/richmondbeach/"; break;
448                 case "1534": url = "http://www.kcls.org/sammamish/"; break;
449                 case "1536": url = "http://www.kcls.org/skykomish/"; break;
450                 case "1541": url = "http://www.kcls.org/skyway/"; break;
451                 case "1537": url = "http://www.kcls.org/snoqualmie/"; break;
452                 case "1546": url = "http://www.kcls.org/valleyview/"; break;
453                 case "1545": url = "http://www.kcls.org/vashon/"; break;
454                 case "1547": url = "http://www.kcls.org/whitecenter/"; break;
455                 case "1548": url = "http://www.kcls.org/woodinville/"; break;
456                 case "1549": url = "http://www.kcls.org/woodmont/"; break;
457                 case "1535": url = "http://www.kcls.org/shoreline/"; break;
458                 case "1540": url = "http://www.kcls.org/servicecenter/"; break;
459                 case "1510": url = "http://www.kcls.org/greenbridge/"; break;
460                 //case "": url = "http://www.kcls.org/federalway/#closure"; break;
461                 case "1559": url = "http://www.kcls.org/libraryexpress/"; break;
462                 case "1556": url = "http://www.kcls.org/renton/"; break;
463                 case "1557": url = "http://www.kcls.org/rentonhighlands/"; break;
464                 default: url = "";
465         }
466         return url;
467 }
468
469 function checkAll(parent, id, name) {//Object, string
470         var obj = typeof(id)=="object"?id:$(id);
471         if(!parent || !obj) return;
472         if(!name) name = id.toString();
473         var nodes = dojo.query('input[name='+name+']', parent);
474         if(!nodes.length) nodes = dojo.query('.'+name, parent);
475         nodes.forEach(function(node, index){
476                 node.checked = obj.checked;
477         });
478 }
479
480 var blinkMeArr = [];
481 function blinkMe(str,bool) {
482         var obj = $(str);
483         if(!obj) return;
484         
485         if(bool) {
486                 clearInterval(blinkMeArr[str]);
487                 hideMe(obj);
488         } else blinkMeArr[str] = setInterval(function(){
489                 obj.blinker?hideMe(obj):unHideMe(obj);
490                 obj.blinker=!obj.blinker;}, 500);
491 }
492
493 // null out all children of parent obj
494 errCounter=0;
495 errCounter2=0;
496 function destroyObj(obj) {
497         errCounter++;
498         if(!obj) return;
499         errCounter2++;
500         for(var i in obj) {
501                 if(typeof(obj[i])=="function" && i=="destroyObj") continue;
502                 if(typeof(obj[i])=="object" && obj[i]!=null && typeof(obj[i].tagName)=="undefined") destroyObj(obj[i]);
503                 try { obj[i]=null; } catch(e){}
504         }
505         obj=null;
506 }
507
508 attachEvt("common","init",mySuperInitFunction);