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