]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/opac/common/js/opac_utils.js
fixed session cookie to work with IE
[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         grabUserPrefs();
482         if(G.user.prefs['opac.hits_per_page'])
483                 COUNT = parseInt(G.user.prefs['opac.hits_per_page']);
484
485         if(G.user.prefs[PREF_DEF_FONT]) 
486                 setFontSize(G.user.prefs[PREF_DEF_FONT]);
487
488         var at = getAuthtime();
489         //if(isXUL()) at = xulG['authtime'];
490
491         if(at && !isXUL()) new AuthTimer(at).run(); 
492         return G.user;
493 }
494
495
496 /* sets the 'prefs' field of the user object to their preferences 
497         and returns the preferences */
498 function grabUserPrefs(user, force) {
499         if(user == null) user = G.user;
500         if(!force && user.prefs) return user.prefs;     
501         var req = new Request(FETCH_USER_PREFS, user.session, user.id());
502         req.send(true);
503         user.prefs = req.result();
504         return user.prefs;
505 }
506
507 function grabFleshedUser() {
508
509         if(!G.user || !G.user.session) {
510                 grabUser();     
511                 if(!G.user || !G.user.session) return null;
512         }
513
514         if(G.user.fleshed) return G.user;
515
516    var req = new Request(FETCH_FLESHED_USER, G.user.session);
517         req.send(true);
518
519         G.user = req.result();
520
521         if(!G.user || G.user.length == 0) { 
522                 G.user = null; return false; 
523                 cookieManager.write(COOKIE_SES,"");
524         }
525
526         G.user.session = ses;
527         G.user.fleshed = true;
528
529         cookieManager.write(COOKIE_SES, ses, '+1y'); /*  update the cookie */
530         return G.user;
531 }
532
533 function checkUserSkin(new_skin) {
534
535         return; /* XXX do some debugging with this... */
536
537         var user_skin = getSkin();
538         var cur_skin = grabSkinFromURL();
539
540         if(new_skin) user_skin = new_skin;
541
542         if(!user_skin) {
543
544                 if(grabUser()) {
545                         if(grabUserPrefs()) {
546                                 user_skin = G.user.prefs["opac.skin"];
547                                 cookieManager.write( COOKIE_SKIN, user_skin, '+1y' );
548                         }
549                 }
550         }
551
552         if(!user_skin) return;
553
554         if( cur_skin != user_skin ) {
555                 var url = buildOPACLink();
556                 goTo(url.replace(cur_skin, user_skin));
557         }
558 }
559
560 function updateUserSetting(setting, value, user) {
561         if(user == null) user = G.user;
562         var a = {};
563         a[setting] = value;
564         var req = new Request( UPDATE_USER_PREFS, user.session, a );
565         req.send(true);
566         return req.result();
567 }
568
569 function commitUserPrefs() {
570         var req = new Request( 
571                 UPDATE_USER_PREFS, G.user.session, null, G.user.prefs );
572         req.send(true);
573         return req.result();
574 }
575
576 function grabSkinFromURL() {
577         var path = findBasePath();
578         path = path.replace("/xml/", "");
579         var skin = "";
580         for( var i = path.length - 1; i >= 0; i-- ) {
581                 var ch = path.charAt(i);
582                 if(ch == "/") break;
583                 skin += ch;
584         }
585
586         var skin2 = "";
587         for( i = skin.length - 1; i >= 0; i--)
588                 skin2 += skin.charAt(i);
589
590         return skin2;
591 }
592
593
594 /* returns a fleshed G.user on success, false on failure */
595 function doLogin(suppressEvents) {
596
597         abortAllRequests();
598
599         var uname = G.ui.login.username.value;
600         var passwd = G.ui.login.password.value; 
601
602         var init_request = new Request( LOGIN_INIT, uname );
603    init_request.send(true);
604    var seed = init_request.result();
605
606    if( ! seed || seed == '0') {
607       alert( "Error Communicating with Authentication Server" );
608       return null;
609    }
610
611         var args = {
612                 password : hex_md5(seed + hex_md5(passwd)), 
613                 type            : "opac", 
614                 org             : getOrigLocation()
615         };
616
617         if( uname.match(REGEX_BARCODE) ) args.barcode = uname; /* make this better */
618         else args.username = uname;
619
620    var auth_request = new Request( LOGIN_COMPLETE, args );
621
622         auth_request.request.alertEvent = false;
623    auth_request.send(true);
624    var auth_result = auth_request.result();
625
626         if(!auth_result) {
627                 alertId('patron_login_failed');
628                 return null;
629         }
630
631         if( checkILSEvent(auth_result) ) {
632
633                 if( auth_result.textcode == 'PATRON_INACTIVE' ) {
634                         alertId('patron_inactive_alert');
635                         return;
636                 }
637
638                 if( auth_result.textcode == 'PATRON_CARD_INACTIVE' ) {
639                         alertId('patron_card_inactive_alert');
640                         return;
641                 }
642
643                 if( auth_result.textcode == 'LOGIN_FAILED' || 
644                                 auth_result.textcode == 'PERM_FAILURE' ) {
645                         alertId('patron_login_failed');
646                         return;
647                 }
648         }
649
650
651         AUTHTIME = parseInt(auth_result.payload.authtime);
652         var u = grabUser(auth_result.payload.authtoken, true);
653         if(u && ! suppressEvents) 
654                 runEvt( "common", "locationChanged", u.ws_ou(), findOrgDepth(u.ws_ou()) );
655
656         checkUserSkin();
657
658         return u;
659 }
660
661 function doLogout(noredirect) {
662
663         /* cancel everything else */
664         abortAllRequests();
665
666         /* be nice and delete the session from the server */
667         if(G.user && G.user.session) { 
668                 var req = new Request(LOGIN_DELETE, G.user.session);
669       req.send(true);
670                 try { req.result(); } catch(E){}
671     }
672
673         G.user = null;
674
675         /* remove any cached data */
676         //cookieManager.remove(COOKIE_IDS);
677         //cookieManager.remove(COOKIE_SRIDS);
678         cookieManager.remove(COOKIE_RIDS);
679         cookieManager.remove(COOKIE_SES);
680         cookieManager.remove(COOKIE_SKIN);
681
682         checkUserSkin("default");
683         COUNT = 10;
684
685
686         var args = {};
687         args[PARAM_TERM] = "";
688         args[PARAM_LOCATION] = getOrigLocation();
689         args[PARAM_DEPTH] = findOrgDepth(getOrigLocation());
690         args.page = "home";
691
692         
693         var nored = false;
694         try{ if(isFrontPage) nored = true; } catch(e){nored = false;}
695         if(!nored) goTo(buildOPACLink(args));
696 }
697
698
699 function hideMe(obj) { addCSSClass(obj, config.css.hide_me); } 
700 function unHideMe(obj) { removeCSSClass(obj, config.css.hide_me); }
701
702
703 /* ----------------------------------------------------------------------- */
704 /* build the org tree */
705 /* ----------------------------------------------------------------------- */
706 function drawOrgTree() {
707         //setTimeout( 'buildOrgSelector(G.ui.common.org_tree, orgTreeSelector);', 10 );
708         setTimeout( 'buildOrgSelector(G.ui.common.org_tree, orgTreeSelector);', 1 );
709 }
710         
711 var orgTreeSelector;
712 function buildOrgSelector(node) {
713         var tree = new SlimTree(node,'orgTreeSelector');
714         orgTreeSelector = tree;
715         for( var i in orgArraySearcher ) { 
716                 var node = orgArraySearcher[i];
717                 if( node == null ) continue;
718                 if(node.parent_ou() == null)
719                         tree.addNode(node.id(), -1, node.name(), 
720                                 "javascript:orgSelect(" + node.id() + ");", node.name());
721                 else {
722                         tree.addNode(node.id(), findOrgUnit(node.parent_ou()).id(), node.name(), 
723                                 "javascript:orgSelect(" + node.id() + ");", node.name());
724                 }
725         }
726         hideMe($('org_loading_div'));
727         unHideMe($('org_selector_tip'));
728         return tree;
729 }
730
731 function orgSelect(id) {
732         showCanvas();
733         runEvt("common", "locationChanged", id, findOrgDepth(id) );
734
735         removeChildren(G.ui.common.now_searching);
736         G.ui.common.now_searching.appendChild(text(findOrgUnit(id).name()));
737 }
738
739 function setFontSize(size) {
740         scaleFonts(size);
741         cookieManager.write(COOKIE_FONT, size, '+1y');
742 }
743
744
745 var resourceFormats = [
746    "text",
747    "moving image",
748    "sound recording", "software, multimedia",
749    "still images",
750    "cartographic",
751    "mixed material",
752    "notated music",
753    "three dimensional object" ];
754
755
756 function modsFormatToMARC(format) {
757    switch(format) {
758       case "text":
759          return "at";
760       case "moving image":
761          return "g";
762       case "sound recording":
763          return "ij";
764       case "sound recording-nonmusical":
765          return "i";
766       case "sound recording-musical":
767          return "j";
768       case "software, multimedia":
769          return "m";
770       case "still images":
771          return "k";
772       case "cartographic":
773          return "ef";
774       case "mixed material":
775          return "op";
776       case "notated music":
777          return "cd";
778       case "three dimensional object":
779          return "r";
780    }
781    return "at";
782 }
783
784
785 function MARCFormatToMods(format) {
786    switch(format) {
787       case "a":
788       case "t":
789          return "text";
790       case "g":
791          return "moving image";
792       case "i":
793          return "sound recording-nonmusical";
794       case "j":
795          return "sound recording-musical";
796       case "m":
797          return "software, multimedia";
798       case "k":
799          return "still images";
800       case "e":
801       case "f":
802          return "cartographic";
803       case "o":
804       case "p":
805          return "mixed material";
806       case "c":
807       case "d":
808          return "notated music";
809       case "r":
810          return "three dimensional object";
811    }
812    return "text";
813 }
814
815 function MARCTypeToFriendly(format) {
816         var words = $('format_words');
817         switch(format) {
818                 case 'a' :
819                 case 't' : return $n(words, 'at').innerHTML;
820                 default:
821                         var node = $n(words,format);
822                         if( node ) return node.innerHTML;
823         }
824         return "";
825 }
826
827 function setResourcePic( img, resource ) {
828         img.setAttribute( "src", "../../../../images/tor/" + resource + ".jpg");
829         img.title = resource;
830 }
831
832
833
834 function msg( text ) {
835         try { alert( text ); } catch(e) {}
836 }
837
838 function findRecord(id,type) {
839         try {
840                 for( var i = 0; i != recordsCache.length; i++ ) {
841                         var rec = recordsCache[i];
842                         if( rec && rec.doc_id() == id ) return rec;
843                 }
844         } catch(E){}
845         var meth = FETCH_RMODS
846         if(type == 'M') meth = FETCH_MRMODS;
847         var req = new Request(meth, id);
848         req.request.alertEvent = false;
849         req.send(true);
850         var res = req.result();
851         if( checkILSEvent(res) ) return null; 
852 }
853
854 function Timer(name, node){
855         this.name = name;
856         this.count = 1;
857         this.node = node;
858 }
859 Timer.prototype.start = 
860         function(){_timerRun(this.name);}
861 Timer.prototype.stop = 
862         function(){this.done = true;}
863 function _timerRun(tname) {
864         var _t;
865         eval('_t='+tname);
866         if(_t.done) return;
867         if(_t.count > 100) return;
868         var str = ' . ';
869         if( (_t.count % 5) == 0 ) 
870                 str = _t.count / 5;
871         _t.node.appendChild(text(str));
872         setTimeout("_timerRun('"+tname+"');", 200);
873         _t.count++;
874 }
875
876 function checkILSEvent(obj) {
877         if( obj && obj.ilsevent != null && obj.ilsevent != 0 )
878                 return parseInt(obj.ilsevent);
879         return null;
880 }
881
882
883 function alertILSEvent(evt, msg) {
884    if(!msg) msg = "";
885         if(msg)
886                 alert(msg +'\n' + evt.textcode + '\n' + evt.desc );
887         else 
888                 alert(evt.textcode + '\n' + evt.desc );
889 }
890
891
892 var __authTimer;
893 function AuthTimer(time) { 
894         this.time = (time - LOGOUT_WARNING_TIME) * 1000; 
895         if(__authTimer) 
896                 try {clearTimeout(__authTimer.id)} catch(e){}
897         __authTimer = this;
898 }
899
900 AuthTimer.prototype.run = function() {
901         this.id = setTimeout('_authTimerAlert()', this.time);
902 }
903
904 function _authTimerAlert() {
905         alert( $('auth_session_expiring').innerHTML );
906         if(!grabUser(null, true)) doLogout();
907 }
908
909
910 function grabUserByBarcode( authtoken, barcode ) {
911         var req = new Request( FETCH_USER_BYBARCODE, authtoken, barcode );
912         req.send(true);
913         return req.result();
914 }
915
916
917 function goHome() {
918         goTo(buildOPACLink({page:HOME}));
919 }
920
921
922 function buildOrgSel(selector, org, offset) {
923         insertSelectorVal( selector, -1, 
924                 org.name(), org.id(), null, findOrgDepth(org) - offset );
925         for( var c in org.children() )
926                 buildOrgSel( selector, org.children()[c], offset);
927 }
928
929
930 function parseForm(form) {
931         if(!form) return {};
932
933         var it = form.replace(/-\w+$/,"");
934         var itf = null;
935         var item_form;
936         var item_type;
937
938         if(form.match(/-/)) itf = form.replace(/^\w+-/,"");
939
940         if(it) {
941                 item_type = [];
942                 for( var i = 0; i < it.length; i++ ) 
943                         item_type.push( it.charAt(i) );
944         }
945
946         if(itf) {
947                 item_form = [];
948                 for( var i = 0; i < itf.length; i++ ) 
949                         item_form.push( itf.charAt(i) );
950         }
951
952         return {item_type: item_type, item_form:item_form};
953 }
954
955
956 function isTrue(x) { return ( x && x != "0" && !(x+'').match(/^f$/i) ); }
957
958 function fetchPermOrgs() {
959         var a = []; /* why does arguments come accross as an object and not an array? */
960         for( var i = 0; i < arguments.length; i++ ) 
961                 a.push(arguments[i])
962
963         var preq = new Request(FETCH_HIGHEST_PERM_ORG, 
964                 G.user.session, G.user.id(), a );
965         preq.send(true);
966         return preq.result();
967 }
968