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