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