]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/opac/common/js/opac_utils.js
login session cookie is now removed on browser close
[Evergreen.git] / Open-ILS / web / opac / common / js / opac_utils.js
1 /* - Request ------------------------------------------------------------- */
2
3 /* define it again here for pages that don't load RemoteRequest */
4 function isXUL() { try { if(IAMXUL) return true;}catch(e){return false;}; }
5
6
7 var cookieManager = new HTTP.Cookies();
8
9 var __ilsEvent; /* the last event the occurred */
10
11 function Request(type) {
12
13         var s = type.split(":");
14         if(s[2] == "1" && isXUL()) s[1] += ".staff";
15         this.request = new RemoteRequest(s[0], s[1]);
16         var p = [];
17
18         if(isXUL()) {
19                 if(!location.href.match(/^https:/))
20                         this.request.setSecure(false);
21
22         } else {
23
24                 if( G.user && G.user.session ) {
25                         /* if the user is logged in, all activity resets the timeout 
26                                 This is not entirely accurate in the sense that not all 
27                                 requests will reset the server timeout - this should
28                                 get close enough, however.
29                         */
30                         var at = getAuthtime();
31                         if(at) new AuthTimer(at).run(); 
32                 }
33         }
34
35         for( var x = 1; x!= arguments.length; x++ ) {
36                 p.push(arguments[x]);
37                 this.request.addParam(arguments[x]);
38         }
39
40         if( getDebug() ) {
41                 var str = "";
42                 for( var i = 0; i != p.length; i++ ) {
43                         if( i > 0 ) str += ", "
44                         str += js2JSON(p[i]);
45                 }
46                 _debug('request ' + s[0] + ' ' + s[1] + ' ' + str );
47         }
48 }
49
50 Request.prototype.callback = function(cal) {this.request.setCompleteCallback(cal);}
51 Request.prototype.send          = function(block){this.request.send(block);}
52 Request.prototype.result        = function(){return this.request.getResultObject();}
53
54 function showCanvas() {
55         for( var x in G.ui.altcanvas ) {
56                 hideMe(G.ui.altcanvas[x]);
57         }
58         hideMe(G.ui.common.loading);
59         unHideMe(G.ui.common.canvas_main);
60         try{G.ui.searchbar.text.focus();}catch(e){}
61 }
62
63 function swapCanvas(newNode) {
64         for( var x in G.ui.altcanvas ) 
65                 hideMe(G.ui.altcanvas[x]);
66
67         hideMe(G.ui.common.loading);
68         hideMe(G.ui.common.canvas_main);
69         unHideMe(newNode);
70 }
71
72 /* finds the name of the current page */
73 var currentPage = null;
74 function findCurrentPage() {
75         if(currentPage) return currentPage;
76
77         var pages = [];
78         for( var p in config.page ) pages.push(config.page[p]);
79         pages = pages.sort( function(a,b){ return - (a.length - b.length); } );
80
81         var path = location.pathname;
82         if(!path.match(/.*\.xml$/))
83                 path += "index.xml"; /* in case they go to  / */
84
85         var page = null;
86         for( var p in pages ) {
87                 if( path.indexOf(pages[p]) != -1)
88                         page = pages[p];
89         }
90
91         for( var p in config.page ) {
92                 if(config.page[p] == page) {
93                         currentPage = p;
94                         return p;
95                 }
96         }
97         return null;
98 }
99
100
101 /* sets all of the params values  ----------------------------- */
102 function initParams() {
103         var cgi = new CGI();    
104
105         /* handle the location var */
106         var org;
107         var loc = cgi.param(PARAM_LOCATION);
108         if( loc ) {
109                 org = findOrgUnit(loc);
110                 if(!org) org = findOrgUnitSN(loc);
111         } 
112         LOCATION        = (org) ? org.id() : null;
113
114         org = null;
115         loc = cgi.param(PARAM_ORIGLOC);
116         if( loc ) {
117                 org = findOrgUnit(loc);
118                 if(!org) org = findOrgUnitSN(loc);
119         }
120         ORIGLOC = (org) ? org.id() : null;
121
122
123         DEPTH = parseInt(cgi.param(PARAM_DEPTH));
124         if(isNaN(DEPTH)) DEPTH = null;
125
126
127         TERM            = cgi.param(PARAM_TERM);
128         STYPE           = cgi.param(PARAM_STYPE);
129         FORM            = cgi.param(PARAM_FORM);
130         //DEPTH         = parseInt(cgi.param(PARAM_DEPTH));
131         OFFSET  = parseInt(cgi.param(PARAM_OFFSET));
132         COUNT           = parseInt(cgi.param(PARAM_COUNT));
133         HITCOUNT        = parseInt(cgi.param(PARAM_HITCOUNT));
134         MRID            = parseInt(cgi.param(PARAM_MRID));
135         RID             = parseInt(cgi.param(PARAM_RID));
136         AUTHTIME        = parseInt(cgi.param(PARAM_AUTHTIME));
137         ADVTERM = cgi.param(PARAM_ADVTERM);
138         ADVTYPE = cgi.param(PARAM_ADVTYPE);
139         RTYPE           = cgi.param(PARAM_RTYPE);
140         SORT            = cgi.param(PARAM_SORT);
141         SORT_DIR        = cgi.param(PARAM_SORT_DIR);
142         DEBUG           = cgi.param(PARAM_DEBUG);
143         CALLNUM = cgi.param(PARAM_CN);
144         LITFORM = cgi.param(PARAM_LITFORM);
145         ITEMFORM        = cgi.param(PARAM_ITEMFORM);
146         ITEMTYPE        = cgi.param(PARAM_ITEMTYPE);
147         AUDIENCE        = cgi.param(PARAM_AUDIENCE);
148         SEARCHES = cgi.param(PARAM_SEARCHES);
149         LANGUAGE        = cgi.param(PARAM_LANGUAGE);
150         TFORM           = cgi.param(PARAM_TFORM);
151         RDEPTH  = cgi.param(PARAM_RDEPTH);
152
153         /* set up some sane defaults */
154         //if(isNaN(DEPTH))              DEPTH           = 0;
155         if(isNaN(RDEPTH))               RDEPTH  = 0;
156         if(isNaN(OFFSET))               OFFSET  = 0;
157         if(isNaN(COUNT))                COUNT           = 10;
158         if(isNaN(HITCOUNT))     HITCOUNT        = 0;
159         if(isNaN(MRID))         MRID            = 0;
160         if(isNaN(RID))                  RID             = 0;
161         if(isNaN(ORIGLOC))      ORIGLOC = 0; /* so we know it hasn't been set */
162         if(isNaN(AUTHTIME))     AUTHTIME        = 0;
163         if(ADVTERM==null)               ADVTERM = "";
164 }
165
166 function clearSearchParams() {
167         TERM            = null;
168         STYPE           = null;
169         FORM            = null;
170         OFFSET  = 0;
171         HITCOUNT = 0;  
172         ADVTERM  = null;
173         ADVTYPE  = null;
174         MRID            = null;
175         RID             = null;
176         RTYPE           = null;
177         SORT            = null;
178         SORT_DIR = null;
179         RLIST           = null;
180         CALLNUM = null;
181         LITFORM = null;
182         ITEMFORM = null;
183         ITEMTYPE = null;
184         AUDIENCE = null;
185         SEARCHES = null;
186         LANGUAGE = null;
187         RDEPTH  = null;
188 }
189
190
191 function initCookies() {
192         FONTSIZE = "regular";
193         var font = cookieManager.read(COOKIE_FONT);
194         scaleFonts(font);
195         if(font) FONTSIZE = font;
196         SKIN = cookieManager.read(COOKIE_SKIN);
197 }
198
199 /* URL param accessors */
200 function getTerm(){return TERM;}
201 function getStype(){return STYPE;}
202 function getLocation(){return LOCATION;}
203 function getDepth(){return DEPTH;}
204 function getForm(){return FORM;}
205 function getTform(){return TFORM;}
206 function getOffset(){return OFFSET;}
207 function getDisplayCount(){return COUNT;}
208 function getHitCount(){return HITCOUNT;}
209 function getMrid(){return MRID;};
210 function getRid(){return RID;};
211 function getOrigLocation(){return ORIGLOC;}
212 function getAuthtime() { return AUTHTIME; }
213 function getSearchBarExtras(){return SBEXTRAS;}
214 function getFontSize(){return FONTSIZE;};
215 function getSkin(){return SKIN;};
216 function getAdvTerm(){return ADVTERM;}
217 function getAdvType(){return ADVTYPE;}
218 function getRtype(){return RTYPE;}
219 function getSort(){return SORT;}
220 function getSortDir(){return SORT_DIR;}
221 function getDebug(){return DEBUG;}
222 function getCallnumber() { return CALLNUM; }
223 function getLitForm() { return LITFORM; }
224 function getItemForm() { return ITEMFORM; }
225 function getItemType() { return ITEMTYPE; }
226 function getAudience() { return AUDIENCE; }
227 function getSearches() { return SEARCHES; }
228 function getLanguage() { return LANGUAGE; }
229 function getRdepth() { return RDEPTH; }
230
231
232 function findBasePath() {
233         var path = location.pathname;
234         if(!path.match(/.*\.xml$/)) path += "index.xml"; 
235         var idx = path.indexOf(config.page[findCurrentPage()]);
236         return path.substring(0, idx);
237 }
238
239 function findBaseURL(ssl) {
240         var path = findBasePath();
241         var proto = (ssl) ? "https:" : "http:";
242         return proto + "//" + location.host + path;
243 }
244
245 /*
246 function buildISBNSrc(isbn) {
247         return "http://" + location.host + "/jackets/" + isbn;
248 }
249 */
250
251 function buildImageLink(name, ssl) {
252         return findBaseURL(ssl) + "../../../../images/" + name;
253 }
254
255 function buildExtrasLink(name, ssl) {
256         return findBaseURL(ssl) + "../../../../extras/" + name;
257 }
258
259 var consoleService;
260 function _debug(str) { 
261         try { dump('dbg: ' + str + '\n'); } catch(e) {} 
262
263         /* potentially useful, but usually just annoying */
264         /*
265         if(!IE) {
266                 if(!consoleService) {
267                         try {
268                                 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
269                                 this.consoleService = Components.classes['@mozilla.org/consoleservice;1']
270                                         .getService(Components.interfaces.nsIConsoleService);
271                         } catch(e) {}
272                 }
273         
274                 try {
275                         if(consoleService) {
276                                 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
277                                 consoleService.logStringMessage(str + '\n');
278                         }
279                 } catch(e){}
280         }
281         */
282 }
283
284 function  buildOPACLink(args, slim, ssl) {
285
286         if(!args) args = {};
287         var string = "";
288
289         if(!slim) {
290                 string = findBaseURL(ssl);
291                 if(args.page) string += config.page[args.page];
292                 else string += config.page[findCurrentPage()];
293         }
294
295         /* this may seem unnecessary.. safety precaution for now */
296         /*
297         if( args[PARAM_DEPTH] == null )
298                 args[PARAM_DEPTH] = getDepth();
299                 */
300
301         string += "?";
302
303         for( var x in args ) {
304                 var v = args[x];
305                 if(x == "page" || v == null || v == undefined || v+'' == 'NaN' ) continue;
306                 if(x == PARAM_OFFSET && v == 0) continue;
307                 if(x == PARAM_COUNT && v == 10) continue;
308                 if(x == PARAM_FORM && v == 'all' ) continue;
309                 if( instanceOf(v, Array) && v.length ) {
310                         for( var i = 0; i < v.length; i++ ) {
311                                 string += "&" + x + "=" + encodeURIComponent(v[i]);
312                         }
313                 } else {
314                         string += "&" + x + "=" + encodeURIComponent(v);
315                 }
316         }
317
318         if(getDebug())
319                 string += _appendParam(DEBUG,           PARAM_DEBUG, args, getDebug, string);
320         if(getOrigLocation() != 1) 
321                 string += _appendParam(ORIGLOC, PARAM_ORIGLOC, args, getOrigLocation, string);
322         if(getTerm()) 
323                 string += _appendParam(TERM,            PARAM_TERM, args, getTerm, string);
324         if(getStype()) 
325                 string += _appendParam(STYPE,           PARAM_STYPE, args, getStype, string);
326         if(getLocation() != 1) 
327                 string += _appendParam(LOCATION, PARAM_LOCATION, args, getLocation, string);
328         if(getDepth() != null) 
329                 string += _appendParam(DEPTH,           PARAM_DEPTH, args, getDepth, string);
330         if(getForm() && (getForm() != 'all') ) 
331                 string += _appendParam(FORM,            PARAM_FORM, args, getForm, string);
332         if(getTform() && (getTform() != 'all') ) 
333                 string += _appendParam(TFORM,           PARAM_TFORM, args, getTform, string);
334         if(getOffset() != 0) 
335                 string += _appendParam(OFFSET,  PARAM_OFFSET, args, getOffset, string);
336         if(getDisplayCount() != 10) 
337                 string += _appendParam(COUNT,           PARAM_COUNT, args, getDisplayCount, string);
338         if(getHitCount()) 
339                 string += _appendParam(HITCOUNT, PARAM_HITCOUNT, args, getHitCount, string);
340         if(getMrid())
341                 string += _appendParam(MRID,            PARAM_MRID, args, getMrid, string);
342         if(getRid())
343                 string += _appendParam(RID,             PARAM_RID, args, getRid, string);
344         if(getAuthtime())
345                 string += _appendParam(AUTHTIME,        PARAM_AUTHTIME, args, getAuthtime, string);
346         if(getAdvTerm())
347                 string += _appendParam(ADVTERM, PARAM_ADVTERM, args, getAdvTerm, string);
348         if(getAdvType())
349                 string += _appendParam(ADVTYPE, PARAM_ADVTYPE, args, getAdvType, string);
350         if(getRtype())
351                 string += _appendParam(RTYPE,           PARAM_RTYPE, args, getRtype, string);
352         if(getItemForm())
353                 string += _appendParam(ITEMFORM,        PARAM_ITEMFORM, args, getItemForm, string);
354         if(getItemType())
355                 string += _appendParam(ITEMTYPE,        PARAM_ITEMTYPE, args, getItemType, string);
356         if(getLitForm())
357                 string += _appendParam(LITFORM, PARAM_LITFORM, args, getLitForm, string);
358         if(getAudience())
359                 string += _appendParam(AUDIENCE,        PARAM_AUDIENCE, args, getAudience, string);
360         if(getSearches())
361                 string += _appendParam(SEARCHES,        PARAM_SEARCHES, args, getSearches, string);
362         if(getLanguage())
363                 string += _appendParam(LANGUAGE,        PARAM_LANGUAGE, args, getLanguage, string);
364         if(getRdepth() != null)
365                 string += _appendParam(RDEPTH,  PARAM_RDEPTH, args, getRdepth, string);
366         if(getSort() != null)
367                 string += _appendParam(SORT,    PARAM_SORT, args, getSort, string);
368         if(getSortDir() != null)
369                 string += _appendParam(SORT_DIR,        PARAM_SORT_DIR, args, getSortDir, string);
370
371         return string.replace(/\&$/,'').replace(/\?\&/,"?");    
372 }
373
374 var xx = 1;
375 function _appendParam( fieldVar, fieldName, overrideArgs, getFunc, string ) {
376
377         var ret = "";
378
379         if(     fieldVar != null && 
380                         (fieldVar +'' != 'NaN') && 
381                         overrideArgs[fieldName] == null &&
382                         getFunc() != null &&
383                         getFunc()+'' != '' ) {
384
385                 ret = "&" + fieldName + "=" + encodeURIComponent(getFunc());
386         }
387
388         return ret;
389 }
390
391 /* ----------------------------------------------------------------------- */
392 function cleanISBN(isbn) {
393    if(isbn) {
394       isbn = isbn.toString().replace(/^\s+/,"");
395       var idx = isbn.indexOf(" ");
396       if(idx > -1) { isbn = isbn.substring(0, idx); }
397    } else isbn = "";
398    return isbn;
399 }       
400
401
402 /* builds a link that goes to the title listings for a metarecord */
403 function buildTitleLink(rec, link) {
404         if(!rec) return;
405         link.appendChild(text(normalize(truncate(rec.title(), 65))));
406         var args = {};
407         args.page = RRESULT;
408         args[PARAM_OFFSET] = 0;
409         args[PARAM_MRID] = rec.doc_id();
410         args[PARAM_RTYPE] = RTYPE_MRID;
411         link.setAttribute("href", buildOPACLink(args));
412 }
413
414 function buildTitleDetailLink(rec, link) {
415         if(!rec) return;
416         link.appendChild(text(normalize(truncate(rec.title(), 65))));
417         var args = {};
418         args.page = RDETAIL;
419         //args[PARAM_OFFSET] = 0;
420         args[PARAM_RID] = rec.doc_id();
421         link.setAttribute("href", buildOPACLink(args));
422 }
423
424 /* 'type' is one of STYPE_AUTHOR, STYPE_SUBJECT, ... found in config.js 
425         'trunc' is the number of characters to show in the string, defaults to 65 */
426 function buildSearchLink(type, string, linknode, trunc) {
427         if(!trunc) trunc = 65;
428         var args = {};
429         args.page = MRESULT;
430         args[PARAM_OFFSET] = 0;
431         args[PARAM_TERM] = string;
432         args[PARAM_STYPE] = type;
433         linknode.appendChild(text(normalize(truncate(string, trunc))));
434         linknode.setAttribute("href", buildOPACLink(args));
435 }
436
437
438 /* ----------------------------------------------------------------------- */
439 /* user session handling */
440 /* ----------------------------------------------------------------------- */
441 /* session is the login session.  If no session is provided, we attempt
442         to find one in the cookies.  If 'force' is true we retrieve the 
443         user from the server even if there is already a global user present.
444         if ses != G.user.session, we also force a grab */
445 function grabUser(ses, force) {
446
447         if(!ses && isXUL()) ses = xulG['authtoken'];
448
449         if(!ses) {
450                 ses = cookieManager.read(COOKIE_SES);
451                 /* https cookies don't show up in http servers.. */
452         }
453
454         if(!ses) return false;
455
456         if(!force) 
457                 if(G.user && G.user.session == ses)
458                         return G.user;
459
460         /* first make sure the session is valid */
461         var request = new Request(FETCH_SESSION, ses, 1 );
462         request.request.alertEvent = false;
463         request.send(true);
464         var user = request.result();
465
466         if(!user) {
467                 doLogout();
468                 return false; /* unable to grab the session */
469         }
470
471         if( !(typeof user == 'object' && user._isfieldmapper) ) {
472                 doLogout();
473                 return false;
474         }
475
476         G.user = user;
477         G.user.fleshed = false;
478         G.user.session = ses;
479         cookieManager.write(COOKIE_SES, ses, -1);
480
481
482         grabUserPrefs();
483         if(G.user.prefs['opac.hits_per_page'])
484                 COUNT = parseInt(G.user.prefs['opac.hits_per_page']);
485
486         if(G.user.prefs[PREF_DEF_FONT]) 
487                 setFontSize(G.user.prefs[PREF_DEF_FONT]);
488
489         var at = getAuthtime();
490         //if(isXUL()) at = xulG['authtime'];
491
492         if(at && !isXUL()) new AuthTimer(at).run(); 
493         return G.user;
494 }
495
496
497 /* sets the 'prefs' field of the user object to their preferences 
498         and returns the preferences */
499 function grabUserPrefs(user, force) {
500         if(user == null) user = G.user;
501         if(!force && user.prefs) return user.prefs;     
502         var req = new Request(FETCH_USER_PREFS, user.session, user.id());
503         req.send(true);
504         user.prefs = req.result();
505         return user.prefs;
506 }
507
508 function grabFleshedUser() {
509
510         if(!G.user || !G.user.session) {
511                 grabUser();     
512                 if(!G.user || !G.user.session) return null;
513         }
514
515         if(G.user.fleshed) return G.user;
516
517    var req = new Request(FETCH_FLESHED_USER, G.user.session);
518         req.send(true);
519
520         G.user = req.result();
521
522         if(!G.user || G.user.length == 0) { 
523                 G.user = null; return false; 
524                 cookieManager.write(COOKIE_SES,"");
525         }
526
527         G.user.session = ses;
528         G.user.fleshed = true;
529
530         cookieManager.write(COOKIE_SES, ses, '+1y'); /*  update the cookie */
531         return G.user;
532 }
533
534 function checkUserSkin(new_skin) {
535
536         return; /* XXX do some debugging with this... */
537
538         var user_skin = getSkin();
539         var cur_skin = grabSkinFromURL();
540
541         if(new_skin) user_skin = new_skin;
542
543         if(!user_skin) {
544
545                 if(grabUser()) {
546                         if(grabUserPrefs()) {
547                                 user_skin = G.user.prefs["opac.skin"];
548                                 cookieManager.write( COOKIE_SKIN, user_skin, '+1y' );
549                         }
550                 }
551         }
552
553         if(!user_skin) return;
554
555         if( cur_skin != user_skin ) {
556                 var url = buildOPACLink();
557                 goTo(url.replace(cur_skin, user_skin));
558         }
559 }
560
561 function updateUserSetting(setting, value, user) {
562         if(user == null) user = G.user;
563         var a = {};
564         a[setting] = value;
565         var req = new Request( UPDATE_USER_PREFS, user.session, a );
566         req.send(true);
567         return req.result();
568 }
569
570 function commitUserPrefs() {
571         var req = new Request( 
572                 UPDATE_USER_PREFS, G.user.session, null, G.user.prefs );
573         req.send(true);
574         return req.result();
575 }
576
577 function grabSkinFromURL() {
578         var path = findBasePath();
579         path = path.replace("/xml/", "");
580         var skin = "";
581         for( var i = path.length - 1; i >= 0; i-- ) {
582                 var ch = path.charAt(i);
583                 if(ch == "/") break;
584                 skin += ch;
585         }
586
587         var skin2 = "";
588         for( i = skin.length - 1; i >= 0; i--)
589                 skin2 += skin.charAt(i);
590
591         return skin2;
592 }
593
594
595 /* returns a fleshed G.user on success, false on failure */
596 function doLogin(suppressEvents) {
597
598         abortAllRequests();
599
600         var uname = G.ui.login.username.value;
601         var passwd = G.ui.login.password.value; 
602
603         var init_request = new Request( LOGIN_INIT, uname );
604    init_request.send(true);
605    var seed = init_request.result();
606
607    if( ! seed || seed == '0') {
608       alert( "Error Communicating with Authentication Server" );
609       return null;
610    }
611
612         var args = {
613                 password : hex_md5(seed + hex_md5(passwd)), 
614                 type            : "opac", 
615                 org             : getOrigLocation()
616         };
617
618         if( uname.match(REGEX_BARCODE) ) args.barcode = uname; /* make this better */
619         else args.username = uname;
620
621    var auth_request = new Request( LOGIN_COMPLETE, args );
622
623         auth_request.request.alertEvent = false;
624    auth_request.send(true);
625    var auth_result = auth_request.result();
626
627         if(!auth_result) {
628                 alertId('patron_login_failed');
629                 return null;
630         }
631
632         if( checkILSEvent(auth_result) ) {
633
634                 if( auth_result.textcode == 'PATRON_INACTIVE' ) {
635                         alertId('patron_inactive_alert');
636                         return;
637                 }
638
639                 if( auth_result.textcode == 'PATRON_CARD_INACTIVE' ) {
640                         alertId('patron_card_inactive_alert');
641                         return;
642                 }
643
644                 if( auth_result.textcode == 'LOGIN_FAILED' || 
645                                 auth_result.textcode == 'PERM_FAILURE' ) {
646                         alertId('patron_login_failed');
647                         return;
648                 }
649         }
650
651
652         AUTHTIME = parseInt(auth_result.payload.authtime);
653         var u = grabUser(auth_result.payload.authtoken, true);
654         if(u && ! suppressEvents) 
655                 runEvt( "common", "locationChanged", u.ws_ou(), findOrgDepth(u.ws_ou()) );
656
657         checkUserSkin();
658
659         return u;
660 }
661
662 function doLogout(noredirect) {
663
664         /* cancel everything else */
665         abortAllRequests();
666
667         /* be nice and delete the session from the server */
668         if(G.user && G.user.session) { 
669                 var req = new Request(LOGIN_DELETE, G.user.session);
670       req.send(true);
671                 try { req.result(); } catch(E){}
672     }
673
674         G.user = null;
675
676         /* remove any cached data */
677         //cookieManager.remove(COOKIE_IDS);
678         //cookieManager.remove(COOKIE_SRIDS);
679         cookieManager.remove(COOKIE_RIDS);
680         cookieManager.remove(COOKIE_SES);
681         cookieManager.remove(COOKIE_SKIN);
682
683         checkUserSkin("default");
684         COUNT = 10;
685
686
687         var args = {};
688         args[PARAM_TERM] = "";
689         args[PARAM_LOCATION] = getOrigLocation();
690         args[PARAM_DEPTH] = findOrgDepth(getOrigLocation());
691         args.page = "home";
692
693         
694         var nored = false;
695         try{ if(isFrontPage) nored = true; } catch(e){nored = false;}
696         if(!nored) goTo(buildOPACLink(args));
697 }
698
699
700 function hideMe(obj) { addCSSClass(obj, config.css.hide_me); } 
701 function unHideMe(obj) { removeCSSClass(obj, config.css.hide_me); }
702
703
704 /* ----------------------------------------------------------------------- */
705 /* build the org tree */
706 /* ----------------------------------------------------------------------- */
707 function drawOrgTree() {
708         //setTimeout( 'buildOrgSelector(G.ui.common.org_tree, orgTreeSelector);', 10 );
709         setTimeout( 'buildOrgSelector(G.ui.common.org_tree, orgTreeSelector);', 1 );
710 }
711         
712 var orgTreeSelector;
713 function buildOrgSelector(node) {
714         var tree = new SlimTree(node,'orgTreeSelector');
715         orgTreeSelector = tree;
716         for( var i in orgArraySearcher ) { 
717                 var node = orgArraySearcher[i];
718                 if( node == null ) continue;
719                 if(node.parent_ou() == null)
720                         tree.addNode(node.id(), -1, node.name(), 
721                                 "javascript:orgSelect(" + node.id() + ");", node.name());
722                 else {
723                         tree.addNode(node.id(), findOrgUnit(node.parent_ou()).id(), node.name(), 
724                                 "javascript:orgSelect(" + node.id() + ");", node.name());
725                 }
726         }
727         hideMe($('org_loading_div'));
728         unHideMe($('org_selector_tip'));
729         return tree;
730 }
731
732 function orgSelect(id) {
733         showCanvas();
734         runEvt("common", "locationChanged", id, findOrgDepth(id) );
735
736         removeChildren(G.ui.common.now_searching);
737         G.ui.common.now_searching.appendChild(text(findOrgUnit(id).name()));
738 }
739
740 function setFontSize(size) {
741         scaleFonts(size);
742         cookieManager.write(COOKIE_FONT, size, '+1y');
743 }
744
745
746 var resourceFormats = [
747    "text",
748    "moving image",
749    "sound recording", "software, multimedia",
750    "still images",
751    "cartographic",
752    "mixed material",
753    "notated music",
754    "three dimensional object" ];
755
756
757 function modsFormatToMARC(format) {
758    switch(format) {
759       case "text":
760          return "at";
761       case "moving image":
762          return "g";
763       case "sound recording":
764          return "ij";
765       case "sound recording-nonmusical":
766          return "i";
767       case "sound recording-musical":
768          return "j";
769       case "software, multimedia":
770          return "m";
771       case "still images":
772          return "k";
773       case "cartographic":
774          return "ef";
775       case "mixed material":
776          return "op";
777       case "notated music":
778          return "cd";
779       case "three dimensional object":
780          return "r";
781    }
782    return "at";
783 }
784
785
786 function MARCFormatToMods(format) {
787    switch(format) {
788       case "a":
789       case "t":
790          return "text";
791       case "g":
792          return "moving image";
793       case "i":
794          return "sound recording-nonmusical";
795       case "j":
796          return "sound recording-musical";
797       case "m":
798          return "software, multimedia";
799       case "k":
800          return "still images";
801       case "e":
802       case "f":
803          return "cartographic";
804       case "o":
805       case "p":
806          return "mixed material";
807       case "c":
808       case "d":
809          return "notated music";
810       case "r":
811          return "three dimensional object";
812    }
813    return "text";
814 }
815
816 function MARCTypeToFriendly(format) {
817         var words = $('format_words');
818         switch(format) {
819                 case 'a' :
820                 case 't' : return $n(words, 'at').innerHTML;
821                 default:
822                         var node = $n(words,format);
823                         if( node ) return node.innerHTML;
824         }
825         return "";
826 }
827
828 function setResourcePic( img, resource ) {
829         img.setAttribute( "src", "../../../../images/tor/" + resource + ".jpg");
830         img.title = resource;
831 }
832
833
834
835 function msg( text ) {
836         try { alert( text ); } catch(e) {}
837 }
838
839 function findRecord(id,type) {
840         try {
841                 for( var i = 0; i != recordsCache.length; i++ ) {
842                         var rec = recordsCache[i];
843                         if( rec && rec.doc_id() == id ) return rec;
844                 }
845         } catch(E){}
846         var meth = FETCH_RMODS
847         if(type == 'M') meth = FETCH_MRMODS;
848         var req = new Request(meth, id);
849         req.request.alertEvent = false;
850         req.send(true);
851         var res = req.result();
852         if( checkILSEvent(res) ) return null; 
853 }
854
855 function Timer(name, node){
856         this.name = name;
857         this.count = 1;
858         this.node = node;
859 }
860 Timer.prototype.start = 
861         function(){_timerRun(this.name);}
862 Timer.prototype.stop = 
863         function(){this.done = true;}
864 function _timerRun(tname) {
865         var _t;
866         eval('_t='+tname);
867         if(_t.done) return;
868         if(_t.count > 100) return;
869         var str = ' . ';
870         if( (_t.count % 5) == 0 ) 
871                 str = _t.count / 5;
872         _t.node.appendChild(text(str));
873         setTimeout("_timerRun('"+tname+"');", 200);
874         _t.count++;
875 }
876
877 function checkILSEvent(obj) {
878         if( obj && obj.ilsevent != null && obj.ilsevent != 0 )
879                 return parseInt(obj.ilsevent);
880         return null;
881 }
882
883
884 function alertILSEvent(evt, msg) {
885    if(!msg) msg = "";
886         if(msg)
887                 alert(msg +'\n' + evt.textcode + '\n' + evt.desc );
888         else 
889                 alert(evt.textcode + '\n' + evt.desc );
890 }
891
892
893 var __authTimer;
894 function AuthTimer(time) { 
895         this.time = (time - LOGOUT_WARNING_TIME) * 1000; 
896         if(__authTimer) 
897                 try {clearTimeout(__authTimer.id)} catch(e){}
898         __authTimer = this;
899 }
900
901 AuthTimer.prototype.run = function() {
902         this.id = setTimeout('_authTimerAlert()', this.time);
903 }
904
905 function _authTimerAlert() {
906         alert( $('auth_session_expiring').innerHTML );
907         if(!grabUser(null, true)) doLogout();
908 }
909
910
911 function grabUserByBarcode( authtoken, barcode ) {
912         var req = new Request( FETCH_USER_BYBARCODE, authtoken, barcode );
913         req.send(true);
914         return req.result();
915 }
916
917
918 function goHome() {
919         goTo(buildOPACLink({page:HOME}));
920 }
921
922
923 function buildOrgSel(selector, org, offset) {
924         insertSelectorVal( selector, -1, 
925                 org.name(), org.id(), null, findOrgDepth(org) - offset );
926         for( var c in org.children() )
927                 buildOrgSel( selector, org.children()[c], offset);
928 }
929
930
931 function parseForm(form) {
932         if(!form) return {};
933
934         var it = form.replace(/-\w+$/,"");
935         var itf = null;
936         var item_form;
937         var item_type;
938
939         if(form.match(/-/)) itf = form.replace(/^\w+-/,"");
940
941         if(it) {
942                 item_type = [];
943                 for( var i = 0; i < it.length; i++ ) 
944                         item_type.push( it.charAt(i) );
945         }
946
947         if(itf) {
948                 item_form = [];
949                 for( var i = 0; i < itf.length; i++ ) 
950                         item_form.push( itf.charAt(i) );
951         }
952
953         return {item_type: item_type, item_form:item_form};
954 }
955
956
957 function isTrue(x) { return ( x && x != "0" && !(x+'').match(/^f$/i) ); }
958
959 function fetchPermOrgs() {
960         var a = []; /* why does arguments come accross as an object and not an array? */
961         for( var i = 0; i < arguments.length; i++ ) 
962                 a.push(arguments[i])
963
964         var preq = new Request(FETCH_HIGHEST_PERM_ORG, 
965                 G.user.session, G.user.id(), a );
966         preq.send(true);
967         return preq.result();
968 }
969