

//======================= Script:   /js/cookies js ()===========================
/*==============================================================================

    Routines written by John Gardner - 2003 - 2005

    See www.braemoor.co.uk/software for information about more freeware
    available.

================================================================================

Routine to write a session cookie

    Parameters:
        cookieName        Cookie name
        cookieValue       Cookie Value
    
    Return value:
        true              Session cookie written successfullly
        false             Failed - persistent cookies are not enabled

   e.g. if (writeSessionCookie("pans","drizzle") then
           alert ("Session cookie written");
        else
           alert ("Sorry - Session cookies not enabled");
*/

function writeSessionCookie (cookieName, cookieValue) {
  if (testSessionCookie()) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
  }
  else return false;
}

function writeSessionCookieWithPath (cookieName, cookieValue) {
  if (testSessionCookie()) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=" + window.location.pathname;
    return true;
  }
  else return false;
}
/*==============================================================================

Routine to get the current value of a cookie

    Parameters:
        cookieName        Cookie name
    
    Return value:
        false             Failed - no such cookie
        value             Value of the retrieved cookie

   e.g. if (!getCookieValue("pans") then  {
           cookieValue = getCoookieValue ("pans2);
        }
*/

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

/*==============================================================================

Routine to see if session cookies are enabled

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testSessionCookie())
           alert ("Session coookies are enabled");
        else
           alert ("Session coookies are not enabled");
*/

function testSessionCookie () {
	return true ;
  /*document.cookie ="testSessionCookie=Enabled";
  if (getCookieValue ("testSessionCookie")=="Enabled")
    return true 
  else
    return false;*/
}

/*==============================================================================

Routine to see of persistent cookies are allowed:

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testPersistentCookie()) then
           alert ("Persistent coookies are enabled");
        else
           alert ("Persistent coookies are not enabled");
*/

function testPersistentCookie () {
  writePersistentCookie ("testPersistentCookie", "Enabled", "minutes", 1);
  if (getCookieValue ("testPersistentCookie")=="Enabled")
    return true  
  else 
    return false;
}

/*==============================================================================

Routine to write a persistent cookie

    Parameters:
        CookieName        Cookie name
        CookieValue       Cookie Value
        periodType        "years","months","days","hours", "minutes"
        offset            Number of units specified in periodType
    
    Return value:
        true              Persistent cookie written successfullly
        false             Failed - persistent cookies are not enabled
    
    e.g. writePersistentCookie ("Session", id, "years", 1);
*/       

function writePersistentCookie (CookieName, CookieValue, periodType, offset) {

  var expireDate = new Date ();
  offset = offset / 1;
  
  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years": 
     var year = expireDate.getYear();     
     // Note some browsers give only the years since 1900, and some since 0.
     if (year < 1000) year = year + 1900;     
     expireDate.setYear(year + offset);
     break;
    case "months":
      expireDate.setMonth(expireDate.getMonth() + offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate() + offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours() + offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes() + offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  } 
  
  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}  

/*==============================================================================

Routine to delete a persistent cookie

    Parameters:
        CookieName        Cookie name
    
    Return value:
        true              Persistent cookie marked for deletion
    
    e.g. deleteCookie ("Session");
*/    

function deleteCookie (cookieName) {

  if (getCookieValue (cookieName)) writePersistentCookie (cookieName,"Pending delete","years", -1);  
  return true;     
}



//======================= Script:   /js/jquery-latest js ()===========================
/*
 * jQuery 1.2.6 - New Wave Javascript
 *
 * Copyright (c) 2008 John Resig (jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $
 * $Rev: 5685 $
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(H(){J w=1b.4M,3m$=1b.$;J D=1b.4M=1b.$=H(a,b){I 2B D.17.5j(a,b)};J u=/^[^<]*(<(.|\\s)+>)[^>]*$|^#(\\w+)$/,62=/^.[^:#\\[\\.]*$/,12;D.17=D.44={5j:H(d,b){d=d||S;G(d.16){7[0]=d;7.K=1;I 7}G(1j d=="23"){J c=u.2D(d);G(c&&(c[1]||!b)){G(c[1])d=D.4h([c[1]],b);N{J a=S.61(c[3]);G(a){G(a.2v!=c[3])I D().2q(d);I D(a)}d=[]}}N I D(b).2q(d)}N G(D.1D(d))I D(S)[D.17.27?"27":"43"](d);I 7.6Y(D.2d(d))},5w:"1.2.6",8G:H(){I 7.K},K:0,3p:H(a){I a==12?D.2d(7):7[a]},2I:H(b){J a=D(b);a.5n=7;I a},6Y:H(a){7.K=0;2p.44.1p.1w(7,a);I 7},P:H(a,b){I D.P(7,a,b)},5i:H(b){J a=-1;I D.2L(b&&b.5w?b[0]:b,7)},1K:H(c,a,b){J d=c;G(c.1q==56)G(a===12)I 7[0]&&D[b||"1K"](7[0],c);N{d={};d[c]=a}I 7.P(H(i){R(c 1n d)D.1K(b?7.V:7,c,D.1i(7,d[c],b,i,c))})},1g:H(b,a){G((b==\'2h\'||b==\'1Z\')&&3d(a)<0)a=12;I 7.1K(b,a,"2a")},1r:H(b){G(1j b!="49"&&b!=U)I 7.4E().3v((7[0]&&7[0].2z||S).5F(b));J a="";D.P(b||7,H(){D.P(7.3t,H(){G(7.16!=8)a+=7.16!=1?7.76:D.17.1r([7])})});I a},5z:H(b){G(7[0])D(b,7[0].2z).5y().39(7[0]).2l(H(){J a=7;1B(a.1x)a=a.1x;I a}).3v(7);I 7},8Y:H(a){I 7.P(H(){D(7).6Q().5z(a)})},8R:H(a){I 7.P(H(){D(7).5z(a)})},3v:H(){I 7.3W(19,M,Q,H(a){G(7.16==1)7.3U(a)})},6F:H(){I 7.3W(19,M,M,H(a){G(7.16==1)7.39(a,7.1x)})},6E:H(){I 7.3W(19,Q,Q,H(a){7.1d.39(a,7)})},5q:H(){I 7.3W(19,Q,M,H(a){7.1d.39(a,7.2H)})},3l:H(){I 7.5n||D([])},2q:H(b){J c=D.2l(7,H(a){I D.2q(b,a)});I 7.2I(/[^+>] [^+>]/.11(b)||b.1h("..")>-1?D.4r(c):c)},5y:H(e){J f=7.2l(H(){G(D.14.1f&&!D.4n(7)){J a=7.6o(M),5h=S.3h("1v");5h.3U(a);I D.4h([5h.4H])[0]}N I 7.6o(M)});J d=f.2q("*").5c().P(H(){G(7[E]!=12)7[E]=U});G(e===M)7.2q("*").5c().P(H(i){G(7.16==3)I;J c=D.L(7,"3w");R(J a 1n c)R(J b 1n c[a])D.W.1e(d[i],a,c[a][b],c[a][b].L)});I f},1E:H(b){I 7.2I(D.1D(b)&&D.3C(7,H(a,i){I b.1k(a,i)})||D.3g(b,7))},4Y:H(b){G(b.1q==56)G(62.11(b))I 7.2I(D.3g(b,7,M));N b=D.3g(b,7);J a=b.K&&b[b.K-1]!==12&&!b.16;I 7.1E(H(){I a?D.2L(7,b)<0:7!=b})},1e:H(a){I 7.2I(D.4r(D.2R(7.3p(),1j a==\'23\'?D(a):D.2d(a))))},3F:H(a){I!!a&&D.3g(a,7).K>0},7T:H(a){I 7.3F("."+a)},6e:H(b){G(b==12){G(7.K){J c=7[0];G(D.Y(c,"2A")){J e=c.64,63=[],15=c.15,2V=c.O=="2A-2V";G(e<0)I U;R(J i=2V?e:0,2f=2V?e+1:15.K;i<2f;i++){J d=15[i];G(d.2W){b=D.14.1f&&!d.at.2x.an?d.1r:d.2x;G(2V)I b;63.1p(b)}}I 63}N I(7[0].2x||"").1o(/\\r/g,"")}I 12}G(b.1q==4L)b+=\'\';I 7.P(H(){G(7.16!=1)I;G(b.1q==2p&&/5O|5L/.11(7.O))7.4J=(D.2L(7.2x,b)>=0||D.2L(7.34,b)>=0);N G(D.Y(7,"2A")){J a=D.2d(b);D("9R",7).P(H(){7.2W=(D.2L(7.2x,a)>=0||D.2L(7.1r,a)>=0)});G(!a.K)7.64=-1}N 7.2x=b})},2K:H(a){I a==12?(7[0]?7[0].4H:U):7.4E().3v(a)},7b:H(a){I 7.5q(a).21()},79:H(i){I 7.3s(i,i+1)},3s:H(){I 7.2I(2p.44.3s.1w(7,19))},2l:H(b){I 7.2I(D.2l(7,H(a,i){I b.1k(a,i,a)}))},5c:H(){I 7.1e(7.5n)},L:H(d,b){J a=d.1R(".");a[1]=a[1]?"."+a[1]:"";G(b===12){J c=7.5C("9z"+a[1]+"!",[a[0]]);G(c===12&&7.K)c=D.L(7[0],d);I c===12&&a[1]?7.L(a[0]):c}N I 7.1P("9u"+a[1]+"!",[a[0],b]).P(H(){D.L(7,d,b)})},3b:H(a){I 7.P(H(){D.3b(7,a)})},3W:H(g,f,h,d){J e=7.K>1,3x;I 7.P(H(){G(!3x){3x=D.4h(g,7.2z);G(h)3x.9o()}J b=7;G(f&&D.Y(7,"1T")&&D.Y(3x[0],"4F"))b=7.3H("22")[0]||7.3U(7.2z.3h("22"));J c=D([]);D.P(3x,H(){J a=e?D(7).5y(M)[0]:7;G(D.Y(a,"1m"))c=c.1e(a);N{G(a.16==1)c=c.1e(D("1m",a).21());d.1k(b,a)}});c.P(6T)})}};D.17.5j.44=D.17;H 6T(i,a){G(a.4d)D.3Y({1a:a.4d,31:Q,1O:"1m"});N D.5u(a.1r||a.6O||a.4H||"");G(a.1d)a.1d.37(a)}H 1z(){I+2B 8J}D.1l=D.17.1l=H(){J b=19[0]||{},i=1,K=19.K,4x=Q,15;G(b.1q==8I){4x=b;b=19[1]||{};i=2}G(1j b!="49"&&1j b!="H")b={};G(K==i){b=7;--i}R(;i<K;i++)G((15=19[i])!=U)R(J c 1n 15){J a=b[c],2w=15[c];G(b===2w)6M;G(4x&&2w&&1j 2w=="49"&&!2w.16)b[c]=D.1l(4x,a||(2w.K!=U?[]:{}),2w);N G(2w!==12)b[c]=2w}I b};J E="4M"+1z(),6K=0,5r={},6G=/z-?5i|8B-?8A|1y|6B|8v-?1Z/i,3P=S.3P||{};D.1l({8u:H(a){1b.$=3m$;G(a)1b.4M=w;I D},1D:H(a){I!!a&&1j a!="23"&&!a.Y&&a.1q!=2p&&/^[\\s[]?H/.11(a+"")},4n:H(a){I a.1C&&!a.1c||a.2j&&a.2z&&!a.2z.1c},5u:H(a){a=D.3k(a);G(a){J b=S.3H("6w")[0]||S.1C,1m=S.3h("1m");1m.O="1r/4t";G(D.14.1f)1m.1r=a;N 1m.3U(S.5F(a));b.39(1m,b.1x);b.37(1m)}},Y:H(b,a){I b.Y&&b.Y.2r()==a.2r()},1Y:{},L:H(c,d,b){c=c==1b?5r:c;J a=c[E];G(!a)a=c[E]=++6K;G(d&&!D.1Y[a])D.1Y[a]={};G(b!==12)D.1Y[a][d]=b;I d?D.1Y[a][d]:a},3b:H(c,b){c=c==1b?5r:c;J a=c[E];G(b){G(D.1Y[a]){2U D.1Y[a][b];b="";R(b 1n D.1Y[a])1X;G(!b)D.3b(c)}}N{1U{2U c[E]}1V(e){G(c.5l)c.5l(E)}2U D.1Y[a]}},P:H(d,a,c){J e,i=0,K=d.K;G(c){G(K==12){R(e 1n d)G(a.1w(d[e],c)===Q)1X}N R(;i<K;)G(a.1w(d[i++],c)===Q)1X}N{G(K==12){R(e 1n d)G(a.1k(d[e],e,d[e])===Q)1X}N R(J b=d[0];i<K&&a.1k(b,i,b)!==Q;b=d[++i]){}}I d},1i:H(b,a,c,i,d){G(D.1D(a))a=a.1k(b,i);I a&&a.1q==4L&&c=="2a"&&!6G.11(d)?a+"2X":a},1F:{1e:H(c,b){D.P((b||"").1R(/\\s+/),H(i,a){G(c.16==1&&!D.1F.3T(c.1F,a))c.1F+=(c.1F?" ":"")+a})},21:H(c,b){G(c.16==1)c.1F=b!=12?D.3C(c.1F.1R(/\\s+/),H(a){I!D.1F.3T(b,a)}).6s(" "):""},3T:H(b,a){I D.2L(a,(b.1F||b).6r().1R(/\\s+/))>-1}},6q:H(b,c,a){J e={};R(J d 1n c){e[d]=b.V[d];b.V[d]=c[d]}a.1k(b);R(J d 1n c)b.V[d]=e[d]},1g:H(d,e,c){G(e=="2h"||e=="1Z"){J b,3X={30:"5x",5g:"1G",18:"3I"},35=e=="2h"?["5e","6k"]:["5G","6i"];H 5b(){b=e=="2h"?d.8f:d.8c;J a=0,2C=0;D.P(35,H(){a+=3d(D.2a(d,"57"+7,M))||0;2C+=3d(D.2a(d,"2C"+7+"4b",M))||0});b-=29.83(a+2C)}G(D(d).3F(":4j"))5b();N D.6q(d,3X,5b);I 29.2f(0,b)}I D.2a(d,e,c)},2a:H(f,l,k){J e,V=f.V;H 3E(b){G(!D.14.2k)I Q;J a=3P.54(b,U);I!a||a.52("3E")==""}G(l=="1y"&&D.14.1f){e=D.1K(V,"1y");I e==""?"1":e}G(D.14.2G&&l=="18"){J d=V.50;V.50="0 7Y 7W";V.50=d}G(l.1I(/4i/i))l=y;G(!k&&V&&V[l])e=V[l];N G(3P.54){G(l.1I(/4i/i))l="4i";l=l.1o(/([A-Z])/g,"-$1").3y();J c=3P.54(f,U);G(c&&!3E(f))e=c.52(l);N{J g=[],2E=[],a=f,i=0;R(;a&&3E(a);a=a.1d)2E.6h(a);R(;i<2E.K;i++)G(3E(2E[i])){g[i]=2E[i].V.18;2E[i].V.18="3I"}e=l=="18"&&g[2E.K-1]!=U?"2F":(c&&c.52(l))||"";R(i=0;i<g.K;i++)G(g[i]!=U)2E[i].V.18=g[i]}G(l=="1y"&&e=="")e="1"}N G(f.4g){J h=l.1o(/\\-(\\w)/g,H(a,b){I b.2r()});e=f.4g[l]||f.4g[h];G(!/^\\d+(2X)?$/i.11(e)&&/^\\d/.11(e)){J j=V.1A,66=f.65.1A;f.65.1A=f.4g.1A;V.1A=e||0;e=V.aM+"2X";V.1A=j;f.65.1A=66}}I e},4h:H(l,h){J k=[];h=h||S;G(1j h.3h==\'12\')h=h.2z||h[0]&&h[0].2z||S;D.P(l,H(i,d){G(!d)I;G(d.1q==4L)d+=\'\';G(1j d=="23"){d=d.1o(/(<(\\w+)[^>]*?)\\/>/g,H(b,a,c){I c.1I(/^(aK|4f|7E|aG|4T|7A|aB|3n|az|ay|av)$/i)?b:a+"></"+c+">"});J f=D.3k(d).3y(),1v=h.3h("1v");J e=!f.1h("<au")&&[1,"<2A 7w=\'7w\'>","</2A>"]||!f.1h("<ar")&&[1,"<7v>","</7v>"]||f.1I(/^<(aq|22|am|ak|ai)/)&&[1,"<1T>","</1T>"]||!f.1h("<4F")&&[2,"<1T><22>","</22></1T>"]||(!f.1h("<af")||!f.1h("<ad"))&&[3,"<1T><22><4F>","</4F></22></1T>"]||!f.1h("<7E")&&[2,"<1T><22></22><7q>","</7q></1T>"]||D.14.1f&&[1,"1v<1v>","</1v>"]||[0,"",""];1v.4H=e[1]+d+e[2];1B(e[0]--)1v=1v.5T;G(D.14.1f){J g=!f.1h("<1T")&&f.1h("<22")<0?1v.1x&&1v.1x.3t:e[1]=="<1T>"&&f.1h("<22")<0?1v.3t:[];R(J j=g.K-1;j>=0;--j)G(D.Y(g[j],"22")&&!g[j].3t.K)g[j].1d.37(g[j]);G(/^\\s/.11(d))1v.39(h.5F(d.1I(/^\\s*/)[0]),1v.1x)}d=D.2d(1v.3t)}G(d.K===0&&(!D.Y(d,"3V")&&!D.Y(d,"2A")))I;G(d[0]==12||D.Y(d,"3V")||d.15)k.1p(d);N k=D.2R(k,d)});I k},1K:H(d,f,c){G(!d||d.16==3||d.16==8)I 12;J e=!D.4n(d),40=c!==12,1f=D.14.1f;f=e&&D.3X[f]||f;G(d.2j){J g=/5Q|4d|V/.11(f);G(f=="2W"&&D.14.2k)d.1d.64;G(f 1n d&&e&&!g){G(40){G(f=="O"&&D.Y(d,"4T")&&d.1d)7p"O a3 a1\'t 9V 9U";d[f]=c}G(D.Y(d,"3V")&&d.7i(f))I d.7i(f).76;I d[f]}G(1f&&e&&f=="V")I D.1K(d.V,"9T",c);G(40)d.9Q(f,""+c);J h=1f&&e&&g?d.4G(f,2):d.4G(f);I h===U?12:h}G(1f&&f=="1y"){G(40){d.6B=1;d.1E=(d.1E||"").1o(/7f\\([^)]*\\)/,"")+(3r(c)+\'\'=="9L"?"":"7f(1y="+c*7a+")")}I d.1E&&d.1E.1h("1y=")>=0?(3d(d.1E.1I(/1y=([^)]*)/)[1])/7a)+\'\':""}f=f.1o(/-([a-z])/9H,H(a,b){I b.2r()});G(40)d[f]=c;I d[f]},3k:H(a){I(a||"").1o(/^\\s+|\\s+$/g,"")},2d:H(b){J a=[];G(b!=U){J i=b.K;G(i==U||b.1R||b.4I||b.1k)a[0]=b;N 1B(i)a[--i]=b[i]}I a},2L:H(b,a){R(J i=0,K=a.K;i<K;i++)G(a[i]===b)I i;I-1},2R:H(a,b){J i=0,T,2S=a.K;G(D.14.1f){1B(T=b[i++])G(T.16!=8)a[2S++]=T}N 1B(T=b[i++])a[2S++]=T;I a},4r:H(a){J c=[],2o={};1U{R(J i=0,K=a.K;i<K;i++){J b=D.L(a[i]);G(!2o[b]){2o[b]=M;c.1p(a[i])}}}1V(e){c=a}I c},3C:H(c,a,d){J b=[];R(J i=0,K=c.K;i<K;i++)G(!d!=!a(c[i],i))b.1p(c[i]);I b},2l:H(d,a){J c=[];R(J i=0,K=d.K;i<K;i++){J b=a(d[i],i);G(b!=U)c[c.K]=b}I c.7d.1w([],c)}});J v=9B.9A.3y();D.14={5B:(v.1I(/.+(?:9y|9x|9w|9v)[\\/: ]([\\d.]+)/)||[])[1],2k:/75/.11(v),2G:/2G/.11(v),1f:/1f/.11(v)&&!/2G/.11(v),42:/42/.11(v)&&!/(9s|75)/.11(v)};J y=D.14.1f?"7o":"72";D.1l({71:!D.14.1f||S.70=="6Z",3X:{"R":"9n","9k":"1F","4i":y,72:y,7o:y,9h:"9f",9e:"9d",9b:"99"}});D.P({6W:H(a){I a.1d},97:H(a){I D.4S(a,"1d")},95:H(a){I D.3a(a,2,"2H")},91:H(a){I D.3a(a,2,"4l")},8Z:H(a){I D.4S(a,"2H")},8X:H(a){I D.4S(a,"4l")},8W:H(a){I D.5v(a.1d.1x,a)},8V:H(a){I D.5v(a.1x)},6Q:H(a){I D.Y(a,"8U")?a.8T||a.8S.S:D.2d(a.3t)}},H(c,d){D.17[c]=H(b){J a=D.2l(7,d);G(b&&1j b=="23")a=D.3g(b,a);I 7.2I(D.4r(a))}});D.P({6P:"3v",8Q:"6F",39:"6E",8P:"5q",8O:"7b"},H(c,b){D.17[c]=H(){J a=19;I 7.P(H(){R(J i=0,K=a.K;i<K;i++)D(a[i])[b](7)})}});D.P({8N:H(a){D.1K(7,a,"");G(7.16==1)7.5l(a)},8M:H(a){D.1F.1e(7,a)},8L:H(a){D.1F.21(7,a)},8K:H(a){D.1F[D.1F.3T(7,a)?"21":"1e"](7,a)},21:H(a){G(!a||D.1E(a,[7]).r.K){D("*",7).1e(7).P(H(){D.W.21(7);D.3b(7)});G(7.1d)7.1d.37(7)}},4E:H(){D(">*",7).21();1B(7.1x)7.37(7.1x)}},H(a,b){D.17[a]=H(){I 7.P(b,19)}});D.P(["6N","4b"],H(i,c){J b=c.3y();D.17[b]=H(a){I 7[0]==1b?D.14.2G&&S.1c["5t"+c]||D.14.2k&&1b["5s"+c]||S.70=="6Z"&&S.1C["5t"+c]||S.1c["5t"+c]:7[0]==S?29.2f(29.2f(S.1c["4y"+c],S.1C["4y"+c]),29.2f(S.1c["2i"+c],S.1C["2i"+c])):a==12?(7.K?D.1g(7[0],b):U):7.1g(b,a.1q==56?a:a+"2X")}});H 25(a,b){I a[0]&&3r(D.2a(a[0],b,M),10)||0}J C=D.14.2k&&3r(D.14.5B)<8H?"(?:[\\\\w*3m-]|\\\\\\\\.)":"(?:[\\\\w\\8F-\\8E*3m-]|\\\\\\\\.)",6L=2B 4v("^>\\\\s*("+C+"+)"),6J=2B 4v("^("+C+"+)(#)("+C+"+)"),6I=2B 4v("^([#.]?)("+C+"*)");D.1l({6H:{"":H(a,i,m){I m[2]=="*"||D.Y(a,m[2])},"#":H(a,i,m){I a.4G("2v")==m[2]},":":{8D:H(a,i,m){I i<m[3]-0},8C:H(a,i,m){I i>m[3]-0},3a:H(a,i,m){I m[3]-0==i},79:H(a,i,m){I m[3]-0==i},3o:H(a,i){I i==0},3S:H(a,i,m,r){I i==r.K-1},6D:H(a,i){I i%2==0},6C:H(a,i){I i%2},"3o-4u":H(a){I a.1d.3H("*")[0]==a},"3S-4u":H(a){I D.3a(a.1d.5T,1,"4l")==a},"8z-4u":H(a){I!D.3a(a.1d.5T,2,"4l")},6W:H(a){I a.1x},4E:H(a){I!a.1x},8y:H(a,i,m){I(a.6O||a.8x||D(a).1r()||"").1h(m[3])>=0},4j:H(a){I"1G"!=a.O&&D.1g(a,"18")!="2F"&&D.1g(a,"5g")!="1G"},1G:H(a){I"1G"==a.O||D.1g(a,"18")=="2F"||D.1g(a,"5g")=="1G"},8w:H(a){I!a.3R},3R:H(a){I a.3R},4J:H(a){I a.4J},2W:H(a){I a.2W||D.1K(a,"2W")},1r:H(a){I"1r"==a.O},5O:H(a){I"5O"==a.O},5L:H(a){I"5L"==a.O},5p:H(a){I"5p"==a.O},3Q:H(a){I"3Q"==a.O},5o:H(a){I"5o"==a.O},6A:H(a){I"6A"==a.O},6z:H(a){I"6z"==a.O},2s:H(a){I"2s"==a.O||D.Y(a,"2s")},4T:H(a){I/4T|2A|6y|2s/i.11(a.Y)},3T:H(a,i,m){I D.2q(m[3],a).K},8t:H(a){I/h\\d/i.11(a.Y)},8s:H(a){I D.3C(D.3O,H(b){I a==b.T}).K}}},6x:[/^(\\[) *@?([\\w-]+) *([!*$^~=]*) *(\'?"?)(.*?)\\4 *\\]/,/^(:)([\\w-]+)\\("?\'?(.*?(\\(.*?\\))?[^(]*?)"?\'?\\)/,2B 4v("^([:.#]*)("+C+"+)")],3g:H(a,c,b){J d,1t=[];1B(a&&a!=d){d=a;J f=D.1E(a,c,b);a=f.t.1o(/^\\s*,\\s*/,"");1t=b?c=f.r:D.2R(1t,f.r)}I 1t},2q:H(t,o){G(1j t!="23")I[t];G(o&&o.16!=1&&o.16!=9)I[];o=o||S;J d=[o],2o=[],3S,Y;1B(t&&3S!=t){J r=[];3S=t;t=D.3k(t);J l=Q,3j=6L,m=3j.2D(t);G(m){Y=m[1].2r();R(J i=0;d[i];i++)R(J c=d[i].1x;c;c=c.2H)G(c.16==1&&(Y=="*"||c.Y.2r()==Y))r.1p(c);d=r;t=t.1o(3j,"");G(t.1h(" ")==0)6M;l=M}N{3j=/^([>+~])\\s*(\\w*)/i;G((m=3j.2D(t))!=U){r=[];J k={};Y=m[2].2r();m=m[1];R(J j=0,3i=d.K;j<3i;j++){J n=m=="~"||m=="+"?d[j].2H:d[j].1x;R(;n;n=n.2H)G(n.16==1){J g=D.L(n);G(m=="~"&&k[g])1X;G(!Y||n.Y.2r()==Y){G(m=="~")k[g]=M;r.1p(n)}G(m=="+")1X}}d=r;t=D.3k(t.1o(3j,""));l=M}}G(t&&!l){G(!t.1h(",")){G(o==d[0])d.4s();2o=D.2R(2o,d);r=d=[o];t=" "+t.6v(1,t.K)}N{J h=6J;J m=h.2D(t);G(m){m=[0,m[2],m[3],m[1]]}N{h=6I;m=h.2D(t)}m[2]=m[2].1o(/\\\\/g,"");J f=d[d.K-1];G(m[1]=="#"&&f&&f.61&&!D.4n(f)){J p=f.61(m[2]);G((D.14.1f||D.14.2G)&&p&&1j p.2v=="23"&&p.2v!=m[2])p=D(\'[@2v="\'+m[2]+\'"]\',f)[0];d=r=p&&(!m[3]||D.Y(p,m[3]))?[p]:[]}N{R(J i=0;d[i];i++){J a=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];G(a=="*"&&d[i].Y.3y()=="49")a="3n";r=D.2R(r,d[i].3H(a))}G(m[1]==".")r=D.5m(r,m[2]);G(m[1]=="#"){J e=[];R(J i=0;r[i];i++)G(r[i].4G("2v")==m[2]){e=[r[i]];1X}r=e}d=r}t=t.1o(h,"")}}G(t){J b=D.1E(t,r);d=r=b.r;t=D.3k(b.t)}}G(t)d=[];G(d&&o==d[0])d.4s();2o=D.2R(2o,d);I 2o},5m:H(r,m,a){m=" "+m+" ";J c=[];R(J i=0;r[i];i++){J b=(" "+r[i].1F+" ").1h(m)>=0;G(!a&&b||a&&!b)c.1p(r[i])}I c},1E:H(t,r,h){J d;1B(t&&t!=d){d=t;J p=D.6x,m;R(J i=0;p[i];i++){m=p[i].2D(t);G(m){t=t.8r(m[0].K);m[2]=m[2].1o(/\\\\/g,"");1X}}G(!m)1X;G(m[1]==":"&&m[2]=="4Y")r=62.11(m[3])?D.1E(m[3],r,M).r:D(r).4Y(m[3]);N G(m[1]==".")r=D.5m(r,m[2],h);N G(m[1]=="["){J g=[],O=m[3];R(J i=0,3i=r.K;i<3i;i++){J a=r[i],z=a[D.3X[m[2]]||m[2]];G(z==U||/5Q|4d|2W/.11(m[2]))z=D.1K(a,m[2])||\'\';G((O==""&&!!z||O=="="&&z==m[5]||O=="!="&&z!=m[5]||O=="^="&&z&&!z.1h(m[5])||O=="$="&&z.6v(z.K-m[5].K)==m[5]||(O=="*="||O=="~=")&&z.1h(m[5])>=0)^h)g.1p(a)}r=g}N G(m[1]==":"&&m[2]=="3a-4u"){J e={},g=[],11=/(-?)(\\d*)n((?:\\+|-)?\\d*)/.2D(m[3]=="6D"&&"2n"||m[3]=="6C"&&"2n+1"||!/\\D/.11(m[3])&&"8q+"+m[3]||m[3]),3o=(11[1]+(11[2]||1))-0,d=11[3]-0;R(J i=0,3i=r.K;i<3i;i++){J j=r[i],1d=j.1d,2v=D.L(1d);G(!e[2v]){J c=1;R(J n=1d.1x;n;n=n.2H)G(n.16==1)n.4q=c++;e[2v]=M}J b=Q;G(3o==0){G(j.4q==d)b=M}N G((j.4q-d)%3o==0&&(j.4q-d)/3o>=0)b=M;G(b^h)g.1p(j)}r=g}N{J f=D.6H[m[1]];G(1j f=="49")f=f[m[2]];G(1j f=="23")f=6u("Q||H(a,i){I "+f+";}");r=D.3C(r,H(a,i){I f(a,i,m,r)},h)}}I{r:r,t:t}},4S:H(b,c){J a=[],1t=b[c];1B(1t&&1t!=S){G(1t.16==1)a.1p(1t);1t=1t[c]}I a},3a:H(a,e,c,b){e=e||1;J d=0;R(;a;a=a[c])G(a.16==1&&++d==e)1X;I a},5v:H(n,a){J r=[];R(;n;n=n.2H){G(n.16==1&&n!=a)r.1p(n)}I r}});D.W={1e:H(f,i,g,e){G(f.16==3||f.16==8)I;G(D.14.1f&&f.4I)f=1b;G(!g.24)g.24=7.24++;G(e!=12){J h=g;g=7.3M(h,H(){I h.1w(7,19)});g.L=e}J j=D.L(f,"3w")||D.L(f,"3w",{}),1H=D.L(f,"1H")||D.L(f,"1H",H(){G(1j D!="12"&&!D.W.5k)I D.W.1H.1w(19.3L.T,19)});1H.T=f;D.P(i.1R(/\\s+/),H(c,b){J a=b.1R(".");b=a[0];g.O=a[1];J d=j[b];G(!d){d=j[b]={};G(!D.W.2t[b]||D.W.2t[b].4p.1k(f)===Q){G(f.3K)f.3K(b,1H,Q);N G(f.6t)f.6t("4o"+b,1H)}}d[g.24]=g;D.W.26[b]=M});f=U},24:1,26:{},21:H(e,h,f){G(e.16==3||e.16==8)I;J i=D.L(e,"3w"),1L,5i;G(i){G(h==12||(1j h=="23"&&h.8p(0)=="."))R(J g 1n i)7.21(e,g+(h||""));N{G(h.O){f=h.2y;h=h.O}D.P(h.1R(/\\s+/),H(b,a){J c=a.1R(".");a=c[0];G(i[a]){G(f)2U i[a][f.24];N R(f 1n i[a])G(!c[1]||i[a][f].O==c[1])2U i[a][f];R(1L 1n i[a])1X;G(!1L){G(!D.W.2t[a]||D.W.2t[a].4A.1k(e)===Q){G(e.6p)e.6p(a,D.L(e,"1H"),Q);N G(e.6n)e.6n("4o"+a,D.L(e,"1H"))}1L=U;2U i[a]}}})}R(1L 1n i)1X;G(!1L){J d=D.L(e,"1H");G(d)d.T=U;D.3b(e,"3w");D.3b(e,"1H")}}},1P:H(h,c,f,g,i){c=D.2d(c);G(h.1h("!")>=0){h=h.3s(0,-1);J a=M}G(!f){G(7.26[h])D("*").1e([1b,S]).1P(h,c)}N{G(f.16==3||f.16==8)I 12;J b,1L,17=D.1D(f[h]||U),W=!c[0]||!c[0].32;G(W){c.6h({O:h,2J:f,32:H(){},3J:H(){},4C:1z()});c[0][E]=M}c[0].O=h;G(a)c[0].6m=M;J d=D.L(f,"1H");G(d)b=d.1w(f,c);G((!17||(D.Y(f,\'a\')&&h=="4V"))&&f["4o"+h]&&f["4o"+h].1w(f,c)===Q)b=Q;G(W)c.4s();G(i&&D.1D(i)){1L=i.1w(f,b==U?c:c.7d(b));G(1L!==12)b=1L}G(17&&g!==Q&&b!==Q&&!(D.Y(f,\'a\')&&h=="4V")){7.5k=M;1U{f[h]()}1V(e){}}7.5k=Q}I b},1H:H(b){J a,1L,38,5f,4m;b=19[0]=D.W.6l(b||1b.W);38=b.O.1R(".");b.O=38[0];38=38[1];5f=!38&&!b.6m;4m=(D.L(7,"3w")||{})[b.O];R(J j 1n 4m){J c=4m[j];G(5f||c.O==38){b.2y=c;b.L=c.L;1L=c.1w(7,19);G(a!==Q)a=1L;G(1L===Q){b.32();b.3J()}}}I a},6l:H(b){G(b[E]==M)I b;J d=b;b={8o:d};J c="8n 8m 8l 8k 2s 8j 47 5d 6j 5E 8i L 8h 8g 4K 2y 5a 59 8e 8b 58 6f 8a 88 4k 87 86 84 6d 2J 4C 6c O 82 81 35".1R(" ");R(J i=c.K;i;i--)b[c[i]]=d[c[i]];b[E]=M;b.32=H(){G(d.32)d.32();d.80=Q};b.3J=H(){G(d.3J)d.3J();d.7Z=M};b.4C=b.4C||1z();G(!b.2J)b.2J=b.6d||S;G(b.2J.16==3)b.2J=b.2J.1d;G(!b.4k&&b.4K)b.4k=b.4K==b.2J?b.6c:b.4K;G(b.58==U&&b.5d!=U){J a=S.1C,1c=S.1c;b.58=b.5d+(a&&a.2e||1c&&1c.2e||0)-(a.6b||0);b.6f=b.6j+(a&&a.2c||1c&&1c.2c||0)-(a.6a||0)}G(!b.35&&((b.47||b.47===0)?b.47:b.5a))b.35=b.47||b.5a;G(!b.59&&b.5E)b.59=b.5E;G(!b.35&&b.2s)b.35=(b.2s&1?1:(b.2s&2?3:(b.2s&4?2:0)));I b},3M:H(a,b){b.24=a.24=a.24||b.24||7.24++;I b},2t:{27:{4p:H(){55();I},4A:H(){I}},3D:{4p:H(){G(D.14.1f)I Q;D(7).2O("53",D.W.2t.3D.2y);I M},4A:H(){G(D.14.1f)I Q;D(7).4e("53",D.W.2t.3D.2y);I M},2y:H(a){G(F(a,7))I M;a.O="3D";I D.W.1H.1w(7,19)}},3N:{4p:H(){G(D.14.1f)I Q;D(7).2O("51",D.W.2t.3N.2y);I M},4A:H(){G(D.14.1f)I Q;D(7).4e("51",D.W.2t.3N.2y);I M},2y:H(a){G(F(a,7))I M;a.O="3N";I D.W.1H.1w(7,19)}}}};D.17.1l({2O:H(c,a,b){I c=="4X"?7.2V(c,a,b):7.P(H(){D.W.1e(7,c,b||a,b&&a)})},2V:H(d,b,c){J e=D.W.3M(c||b,H(a){D(7).4e(a,e);I(c||b).1w(7,19)});I 7.P(H(){D.W.1e(7,d,e,c&&b)})},4e:H(a,b){I 7.P(H(){D.W.21(7,a,b)})},1P:H(c,a,b){I 7.P(H(){D.W.1P(c,a,7,M,b)})},5C:H(c,a,b){I 7[0]&&D.W.1P(c,a,7[0],Q,b)},2m:H(b){J c=19,i=1;1B(i<c.K)D.W.3M(b,c[i++]);I 7.4V(D.W.3M(b,H(a){7.4Z=(7.4Z||0)%i;a.32();I c[7.4Z++].1w(7,19)||Q}))},7X:H(a,b){I 7.2O(\'3D\',a).2O(\'3N\',b)},27:H(a){55();G(D.2Q)a.1k(S,D);N D.3A.1p(H(){I a.1k(7,D)});I 7}});D.1l({2Q:Q,3A:[],27:H(){G(!D.2Q){D.2Q=M;G(D.3A){D.P(D.3A,H(){7.1k(S)});D.3A=U}D(S).5C("27")}}});J x=Q;H 55(){G(x)I;x=M;G(S.3K&&!D.14.2G)S.3K("69",D.27,Q);G(D.14.1f&&1b==1S)(H(){G(D.2Q)I;1U{S.1C.7V("1A")}1V(3e){3B(19.3L,0);I}D.27()})();G(D.14.2G)S.3K("69",H(){G(D.2Q)I;R(J i=0;i<S.4W.K;i++)G(S.4W[i].3R){3B(19.3L,0);I}D.27()},Q);G(D.14.2k){J a;(H(){G(D.2Q)I;G(S.3f!="68"&&S.3f!="1J"){3B(19.3L,0);I}G(a===12)a=D("V, 7A[7U=7S]").K;G(S.4W.K!=a){3B(19.3L,0);I}D.27()})()}D.W.1e(1b,"43",D.27)}D.P(("7R,7Q,43,85,4y,4X,4V,7P,"+"7O,7N,89,53,51,7M,2A,"+"5o,7L,7K,8d,3e").1R(","),H(i,b){D.17[b]=H(a){I a?7.2O(b,a):7.1P(b)}});J F=H(a,c){J b=a.4k;1B(b&&b!=c)1U{b=b.1d}1V(3e){b=c}I b==c};D(1b).2O("4X",H(){D("*").1e(S).4e()});D.17.1l({67:D.17.43,43:H(g,d,c){G(1j g!=\'23\')I 7.67(g);J e=g.1h(" ");G(e>=0){J i=g.3s(e,g.K);g=g.3s(0,e)}c=c||H(){};J f="2P";G(d)G(D.1D(d)){c=d;d=U}N{d=D.3n(d);f="6g"}J h=7;D.3Y({1a:g,O:f,1O:"2K",L:d,1J:H(a,b){G(b=="1W"||b=="7J")h.2K(i?D("<1v/>").3v(a.4U.1o(/<1m(.|\\s)*?\\/1m>/g,"")).2q(i):a.4U);h.P(c,[a.4U,b,a])}});I 7},aL:H(){I D.3n(7.7I())},7I:H(){I 7.2l(H(){I D.Y(7,"3V")?D.2d(7.aH):7}).1E(H(){I 7.34&&!7.3R&&(7.4J||/2A|6y/i.11(7.Y)||/1r|1G|3Q/i.11(7.O))}).2l(H(i,c){J b=D(7).6e();I b==U?U:b.1q==2p?D.2l(b,H(a,i){I{34:c.34,2x:a}}):{34:c.34,2x:b}}).3p()}});D.P("7H,7G,7F,7D,7C,7B".1R(","),H(i,o){D.17[o]=H(f){I 7.2O(o,f)}});J B=1z();D.1l({3p:H(d,b,a,c){G(D.1D(b)){a=b;b=U}I D.3Y({O:"2P",1a:d,L:b,1W:a,1O:c})},aE:H(b,a){I D.3p(b,U,a,"1m")},aD:H(c,b,a){I D.3p(c,b,a,"3z")},aC:H(d,b,a,c){G(D.1D(b)){a=b;b={}}I D.3Y({O:"6g",1a:d,L:b,1W:a,1O:c})},aA:H(a){D.1l(D.60,a)},60:{1a:5Z.5Q,26:M,O:"2P",2T:0,7z:"4R/x-ax-3V-aw",7x:M,31:M,L:U,5Y:U,3Q:U,4Q:{2N:"4R/2N, 1r/2N",2K:"1r/2K",1m:"1r/4t, 4R/4t",3z:"4R/3z, 1r/4t",1r:"1r/as",4w:"*/*"}},4z:{},3Y:H(s){s=D.1l(M,s,D.1l(M,{},D.60,s));J g,2Z=/=\\?(&|$)/g,1u,L,O=s.O.2r();G(s.L&&s.7x&&1j s.L!="23")s.L=D.3n(s.L);G(s.1O=="4P"){G(O=="2P"){G(!s.1a.1I(2Z))s.1a+=(s.1a.1I(/\\?/)?"&":"?")+(s.4P||"7u")+"=?"}N G(!s.L||!s.L.1I(2Z))s.L=(s.L?s.L+"&":"")+(s.4P||"7u")+"=?";s.1O="3z"}G(s.1O=="3z"&&(s.L&&s.L.1I(2Z)||s.1a.1I(2Z))){g="4P"+B++;G(s.L)s.L=(s.L+"").1o(2Z,"="+g+"$1");s.1a=s.1a.1o(2Z,"="+g+"$1");s.1O="1m";1b[g]=H(a){L=a;1W();1J();1b[g]=12;1U{2U 1b[g]}1V(e){}G(i)i.37(h)}}G(s.1O=="1m"&&s.1Y==U)s.1Y=Q;G(s.1Y===Q&&O=="2P"){J j=1z();J k=s.1a.1o(/(\\?|&)3m=.*?(&|$)/,"$ap="+j+"$2");s.1a=k+((k==s.1a)?(s.1a.1I(/\\?/)?"&":"?")+"3m="+j:"")}G(s.L&&O=="2P"){s.1a+=(s.1a.1I(/\\?/)?"&":"?")+s.L;s.L=U}G(s.26&&!D.4O++)D.W.1P("7H");J n=/^(?:\\w+:)?\\/\\/([^\\/?#]+)/;G(s.1O=="1m"&&O=="2P"&&n.11(s.1a)&&n.2D(s.1a)[1]!=5Z.al){J i=S.3H("6w")[0];J h=S.3h("1m");h.4d=s.1a;G(s.7t)h.aj=s.7t;G(!g){J l=Q;h.ah=h.ag=H(){G(!l&&(!7.3f||7.3f=="68"||7.3f=="1J")){l=M;1W();1J();i.37(h)}}}i.3U(h);I 12}J m=Q;J c=1b.7s?2B 7s("ae.ac"):2B 7r();G(s.5Y)c.6R(O,s.1a,s.31,s.5Y,s.3Q);N c.6R(O,s.1a,s.31);1U{G(s.L)c.4B("ab-aa",s.7z);G(s.5S)c.4B("a9-5R-a8",D.4z[s.1a]||"a7, a6 a5 a4 5N:5N:5N a2");c.4B("X-9Z-9Y","7r");c.4B("9W",s.1O&&s.4Q[s.1O]?s.4Q[s.1O]+", */*":s.4Q.4w)}1V(e){}G(s.7m&&s.7m(c,s)===Q){s.26&&D.4O--;c.7l();I Q}G(s.26)D.W.1P("7B",[c,s]);J d=H(a){G(!m&&c&&(c.3f==4||a=="2T")){m=M;G(f){7k(f);f=U}1u=a=="2T"&&"2T"||!D.7j(c)&&"3e"||s.5S&&D.7h(c,s.1a)&&"7J"||"1W";G(1u=="1W"){1U{L=D.6X(c,s.1O,s.9S)}1V(e){1u="5J"}}G(1u=="1W"){J b;1U{b=c.5I("7g-5R")}1V(e){}G(s.5S&&b)D.4z[s.1a]=b;G(!g)1W()}N D.5H(s,c,1u);1J();G(s.31)c=U}};G(s.31){J f=4I(d,13);G(s.2T>0)3B(H(){G(c){c.7l();G(!m)d("2T")}},s.2T)}1U{c.9P(s.L)}1V(e){D.5H(s,c,U,e)}G(!s.31)d();H 1W(){G(s.1W)s.1W(L,1u);G(s.26)D.W.1P("7C",[c,s])}H 1J(){G(s.1J)s.1J(c,1u);G(s.26)D.W.1P("7F",[c,s]);G(s.26&&!--D.4O)D.W.1P("7G")}I c},5H:H(s,a,b,e){G(s.3e)s.3e(a,b,e);G(s.26)D.W.1P("7D",[a,s,e])},4O:0,7j:H(a){1U{I!a.1u&&5Z.9O=="5p:"||(a.1u>=7e&&a.1u<9N)||a.1u==7c||a.1u==9K||D.14.2k&&a.1u==12}1V(e){}I Q},7h:H(a,c){1U{J b=a.5I("7g-5R");I a.1u==7c||b==D.4z[c]||D.14.2k&&a.1u==12}1V(e){}I Q},6X:H(a,c,b){J d=a.5I("9J-O"),2N=c=="2N"||!c&&d&&d.1h("2N")>=0,L=2N?a.9I:a.4U;G(2N&&L.1C.2j=="5J")7p"5J";G(b)L=b(L,c);G(c=="1m")D.5u(L);G(c=="3z")L=6u("("+L+")");I L},3n:H(a){J s=[];G(a.1q==2p||a.5w)D.P(a,H(){s.1p(3u(7.34)+"="+3u(7.2x))});N R(J j 1n a)G(a[j]&&a[j].1q==2p)D.P(a[j],H(){s.1p(3u(j)+"="+3u(7))});N s.1p(3u(j)+"="+3u(D.1D(a[j])?a[j]():a[j]));I s.6s("&").1o(/%20/g,"+")}});D.17.1l({1N:H(c,b){I c?7.2g({1Z:"1N",2h:"1N",1y:"1N"},c,b):7.1E(":1G").P(H(){7.V.18=7.5D||"";G(D.1g(7,"18")=="2F"){J a=D("<"+7.2j+" />").6P("1c");7.V.18=a.1g("18");G(7.V.18=="2F")7.V.18="3I";a.21()}}).3l()},1M:H(b,a){I b?7.2g({1Z:"1M",2h:"1M",1y:"1M"},b,a):7.1E(":4j").P(H(){7.5D=7.5D||D.1g(7,"18");7.V.18="2F"}).3l()},78:D.17.2m,2m:H(a,b){I D.1D(a)&&D.1D(b)?7.78.1w(7,19):a?7.2g({1Z:"2m",2h:"2m",1y:"2m"},a,b):7.P(H(){D(7)[D(7).3F(":1G")?"1N":"1M"]()})},9G:H(b,a){I 7.2g({1Z:"1N"},b,a)},9F:H(b,a){I 7.2g({1Z:"1M"},b,a)},9E:H(b,a){I 7.2g({1Z:"2m"},b,a)},9D:H(b,a){I 7.2g({1y:"1N"},b,a)},9M:H(b,a){I 7.2g({1y:"1M"},b,a)},9C:H(c,a,b){I 7.2g({1y:a},c,b)},2g:H(k,j,i,g){J h=D.77(j,i,g);I 7[h.36===Q?"P":"36"](H(){G(7.16!=1)I Q;J f=D.1l({},h),p,1G=D(7).3F(":1G"),46=7;R(p 1n k){G(k[p]=="1M"&&1G||k[p]=="1N"&&!1G)I f.1J.1k(7);G(p=="1Z"||p=="2h"){f.18=D.1g(7,"18");f.33=7.V.33}}G(f.33!=U)7.V.33="1G";f.45=D.1l({},k);D.P(k,H(c,a){J e=2B D.28(46,f,c);G(/2m|1N|1M/.11(a))e[a=="2m"?1G?"1N":"1M":a](k);N{J b=a.6r().1I(/^([+-]=)?([\\d+-.]+)(.*)$/),2b=e.1t(M)||0;G(b){J d=3d(b[2]),2M=b[3]||"2X";G(2M!="2X"){46.V[c]=(d||1)+2M;2b=((d||1)/e.1t(M))*2b;46.V[c]=2b+2M}G(b[1])d=((b[1]=="-="?-1:1)*d)+2b;e.3G(2b,d,2M)}N e.3G(2b,a,"")}});I M})},36:H(a,b){G(D.1D(a)||(a&&a.1q==2p)){b=a;a="28"}G(!a||(1j a=="23"&&!b))I A(7[0],a);I 7.P(H(){G(b.1q==2p)A(7,a,b);N{A(7,a).1p(b);G(A(7,a).K==1)b.1k(7)}})},9X:H(b,c){J a=D.3O;G(b)7.36([]);7.P(H(){R(J i=a.K-1;i>=0;i--)G(a[i].T==7){G(c)a[i](M);a.7n(i,1)}});G(!c)7.5A();I 7}});J A=H(b,c,a){G(b){c=c||"28";J q=D.L(b,c+"36");G(!q||a)q=D.L(b,c+"36",D.2d(a))}I q};D.17.5A=H(a){a=a||"28";I 7.P(H(){J q=A(7,a);q.4s();G(q.K)q[0].1k(7)})};D.1l({77:H(b,a,c){J d=b&&b.1q==a0?b:{1J:c||!c&&a||D.1D(b)&&b,2u:b,41:c&&a||a&&a.1q!=9t&&a};d.2u=(d.2u&&d.2u.1q==4L?d.2u:D.28.5K[d.2u])||D.28.5K.74;d.5M=d.1J;d.1J=H(){G(d.36!==Q)D(7).5A();G(D.1D(d.5M))d.5M.1k(7)};I d},41:{73:H(p,n,b,a){I b+a*p},5P:H(p,n,b,a){I((-29.9r(p*29.9q)/2)+0.5)*a+b}},3O:[],48:U,28:H(b,c,a){7.15=c;7.T=b;7.1i=a;G(!c.3Z)c.3Z={}}});D.28.44={4D:H(){G(7.15.2Y)7.15.2Y.1k(7.T,7.1z,7);(D.28.2Y[7.1i]||D.28.2Y.4w)(7);G(7.1i=="1Z"||7.1i=="2h")7.T.V.18="3I"},1t:H(a){G(7.T[7.1i]!=U&&7.T.V[7.1i]==U)I 7.T[7.1i];J r=3d(D.1g(7.T,7.1i,a));I r&&r>-9p?r:3d(D.2a(7.T,7.1i))||0},3G:H(c,b,d){7.5V=1z();7.2b=c;7.3l=b;7.2M=d||7.2M||"2X";7.1z=7.2b;7.2S=7.4N=0;7.4D();J e=7;H t(a){I e.2Y(a)}t.T=7.T;D.3O.1p(t);G(D.48==U){D.48=4I(H(){J a=D.3O;R(J i=0;i<a.K;i++)G(!a[i]())a.7n(i--,1);G(!a.K){7k(D.48);D.48=U}},13)}},1N:H(){7.15.3Z[7.1i]=D.1K(7.T.V,7.1i);7.15.1N=M;7.3G(0,7.1t());G(7.1i=="2h"||7.1i=="1Z")7.T.V[7.1i]="9m";D(7.T).1N()},1M:H(){7.15.3Z[7.1i]=D.1K(7.T.V,7.1i);7.15.1M=M;7.3G(7.1t(),0)},2Y:H(a){J t=1z();G(a||t>7.15.2u+7.5V){7.1z=7.3l;7.2S=7.4N=1;7.4D();7.15.45[7.1i]=M;J b=M;R(J i 1n 7.15.45)G(7.15.45[i]!==M)b=Q;G(b){G(7.15.18!=U){7.T.V.33=7.15.33;7.T.V.18=7.15.18;G(D.1g(7.T,"18")=="2F")7.T.V.18="3I"}G(7.15.1M)7.T.V.18="2F";G(7.15.1M||7.15.1N)R(J p 1n 7.15.45)D.1K(7.T.V,p,7.15.3Z[p])}G(b)7.15.1J.1k(7.T);I Q}N{J n=t-7.5V;7.4N=n/7.15.2u;7.2S=D.41[7.15.41||(D.41.5P?"5P":"73")](7.4N,n,0,1,7.15.2u);7.1z=7.2b+((7.3l-7.2b)*7.2S);7.4D()}I M}};D.1l(D.28,{5K:{9l:9j,9i:7e,74:9g},2Y:{2e:H(a){a.T.2e=a.1z},2c:H(a){a.T.2c=a.1z},1y:H(a){D.1K(a.T.V,"1y",a.1z)},4w:H(a){a.T.V[a.1i]=a.1z+a.2M}}});D.17.2i=H(){J b=0,1S=0,T=7[0],3q;G(T)ao(D.14){J d=T.1d,4a=T,1s=T.1s,1Q=T.2z,5U=2k&&3r(5B)<9c&&!/9a/i.11(v),1g=D.2a,3c=1g(T,"30")=="3c";G(T.7y){J c=T.7y();1e(c.1A+29.2f(1Q.1C.2e,1Q.1c.2e),c.1S+29.2f(1Q.1C.2c,1Q.1c.2c));1e(-1Q.1C.6b,-1Q.1C.6a)}N{1e(T.5X,T.5W);1B(1s){1e(1s.5X,1s.5W);G(42&&!/^t(98|d|h)$/i.11(1s.2j)||2k&&!5U)2C(1s);G(!3c&&1g(1s,"30")=="3c")3c=M;4a=/^1c$/i.11(1s.2j)?4a:1s;1s=1s.1s}1B(d&&d.2j&&!/^1c|2K$/i.11(d.2j)){G(!/^96|1T.*$/i.11(1g(d,"18")))1e(-d.2e,-d.2c);G(42&&1g(d,"33")!="4j")2C(d);d=d.1d}G((5U&&(3c||1g(4a,"30")=="5x"))||(42&&1g(4a,"30")!="5x"))1e(-1Q.1c.5X,-1Q.1c.5W);G(3c)1e(29.2f(1Q.1C.2e,1Q.1c.2e),29.2f(1Q.1C.2c,1Q.1c.2c))}3q={1S:1S,1A:b}}H 2C(a){1e(D.2a(a,"6V",M),D.2a(a,"6U",M))}H 1e(l,t){b+=3r(l,10)||0;1S+=3r(t,10)||0}I 3q};D.17.1l({30:H(){J a=0,1S=0,3q;G(7[0]){J b=7.1s(),2i=7.2i(),4c=/^1c|2K$/i.11(b[0].2j)?{1S:0,1A:0}:b.2i();2i.1S-=25(7,\'94\');2i.1A-=25(7,\'aF\');4c.1S+=25(b,\'6U\');4c.1A+=25(b,\'6V\');3q={1S:2i.1S-4c.1S,1A:2i.1A-4c.1A}}I 3q},1s:H(){J a=7[0].1s;1B(a&&(!/^1c|2K$/i.11(a.2j)&&D.1g(a,\'30\')==\'93\'))a=a.1s;I D(a)}});D.P([\'5e\',\'5G\'],H(i,b){J c=\'4y\'+b;D.17[c]=H(a){G(!7[0])I;I a!=12?7.P(H(){7==1b||7==S?1b.92(!i?a:D(1b).2e(),i?a:D(1b).2c()):7[c]=a}):7[0]==1b||7[0]==S?46[i?\'aI\':\'aJ\']||D.71&&S.1C[c]||S.1c[c]:7[0][c]}});D.P(["6N","4b"],H(i,b){J c=i?"5e":"5G",4f=i?"6k":"6i";D.17["5s"+b]=H(){I 7[b.3y()]()+25(7,"57"+c)+25(7,"57"+4f)};D.17["90"+b]=H(a){I 7["5s"+b]()+25(7,"2C"+c+"4b")+25(7,"2C"+4f+"4b")+(a?25(7,"6S"+c)+25(7,"6S"+4f):0)}})})();',62,669,'|||||||this|||||||||||||||||||||||||||||||||||if|function|return|var|length|data|true|else|type|each|false|for|document|elem|null|style|event||nodeName|||test|undefined||browser|options|nodeType|fn|display|arguments|url|window|body|parentNode|add|msie|css|indexOf|prop|typeof|call|extend|script|in|replace|push|constructor|text|offsetParent|cur|status|div|apply|firstChild|opacity|now|left|while|documentElement|isFunction|filter|className|hidden|handle|match|complete|attr|ret|hide|show|dataType|trigger|doc|split|top|table|try|catch|success|break|cache|height||remove|tbody|string|guid|num|global|ready|fx|Math|curCSS|start|scrollTop|makeArray|scrollLeft|max|animate|width|offset|tagName|safari|map|toggle||done|Array|find|toUpperCase|button|special|duration|id|copy|value|handler|ownerDocument|select|new|border|exec|stack|none|opera|nextSibling|pushStack|target|html|inArray|unit|xml|bind|GET|isReady|merge|pos|timeout|delete|one|selected|px|step|jsre|position|async|preventDefault|overflow|name|which|queue|removeChild|namespace|insertBefore|nth|removeData|fixed|parseFloat|error|readyState|multiFilter|createElement|rl|re|trim|end|_|param|first|get|results|parseInt|slice|childNodes|encodeURIComponent|append|events|elems|toLowerCase|json|readyList|setTimeout|grep|mouseenter|color|is|custom|getElementsByTagName|block|stopPropagation|addEventListener|callee|proxy|mouseleave|timers|defaultView|password|disabled|last|has|appendChild|form|domManip|props|ajax|orig|set|easing|mozilla|load|prototype|curAnim|self|charCode|timerId|object|offsetChild|Width|parentOffset|src|unbind|br|currentStyle|clean|float|visible|relatedTarget|previousSibling|handlers|isXMLDoc|on|setup|nodeIndex|unique|shift|javascript|child|RegExp|_default|deep|scroll|lastModified|teardown|setRequestHeader|timeStamp|update|empty|tr|getAttribute|innerHTML|setInterval|checked|fromElement|Number|jQuery|state|active|jsonp|accepts|application|dir|input|responseText|click|styleSheets|unload|not|lastToggle|outline|mouseout|getPropertyValue|mouseover|getComputedStyle|bindReady|String|padding|pageX|metaKey|keyCode|getWH|andSelf|clientX|Left|all|visibility|container|index|init|triggered|removeAttribute|classFilter|prevObject|submit|file|after|windowData|inner|client|globalEval|sibling|jquery|absolute|clone|wrapAll|dequeue|version|triggerHandler|oldblock|ctrlKey|createTextNode|Top|handleError|getResponseHeader|parsererror|speeds|checkbox|old|00|radio|swing|href|Modified|ifModified|lastChild|safari2|startTime|offsetTop|offsetLeft|username|location|ajaxSettings|getElementById|isSimple|values|selectedIndex|runtimeStyle|rsLeft|_load|loaded|DOMContentLoaded|clientTop|clientLeft|toElement|srcElement|val|pageY|POST|unshift|Bottom|clientY|Right|fix|exclusive|detachEvent|cloneNode|removeEventListener|swap|toString|join|attachEvent|eval|substr|head|parse|textarea|reset|image|zoom|odd|even|before|prepend|exclude|expr|quickClass|quickID|uuid|quickChild|continue|Height|textContent|appendTo|contents|open|margin|evalScript|borderTopWidth|borderLeftWidth|parent|httpData|setArray|CSS1Compat|compatMode|boxModel|cssFloat|linear|def|webkit|nodeValue|speed|_toggle|eq|100|replaceWith|304|concat|200|alpha|Last|httpNotModified|getAttributeNode|httpSuccess|clearInterval|abort|beforeSend|splice|styleFloat|throw|colgroup|XMLHttpRequest|ActiveXObject|scriptCharset|callback|fieldset|multiple|processData|getBoundingClientRect|contentType|link|ajaxSend|ajaxSuccess|ajaxError|col|ajaxComplete|ajaxStop|ajaxStart|serializeArray|notmodified|keypress|keydown|change|mouseup|mousedown|dblclick|focus|blur|stylesheet|hasClass|rel|doScroll|black|hover|solid|cancelBubble|returnValue|wheelDelta|view|round|shiftKey|resize|screenY|screenX|relatedNode|mousemove|prevValue|originalTarget|offsetHeight|keyup|newValue|offsetWidth|eventPhase|detail|currentTarget|cancelable|bubbles|attrName|attrChange|altKey|originalEvent|charAt|0n|substring|animated|header|noConflict|line|enabled|innerText|contains|only|weight|font|gt|lt|uFFFF|u0128|size|417|Boolean|Date|toggleClass|removeClass|addClass|removeAttr|replaceAll|insertAfter|prependTo|wrap|contentWindow|contentDocument|iframe|children|siblings|prevAll|wrapInner|nextAll|outer|prev|scrollTo|static|marginTop|next|inline|parents|able|cellSpacing|adobeair|cellspacing|522|maxLength|maxlength|readOnly|400|readonly|fast|600|class|slow|1px|htmlFor|reverse|10000|PI|cos|compatible|Function|setData|ie|ra|it|rv|getData|userAgent|navigator|fadeTo|fadeIn|slideToggle|slideUp|slideDown|ig|responseXML|content|1223|NaN|fadeOut|300|protocol|send|setAttribute|option|dataFilter|cssText|changed|be|Accept|stop|With|Requested|Object|can|GMT|property|1970|Jan|01|Thu|Since|If|Type|Content|XMLHTTP|th|Microsoft|td|onreadystatechange|onload|cap|charset|colg|host|tfoot|specified|with|1_|thead|leg|plain|attributes|opt|embed|urlencoded|www|area|hr|ajaxSetup|meta|post|getJSON|getScript|marginLeft|img|elements|pageYOffset|pageXOffset|abbr|serialize|pixelLeft'.split('|'),0,{}))



//======================= Script:   /js/accordion js ()===========================
// accordion library for expanding and contracting menus

function AccordionExpand( el , antype ) {
	if ( antype == "none" ) {
   		el.next().show();
 	} else {
		el.next().slideDown("normal"); 
	}	    
	el.addClass("selected");
}

function AccordionRetract( el , antype ) {
	var nextel = el.next() ;
	if ( nextel.css("display") != "none" ) {
   	 	if ( antype == "none" ) {
	   		nextel.hide();
	 	} else {
   			nextel.slideUp("slow"); 
		} 
	}            
	el.removeClass("selected");  
}

function AccordionToggle( el , antype ) {
    if(typeof(el) == "undefined") {return;} // Make sure el is not null and el.attr('class')
	if (typeof(el.attr("class")) != "undefined" && el.attr("class").indexOf("selected") != -1) {   
		AccordionRetract( el , antype ) ;
	} else {
	 	ApplyBehavior( el , antype ) ;
	    AccordionExpand( el , antype ) ;
	}
}

function ApplyBehavior( el , antype ) { 
	if ( accordionBehavior == "one" ) { // this is set in jquery.thdl.js
		var sib_class = el.attr("class") ; 
		var zpar = el.parents("@id[list]").attr("id") ;
		// Used to have ... + sib_class + ":visible" ... instead of ".head:visible" so it wasn't recognizing
		// global links which have another class
		jQuery( "#" + zpar + " .head:visible" ).each(function(){ 
            AccordionRetract(jQuery(this) , antype);
        }) ;
	}
} 

function RetrieveAccordionCookies() {
    
    //alert(pg_cookie_nm);
	var menus_string = getCookieValue( cookie_menu ) ;
	
	if (jQuery("#side-column div[id~='tab']").length > 0) {
	   // if there are multiple tabs in the side-column. Forget about cookies for now.
	   jQuery("#side-column div[id~='tab']").each(function() {
            AccordionToggle(jQuery(this).find(".head:first") , "none" ) ;
       });
    } else if ( menus_string.length > 0 ) {
	
		//loop through stored indices and activate
	   	var marray = menus_string.split(",");
		for( var i=0 ; i<marray.length-1 ; i++ ) {      
            var menu = jQuery(".list0 .head").eq(marray[i])[0]; 
			AccordionToggle( jQuery(menu) , "none" ) ;
		}
	} else { // default to first item of both levels
	    AccordionToggle( jQuery('.head:first') , "none" ) ;
	}
}
       
function SetAccordionCookies() {
		var cookie_string = "" ;    
	    jQuery( '#side-column .head[class*=selected]' ).each( function(i) { //pull out all selected menus and submenus
			cookie_string += jQuery(".list0 .head").index(jQuery(this)[0]) + "," ; //store absolute index (position among all .head_big and .head descendants of #list0)
	    }); 
		//alert(cookie_string);
		if ( !writeSessionCookieWithPath( cookie_menu , cookie_string ) ) { //cookie_menu is set in jquery.thdl.js
			alert ( "Note: Cookies must be enabled for your preferences to be saved." );
		}
}



//======================= Script:   /js/fn js ()===========================
/* functions should be in alphabetical order */

// add onclick methods for all links that reference wikis (the #wiki= signifier is added to wiki links in the wiki_reader.php script) 
function ActivateLinks( parent_element ) {
    // Wiki Links
	jQuery(parent_element).find("a[href*=#wiki], a[href*=#essay], a[href*=#jiats], a[href*=#spt]").click(function() {
		var hash = this.href;
		hash = hash.replace(/^.*#/, '');
		if(jQuery.browser.msie || jQuery.browser.safari) { jQuery.history.load(hash);}
		//jQuery.historyLoad(hash);  // This calls pageload function in class_external.js
	});
	
	// for iframe button toggling
	jQuery(parent_element).find("ul#masthead-navbar a[href^=#iframe]").click( function() {
		ToggleNavButton( this.href ) ;
	}) ;
	
	jQuery("a[href^=#thl-popup]").each(function() {
		if(jQuery("head link[href*=jqModal]").length ==0 ) {
			jQuery("head link:last").after('<link rel="stylesheet" type="text/css" href="/global/css/jqModal.css" media="all" />');
		} 
		var winid = "jqmwin" + (jQuery(".jqmWindow").length + 1);
		var popurl = jQuery(this).attr("href");
		popurl = popurl.substring(popurl.indexOf("=") + 1);
		var pageurl = popurl;
		if(jQuery(this).hasClass("thl-content")) { popurl = "/global/php/thl_reader.php?url=" + popurl;}
		jQuery("body").append('<div id="' + winid + '" class="jqmWindow" style="overflow: hidden;"><div class="closebtn"><a href="#">Close</a></div>' +
			'<div class="viewalone"><a href="' + pageurl + '" onclick="javascript:jQuery(this).parents(\'.jqmWindow\').jqmHide();">View this ' + 'Page Alone</a></div><iframe width="98%" height="100%" src="' + popurl + '" style="margin-top: 8px; background-color: white;"></iframe></div>');
		jQuery("#" + winid).jqm({trigger: jQuery(this), closeClass: "closebtn"});
	});
}

function ActivatePopupLinks(jqParent) {
	
	jQuery(jqParent).find("a.popupwin, a[href*=php]").click(function () {
		var myhref = jQuery(this).attr("href");
		jQuery("#popHistory").append("<p>" + myhref + "</p>");
		if(myhref.indexOf("panoramas") > -1) {
			doPano(jqParent,myhref);
		} else {
			jQuery(jqParent).html("<div></div>");
			jQuery("#popHistory").append("<p>" + myhref + "</p>");
			jQuery(jqParent).load(myhref, function() {ActivatePopupLinks(jqParent);});
		}
		return false;
	});
	
	jQuery(jqParent).find(".popback a, .backlink a").click(function () {
		if(jQuery("#popHistory p:last").length ==0 ) {return false;}
		var backUrl = jQuery("#popHistory p:last").prev("p").text();
		if(backUrl == jQuery("#popHistory p:last").text() && typeof(jQuery("#popHistory p:last").prev("p").prev("p")) == "object") {
			backUrl = jQuery("#popHistory p:last").prev("p").prev("p").text();
			jQuery("#popHistory p:last").remove();
		}
		jQuery("#popHistory p:last").remove();
		jQuery(jqParent).html("<div></div>");
		jQuery(jqParent).load(backUrl, function() {ActivatePopupLinks(jqParent);});	
		return false;
	});
	
	jQuery(jqParent).find(".conx-content a#show-img-btn, .conx-content a#show-txt-btn").click(function () {
		if(jQuery(jqParent).find("#show-img-btn").css("display") == "none") {
			jQuery(jqParent).find("#show-img-btn").show();
			jQuery(jqParent).find("#show-txt-btn").hide();
			jQuery(jqParent).find("#image-div").hide();	
			jQuery(jqParent).find("#img-display").hide();
			jQuery(jqParent).find("#text-div").show();
		} else {
			jQuery(jqParent).find("#show-img-btn").hide();
			jQuery(jqParent).find("#show-txt-btn").show();
			jQuery(jqParent).find("#image-div").show();	
			jQuery(jqParent).find("#img-display").show();
			jQuery(jqParent).find("#text-div").hide();
		}
		return false;
	});
	
		//alert("number of thl-popups in " + jQuery(jqParent).attr("id") + ": " + jQuery(jqParent).find("a[href*=thl-popup]").length);
	try { // Need Try as IE throws error for the onClick find
		
		jQuery(jqParent).find("a[href*=#essay]").unbind("click").click(function () {
			var myref = jQuery(this).attr("href");
			myref  = myref.substr(myref.indexOf("essay=") + 6);
			jQuery(jqParent).load("/global/php/essay_reader.php?url=" + myref + "&type=popup", 
				function() {	
					jQuery(jqParent).jqmAddClose(".closebtn");
					ActivatePopupLinks(jqParent);
				}
			);
			if(jQuery(this).attr("href").indexOf("thl-popup") > -1) {jQuery(this).attr("href",myref);}
			return false;
		});
		
		jQuery(jqParent).find("a[href*=thl-popup]:not([href*=#essay])").unbind("click").click(function () {
			var myref = jQuery(this).attr("href");
			myref  = myref.substr(myref.indexOf("=") + 1);
			jQuery(jqParent).html("");
			jQuery(jqParent).load(myref, function() {
				jQuery("#popHistory").append("<p>" + myref + "</p>"); 
				ActivatePopupLinks(jqParent);
			});
			return false;
		});
		
		jQuery(".essay-body a[href*=Conx]").click(function() {
			var myhref = (jQuery(this).attr("href")).replace("file:","");
			jQuery(jqParent).load(myhref, function() {jQuery("#popHistory").append("<p>" + myhref + "</p>"); ActivatePopupLinks(jqParent);});
			return false;
		});
		
		jQuery(".essay-body a[href*=img-db]").click(function() {
			var myhrf = (jQuery(this).attr("href")).replace("file:","");
			var imgid = myhrf.substring(myhrf.indexOf("=") +1);
			var imgurl = "/global/php/old-img-db.php?url=" + imgid + "&backlink=yes";
			jQuery(jqParent).load(imgurl,function() {
				jQuery("#popHistory").append("<p>" + imgurl + "</p>"); 
				ActivatePopupLinks( jqParent);
				//jQuery(jqParent + " div.closebtn").click(function() {alert("yup!");});
			});
			return false;
			
		});
		
		// IE throws error here
		jQuery(jqParent).find("a[onClick*=loadPopup]").each(function () {
			var myclick = jQuery(this).attr("onClick");
			jQuery(this).attr("onClick",myclick.replace("loadPopup(","loadPopupGeneral('#" + jQuery(jqParent).attr("id") + "',"));
		});
	
	} catch (e) {}
	
	jQuery(jqParent).jqmAddClose(".closebtn");
	
}

function loadPopupGeneral(jqParent,url, txtdivhide) {
	if(typeof(txtdivhide) != "undefined" && txtdivhide) {
		jQuery(jqParent).find("#text-div").hide();
	}
	jQuery(jqParent).find("#image-div *").hide();
	jQuery(jqParent).find("#img-display").html('<p style="margin-left: 10px">Loading ...</p>');
	jQuery(jqParent).find("#img-display").load(url,function() {jQuery(jqParent).find(".phpBackLink").click(function() {popupBackGeneral(jqParent);});}).show();
}

function popupBackGeneral(jqParent,txtdivshow) {
	if(typeof(txtdivshow) != "undefined" && txtdivshow) { jQuery(jqParent).find("#text-div").show(); }
	jQuery(jqParent).find("#img-display").hide();
	jQuery(jqParent).find("#image-div *").show();
}

function doPano(jqParent, myhref) {
	jQuery(jqParent).html('<div class="conx-content"></div>');
	var conxCont = jQuery(jqParent).find(".conx-content");
	jQuery.ajax({
			url: myhref,
			success: function( pdoc ) {
				jQuery(conxCont).append(jQuery(pdoc).find(".pano-header"))
					.append(jQuery(pdoc).find("div.pano-container object"));
				jQuery(conxCont).find(".pano-header").prepend(jQuery(pdoc).find("h1:eq(1)"));
				jQuery(conxCont).find("object").attr("height","400");
				jQuery(conxCont).prepend('<p class="backlink"><a href="javascript: window.history.back();">Back to Feature 	Information</a></p>');
				jQuery(conxCont).find("a[href*=/panoramas/]").each(function() { 
					var myhref = jQuery(this).attr("href"); 
					jQuery(this).attr("href",myhref.replace('/panoramas/','/map/'));
				});
				ActivatePopupLinks(jqParent);
			}
	});
}

function AddGoogleSearchScript() {
// google search box watermark script
	jQuery.getScript("http://google.com/coop/cse/brand?form=side-search-form");
}

/*======== AddTopAnchor - Adds <a name="top"></a> at the beginning of the body element ========================================*/
function AddTopAnchor() {
	jQuery("body").prepend('<a name="top"></a>');
}

/*=========== ApplyStyle - changes the style (font-sheet for now) and stores selection in cookie (relies on cookies.js) ========*/
function ApplyStyle( zstyle ) {
	jQuery('#font_style').attr( "href" , zstyle ) ;
	writePersistentCookie (cookie_font, zstyle, "months", 1) ;
}

/*========== AssimilateCookies - Cookie Checking (depends on cookies.js) ======================================================*/
function AssimilateCookies() {	
	// retrieve cookies for menu prefs (the function for setting them is and has to be in jquery.accordion.js)
	RetrieveAccordionCookies() ;
	
	// retrieve language cookie
	
	// var cookie_lang = getCookieValue( cookie_lang ) ; - commented out / mark 8-5-08
	// if ( cookie_lang.length < 3 ) {
	// 	thdl_lang = "eng" ; // default to english if the cookie wasn't found or is empty
	// }
	// retrieve tooltip pref and activate
	// TooltipToggle( getCookieValue( cookie_tool ) ) ;	 - commented out / mark 8-5-08
	
	// retrieve style cookie
	// ApplyStyle( getCookieValue( cookie_font ) ) ; - commented out / mark 8-5-08
	
}


/*================== cssCheckbox jquery script from Kawika http://kawika.org/ ==========================*/
jQuery(function(){

	// Apply CSS styling to checkboxes
	try {
   		jQuery(".search-selections").cssCheckbox();
   		
   		// Capture form submit
   		/*
   		jQuery("form").submit(function() {
   
   			var string = "";
   			jQuery(":checkbox", this).each(function(){
   				string += this.name + ": " + this.checked + "\n"
   			});
   			alert(string);
   			return false;
   		});
   		*/
   		// Handle toggling all
   		jQuery('#chk_toggle').click(function(){
   			
   			if (jQuery(this).text() == 'Select All') {
   				jQuery(this).text('Select None');
   				jQuery('.search-selections label').cssCheckboxCheck();
   			}
   			else {
   				jQuery(this).text('Select All');
   				jQuery('.search-selections label').cssCheckboxUncheck();
   			}
   		});
   		
   		jQuery('.default').cssCheckboxCheck();
   	} catch (e) {}
});

/* CheckTIDSearch - if there's a tid variable search for it */
function CheckTIDSearch() {
	if((window.location.href).indexOf("/spt") > -1) {return;}
	var qs = window.location.search;
	if (qs == null || typeof(qs) != "string" || qs.toLowerCase().indexOf("tid=") == -1) { return; }
	var kvpairs = qs.split('&');
	var tid = "";
	for(var n=0; n<kvpairs.length; n++) {
		if(kvpairs[n].toLowerCase().indexOf('tid') > -1) {
			tid = kvpairs[n].substring(kvpairs[n].indexOf("=") +1 );
			break;
		}
	}
	jQuery.ajax({
		url: "/global/php/thl-id-search.php",
		data: "tid=" + tid,
		async: false,
		success: function( data ) {
			var url = jQuery(data).find("url").text();
			url = url.replace(/\/\//g,'/').replace('http:','http:/');
			window.location.href = url;
		}
	});
}

/*=============== ConvertExternalLinks - External Links covered with substitute for target="blank" by rel="external" ==============*/

function ConvertExternalLinks() {
	if (!document.getElementsByTagName) {
		return;
	} else {
		var anchors = document.getElementsByTagName("a");
		var hostname = "www.thlib.org";
		try {hostname = window.location.host} catch (e) {}
		for (var i=0, len=anchors.length; i<len; i++) {
			var anchor = anchors[i]; 
			if (anchor.getAttribute("href")) {
				var myhref = anchor.getAttribute("href");
				if(anchor.getAttribute("rel") == "external") { anchor.target = "_blank";}
				/* Remove staging. from links if we're not on staging server */
				if(myhref.indexOf("staging.") > -1 && hostname.indexOf("thlib") > -1 ) {
					var newhref = myhref.replace("staging.thdl.org","www.thlib.org")
						.replace("staging.places","places")
						.replace("staging.tmb","tmb")
						.replace("staging.ndlb","ndlb")
						.replace("staging.ttt","ttt")
						.replace("staging.mms","mms")
						.replace("thdl.org","thlib.org");
					anchor.setAttribute("href",newhref);
				}
			}
		}
	}
}

/*==============================================================================
DoExternalContent: 
    initializes Ajax objects for getting external content and
    inserts wiki content in teaser boxes and 
    inserts other external content 
=============================================================================== */
function DoExternalContent() {
    
    // Initalize the two Ajax objects
    contentLoader = new External(); // For loading external content into a page
    wikiLoader = new WikiLoader();  // For loading wiki content into teaser boxes.
    
    // if shell-one has class wikibody, then the body is loaded from a wiki by just adding the #wiki has 
    // variable. There should only be one of these per page.
    jQuery(".wikibody").each ( function () {
        var url = jQuery(this).find("a:first").attr("href");
        window.location.hash = "#wiki=" + url;
	if(jQuery.browser.msie || jQuery.browser.safari) {
		jQuery.history.load((window.location.hash).replace(/^.*#/, '')); 
	}
        return;
    });
    
    // Same for spt
    jQuery(".sptbody").each ( function () {
        var url = jQuery(this).find("a:first").attr("href");
        window.location.hash = "#spt=" + url;
	if(jQuery.browser.msie || jQuery.browser.safari) {
		jQuery.history.load((window.location.hash).replace(/^.*#/, '')); 
	}
        return;
    });
    
    // Same for Essays
    jQuery(".essaybody").each ( function () {
        var url = jQuery(this).find("a:first").attr("href");
        window.location.hash = "#essay=" + url;
	if(jQuery.browser.msie || jQuery.browser.safari) {
		jQuery.history.load((window.location.hash).replace(/^.*#/, '')); 
	}
        return;
    });
    // Load Teaser boxes
    jQuery(".wikitext").each( function () {
        jQuery(this).removeClass("wikitext");
        wikiLoader.getWikiContent(this);
    });
    
    // Load external content into areas with <a class="externalcontent"
    
    jQuery("a.externalcontent").each( function () {
        jQuery(this).removeClass("externalcontent"); // first class indicates external content
        var type = jQuery(this).attr("class"); // second class is type
        var parent = jQuery(this).parent();
        var server = "www.thlib.org";
	try {server = window.location.hostname;} catch (e) {}
	server = "http://" + server;
        var url = "";
        if (type == 'jiats') {
	    url = "http://localhost:8080/cocoon/texts/jiats" + url;
        } else if (type =='essay') {
            url = "http://localhost:8080/cocoon/texts/essays" + url;
        }
        url = url + jQuery(this).attr('href');
        contentLoader.InsertMarkup(jQuery(this).parent(),url);
    });
}

/*==============================================================================
EmbedQT and its onShow function insertVideo
    converts all links to QT videos into links for popup div to display video
    loc = JQuery selector for element that contains links
*/
function EmbedQT(loc) {
	if(typeof(loc) == "undefined" || loc == "") {loc = "body";}
	if(jQuery("head link[href*=jqModal]").length == 0 ) {
		jQuery("head link:last").after('<link rel="stylesheet" type="text/css" href="/global/css/jqModal.css" media="all" />');
	}
	if(jQuery(loc).find("a[href*=.mp4]").length == 0) { return;}
	jQuery(loc).find("a[href*=.mp4]").each(function () {
		if(jQuery(this).attr("class") != "switchvid") {
			var winid = "jqmwin" + (jQuery(".jqmWindow").length + 1);
			jQuery("body").append('<div id="' + winid + '" class="jqmWindow" style="overflow: hidden;"><div class="jqmWrapper"><div class="closebtn"><a class="jqmClose" href="#">Close</a></div></div></div>');
			jQuery("#" + winid).jqm({trigger: this, closeClass: "closebtn", onShow: insertVideo, onHide: removeVideo}); // Window opened on trigger click
		}
	});
};

var insertVideo=function(hash){ 
	var myhref = jQuery(hash.t).attr("href"); // Movie URL is the trigger link's href
	if(myhref.substr(0,1) == "/") { myhref = "http://www.thlib.org" + myhref; }
	var wdth = "480";
	var hgt = "416";
	if(myhref.indexOf("?") > -1) {
		var qind = myhref.indexOf("?");
		var ss = myhref.substr(qind);
		myhref = myhref.substr(0,qind);
		var pts = (ss.replace("?","").split("&"));
		for(var p in pts) {
			var ppts = pts[p].split("=");
			if(ppts[0] == "w") { wdth = ppts[1]; }
			if(ppts[0] == "h") { hgt = ppts[1]; }
		}
	}
	hash.w.show();
	if(hash.w.find(".jqmVideo").length == 0) {
		var embedtag = '<embed src="' + myhref + '"  type="video/quicktime" target="myself" width="' + wdth + '" height="' + hgt + '" controller="true" autoplay="true" pluginspage="http://www.apple.com/quicktime/download/"></embed>';
		if(jQuery.browser.msie) { embedtag = "";}
		hash.w.find(".jqmWrapper").append('<div class="jqmVideo"><object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"  width="' + wdth + '" height="' + hgt + '" codebase="http://www.apple.com/qtactivex/qtplugin.cab"><param name="src" value="' + myhref + '"><param name="autoplay" value="true"><param name="controller" value="true"><param name="type" value="video/quicktime"><param name="width" value="' + wdth + '"><param name="height" value="' + hgt + '"><param name="pluginspage" value="http://www.apple.com/quicktime/download/indext.html">' + embedtag + '</object></div>');
	}
};

var removeVideo=function(hash) { 
	hash.w.find(".jqmWrapper .jqmVideo").hide();
	hash.w.hide("fast",function () {hash.o.remove(); hash.w.find(".jqmWrapper .jqmVideo").remove(); });
}; 

/* ================== Flicker Fix for the cursor in IExplorer ======================================= */

//  jed any thoughts on the usefullness of this one... mark 8-5

 try { document.execCommand("BackgroundImageCache", false, true); } catch(err) {}

 
 /* =================  Go To Page For Drop Down page switches in Essays ============================= */
function GoToPage(url) {
	if (url.charAt(0) == "#") { // if it begins with a hash, then it's an ajax call. load it.
		window.location.hash = url;
		if (jQuery.browser.msie) {
			url = url.replace(/^.*#/, '');
			jQuery.historyLoad(url); // Need to specifically call this history load function for IE to get hash urls to work
		} 
	} else if(url == "print") { // Print view for essay and jiats
		var myhash = window.location.hash;
		var myloc = "essay=/";
		if(myhash.indexOf("/all/") > -1) {
			window.print();
			try { 
				document.forms.formats.formsel[1].selected = true; // Change selected format to whole document
			} catch (e) {}
		} else {
			if(myhash.indexOf('jiats=') > -1) {
				myhash = myhash.replace(/\/[abc]\d+\//,'');
				myloc = "jiats=/";
			} else if (myhash.indexOf('/s/') > -1) {
				myhash = myhash.substring(0,myhash.indexOf('/s/'));
			}
			var mhparts = myhash.split("/");
			mhparts.shift();
			window.location.hash = (myloc + mhparts.join("/") + "/all/").replace('//','/');
			writePersistentCookie("essayprinting","on","minutes",1);
		}
	} else if(url == "section") { // Section by Section view for essay and jiats
		var cntxt = ".essay-toc ";
		if(jQuery(cntxt + "a").length ==0) { cntxt = ".article-toc ";}
		var sellnk = jQuery(cntxt + "a:first");
		if(jQuery(cntxt + "a.selected").length > 0) { sellnk = jQuery(cntxt + "a.selected"); } else { jQuery(sellnk).addClass("selected"); }
		window.location.href = jQuery(sellnk).attr("href");
	} else { // Default try to load URL given
		window.location.href = url;
	}
}
 
 /*================= jQuery Hover =============================================================*/
 
 // this is only in JIATS so far afik, mark 8-5-08
 
 
function InitStripeHover(){
    jQuery(".stripe-hover dd").mouseover(
        function() {
            jQuery(this).addClass("over");}).mouseout(function() {jQuery(this).removeClass("over");
        });
    jQuery(".stripe-hover dd:even").addClass("alt");
}




 
/*==============================================================================
InitAccordion - Initiate accordion functionality for sidenav (relies on accordion.js)  

NOTE: the element to be expanded/contracted must be the next sibling of 
the element that is clicked. =================================================*/

function InitAccordion() {
    //the headers for the two-tier menu must have the class head, and must be within the #side-column div
    // Bug fix by targetting the a tag and then toggling parent (ndg; 02-06-08)
	
	/* jev3a 7/25/08 commented this out because it seems unnecessary
	jQuery('#side-column .head').click(function(){ 
    	AccordionToggle( jQuery(this).parent() );
		SetAccordionCookies() ;
		return false; // need this to disable going to #
	}); */
	
    jQuery('#side-column .head a').click(function(){ 
    	AccordionToggle( jQuery(this).parent() );
		SetAccordionCookies() ;
		return false; // need this to disable going to #
	});
}

/*=================== InitLanguages - Set up language selection and store in cookie (depends on cookies.js) ============*/


// this is not being used yet for this August launch... stash it, mark 8-5-08


//function InitLanguages() {		
	
//	jQuery('#languages a').click(function()
//		{
//			thdl_lang = jQuery(this).attr('href').substr(1) ; 					//pull the language off the hash of the href tags
//			jQuery('#thdl_index_menu').load('thdl_index_'+thdl_lang+'.html') ;	//ajax the proper menu, looking for a local thdl_index_<two-letter language abbreviation>.html file
//			writePersistentCookie( cookie_lang, thdl_lang, "years", 1 ) ;	//set persistent cookie
//			return false;
//		}
//	);
	
// }


/*================== Watermark Labels - Overlabel Text on Forms, eg Search Box ========================*/
jQuery(function($){
    if(jQuery("#search-field-1").length > 0) {
        jQuery("#search-field-1").Watermark("Enter Search Terms");
    }
});

/*================== InitSideColumn - prevents side column from disappearing. ========================*/

function InitSideColumn() {
	// Code added by Than 2007-10-24

	// Show side column fixes bug of it disappearing
    
    jQuery("#side-column *").show();
    jQuery("#side-column *.hidden").hide();
    jQuery("#side-column *.scholar").hide();
    jQuery("#side-column *.popular").show();
    
    // Hide search form
    if(getCookieValue("thdlsformstatus") != "show") {
        jQuery(".side-search-form").hide();
        writeSessionCookie("thdlsformstatus", "hide");
    }
    // Implement head link of search form to toggle showing or hiding form
    jQuery(".side-search-header a").click(function () {
        jQuery(".side-search-form").slideToggle();
        writeSessionCookie("thdlsformstatus", ((getCookieValue("thdlsformstatus") == "show")?"hide":"show"));
    });
    
    // Hide Search box if empty
    var el = "#side-column-search, #side-column-search *";
    if (String(jQuery(el).text()).replace(/\s/g,"").length == 0) { jQuery(el).hide();}
    
    jQuery("#side-column li a").each(function () {
        if(jQuery(this).attr("href") == window.location.hash) {jQuery(this).addClass("selected");}
        jQuery(this).click(function () {
            jQuery("#side-column li a").removeClass("selected");
            jQuery(this).addClass("selected");
        });
    });
    
    if(jQuery("#side-column .list0 h4#side-home-link a").length > 0) {
        var hmlnk = jQuery("#side-column .list0 h4#side-home-link a").attr("href");
        var mypth = window.location.pathname;
        if(hmlnk != mypth && hmlnk != mypth + "index.php" ) { // did have - && hmlnk + "index.php" != mypth - but this was causing homelinks to not appear
            jQuery("#side-column .list0 h4#side-home-link").css("visibility","visible").css("line-height","150%");
        }
    }
    
    if(jQuery.browser.msie) {ActivateLinks("#side-column");}
    
    
    // Hide big head if empty removed for now...code commented out 1-15-08 mark
    // el = ".head_big, .head_big *";
    // if (String(jQuery(el).text()).replace(/\s/g,"").length == 0) { jQuery(el).hide();}
}

/*=================== InitStyling - for making the style preferences clickable ==========================*/

// this is not being used yet for this August launch... stash it, mark 8-5-08

//function InitStyling() {
//	jQuery('.styleswitch').click(function(){
//		ApplyStyle( jQuery(this).attr( "href" ) ) ;
//		return false;
//	}) ;
// }

/* Function to load a URL into a jqModal popup div from a link within that div */
function loadPopupUrl(lnk,url) {
	if(url == "back") {
		var prntDiv = jQuery(".phpBackLink").parents("div.jqmWindow");
		var oldhtml = jQuery("body div#oldHtml");
		if(jQuery(oldhtml).length == 1) {
			jQuery(prntDiv).html(jQuery(oldhtml).html());
			jQuery(prntDiv).jqmAddClose('.jqmClose'); 
			jQuery(oldhtml).remove();
		}
	} else {
		var prntDiv = jQuery(lnk).parents("div.jqmWindow");
		var oldhtml = jQuery(prntDiv).html();
		jQuery(prntDiv).load(url);
		jQuery("body").append('<div id="oldHtml" style="display:none;"></div>');
		jQuery("#oldHtml").html(oldhtml);
	}
}

/*==================== Navigation Menu Dropdown Style - this function is to assist IE5.5+ - otherwise the dropdown is pure CSS ===========*/

navHover = function() {
    try {
    	var lis = document.getElementById("navmenu-h").getElementsByTagName("LI");
    	for (var i=0, len=lis.length; i<len; i++) {
    		lis[i].onmouseover=function() {
    			this.className+=" iehover";
    		}
    		lis[i].onmouseout=function() {
    			this.className=this.className.replace(new RegExp(" iehover\\b"), "");
    		}
    	}
    } catch (e) {}
}

navHover = function() {
    try {
    	var lis = document.getElementById("navmenu-sera-maps").getElementsByTagName("LI");
    	for (var i=0, len=lis.length; i<len; i++) {
    		lis[i].onmouseover=function() {
    			this.className+=" iehover";
    		}
    		lis[i].onmouseout=function() {
    			this.className=this.className.replace(new RegExp(" iehover\\b"), "");
    		}
    	}
    } catch (e) {}
}

if (window.attachEvent) window.attachEvent("onload", navHover);

/* Function to scroll to an element by their ID */
function scrollToId(locid) {
	if(locid.indexOf("#") ==0) { locid = locid.substr(1); }
	try {
		var obj = document.getElementById(locid);
		if (typeof(obj) == "undefined" || obj == null) {
			obj = jQuery("*[name=" + locid + "]");
		}
		var curtop = 0;
		if(obj && typeof(obj) != "undefined" && obj != null) {
			window.scrollTo(0,(jQuery(obj).offset().top - 25));
		}
		if(locid.indexOf('top') > -1 && jQuery("#list1 li a[href*='scrollToId']").length > 0) {
			jQuery("#list1 li a[class='selected']").removeClass("selected");
			jQuery("#list1 li a:first").addClass("selected");
		}
	} catch (e) {}
}

function scrollToAnchor(aname) {
	if(aname.indexOf("#") ==0) { aname = aname.substr(1); }
	try {
		var obj = jQuery("a[name=" + aname + "]").parent();
		if (typeof(obj) == "undefined") {
			obj = document.getElementById(aname);
		}
		var curtop = 0;
		if(obj && typeof(obj) != "undefined") {
			window.scrollTo(0,jQuery(obj).offset().top);
		}
	} catch (e) {}
}

/*==============================================================================
SetBrowserTitle : Function for setting the browser's title bar to either the value of
                  a custom meta element or to the first h1 in the content area.
    The custom meta tag should look like: <meta id="thdltitle" name="THLtitle" content="{Put title text here}" ></meta>
    This is added to the header using the $add_header variable in the PHP file.
================================================================================ */
function SetBrowserTitle() {
    if((window.location.href).indexOf("/spt") > -1) {return;}
    var thdlt = jQuery("meta#thdltitle, meta[name='thdltitle']");
    var h1s = jQuery("#content h1:first");
    if (thdlt.length > 0) {
        document.title = jQuery(thdlt[0]).attr("content");
    } else if (h1s.length > 0) {
        document.title = jQuery(h1s[0]).text();
    } else if ((window.location.href).indexOf("/jiats/") > -1) {
	    document.title = "Journal of the International Association of Tibetan Studies";
    } else {
        document.title = "The Tibetan and Himalayan Library";
    }
}

var monthname=new Array("January","February","March","April","May","June","July","August","September","October","November","December");

function showReference(el, ev, pn) {
    var xval = el.offsetTop;
    var yval = el.offsetLeft;
    if (yval < 300) {yval = 310;}
    jQuery("#citation-box").hide();
    jQuery("#citation-box").removeClass("hide");
    jQuery("#citation-box").css("top",xval - 100);
    jQuery("#citation-box").css("left",yval - 300);
    jQuery("#citation-box #refpgnum").text(pn);
    var td = new Date();
    var tdstr = monthname[td.getMonth()] + " " + td.getDate() + ", " + td.getFullYear();
    jQuery("#citation-box #todaysdate").text(tdstr);
    jQuery("#citation-box").show();
}

/*========= NyroModal Sitemap Popup - new aug 08 ==============


	function() {
		jQuery('a.nyroModal').nyroModal();
		jQuery.fn.nyroModal.settings.showBackground = function(elts, settings, callback) {
			elts.bg.css({opacity:0}).fadeTo(500, 0.00, callback);
		};

		function preloadImg(image) {
			var img = new Image();
			img.src = image;
		};

		preloadImg('images/ajaxLoader.gif');
		preloadImg('images/prev.gif');
		preloadImg('images/next.gif');
		// ====== the next two preload image are for the galleria image so
		// ====== they need to go in the fn for Galleria but Safari was puking them out 
		// ====== if anyone could suggest a better way to do this for marco email me
		preloadImg('images/arrow-img-next.gif');
		preloadImg('images/arrow-img-next.gif');
	};
*/


/*==============================================================================
SwitchView (type)
    This is used in Essay display to switch between different views of an essay.
    The proposed types are:
        "scholar": Scholarly view with Wylie
        "popular": Popular view with phonetics
        "tibetan": Tibetan view with Unicode Tibetan script (Not yet available).
*/

function SwitchView( view ) {
	if(view == "popular") {
		jQuery(".popular").show();
		jQuery(".scholar").hide();
	} else if (view == "scholar") {
		jQuery(".scholar").show();
		jQuery(".popular").hide();
	}
	writePersistentCookie ("thl-essay-view",view, "years", 1);
}

/*============== tzr-box-1 Header - Alternating Blue Header =============================*/
  jQuery(function(){
    jQuery(".tzr-box1:odd").addClass("alt");
  });
  

/*==============================================================================

ToggleNavButton - emulates going to a new page for the buttons in masthead-navbar

*/


// this array is for properly toggling buttons when iframe is retrieved without other cues for what to set the body class to
// we could append this initially in the url, but we're trying to make this as easy for mid-level developers as possible
// however, if performance really becomes an issue, we'll have to switch
var legend = new Array() ;
legend["/categories/119/"] = { zclass: 'genres' } ;	// literary encyclopedia genres
legend["/media_collection_associations?collection_id=22"] = { zclass: 'images' } ; // sera images
legend["/media_collection_associations?collection_id=35"] = { zclass: 'images' } ; // drepung images


function ToggleNavButton( body_class ) {	
	if ( typeof( body_class ) == 'undefined') {			// if we're undoing the simulation, returning to original class (called with ToggleNavButton(), no args)
		var body_class = class_old ;
	} else if ( body_class.indexOf('iframe=') > -1 ) { 	// if coming from bookmark where we have no other context, we have to examine legend array to get class
		hash = body_class ;
		for ( i in legend ) {
			if ( hash.indexOf( i ) > -1 ) {
				var body_class = legend[i].zclass ;
				break ;
			}
		}
		class_old = jQuery('body').attr('class') ; 	// if this is the first call, store old class info for toggling back
	} else {										
		// unknown usage
	}
	jQuery('body').removeClass().addClass( body_class ) ;
	return false ;
}


/*=================== Trim -- simple function to remove white space (actual spaces) at the beginning or end of a string. */
function Trim(txt) {
    if (typeof(txt) == "undefined" || typeof(txt) == "object" || txt.length == 0 ) {return "";}
    while (txt.length > 0 && txt.substr(0,1) == " ") { txt = txt.substr(1); }
    while (txt.lastIndexOf(' ') == (txt.length - 1)) {
	    if(txt.length == 0) {return "";}
	    txt = txt.substr(0,txt.length - 1); 
    }
    txt = txt.replace(/\s+/g,' ');
    return txt;
}

/*================== UncryptMailto - for unencrypting mailto addresses (the encrypting function is not available on this site) */

function UnCryptMailto( s )
	{
		var n = 0;
		var r = "";
		for( var i = 0; i < s.length; i++)
		{
			n = s.charCodeAt( i );
			if( n >= 8364 )
			{
				n = 128;
			}
			r += String.fromCharCode( n - 1 );
		}
		return r;
	}
	function linkTo_UnCryptMailto( s )
	{
		location.href=UnCryptMailto( s );
	}

/*================== Side-Column Toggle Navigation ===========*/
jQuery(function() {
	jQuery(".sideMenuAction").click( function() {
		if (jQuery("#fxSideMenu").css("display")=="none") {
			jQuery("#fxSideMenu").fadeIn("normal");
			jQuery("#sideMenuLink").css("background-position", "0% 100%");
		} else {
			jQuery("#sideMenuLink").css("background-position", "0% 0%");
			jQuery("#fxSideMenu").hide();
		}
		return false;
	});  
}); 

/*=================== Sitemap Toggle Navigation =================*/

jQuery(function() {
	jQuery(".sitemapAction").click( function() {
		if (jQuery("#fxSitemap").css("display")=="none") {
			jQuery("#fxSitemap").fadeIn("fast");
			if(jQuery(".vsplitbar").length > 0) {jQuery(".vsplitbar").hide();}
		} else {
			jQuery("#closeSitemap").html('Close');
			jQuery("#fxSitemap").hide();
			if(jQuery(".vsplitbar").length > 0) {jQuery(".vsplitbar").show();}
		}
		return false;
	});  
});

/*==================== Side-Column Tab Navigation and Content Tabs as seen in Geotourism Featured Places */

jQuery(function() {
    //jQuery('#side-column-tabs > ul').tabs({ fxShow: { height: 'toggle' } });
	//jQuery('#content-tabs > ul').tabs({ fxShow: { height: 'show', opacity: 'toggle' } });
	
	var pid = jQuery("#wiki-panel a").attr("href");
	jQuery(".ui-tabs-panel a[href^=#wiki]").click(function () {
        
        var whref = jQuery(this).attr("href");
        whref = whref.substring(whref.indexOf("=") + 1);
        jQuery("#content-tabs > ul li.ui-tabs-selected").removeClass("ui-tabs-selected");
        jQuery("#wiki-panel").addClass("ui-tabs-selected");
        //contentLoader.InsertMarkup(pid,whref);
        window.scrollTo(0,0);
        return false;
    });
    
    jQuery('#content-tabs .ui-tabs-nav a').click(function() {
        jQuery("#side-column a.selected").removeClass("selected");
    });
});






//======================= Script:   /js/jquery history1 0beta js ()===========================
/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 * API rewrite by Lauris Bukðis-Haberkorns
 *
 * Added to THL by ndg 11/10/08. This version supercedes the older version named jquery.history.js
 * ndg modified iframe prepend to include src attribute set to href of present window to circumvent security restrictions on iframes in IE
 */

(function($) {

function History()
{
	this._curHash = '';
	this._callback = function(hash){};
};

jQuery.extend(History.prototype, {

	init: function(callback) {
		this._callback = callback;
		this._curHash = location.hash;
		this._lastHash = location.hash;
		if(jQuery.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (this._curHash == '') {
				this._curHash = '#';
			}

			// add hidden iframe for IE
			jQuery("body").prepend('<iframe id="jQuery_history" style="display: none;" ></iframe>');
			var iframe = jQuery("#jQuery_history")[0].contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = this._curHash;
		} else if (jQuery.browser.safari) {
			// etablish back/forward stacks
			this._historyBackStack = [];
			this._historyBackStack.length = history.length;
			this._historyForwardStack = [];
			this._isFirst = true;
			this._dontCheck = false;
		}
		this._callback(this._curHash.replace(/^#/, ''));
		setInterval(this._check, 100);
	},

	add: function(hash) {
		// This makes the looping function do something
		this._historyBackStack.push(hash);
		
		this._historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this._isFirst = true;
	},
	
	_check: function() {
		if(jQuery.browser.msie) {
			// On IE, check for location.hash of iframe
			var ihistory = jQuery("#jQuery_history")[0];
			try {
				var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
				var current_hash = iframe.location.hash;
				if(current_hash != jQuery.history._curHash) {
				
					location.hash = current_hash;
					jQuery.history._curHash = current_hash;
					jQuery.history._callback(current_hash.replace(/^#/, ''));
					
				}
			} catch (e) {
				var current_hash = location.hash;
				if(current_hash != this._lastHash) {
					jQuery.history._callback(current_hash.replace(/^#/, ''));
					this._lastHash = current_hash;
				}
			}
		} else if (jQuery.browser.safari) {
			if (!jQuery.history._dontCheck) {
				var historyDelta = history.length - jQuery.history._historyBackStack.length;
				
				if (historyDelta) { // back or forward button has been pushed
					jQuery.history._isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.history._historyForwardStack.unshift(jQuery.history._historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) jQuery.history._historyBackStack.push(jQuery.history._historyForwardStack.shift());
					}
					var cachedHash = jQuery.history._historyBackStack[jQuery.history._historyBackStack.length - 1];
					if (cachedHash != undefined) {
						jQuery.history._curHash = location.hash;
						jQuery.history._callback(cachedHash);
					}
				} else if (jQuery.history._historyBackStack[jQuery.history._historyBackStack.length - 1] == undefined && !jQuery.history._isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						jQuery.history._callback(document.URL.split('#')[1]);
					} else {
						jQuery.history._callback('');
					}
					jQuery.history._isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != jQuery.history._curHash) {
				jQuery.history._curHash = current_hash;
				jQuery.history._callback(current_hash.replace(/^#/, ''));
			}
		}
	},

	load: function(hash) {
		var newhash;
		
		if (jQuery.browser.safari) {
			newhash = hash;
		} else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		this._curHash = newhash;
		
		if (jQuery.browser.msie) {
			try {
				var ihistory = jQuery("#jQuery_history")[0]; // TODO: need contentDocument?
				var iframe = ihistory.contentWindow.document;
				iframe.open();
				iframe.close();
				iframe.location.hash = newhash;
				this._callback(hash);
			} catch (e) {}
		} else if (jQuery.browser.safari) {
			this._dontCheck = true;
			// Manually keep track of the history values for Safari
			this.add(hash);
			
			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {jQuery.history._dontCheck = false;};
			window.setTimeout(fn, 200);
			this._callback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		} else {
		  this._callback(hash);
		}
	}
});

jQuery(document).ready(function() {
	jQuery.history = new History(); // singleton instance
});

})(jQuery);



//======================= Script:   /js/class_external js ()===========================
/* This is an ajax import pseudo-class for javascript for including wikis, essays, or
 * in the future other external pages into a THL page. 
 * The dependencies are:
 *
 * 1. Links should have #wiki= or #essay= prepended to the public url path from the collab site
 * that leads to the targeted wiki. In other words, an "a" element might look like this:
 *
 * <a href="#wiki=/access/wiki/site/71015a3a-5b85-424d-8056-8c5d527dd584/business%20hours.html">Text</a>
 *
 * 2. The various reader scripts, such as wiki_reader.php. Its relative location is set in the wiki_reader_url variable, etc. below.
 *
 * Aside from these two you can drop this whole file into a document as a linked script and
 * it should work. If it doesn't, you may need to check that PHP is allowed to read remote urls.
 *
 * This is based on the object created by Jed (jev3a@virginia.edu) and generaliczed by Than (ndg8f@virginia.edu)
 *
 */


function External() {

	var gen_reader_url = "/global/php/gen_reader.php" ;
	var wiki_reader_url = "/global/php/wiki_reader.php" ; // this script has the collab site hard-coded so it can't be used for just any ajax
	var essay_reader_url = "/global/php/essay_reader.php" ; 
	var jiats_reader_url = "/global/php/jiats_reader.php" ; 
	var old_img_url = "/global/php/old-img-db.php" ; 
	var spt_reader_url = "/global/php/spt_reader.php" ; 
	var spt_home = "http://datastore.lib.virginia.edu/tibet/spt/";
	var cat_reader_url = "/encyclopedias/literary/php/cat_reader.php" ;
	var loading_message = '<div class="shell-1">' + '<p>' +
        '<img src="http://thlib.org/global/images/ajax-loader.gif" style="float: left; vertical-align: middle; border: none;" id="loadimg"/>' +
        '<span style="color: white;">...</span> <em>Loading ....</em>' + '</p></div>'; //jev3a 8.18.08 made link absolute for external calls
	
	// add onclick methods for all links that reference an external page 
    // e.g., the #wiki= signifier is added to wiki links in the wiki_reader.php script
	function ActivateLinks( parent_element ) {
		jQuery( "#ie-root " + parent_element + " a[href*=#wiki], " +
		   "#ie-root " + parent_element + " a[href*=#essay], " + 
		   "#ie-root " + parent_element + " a[href*=#jiats], " + 
		   "#ie-root " + parent_element + " a[href*=#spt]").click(function() {

			jQuery.history.load(this.href.replace(/^.*#/, '')); // historyLoad is part of the jquery.history.js package
				
		});
		   
		// Deal with internal anchor links
		
		jQuery("a[href*=#]").each(function () {
			var mhrf = jQuery(this).attr("href");
			if(mhrf.indexOf("=") == -1 && mhrf != "#") {
				jQuery(this).click(function () {
					var hf = jQuery(this).attr("href");
					hf = hf.substr(hf.indexOf("#") + 1);
					scrollToId(hf);
					return false;
				});
			}
		});
	
	}
	
	function ActivateNavArrows(pref) {
		jQuery(pref + " a.backarrow").click(function() {
			// When back arrow clicked
			var tocclass = ".essay-toc ";
			if(jQuery(".article-toc").length > 0) { tocclass = ".article-toc ";}
			var toclnks = jQuery(tocclass + "li[class!='control'] a"); // get all toc links
			var tind = -1;
			for (var n = 1; n < toclnks.length; n++) { // exclude first toc link because cannot go backward
				if(jQuery(toclnks[n]).hasClass("selected")) { // iterate through them until selected is found
					tind = n - 1; 			 // take the next one 
					break;
				}
			}
			if(tind > -1) { // follow the link found (one before the one selected)
				var preva = jQuery(toclnks[tind]);
				var prh = jQuery(preva).attr("href");
				try {
					window.location.hash = "#" + prh.substring(prh.indexOf("#") + 1); // IE gives full url here. Just take hash value.
					jQuery(tocclass + "li[class!='control'] a.selected").removeClass("selected");
					jQuery(preva).addClass("selected");
				} catch (e) {}
			}
		});
		
		jQuery(pref + " a.forwardarrow").click(function() {
			// When forward arrow clicked
			var tocclass = ".essay-toc ";
			if(jQuery(".article-toc").length > 0) { tocclass = ".article-toc ";}
			var toclnks = jQuery(tocclass + "li[class!='control'] a"); // get all toc links
			var tind = -1;
			for (var n = 0; n < toclnks.length - 1; n++) { // exclude last toc link because cannot go forward
				if(jQuery(toclnks[n]).hasClass("selected")) { // iterate through them until selected is found
					tind = n + 1; 			 // take the next one 
					break;
				}
			}
			if(tind > -1) { // follow the link found (next one after selected)
				var fora = jQuery(toclnks[tind]);
				var fwh = jQuery(fora).attr("href");
				try {
					window.location.hash = "#" + fwh.substring(fwh.indexOf("#") + 1); // IE gives full url here. Just take hash value.
					jQuery(tocclass + "li[class!='control'] a.selected").removeClass("selected");
					jQuery(fora).addClass("selected");
				} catch (e) {}
			}
		});
		
		jQuery(pref + " a.uparrow").click(function() {
			var tocclass = ".essay-toc ";
			if(jQuery(".article-toc").length > 0) { tocclass = ".article-toc ";}
			var firsta = jQuery(tocclass + "li[class!='control']:eq(0)").children("a");
			if(jQuery(firsta).attr("href")) {
				var fwh = jQuery(firsta).attr("href");
				try {
					window.location.hash = "#" + fwh.substring(fwh.indexOf("#") + 1); // IE gives full url here. Just take hash value.
					jQuery(tocclass + "li[class!='control'] a.selected").removeClass("selected");
					jQuery(firsta).addClass("selected");
				} catch (e) {}
			}
		});
	}

	function CreateEssayToc(url) {
		var sid = "";
		var sind = url.indexOf('/s/');
		if (sind > -1) {   
		    sid = url.substring(sind + 3).replace(/\//g,'');
		    url = url.substring(0,url.indexOf('/s/'));
		}
		url += '/toc/';
		url = url.replace('/all/','/').replace('/ /','/'); // had replace("/%20/","/").replace(/\/\//g,'/').
		if (sid.length > 0) { url += "&sid=" + sid;}
		jQuery.ajax({
			url: essay_reader_url,
			data: "url=" + url,
			success: function( data ) {
				jQuery("#list1").html( data ) ;
				var lhtml = jQuery("#tocholder").html();
				jQuery("#list1").html(lhtml);
				
				// Deal with relative links in TOC
				jQuery("#list0 a[href^='file:']").each(function () {
				    var hrf = jQuery(this).attr("href");
				    jQuery(this).attr("href",hrf.replace('file:','').replace('///','/'));
				});
				getDefaultSideColumn(true);
				DoViewAndFormat();
				ActivateNavArrows("#side-column");
				UpdateEssayToc();
				jQuery(".essay-toc a[href*='#essay']").click(function () {
					try {
						var lnkhash = window.location.hash;
						if(lnkhash.indexOf("/all/") > -1) {
							var sectId = (jQuery(this).attr("href")).match(/[abc]\d+/);
							if(jQuery(this).attr("href").indexOf("/notes") > -1) { sectId = "notes"; }
							scrollToId(sectId);
							return false;
						} 
						jQuery(".essay-toc .selected").removeClass("selected");
						jQuery(this).addClass("selected");
					} catch (e) {}
				});
			}
		});
    }
     
	function DoAjax( url, loc, callType ) {
    // Function to perform the Ajax calls takes 3 variables:
    //      1. url : the relative URL of the resource to open
    //      2. loc : the JQuery selector string for the div into which the content is to be put
    //      3. callType : type of Ajax call, e.g., "wiki", "essay", "cat"
        // Ignore calls for catalogs as they are handled by class_catalog.js in the literature encyclopedia
	
        if(callType == "cat") {return;}
		// Check to see if it is a wiki resource download in which case call OpenResource
		if(url.indexOf('content/') > -1) {                                                                                 
			OpenResource(url);
			return;
		}
		
		// ajax loading animation control (triggers anytime ajax is run, so might want to get specific for different kinds of ajax)
		
		jQuery(loc).html(loading_message);
		var callUrl = "";
		var isPrint = 0;
		callType = callType.replace("#",""); // for Safari
		switch(callType) {
		    case "cat": 
			return; // Not handling catalog calls here but in the literary site for now. So quit this function
			callUrl = cat_reader_url;
			break;
		    case "essay":
			callUrl = essay_reader_url;
			if (url.substring(0,1) != '/') { url = '/' + url;}
			if (url.indexOf('/print/') > 0) { url = url.replace('/print/','/all/'); isPrint = 1;}
			if (jQuery("#essay-toc-id").length == 0 && jQuery("#essay-id").length > 0) {CreateEssayToc(url);}
			break;
		    case "essaypg":
			callUrl = essay_reader_url;
			break;
		    case "jiats":
			callUrl = jiats_reader_url;
			if(isProtectedIssue(url) && getCookieValue('thl-jiats-pwd') != jiatspwd) {
				writePersistentCookie("jiatsurl",url,"days",7); 
				window.location.href = "/collections/texts/jiats/login.php";
				return;
			}
			if( typeof(checkJIATSTocByUrl)== 'function' ) {checkJIATSTocByUrl(url);}
			break;
		    case "spt":
			callUrl = spt_reader_url;
			break;
		    case "wiki":
			callUrl = wiki_reader_url;
			break;
		    case "oldimg":
			callUrl = old_img_url;
			break;
		    case "book":
			callUrl = book_reader_url; // this is defined in book.js
			break;
		}
		zhost = "www.thlib.org" ;
		try {zhost = window.location.host; } catch (e) {}
		if ( zhost.indexOf( 'tmb' ) > -1 || zhost.indexOf( 'places' ) > -1 ) { // if calling wiki from ror app (need to add better checking mechanism here)
			
			function exframeloaded() { // called when iframe has loaded
				var el = document.getElementById('ex_frame') ;
				if ( el.contentDocument ) {					
					jQuery(loc).html( el.contentDocument.getElementById('ex_wrapper').innerHTML ) ;
				} else {
					jQuery(loc).html( el.contentWindow.document.getElementById('ex_wrapper').innerHTML ) ;
				}
				ProcessDataWikis(loc) ;
				try {
					jQuery("#sideMenuLink").css("background-position", "0% 0%");
					jQuery("#fxSideMenu").fadeOut("fast");
				} catch( err ) { }
			}
			
			document.domain = zdomain_short ; // zdomain and zdomain_short both set in jquery.thdl.js
			var el = document.createElement('IFRAME') ; // have to create iframe to get wiki_reader content
			el.id = 'ex_frame' ;
			el.style.display = 'none' ;
			el.src = "http://" + zdomain + "/global/php/wiki_reader.php?url=" + url ;
			if (el.addEventListener) {
				el.addEventListener('load', exframeloaded, false);
			}
			else if (el.attachEvent) {
				el.attachEvent('onload', exframeloaded);
			}
			document.body.appendChild(el) ; // hide iframe at bottom of body
		} else {
			  jQuery.ajax({
				url: callUrl,
				data: "url=" + url,
				async: true,
				success: function( data ) {
					jQuery(loc).html( data ) ; // plug data into content area
					switch(callType) { // For cat and essay calls add jQuery("body").removeClass("wiki"); to the process function
					    case "cat": 
						alert("Shouldn't get this far in class_external!");
						break;
					    case "essay":
						ProcessDataEssays(loc);
						if (jQuery("#essay-id").length > 0 && (jQuery("#essay-toc-id").length == 0 ||   jQuery("#essay-toc-id").text() != jQuery("#essay-id").text())) {CreateEssayToc(url);}
						UpdateEssayToc();
						break;
					    case "essaypg":
						ProcessDataEssays(loc);
						break;
					    case "jiats":
						ProcessDataJiats(loc);
						UpdateJIATSTocLinks();
						break;
					    case "spt":
						ProcessDataSpt(loc);
						break;
					    case "wiki":
						ProcessDataWikis(loc) ;
						ShowSideHomeLink();
						break;
					    case "book":
						ProcessDataBook(loc); // this is found in book.js
						break;
					}
					window.status = "Done";
				}
			}) ;
		}
	}
	
	function DoViewAndFormat() {
		// Set the view to cookie value if there is one. Otherwise, set to popular
		var thlview = getCookieValue("thl-essay-view");
		if(thlview) {
			SwitchView(thlview);
			if(document.forms.views != null && document.forms.views.viewsel != null) {document.forms.views.viewsel.value = thlview;}
		} else {
			SwitchView("popular");
		}
		// Deal with Formats
		// depending on hash value choose corresponding format in drop down list
		try {
			if(typeof(document) != "undefined") {
				var hsh = document.location.hash;
				document.forms.formats.formsel[0].selected = true; 
				for (fn=0; fn < document.forms.formats.formsel.length; fn++){
					var fs = document.forms.formats.formsel[fn];
					if(fs.value == hsh || fs.value == "#" + hsh || hsh == "#" + fs.value) {
						fs.selected = true;
						break;
					}
				}
			}
		} catch (e) {}
	}
	
	function getDefaultSideColumn(appendToEnd) {
	
        var mypath = window.location.pathname;
        mypath = mypath.substring(0,mypath.lastIndexOf('/')) + "/side-column.php";
	jQuery.ajax({
		url: "/global/php/side-column-reader.php",
		data: "url=" + mypath + "&type=2",
		success: function( data ) {
			if(typeof(appendToEnd) != "undefined" && appendToEnd == true) {
				jQuery(data).find("h4#side-home-link").attr("id","extra-shl").css("display","none");
				jQuery("#list1").append(jQuery(data).find("#list1").html());
				jQuery("#list1").find("h4:eq(1)").remove();
				
				jQuery("#list1 h3.head").removeClass("selected").next("ul").hide();
				jQuery("#list1 h3.head:first").addClass("selected");
			} else {
				jQuery("#list0").html(jQuery(data).find("#list0").html());
			}
			InitAccordion();
			InitSideColumn();
			jQuery("#list1 h3").next("ul").hide();
			jQuery("#list1 h3:first").next("ul").show();
			ShowSideHomeLink();
		}
	});
    }
    
    function HighlightNav() {
    // Do highlighting of side-area link if it is in the hash
    	try {
		var wl = window.location.href;
		if(wl.indexOf("#wiki=") > -1) { wl = window.location.hash;} else {wl = window.location.pathname;}
		wl = wl.replace(/\s/g,'%20');
	
		jQuery("#list0 a").each(function() {
		    
			hrf = jQuery(this).attr("href");
			// cylce through all links in side area
			// if the href has #wiki in it and is found within window URL, then highlight it!
		       //alert("href: " + hrf + "\nwl: " + wl + "\nmatches: " +  (hrf == wl));
			if(typeof(hrf) != "undefined" && hrf == wl) {
			    // Remove any previously selected link
			    jQuery("#list0 a").removeClass("selected");
			    // Select the present matching link
			    jQuery(this).addClass("selected");
			    // Find parent ul's previous h3 and its class
			    var navgroup = jQuery(this).parents("ul").prev("h3");
			    var navclass = jQuery(navgroup).attr("class");
			    // if it's not selected by accordion, then call the accordion for it
			    if(typeof(navclass)!= "undefined" && navclass.indexOf("selected") == -1) {
				AccordionToggle(jQuery(navgroup), "none");
			    }
			}
		});
            } catch(e) {}
    }
     
	function HistoryInit() {
		jQuery.history.init(pageload);
		jQuery("a[href^=#wiki], a[href^=#jiats], a[href^=#essay], a[href^=#spt]").click(function(){
			jQuery.history.load(this.href.replace(/^.*#/, ''));
			return false;
		});
		/*
		// Initialize ajax history plugin.
		// The callback is called at once by present location.hash. 
		jQuery.historyInit(pageload);
		
		jQuery("a[rel='history']").click(function(){
			// 
			var hash = this.href;
			hash = hash.replace(/^.*#/, '');
			// moves to a new page. 
			// pageload is called at once. 
			jQuery.historyLoad(hash);
			return false;
		});*/
		
	}
	
	/* This is an publically accessible function of the External object
	   that allows content to be retrieved from an external source and 
	   inserted into the specificed location.
	       loc = a JQuery element object or a selector
	       url = a url on THL to a reader (generally a php file) that access external content
	*/
	External.prototype.InsertMarkup = function(loc,url) {
		var reader = gen_reader_url;
		if(url.indexOf('/wiki/') > 0) { reader = wiki_reader_url;}
		if(url.indexOf('/essays/') > -1) { reader = essay_reader_url; url = url.replace('/essays','');}
		jQuery(loc).html(loading_message);
		jQuery(loc).load(reader + "?url=" + url, {}, function () {
			InitStripeHover();
			if (reader == essay_reader_url) { ProcessDataEssays(loc); }
			if (reader == wiki_reader_url) { ProcessDataWikis(loc); }
			var locstr = "#content";
			if (jQuery(loc).attr("id").length > 0) { 
				locstr = "#" + jQuery(loc).attr("id");
			} else if (jQuery(loc).attr("class").length > 0) { 
				locstr = "." + jQuery(loc).attr("class");
			}
			ActivateLinks(locstr);
		}); 
	}
	
	function OpenResource(rurl) {
        // Opens a wiki resource which is a downloadable file.
        if (rurl.charAt(0) != "/") { rurl = "/" + rurl;};
        newurl = "https://collab.itc.virginia.edu" + rurl;
	try { window.location.href = newurl; } catch (e) {}
    }
        
    function ProcessDataEssays(loc) {
         // Set the page title
	 var doctitle = "Tibetan and Himalayan Library Essay";
	 if (jQuery("div.title").text()) { doctitle = Trim(jQuery("div.title").text()) + " (a THL Essay)"; }
	 if (jQuery("#essay-title").text()) { doctitle = Trim(jQuery("#essay-title").text()); }
        document.title = doctitle.replace(/^\s+|\s+$/g, '');
	
	// Deal with view
	DoViewAndFormat();
	
	// Activate Nav Arrows
	ActivateNavArrows("#content");
	
        // Deal with images
        var jqsel = "div.essay-img img:not([src*='arrow'])";
        if(jQuery(jqsel).length == 0) { jqsel = "#content img:not([src*='arrow'])";}
        jQuery(jqsel).each(function () { ProcessImage(jQuery(this)); });
        
	// Embed QuickTime Videos
	EmbedQT(loc);
	
        // Deal with links
        
        jQuery(".essay-body a[href^='file:']").each(function () {
            var hrf = jQuery(this).attr("href");
            jQuery(this).attr("href",hrf.replace('file:','').replace('///','/'));
        });
        
        // Deal with back link in popup boxes
        jQuery("a.back2essay").each(function() {
            jQuery(this).attr("href",jQuery('#side-column a.selected').attr('href'));
        });
        
        jQuery(".essay-body span.tbrc-ref").bind("click", function(e){
              var str = "( " + e.pageX + ", " + e.pageY + " )";
              doTBRCcall(jQuery(this).find("span.key").text(), e.pageX, e.pageY);
            });
	
	// Links to Anchors
	// Notes in essay
	jQuery(".essay-body a.note").click(function () {
		var myid = jQuery(this).attr("href").replace('#','');
		scrollToId(myid);
		return false;
	});
	
	// other in page anchors
	jQuery(".essay-body a[href^=#]").each(function () {
		if(jQuery(this).attr("href").indexOf('=') == -1) {
			var myid = jQuery(this).attr("href");
			if(jQuery(myid).length > 0) {
				myid = myid.replace('#','');
				jQuery(this).click(function () { 
					scrollToId(myid);
					return false;
				});
			}
		}
	});
	
	// Deal with links to old images
	jQuery(".essay-body a[href^='/#oldimg']").each(function() {
			var myhref = jQuery(this).attr("href");
			jQuery(this).attr("href",myhref.replace('/#','#'));
	});
	
	// Deal with Wiki links
	jQuery(".essay-body a[href*='#wiki=']").each(function() {

			var myhref = jQuery(this).attr("href");
			// if it's in an essay, make it a popup window.
			if(jQuery(this).parents("div.essay-body").length > 0) {
				var winid = "jqmwin" + (jQuery(".jqmWindow").length + 1);
				myhref = wiki_reader_url + "?url=" + myhref.substring(myhref.lastIndexOf('=') +1) + "&type=popup";
				jQuery("body").append('<div id="' + winid + '" class="jqmWindow" style="overflow: auto;"><div class="closebtn"><a href="#">Close</a></div></div>');
				jQuery("#" + winid).jqm({ajax: myhref, trigger: this, closeClass: "closebtn", onLoad: function () {ProcessDataWikis("#" + winid);}});
			} else {
				jQuery(this).attr("href",myhref.substring(myhref.indexOf("#wiki")));
			}
	});
	
        //jQuery("span.tbrc-ref").click(function() {doTBRCcall(jQuery(this).find("span.key").text());});  Test call to get info from TBRC via Ajax
	
	if(jQuery(".essay-body a[href*=Conx], .essay-body a[href*=img-db], .essay-body a[href*=thl-popup]").length > 0 && jQuery("head link[href*=jqModal]").length ==0 ) {
		jQuery("head link:last").after('<link rel="stylesheet" type="text/css" href="/global/css/jqModal.css" media="all" />');
	}                                                                               
	jQuery(".essay-body a[href*=Conx]").each(function() {
		if(jQuery(this).attr("href").indexOf("thl-popup") == -1) {
			var winid = "jqmwin" + (jQuery(".jqmWindow").length + 1);
			jQuery("body").append('<div id="' + winid + '" class="jqmWindow" style="overflow: auto;"><a href="#" class="jqmClose">Close</a><hr/> </div>');
			var myhref = (jQuery(this).attr("href")).replace("file:","").replace("///","/");
			jQuery("#" + winid).jqm({ajax: myhref, trigger: this, onLoad: function() {jQuery("#popHistory").append("<p>" + myhref + "</p>"); ActivatePopupLinks("#" + winid);}});
		}
	});
	jQuery(".essay-body a[href*=img-db]").each(function() {
		if(jQuery(this).attr("href").indexOf("thl-popup") == -1) {
			var winid = "jqmwin" + (jQuery(".jqmWindow").length + 1);
			var myhrf = (jQuery(this).attr("href")).replace("file:","").replace("///","/");
			var imgid = myhrf.substring(myhrf.indexOf("=") +1);
			var imgurl = old_img_url + "?url=" + imgid + "&backlink=no";
			jQuery("body").append('<div id="' + winid + '" class="jqmWindow" style="overflow: auto;"><div class="closebtn"><a href="#">Close</a></div></div>');
			jQuery("#" + winid).jqm({ajax: imgurl, trigger: this, closeClass: "closebtn", onLoad: function() {jQuery("#popHistory").append("<p>" + imgurl + "</p>"); ActivatePopupLinks("#" + winid);}});
		}
	});
	jQuery(".essay-body a[href*=thl-popup]").each(function() {
		var winid = "jqmwin" + (jQuery(".jqmWindow").length + 1);
		var myhrf = (jQuery(this).attr("href")).replace("file:","").replace("///","/").replace("//","/");
		var popurl = myhrf.substring(myhrf.indexOf("=") +1);
		var wwind = popurl.indexOf('www.');
		if(wwind > -1) { 
			popurl = "http://" + popurl.substring(wwind); 
			jQuery("body").append('<div id="' + winid + '" class="jqmWindow" style="overflow: hidden;"><div class="closebtn"><a href="#">Close</a></div>' +
				'<div class="viewalone"><a href="' + popurl + '" target="_blank" onclick="javascript:jQuery(this).parents(\'.jqmWindow\').jqmHide();">View this ' + 'Page Alone</a></div><iframe width="98%" height="100%" src="' + popurl + '" style="margin-top: 8px;"></iframe></div>');
			jQuery("#" + winid).jqm({modal: false, trigger: this, closeClass: "closebtn"});
		} else {
			if(popurl.indexOf("file") == 0 ) {popurl = popurl.substring(popurl.indexOf('/')); }
			if(popurl.indexOf("essay=") > -1) { popurl = essay_reader_url + "?url=" + popurl.substring(popurl.lastIndexOf('=') +1) + "&type=popup";}
			jQuery("body").append('<div id="' + winid + '" class="jqmWindow" style="overflow: auto;"><div class="closebtn"><a href="#">Close</a></div></div>');
			jQuery("#" + winid).jqm({ajax: popurl, trigger: this, closeClass: "closebtn", onLoad: function() {jQuery("#popHistory").append("<p>" + popurl + "</p>"); 		
				ActivatePopupLinks("#" + winid);}});
		}
	});
	
	jQuery(".essay-body a.internal-popup").each(function() {
		jQuery("#" + jQuery(this).attr("href")).jqm({trigger: this, closeClass: "closebtn"});
	});
	
	if(jQuery("popHistory").length == 0) {jQuery("body").append('<div id="popHistory" style="display: none;"></div>');}
	
	if(getCookieValue("essayprinting") == "on" && jQuery("#essay-id").length == 1) {
		if(jQuery("html head link[href*=thdl-print]").length == 0) {
			jQuery("html head link:last").after('<link rel="stylesheet" type="text/css" href="/global/css/thdl-print.css" media="print" />');
		}
		window.print();
		deleteCookie("essayprinting");
		try { 
			document.forms.formats.formsel[1].selected = true; // Change selected format to whole document
		} catch (e) {}
	}
    }
    
    
    function doTBRCcall(tbrcid, xval, yval) {
        jQuery("body").append('<div id="tbrccontainer"></div><div id="tbrcpop"></div>');
        jQuery.ajax({
			url: "/global/php/essay_reader.php",
			data: "url=/tbrc/persons/" + tbrcid,
			success: function( data ) {
			    jQuery("#tbrcpop").append('<div id="clsbtn"><p>&nbsp;</p></div>')
                    .append( data );
                    
                if(yval > 400) { jQuery("#tbrcpop").css("top", (yval - 200) + "px");}
                if(xval < 300) {
                    jQuery("#tbrcpop").css("left", (xval + 50) + "px");
                } else if (xval > 400) {
                    jQuery("#tbrcpop").css("left", (xval - 300) + "px");
                }
                
                jQuery("#tbrccontainer").show().css("height",(parseInt(jQuery("#content").css("height")) + 400) + "px");
                jQuery("#tbrcpop").show();
                    
				jQuery("#clsbtn").click(function() {jQuery("#tbrcpop").hide().remove(); jQuery("#tbrccontainer").remove();});
			}
		});
		
    }
    
    function ProcessDataJiats(loc) {
        var myhash = "";
	try { myhash = window.location.hash; } catch (e) {}
        InitStripeHover();  
	
        jQuery(".jiats-box p").each(function() {
            var phtml = jQuery(this).html();
            var txtlen = (jQuery(this).html()).length - (jQuery(this).text()).length + 150;
            var alnk = jQuery(this).next("a").clone();
            var pind = phtml.substring(txtlen).indexOf(' ') + txtlen;
            phtml = phtml.substring(0,pind); // + '.... '
            if (phtml.substring(phtml.length - 1) == ".") {
                phtml = phtml.substring(0,phtml.length - 1);
            }
            jQuery(this).html(phtml + '.... ');
            jQuery(this).append(alnk);
            jQuery(this).next("a").remove();
        });
	
	// Set Browser title
	if(jQuery("h2.title").length > 0) {
		var src = jQuery("p.biblline").text();
		src = src.substring(0,src.indexOf('(') - 1).replace(', no.','') + ": ";
		var title = jQuery("h2.title").clone();
		jQuery(title).find(".popular").remove();
		title = jQuery(title).text();
		var lchar = title.substr(title.length - 1);
		lchar = lchar.replace(/[\s\d]+/,"");
		while(lchar == "" && title.length > 5) {
		    title = title.substr(0,title.length - 1);
		    lchar = title.substr(title.length - 1);
		    lchar = lchar.replace(/[\s\d]+/,"");
		}
		if(title.indexOf(":") > 0) {title = title.substring(0,title.indexOf(":"));}
		document.title = (src + title).replace(/^\s+|\s+$/g, '');
	} else if (jQuery("div.title").length > 0) {
		var src = jQuery("div.source").text();
		src = src.substring(0,src.indexOf('(') - 1).replace(', no.','') + ": ";
		var title = jQuery("div.title").clone();
		jQuery(title).find(".popular").remove();
		title = jQuery(title).text();
		document.title = (src + title).replace(/^\s+|\s+$/g, '');
	} else {
		document.title = "Journal of the International Association of Tibetan Studies";
	}
	
	// Deal with view
	DoViewAndFormat();
	
        // Deal with IMAGES
        var jqsel = "div.essay-body img:not([src*='arrow'])";
        if (jQuery(jqsel).length == 0) {jqsel = "#content img:not([src*='arrow'])";}
        jQuery(jqsel).each(function() { ProcessImage(jQuery(this)); });
        doJiatsImgLinks(); // Click images to get larger version in popup.
	
	// Embed QuickTime Videos
	EmbedQT(loc);
	
        // Deal with Links
        ActivateLinks("");
	   ActivateNavArrows("#content");
	   jQuery("a[href^=file:]").each(function() { 
			   var myhref = jQuery(this).attr("href");
			   jQuery(this).attr("href",myhref.replace("file:","").replace("///","/"));
	   });
        // Notes in articles
	jQuery("a.note").click(function () {
		var myid = jQuery(this).attr("href").replace('#','');
		scrollToId(myid);
		return false;
	});
        
	// Check TOC (function in /collections/texts/jiats/js/jiats.js file
	//checkJIATSToc();
	
        if(myhash.indexOf("jiats=") > -1) {ShowSideHomeLink();}
        
        jQuery('a.thickbox, area.thickbox, input.thickbox').attr("title","Citation for JIATS Article");
        tb_init('a.thickbox, area.thickbox, input.thickbox');
	
	if(getCookieValue("essayprinting") == "on" && jQuery("#jiats-page-id").length == 1) {
		window.print();
		deleteCookie("essayprinting");
		try { 
			document.forms.formats.formsel[1].selected = true; // Change selected format to whole document
		} catch (e) {}
	}
	

    }
    
    function ProcessDataSpt(loc) {
	ActivateLinks(loc);
        jQuery(".ResourceTitle").each (function () {
            var thtml = jQuery(this).html();
            var ind = thtml.indexOf('(');
            if (ind > 0) {
                var wyl = thtml.substr(ind + 1);
                wyl = wyl.replace(')','');
                thtml = thtml.substr(0,ind);
                jQuery(this).html('<span class="title-tib">' + thtml + '</span> ').append('<span class="title-wylie">' + wyl + '</span>');
            }
        });
        
        jQuery("img[src^='SPTUI']").each(function () {
            var mysrc = jQuery(this).attr("src");
            mysrc = spt_home + mysrc;
            jQuery(this).attr("src",mysrc);
        });
    }
    
    function ProcessDataWikis(loc) {
	// Process data returned from wikis to fit into THL pages.
	jQuery("#fxSitemap").hide();                                                                                                            

	// Remove extraneous wiki tags (This may need to be changed as Collab changes its markup)
	var wcontent = jQuery("div.rwiki_RenderedContent").html();
	jQuery("div.publicview").html(wcontent);
	
	// Set body class to wiki
	jQuery("body").addClass("wiki");
	
	// Hide Breadcrumbs
	jQuery("#rwiki_content").prev("a").hide(); // hide breadcrumb links
	    
	// remove external link images
	jQuery('div.publicview img[title^=external]').remove() ;
	
	// convert image links from a wiki into images
	//jQuery('a[href*=.jpg]').each(function() {
	//	var src = jQuery(this).attr("href");
	//	jQuery("#content p:contains('a'):eq(0)").before('<div class="img-right-shadow"><div><img src="' + src + '" class="f-right"></img></div></div>');
	//	jQuery(this).remove();
	//});
	
	
	// mark-than - plain img style, note the self-closing img tag and no need to add float class to img
	jQuery('a[href*=.jpg], a[href*=.gif], a[href*=.png]').each(function() {
		var src = jQuery(this).attr("href");
		jQuery("#content p:contains('a'):eq(0)").before('<div class="img-left-plain"><img src="' + src + '" /></div>');
		jQuery(this).remove();
	});
	
	
	// Remove first link which repeats the page name unnecessarily (Added since new Collab)
	// Taking this out for tabs. Does this affect other wiki pages?
	//jQuery("#content a:first").remove();
	
	// Remove span nobrs
	jQuery("#content .nobr").each(function () {
		 var innards = jQuery(this).html();
		 jQuery(this).before(innards);
		 jQuery(this).remove();
	});
	
	// Deal with <b class="bold">
	jQuery("b.bold").each(function () {
		var cnt = jQuery(this).html();
		jQuery(this).after("<strong>" + cnt + "</strong>");
		jQuery(this).remove();
        });
        
        // Deal with lists within lists
        jQuery("li li").css("list-style-type","none").css("margin-left","0pt");
		
	// Set Target for extra-THL Links
	jQuery("*[target='rwikiexternal']").each(function() {
		var myhref = jQuery(this).attr("href");
		jQuery(this).removeAttr("target");
		if (typeof(myhref) == "string" && 
			((myhref.indexOf("www.thdl") == -1 && myhref.indexOf("old.thdl") == -1 && myhref.indexOf("thdl.org") > -1) || myhref.indexOf("thlib") > -1)) {
			jQuery(this).attr("rel","");
		} else if (myhref.indexOf("https://collab") == 0) {  // then it's a download
			jQuery(this).attr("rel","");
		} else {
			jQuery(this).attr("rel","external");
		}
	});
	ConvertExternalLinks();
	// Fix table styles
	jQuery(".wiki-table *").css("vertical-align","top").css("padding","2px");
	
	// scrub bad characters
	jQuery('div.publicview a[href*=%26]').each( function(i) { // %26 is the & character, which can cause wiki and nav choking
		this.href = this.href.replace( "%26" , "|amp|" ) ;
	}) ;
		
	// Do links to essays
	jQuery('div.publicview a[href*=ESSAY],div.publicview a[href*=essay/]').each(function() {
            var hrf = jQuery(this).attr("href");
            hrf = hrf.replace(/http\:\/\/ESSAY/i, "#essay=");
            jQuery(this).attr("href",hrf);
            jQuery(this).attr("target","");
        });
        
        // Deal with links to SPT
        jQuery('div.publicview a[href*=SPTHOME],div.publicview a[href*=spthome]').each(function() {
            var hrf = jQuery(this).attr("href");
            hrf = hrf.replace("http://SPTHOME/", "#spt=");
            jQuery(this).attr("href",hrf);
            jQuery(this).attr("target","");
        });
        
        // Deal with wiki internal links
	var wdhash =  window.location.hash;
        jQuery('div.publicview a[href^=#wiki]').each(function () {
		var myhrf = jQuery(this).attr("href");
		var ind = myhrf.indexOf('#wiki') + 1;
		var linkhash =  myhrf.substring(ind);
		ind = linkhash.indexOf('#');
		if(wdhash.indexOf(linkhash) > -1 && ind > -1 ) {
			var divid = myhrf.substring(ind + 2);
			jQuery(this).click(function() {
				scrollToAnchor(divid);
				//alert(divid);
				return false;
			});
		}
	});
	
	// Deal with internal link in the present pages wiki call hash
	var h2ind = wdhash.substr(2).indexOf("#");
	if(h2ind > -1) {
		var divid = wdhash.substring(h2ind + 2);
		scrollToAnchor(divid);
	}
        
	// remove wiki "thdl" footer and put it in main page footer if not already there
	var targ_el = jQuery('div.publicview h3.heading-h6:contains("unrestricted use")') ;
	if ( jQuery('#subFooter h3.heading-h6').get() == "" ) {
		targ_el.appendTo('#subFooter') ;
	} else { 
		targ_el.remove() ;
	}
	
        // Deal with space in tags within <pre> code
        jQuery("span.java-quote").each(function(){
            var shtml = jQuery(this).html();
            jQuery(this).before(shtml);
            jQuery(this).remove();
        });
        
        jQuery("pre").each(function(){
            var phtml = jQuery(this).html();
            phtml = phtml.replace(/\s+\&gt\;/g,"&gt;");
            phtml = phtml.replace(/\&lt\;\s+/g,"&lt;");
            phtml = phtml.replace(/\/\n(\s)+/,"/");
            phtml = phtml.replace(/=\s+\"/g,"=\"");
            jQuery(this).html(phtml);
        });
	    
	// Embed QuickTime Videos
	EmbedQT(loc);
		
        // remove any copywrite notice in wiki page itself
        jQuery("h3.heading-h6 a[name^='Providedforunrestricteduse']").parent().hide(); 
	jQuery("h3.heading-h6 a[name^='Thispage']").parent().hide();
	
        // Deal with other h3-h6 links
        //jQuery("h3.heading-h6:last").removeClass("heading-h6").addClass("wikifooterh6");
        
	if(loc.indexOf("jqmwin") == -1) {
		// Set the page title, if it's not a popup window
		document.title = jQuery("h3.heading-h1:first").text().replace(/^\s+|\s+$/g, '');
	}
		
	jQuery(loc).show() ; // i don't know why, but having this here seems to smooth transitions
	
	ActivateLinks( 'div.publicview' ) ;
	
	HighlightNav() ; // function added by Than to highlight chosen Nav link
			
	} // End of Process Data Wikis Function
	
	// variables relevant to pageload
	External.prototype.doneAjax = 0;
	var lasthash = "";
	
	// bookmarking and ajax initiation (jev3a 7/3/08 says: we need to farm these out to different methods to tighten up the code!)
	function pageload(hash) {
		/*if (hash == "" && jQuery.browser.safari) {  hash = location.hash;}
		if(hash == lasthash) { d = new Date; window.status = "returning " + location.hash + " : " + hash; return; }
		lasthash = hash;*/
		if (hash && ( hash.indexOf('=') == -1 || hash.indexOf('=') == hash.length - 1 ) && hash.indexOf( "img/") != 0 ) {return;} // if not a wiki= or essay= or something like that, then return. /img is for mms
		if (hash && hash != "#" && hash != "" && hash.indexOf("iframe") == -1) { // if a hash exists initially, assume it's an ajax ref (for iframe issues, see app_plug.js, jev3a@virginia.edu)
			window.scrollTo(0,0);           	// Scroll to top
			if ( hash.indexOf( 'img/') != -1 ) { 	// for the mms galleria, going back and forth between wiki and mms (temp solution, not great)
				if ( typeof(loc_old_exists) != "undefined" ) {
					reloadPage();
				} else {
					onPageLoad( hash ) ;			//galleria.js
					External.prototype.doneAjax = 1;
				}
			} else {
				if(jQuery.browser.safari) {  hash = window.location.hash;}
				ext_url = ScrubURL( hash ) ;	// perform a number of operations, like url encoding to make it ready 
				// for ajax
				hashType = hash.slice(0, hash.indexOf("="));
				var loc = "#content";
				if ( typeof(loc_old_exists) == "undefined" ) {
					loc_old_exists = 1 ; // for restoring old info
				}
				
				DoAjax(ext_url, loc, hashType) ;
				if(hash.indexOf('wiki=') > -1 && jQuery("#essayurl").length == 1) { getDefaultSideColumn();}
				External.prototype.doneAjax = 1;
			}
		}  else if (typeof(hash) != "undefined" && hash.indexOf("iframe") != -1) { 	//for iframes (for iframe issues, see app_plug.js, jev3a@virginia.edu)
			if ( hash.indexOf("&bookmark=true") != -1 && thlplug.status == "on" ) { 	//if  bookmarking an iframe
				//url = window.location.href.split("&bookmark") ;
				//url = url[0] ;
				//window.location.hash = url ;
				thlplug.bookmark() ;
			} 
			if ( thlplug.status != "on" ) {				// the only reason this would be on is if we've just bookmarked, in which case we don't want to go
				window.scrollTo(0,0) ;           		// Scroll to top
				try {
					thlplug.swap( window.location.href ) ;
					ToggleNavButton( hash ) ; // in fn.js, attempts to do proper masthead-navbar button toggling
				} catch( err ) {
					//alert("1: " + err.description) ; 	// /global/js/app_plug.js not included, which is okay
				}
			}
		} else if (hash == "" && (typeof(thlplug) != "undefined") ) {			
			if ( thlplug.status == "on" ) {
				try {
					reloadPage() ;
					//thlplug.swap_undo() ; 
					//ToggleNavButton() ; // in fn.js, restores masthead-navbar button to original state					
				} catch( err ) {
					//alert("2: " + err.description) ;// /global/js/app_plug.js not included, which is okay
				}
			} else if (External.prototype.doneAjax == 1) {
				reloadPage();
				External.prototype.doneAjax = 0;
			} 
		} 
	}
    
	function ProcessImage(imgel) {
		var mysrc = jQuery(imgel).attr("src");
		var imgdiv = jQuery(imgel).parent().parent();
		var myclass = jQuery(imgdiv).attr("class");
		if (typeof(mysrc) == "undefined" || mysrc == "" ) {
			return;
		}
		if(typeof(myclass) == "undefined" || myclass== "") {
			var pars = jQuery(imgel).parents();
			for(var n=0; n<pars.length; n++) {
				myclass = jQuery(pars[n]).attr("class");
				if(typeof(myclass) == "string" && myclass.indexOf("img-") > -1 && myclass.indexOf("-shadow")) {
					imgdiv =jQuery(pars[n]);
					break;
				}
			}
			if(typeof(myclass) == "undefined" || myclass== "") {
				var imgpars = jQuery(imgel).parents().map(function () { return this.tagName; }).get().join(", ");
				return;
			}
		} 
		var jiatsbase = "www.thlib.org";
		try {jiatsbase = window.location.host;} catch (e) {}
		if (jiatsbase.indexOf("staging") > -1) {
			jiatsbase = "staging.texts.thlib.org";
		} else if (jiatsbase.indexOf(".thdl.org") > -1 || jiatsbase.indexOf(".thlib.org") > -1) {
			jiatsbase = "texts.thlib.org";
		} else {
			jiatsbase = jiatsbase + ":8080/cocoon/texts";
		}
		jiatsbase = jiatsbase + "/jiats";
		if(mysrc.search(/jiats-img/i) > -1) {
			mysrc = mysrc.replace(/jiats-img/i,jiatsbase);
		}
		jQuery(imgel).attr("src", mysrc);
		var imgid =  "#" + jQuery(imgel).attr("id");
		// Fix image captions
		jQuery('.img-left-shadow img, .img-right-shadow img').bind('load readystatechange', function(e) {
			if (this.complete || (this.readyState == 'complete' && e.type == 'readystatechange')) {
				jQuery(this).parents(".img-left-shadow, .img-right-shadow").find("h6:eq(0)").width(jQuery(this).width());
			}
		});
		jQuery(".img-left-shadow h6, .img-right-shadow h6").each(function() {
			var wd = jQuery(this).prev("div").find("img").width();
			if(wd > 0) {jQuery(this).width(wd); }
		});
	}
    
	function reloadPage() {
		if(jQuery.browser.msie) {
			window.location.reload();
		} else {
			try { window.location.reload(); } catch(err) {
				var myloc = window.location.href;
				window.location.href = myloc;
			}
		}
	}
    
	function ScrubURL( url ) {
		//var output = url.replace(/wiki=/, '') ;		// strip everything but url
		var output = url.substring(url.indexOf('=') + 1);
		if (url.indexOf('=') == -1) {output = url;}
		output = output.replace( /\|amp\||\&/ , "%26" ) ;// take care of nastiness like & characters
		return output ;
	}
	
	function ShowSideHomeLink() {
		if(jQuery("#side-column .list0 h4#side-home-link a").length > 0) {
			// move side home link to top if essay toc is inserted before it.
			if(jQuery("#side-home-link").prev().length > 0) {
				var myhtml = jQuery("#side-home-link").toXML();
				jQuery("#side-home-link").remove();
				jQuery("#side-column .list1").prepend(myhtml);
			}
			jQuery("#side-column .list0 h4#side-home-link").css("visibility","visible").css("line-height","150%").css("margin-top","0px");
			jQuery("#side-column p#side-home-link-test").css("visibility","visible");
			try {
				if(window.location.hash=="") {
					if(jQuery("#side-column .list0 h4#side-home-link").css("visibility") == "visible") {
						jQuery("#side-column .list0 h4#side-home-link").css("visibility","hidden").css("line-height","0%");
						jQuery("#side-column p#side-home-link-test").css("visibility","hidden");
					}
				}
			} catch (e) {}
		}
	}
        
	function UpdateEssayToc() {
		jQuery(".essay-toc .selected").removeClass("selected");
		jQuery(".essay-toc a[href*='#essay']").each(function () {
			var mylnk = jQuery(this).attr("href");
			if(mylnk == window.location || mylnk == window.location.href || mylnk == window.location.hash) {
				jQuery(this).addClass("selected");
			}
		});	
		if(jQuery(".essay-toc .selected").length == 0) { jQuery(".essay-toc a[href*='#essay']:first").addClass("selected"); }
	}
	
	//ActivateLinks( "body" ) ;

	HistoryInit() ;	
	
}

var contentLoader;



//======================= Script:   /js/class_wikiloader js ()===========================

// JS Object for loading Wiki content into parts of a THL page such as Tzr boxes
// WikiLoader Contstructor
function WikiLoader() {
	var wiki_reader_url = "/global/php/wiki_reader.php" ; 
	
	// Wikiloader object function to insert content in el.
	WikiLoader.prototype.getWikiContent = function(el) {
	
	var cls = jQuery(el).attr("class");
	
	if (typeof(cls) == "undefined") {return;}
	if (cls.indexOf("tzr-intro-1") > -1) {
		
		cls = "tzr-intro-1";
		jQuery(el).append('<p class="wtarg">Loading .... </p>');
	
	} else if (cls.indexOf("tzr-box1") > -1) {
		
		cls = "tzr-box1";
		jQuery(el).append('<p class="wtarg">Loading .... </p>');
	
	} else if (cls.indexOf("tzr-1") > -1) {
		
		cls = "tzr-1";
		jQuery(el).append('<div class="wtarg">Loading .... </div>');
	
	} else if (el.tagName.toLowerCase() == "p") {
		
		cls = "p";
		jQuery(el).addClass("wtarg");
		jQuery(el).prepend("Loading ...");
		
	} else if (cls == "full") {
		jQuery(el).append('<p class="wtarg">Loading .... </p>');
	} else {
		/*Unknown type. Just return without doing anything */
		return;
	}
	
	var ael = jQuery(el).find("a.wiki:first");
	jQuery(ael).hide();
	var wurl = jQuery(ael).attr("href");
	
	if (typeof(wurl) == "undefined" || wurl.indexOf('/.html') > -1) { 
		jQuery(el).html("<h4><a>No Wiki Page Set</a></h4><p><b>No wiki page set for this box!</b></p>"); 
		return;
	}
	jQuery(el).append('<div class="wikicontent" style="visibility: hidden; display: none;"></div>');
	var wcnt = jQuery(el).children("div.wikicontent:first");
	jQuery.ajax({
		url: wiki_reader_url,
		data: "url=" + wurl + "&type=box",
		success: function (data) {
			jQuery(wcnt).html(data);
			processWikiContent(el, cls);
		}
	});
    }
        
    function processWikiContent(el, cls) {
	    
        var wsrc = jQuery(el).children("div.wikicontent:first"); // Wiki Source
        var ctarg = jQuery(el).find(".wtarg");  // Target paragraph where content goes
        var ael = jQuery(el).find("a.wiki:first"); // a tag linking to wiki;
        var wurl = jQuery(ael).attr("href"); // wiki URL;
        var spcs = jQuery(ael).attr("class").replace("wiki","");
        var specs = new Specs(spcs); // The specs object from the class attribute of the a tag
        var len = specs.getSpec("c");
        var lnktxt = "";
        
        jQuery(ael).remove();  // Remove wiki a tag
        
        if(cls == "tzr-intro-1") {
            if(!len) {
                if (jQuery(el).attr("class").indexOf('stacked') > -1) { 
                    len = 225;
                } else {
                    len = 400
                }
            }
            jQuery(ctarg).html(getCharRun(wsrc,len,wurl));
            if (!specs.opt("read more")) {
                
                loc = getLoc(wsrc, wurl);
                alnk = '<a href="' + loc + '" class="read-more">';     
                if(loc == "#wiki=" + wurl) {
                    lnktxt = "Read More"; 
                } else {
                    lnktxt = getLinkText(wsrc);
                }
                jQuery(ctarg).find("p:last").append("... " + alnk + lnktxt + "</a>");
            }
            if (!specs.opt("drop cap")) { 
                doDropCap(jQuery(ctarg));
            }
            jQuery(ctarg).replaceWith(jQuery(ctarg).html());
        // TZR-BOX1 Class
         } else if (cls == "tzr-box1") {  
            jQuery(wsrc).find("a.anchorpoint").remove();    
            h4txt = jQuery(wsrc).find("h3.heading-h1:first").html();
            
            h5 = "";
            if (jQuery(wsrc).find("h3.heading-h2:first").length > 0 && !specs.opt("no head")) {
                h5 = "<h5>" + jQuery(wsrc).find("h3.heading-h2:first").html() + "</h5>";
            } 
            
            h6 = "";
            if (jQuery(wsrc).find("h3.heading-h3:first").length > 0 && !specs.opt("no head")) {
                h6 = "<h6>" + jQuery(wsrc).find("h3.heading-h3:first").html() + "</h6>";
            } 
            
            if(h5 == "" && h6 == "") {
                jQuery(el).children("p:first").css("padding-top", "6pt");
            }
            
            if(!len) {len = "300"}; // was "all"
            //jQuery(ctarg).before(h5).before(h6);// had .before(h6) ...
            var mytxt = getCharRun(wsrc,len,wurl);
	    //alert(jQuery(ctarg).toXML());
	    jQuery(ctarg).html(mytxt); 
            
            loc = getLoc(wsrc, wurl);
            alnk = '<a href="' + loc + '">'; 
            
            if(jQuery(el).children("h4:first").length == 0) {
                jQuery(el).prepend("<h4></h4>");
            }
            jQuery(el).children("h4:first").html('<a href="' + loc + '">' + h4txt + '</a>');
            
            if(jQuery(wsrc).find("a:contains('image')").length > 0) {
                var imga = jQuery(wsrc).find("a:contains('image')");
                var isrc = jQuery(imga).attr('href');
                var caption = "";
                if(jQuery(wsrc).find("div.caption").length > 0) {
                    caption = jQuery(wsrc).find("div.caption p").text();
                    jQuery(wsrc).find("div.caption").remove();
                }
                jQuery(el).children("h4:first").after(alnk + '<img src="' + isrc + '" title="' + caption +'"/></a>');
            }
            
            jQuery(el).children("img:first").wrap(alnk + "</a>");
            if (!specs.opt("read more")) {
                if(loc == "#wiki=" + wurl) {
                    lnktxt = "Read More"; 
                } else {
                    lnktxt = getLinkText(wsrc);
                }
		var lastp = jQuery(ctarg).find(">*:last");
		if(typeof(lastp) == "object" && lastp.text && lastp.text() != "") {
			jQuery(lastp).html(jQuery(lastp).html().replace("\u2026","..."));
			if(jQuery(lastp).text().indexOf("\u2026") == -1 && jQuery(lastp).text().indexOf("...") == -1) {jQuery(lastp).append("...");}
			jQuery(lastp).append(" <a href=\"" + loc + "\" class=\"read-more\">" + lnktxt + "</a>");
		}
            }
            if (specs.opt("drop cap")) { 
                doDropCap(jQuery(ctarg));
            }
            jQuery(ctarg).replaceWith(jQuery(ctarg).html());
        // TZR-1 Class
        } else if (cls == "tzr-1") { 
            
            h4txt = jQuery(wsrc).find("h3.heading-h1:first").html();
            h5 = "";
            if (jQuery(wsrc).find("h3.heading-h2:first").length > 0 && !specs.opt("no head")) {
                h5 = "<h5>" + jQuery(wsrc).find("h3.heading-h2:first").html() + "</h5>";
            } else {
                jQuery(el).children("p:first").css("padding-top", "6pt");
            }
            
            h6 = "";
            if (jQuery(wsrc).find("h3.heading-h3:first").length > 0 && !specs.opt("no head")) {
                h6 = "<h6>" + jQuery(wsrc).find("h3.heading-h3:first").html() + "</h6>";
            }
            
            if(!len) {len = "300"}; // was "all"
            jQuery(ctarg).html(getCharRun(wsrc,len,wurl)); // had .prepend(h6).prepend(h5)
            
            loc = getLoc(wsrc, wurl);
            alnk = '<a href="' + loc + '">'; 
            
            if(jQuery(el).children("h4:first").length == 0) {
                jQuery(el).prepend("<h4></h4>");
            } else {
                h4 = jQuery(el).children("h4:first").html();
            }
            /*if(specs.opt("read more")) { loc = "javascript: alert('This section is not yet available!');"; }*/
            
            jQuery(el).children("h4:first").html('<a href="' + loc + '">' + h4txt + '</a>');
            
            
            if(jQuery(wsrc).find("a:contains('image'):last").length > 0) {
                var imga = jQuery(wsrc).find("a:contains('image'):last");
                var isrc = jQuery(imga).attr('href');
                var caption = "";
                if(jQuery(wsrc).find("div.caption").length > 0) {
                    caption = jQuery(wsrc).find("div.caption p").text();
                    jQuery(wsrc).find("div.caption").remove();
                }
                jQuery(el).children("h4:first").after(alnk + '<img src="' + isrc + '" title="' + caption +'" /></a>')
            }
            
            jQuery(el).children("img:first").wrap(alnk + "</a>");
            
            if(!specs.opt("read more")) {
			var lastp = jQuery(ctarg).children("*:last");
			if(typeof(lastp) == "object" && lastp.text && lastp.text() != "") {
				jQuery(lastp).append("... ");
				var lhtml = jQuery(lastp).html();
				if(lhtml != null && typeof(lhtml) == "string") {jQuery(lastp).html(lhtml.replace(". ...","..."));}
			}                                                            
			if(loc == "#wiki=" + wurl) {
				lnktxt = "Read More"; 
			} else {
				lnktxt = getLinkText(wsrc);
			}
			if(jQuery(ctarg).children("*:last").text() != "") {jQuery(ctarg).children("*:last").append("  <a href=\"" + loc +  "\" class=\"read-more\">" + lnktxt + "</a>");}
            }
            
            if (specs.opt("drop cap")) { 
                doDropCap(jQuery(ctarg));
            }
            
        } else if (cls == "p") {
            if (!len) { len = 400; }
            jQuery(el).html(getCharRun(wsrc,len,wurl));
            jQuery(el).find("p").each(function() {
	            var ftxt = "";
		    if(jQuery(this).next("p").length > 0) { ftxt = "<br/><br/>";}
		   jQuery(this).replaceWith(jQuery(this).html() + ftxt);
	    });
            if (!specs.opt("read more")) {
                loc = getLoc(wsrc, wurl);
                alnk = '<a href="' + loc + '" class="read-more">'; 
                if(loc == "#wiki=" + wurl) {
                    lnktxt = "Read More"; jQuery(el).append("... ");
                } else {
                    lnktxt = getLinkText(wsrc);
                }
                jQuery(el).append("  " + alnk + lnktxt + "</a>");
            }
            
            if (specs.opt("drop cap")) { 
                doDropCap(el);
            }
            
        } else if (cls == "full") {
	    jQuery(el).html(jQuery(wsrc).html());
	    jQuery("ul.star").removeClass("star").addClass("bullet-blue");
	    jQuery(".heading-h6, .heading-h1").remove();
	    jQuery(el).removeClass("full").addClass("wiki");
	}
        
        jQuery(ctarg).removeClass('wtarg');
        if(cls != "p" || cls != "full") {jQuery(wsrc).remove();} // P tag get's its content replaced including wiki source.

	// remove external link images
	jQuery('img[title^=external]').remove() ;
	jQuery('img[alt^=external]').remove() ;
	jQuery('img[src*=icklearrow]').remove() ;
	jQuery('img[src=""]').remove() ;
	
	// Remove span nobrs
	jQuery("span.nobr").each(function () {
		 var innards = jQuery(this).html();
		 jQuery(this).before(innards);
		 jQuery(this).remove();
	});
	
	// Set Target for extra-THL Links
	jQuery("*[target='rwikiexternal']").each(function() {
		var myhref = jQuery(this).attr("href");
		jQuery(this).removeAttr("target");
		if (typeof(myhref) == "string" && 
			(myhref.substr(0,1) == "/" || (myhref.indexOf("www.thdl") == -1 && myhref.indexOf("old.thdl") == -1 && myhref.indexOf("thdl.org") > -1) || myhref.indexOf("thlib") > -1)) {
			jQuery(this).attr("rel","");
		} else {
			jQuery(this).attr("rel","external");
		}
	});
	
	ConvertExternalLinks();
	
	// Fix table styles
	jQuery(".wiki-table *").css("vertical-align","top").css("padding","2px");
	
	// scrub bad characters
	jQuery('a[href*=%26]').each( function(i) { // %26 is the & character, which can cause wiki and nav choking
		this.href = this.href.replace( "%26" , "|amp|" ) ;
	}) ;
	
	// Embed QuickTime Videos
	EmbedQT(el);
	ActivateLinks(el);
    }
    
    function getLoc(wsrc, wurl) {
        var loc;
        if(jQuery(wsrc).find("div.resource-link a:first").length > 0) {
            loc = jQuery(wsrc).find("div.resource-link a:first").attr("href");
        }
        // function for adjustion the location URL of the Read more
        if (typeof(loc) == "string" && loc.length > 0) {
            loc = loc.replace("http://WIKI", "#wiki=").replace("http://wiki", "#wiki=");
            loc = loc.replace("http://ESSAYPG", "#essaypg=").replace("http://essaypg", "#essaypg=");
            loc = loc.replace("http://ESSAY", "#essay=").replace("http://essay", "#essay=");
            loc = loc.replace("http://DOMAIN/", "/").replace("http://domain/", "/"); 
        } else { 
            loc = "#wiki=" + wurl;
        }
        return loc;
    }
    
    function getLinkText(wsrc) {
        var lnktxt = "Explore!";
        if(jQuery(wsrc).find("div.resource-link a:first").length > 0) {
            var lnk =  jQuery(wsrc).find("div.resource-link a:first");
	    //alert(jQuery(lnk).attr("href")+ " : " + jQuery(lnk).text());
	    var mylnktxt = jQuery(lnk).text();
	    var lnkhref = jQuery(lnk).attr("href");
	    if(lnkhref.indexOf("essay") > -1 || lnkhref.indexOf("ESSAY") > -1) { lnktxt = "Read More";}
            if(typeof(mylnktxt) == "string" && mylnktxt != lnkhref && lnkhref.indexOf(mylnktxt) == -1 && mylnktxt.indexOf('/') == -1) {
                lnktxt = Trim(mylnktxt);
            }
        }
        return lnktxt;
    }
    
	function getCharRun(wsrc, len, wurl) {
		var nsrc = jQuery(wsrc).find("#wout");
		jQuery(nsrc).find(".heading-h2").each(function () {
			var mhtl = jQuery(this).html();
			jQuery(this).replaceWith('<h5 class="whead">' + mhtl + "</h5>");
		});
		var pels = jQuery(nsrc).children().filter(function () {return jQuery(this).attr("class") == "paragraph" || jQuery(this).attr("class") == "whead";});
		var cntlen = 0;
		var phtml = "";
		var isOpen = false;
		var debug = "";
		var diff = 0;
		try {
			if (len == "all") {
				if( jQuery(nsrc).find(".whead:eq(0)").html() != null) {
					phtml = '<h5 class="whead">' + jQuery(nsrc).find(".whead:eq(0)").html() + "</h5>";
				}
				jQuery(wsrc).find("p, ul, blockquote").each(function() {
						if(!jQuery(this).parent().hasClass("resource-link") && jQuery(this).find("img").length ==0 && !jQuery(this).parent().hasClass("caption")) {
							phtml += jQuery(this).toXML();
						}
				});
				phtml = phtml.replace(/class="star"/,'class="bullet-blue"');
				return phtml;
			} else {
				for(var nf = 0; nf < pels.length; nf++) {
					cntlen += ((jQuery(pels[nf]).text()).length) * 1;
					if(cntlen > len ) {
						diff = cntlen - len; 
						var myhtml = jQuery(pels[nf]).html();
						var stt = myhtml.length - diff;
						var nextsp = myhtml.substr(stt).indexOf(" ");
						myhtml = myhtml.substr(0,stt + nextsp);
						var mytag = jQuery(pels[nf]);
						jQuery(mytag).html(myhtml);
						phtml += " " + jQuery(mytag).toXML();
						return phtml;
					}
					phtml += " " + jQuery(pels[nf]).toXML(); 
				}
				var outStr = "";
				var chrct = 0
				var intag = false;
				for (var n=0; n<len; n++) {
					var chr = phtml.substr(n,1);
					if(!intag && chr == "<") {
						intag = true;
						if(phtml.substr(n + 1, 1) == "/") {
							isOpen = false;
						} else {
							isOpen = true;
						}
					} else if (intag && chr == ">") {
						intag = false;
					} else if (intag == false) {
						chrct += 1;
						if(chrct >= len && isOpen == false) {
							if(intag) {
								outStr += phtml.substr(n,phtml.substr(n).indexOf(">"));
							} else {
								outStr += phtml.substr(n,phtml.substr(n).indexOf(" "));
							}
							break;
						}
					}
					outStr += chr;
				}
				phtml = outStr;
			}
		} catch (e) {
		phtml = "Problem loading content! (" + typeof(phtml) + ":" + phtml + ") <!-- "  + e.toString() + " --> Possibly incorrect " +
		"<a href=\"https://collab.itc.virginia.edu" + wurl + "\" target=\"_blank\">wiki url</a>!<br/>";
	}
	
	var lastOpn = phtml.lastIndexOf("<");
	var lastCls = phtml.lastIndexOf(">");
	if(lastCls < lastOpn) {phtml = phtml.substring(0,lastCls);}
	
	return phtml;
}
    
    function doDropCap(el) {
        var elcnt = Trim(jQuery(el).html());
        var chr1 = elcnt.substr(0,1);
        while (chr1 == "<") {
            el = jQuery(el).children()[0];
            elcnt = Trim(jQuery(el).html());
            chr1 = elcnt.substr(0,1);
        }
        if(chr1 == "") {return;}
        elcnt = '<span class="dropcap">' + chr1 + '</span>' + elcnt.substr(1);
        jQuery(el).html(elcnt);
    }
        
} /* End of Wiki Loader Object */


/* Specs object functions */
function Specs(spcs) {
    this.spcs = spcs;
    this.sarr = spcs.split(' ');
}

Specs.prototype.getSpec = function(sp) {
    for (var n in this.sarr) {
        if(this.sarr[n].indexOf(sp) > -1 ) {
            return this.sarr[n].replace(sp,'');
        }
    }
    return false;
}

Specs.prototype.isSpec = function(sp) {
    for (var n in this.sarr) {
        if(this.sarr[n].indexOf(sp) > -1 ) {
            return true;
        }
    }
    return false;
}

Specs.prototype.opt = function (nm) {
    if(this.getSpec('o')) {
        switch (nm.toLowerCase().replace(' ','-')) {
            case "read-more":
                if(this.getSpec('o').toLowerCase().indexOf('1') > -1) { return true; }
                break;
                
            case "drop-cap":
                if(this.getSpec('o').toLowerCase().indexOf('2') > -1) { return true; }
                break;
                
            case "no-head":
                if(this.getSpec('o').toLowerCase().indexOf('3') > -1) { return true; }
                break;
                
            default :
            
                break;
        }
    }
    return false;
}

var wikiLoader;



//======================= Script:   /js/jquery thdl js ()===========================
// most of the functions on this page and their explanations can be found in fn.js

/* code to run before html content loads */

// system-wide variables (cookies could be consolidated into a single "prefs" cookie or something)

zmode = "testing" ; // "testing" or "production" (should also be set in ../php/fn.php)
zdomain = ( zmode == "testing" ) ? "staging.thlib.org" : "thlib.org" ;
zdomain_short = zdomain.replace(/staging\./ , "" ) ;

cookie_menu = "menus" ;		// name of cookie that holds menu state
// Use pg location for cookie name for this page's accordion settings
cookie_menu = cookie_menu + window.location.pathname;
cookie_menu =  cookie_menu.replace(/\//g,':');
cookie_lang = "lang" ;		// name of cookie that holds language pref
// cookie_tool = "jtooltips" ;	// name of cookie for tooltip prefs - commented out 8-5-08 mark
// cookie_font = "fstyle" ;		// name of cookie for font sheet prefs - commented out 8-5-08 mark
thdl_lang = "eng" ;			// default language for site
accordionBehavior = "one";  // "one" or "many". "one" means that only one menu in the sidenav can show at a time -- all others will automatically collapse

CheckTIDSearch(); // If THL ID param is passed to any page, jump right into a THL ID search, relocating either to resource or not found page. 
				// This works as long as fn.js is loaded before this file.

/* code to be run after the page is fully loaded */
jQuery(document).ready(function() {
    
	ActivateLinks('body');	
	
	AddGoogleSearchScript();
	
	AddTopAnchor();
	
	ConvertExternalLinks() ;
	
	// InitLanguages() ;   - mark 8-5-08
	
	// InitTooltipPrefs() ;  - mark 8-5-08
	
	InitAccordion() ;
			
	// InitStyling() ;  - mark 8-5-08
	
	InitSideColumn() ;
			
	AssimilateCookies() ;
	
	DoExternalContent() ;
	
	InitStripeHover() ;
	
	SetBrowserTitle() ;
	
	EmbedQT() ;
	
	// SlideShowInit() ;  - mark 8-5-08
	
}); 





//======================= Script:   /js/jquery checkbox js ()===========================
jQuery.fn.checkboxToggle = function(opt){

   var check = jQuery(this).next()[0].checked == true;
   jQuery(this)
		   .attr({ src: check ? opt.unchecked : opt.checked })
		   .next()[0].checked = !check;
}

jQuery.fn.checkbox = function(opt){
   jQuery(":checkbox", this)

	   // Hide each native checkbox
	   .hide()

	   // Iterate through checkboxes and do all the magical stuff
	   .each(function (){

		   jQuery("<img>")

			   // Set image attributes
			   .attr({src: this.checked ? opt.checked : opt.unchecked, alt: "" })

			   //
			   .click(function() {
				   jQuery(this).checkboxToggle(opt);
			   })

			   // Attach image
			   .insertBefore(this);
	   });
}

jQuery.fn.cssCheckboxToggle = function(){
   jQuery(this).each(function(){
      var label = jQuery(this);
      label.toggleClass("checked");
      var check = jQuery(":checkbox[@name='"+label.attr("for")+"']")[0];
      check.checked = !check.checked;
   });
}

jQuery.fn.cssCheckboxCheck = function(){
   jQuery(this).each(function(){
      var label = jQuery(this);
      label.addClass("checked");
      var check = jQuery(":checkbox[@name='"+label.attr("for")+"']")[0];
      if(typeof(check) != 'undefined') {check.checked = true;}
   });
}

jQuery.fn.cssCheckboxUncheck = function(){
   jQuery(this).each(function(){
      var label = jQuery(this);
      label.removeClass("checked");
      var check = jQuery(":checkbox[@name='"+label.attr("for")+"']")[0];
      if(typeof(check) != 'undefined') {check.checked = false;}
   });
}

jQuery.fn.cssCheckbox = function(){
   jQuery(":checkbox", this)

	   // Hide native checkboxes
	   .hide()

	   // Find related labels and add all the fancy stuff
	   .each(function(){

		   var check = this;
		   var jlabel = jQuery("label[@for='"+jQuery(check).attr("name")+"']");

		   // Initial state check
		   if (check.checked) {
			   jlabel.addClass("checked");
		   }

		   jlabel

			   // Label hover state
			   .hover(
				   function() { jQuery(this).addClass("over"); },
				   function() { jQuery(this).removeClass("over"); }
			   )

			   // Label click state
			   .click(function(){
				   jQuery(this).cssCheckboxToggle();
			   });
	   });
}




// Where the class "default_checked" is applied to the <label> of the checkboxes you want checked by default.
 jQuery(function(){
    try {
        jQuery(".default-ck").cssCheckboxCheck();
    } catch (e) {}
 });

 /* ---- may drop this mark 2-12-08
// Where the class "default_checked" is applied to the <input> check boxes you want checked by default.
 jQuery(function(){
    jQuery(".default-ck").prev().cssCheckboxCheck({checked: "/global/images/checkbox-on.png", unchecked: "/global/images/checkbox-off.png"});
 });
 */



//======================= Script:   /js/jquery watermarkinput js ()===========================
/*
 * Copyright (c) 2007 Josh Bush (digitalbush.com)
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:

 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE. 
 */
 
/*
 * Version: Beta 1
 * Release: 2007-06-01
 */ 
(function($) {
	var map=new Array();
	jQuery.Watermark = {
		ShowAll:function(){
			for (var i=0, len=map.length;i<len;i++){
				if(map[i].obj.val()==""){
					map[i].obj.val(map[i].text);					
					map[i].obj.css("color",map[i].WatermarkColor);
				}else{
				    map[i].obj.css("color",map[i].DefaultColor);
				}
			}
		},
		HideAll:function(){
			for (var i=0, len=map.length;i<len;i++){
				if(map[i].obj.val()==map[i].text)
					map[i].obj.val("");					
			}
		}
	}
	
	jQuery.fn.Watermark = function(text,color) {
		if(!color)
			color="#aeaeae";
		return this.each(
			function(){		
				var input=jQuery(this);
				var defaultColor=input.css("color");
				map[map.length]={text:text,obj:input,DefaultColor:defaultColor,WatermarkColor:color};
				function clearMessage(){
					if(input.val()==text)
						input.val("");
					input.css("color",defaultColor);
				}

				function insertMessage(){
					if(input.val().length==0 || input.val()==text){
						input.val(text);
						input.css("color",color);	
					}else
						input.css("color",defaultColor);				
				}

				input.focus(clearMessage);
				input.blur(insertMessage);								
				input.change(insertMessage);
				
				insertMessage();
			}
		);
	};
})(jQuery);


//======================= Script:   /js/jquery menus utilities js ()===========================
/*-------------------------------------------------------------------- 
Utility functions
Version: 1.0, 01.18.2008

By: Maggie Costello Wachs (maggie@filamentgroup.com)
	http://www.filamentgroup.com
		
Copyright (c) 2007 Filament Group
Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)

Dependencies:
	jQuery library
--------------------------------------------------------------------*/

function sortBigToSmall(a, b) { return b - a; };

function getScrollTop(){
	return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
};

function getScrollLeft(){
	return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
};

function getWindowHeight(){
	var de = document.documentElement;
	return self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
};

function getWindowWidth(){
	var de = document.documentElement;
	return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
};

// getTotalWidth/Height finds the width/height of an element including padding
jQuery.fn.getTotalWidth = function(){
	return jQuery(this).width() + parseInt(jQuery(this).css('paddingRight')) + parseInt(jQuery(this).css('paddingLeft'));
};

jQuery.fn.getTotalHeight = function(){
	return jQuery(this).height() + parseInt(jQuery(this).css('paddingTop')) + parseInt(jQuery(this).css('paddingBottom'));
};

// assign random ids to a single element or a group of child elements
jQuery.fn.setRandomId = function(settings){
	var settings = jQuery.extend({
		children: null, // selectors for child elements (acts only on the caller element by default)
		attribute: null // attribute, if not id (default)
	}, settings);
	
	var thisAttr = settings.attribute || 'id';
		
	var setId = function(el){
		var newId = 'id_' + Math.floor(Math.random()*9999);
		el.attr(thisAttr, newId);
	};
	
	if (settings.children) {
		jQuery(this).find(settings.children).each(setId(jQuery(this)));
	}
	else { setId(jQuery(this)); }
	
	return jQuery(this);
};

// Test to see if this element will fit in the viewport
/* Parameters:
	@el = element to position, required
	@leftOffset / @topOffset = optional parameter if the offset cannot be calculated (i.e., if the object is in the DOM but is set to display: 'none')
*/
function fitHorizontal(el, leftOffset){
	var leftVal = parseInt(leftOffset) || jQuery(el).offset().left;
	return (leftVal + jQuery(el).width() <= getWindowWidth() + getScrollLeft() && leftVal - getScrollLeft() >= 0);
};

function fitVertical(el, topOffset){
	var topVal = parseInt(topOffset) || jQuery(el).offset().top;
	return (topVal + jQuery(el).height() <= getWindowHeight() + getScrollTop() && topVal - getScrollTop() >= 0);
};


//======================= Script:   /js/jquery menus js ()===========================
/*-------------------------------------------------------------------- 
Scripts for creating and manipulating custom menus based on standard <ul> markup
Version: 1.0, 01.18.2008

By: Maggie Costello Wachs (maggie@filamentgroup.com) and Scott Jehl (scott@filamentgroup.com)
	http://www.filamentgroup.com
	* reference article: http://www.filamentgroup.com/lab/jquery_ipod_style_drilldown_menu/
		
Copyright (c) 2008 Filament Group
Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)

Dependencies:
	jQuery library
	position.jQuery.js
	utilities.js
--------------------------------------------------------------------*/

/* Parameters: 
@settings: see notes below
@positionOpts: // the orientation of the menu relative to the link that calls it
	posX: 'left', 
	posY: 'bottom',
	offsetX: 0,
	offsetY: 0,
	directionH: 'right',
	directionV: 'down', 
	detectH: true, // do horizontal collision detection
	detectV: true, // do vertical collision detection
	linkToFront: false // make the caller link appear over the menu (visual effect)
*/

function Menu(caller, settings) {
	var settings = jQuery.extend({
		content: null, // markup string to be inserted into the menu
		positionOpts: {offsetY: 5}, // see alternate options above -- must be passed in object notation, i.e., { offsetX: 10 }
		width: 216, // width of menu container
		maxHeight: 200, // max height of menu (if a drilldown: height does not include breadcrumb)
		showSpeed: 500, // show/hide speed in milliseconds
		callerOnState: 'btnMenuOn', // class to change the appearance of the link when the menu is showing
		itemHover: 'hover', // class for menu option hover state
		altClasses: null, // any additional classes for the menu container, separated by spaces
		crossSpeed: 200, // cross-fade speed for multi-level menus
		selectCategories: false, // false = selecting a category will navigate you to the next level until you reach a leaf node; true = each category is an accepted value in addition to leaf node
		nextMenuLink: 'nextLevel', // class to identify the link used in the multi-level menu to show the next level -- include the preceding "."
		topLinkText: 'All'
	}, settings);
	
	var menuLink = jQuery(caller);
	var menu = jQuery('<div class="menuContainer">'+settings.content+'</div>');
	var menuOpen = false;
	
	if (settings.selectCategories) {
		menu.find('li:has(ul)').each(function(){
			jQuery(this).find('a:first').after('<a href="#" class="'+settings.nextMenuLink+'">View next level &gt;</a>');
		});
	};
	
	this.create = function(){		
		if (settings.content) {
		
			menu.css({
				position: 'absolute', 
				top: 0, 
				left: '-9999px'
			});
			
			if (settings.altClasses) { menu.addClass(settings.altClasses); };
			if (menuLink.width() > menu.width()) { menu.css({ width: menuLink.width() }); };
			
			menu.appendTo('body').setRandomId({ attribute: 'menuid' }).css({ width: settings.width }).find('ul:first').addClass('menu').css({ position: 'relative' });
			
			// close all open menus			
			jQuery('*[menuid]').parent().trigger('click');					
						
			if (settings.callerOnState) { menuLink.addClass(settings.callerOnState); };
			
			// if there are multiple levels, create a drilldown menu
			if (menu.children('ul').size() > 0) { this.drilldown(menu, settings); };			
			
			menu.positionObject(menuLink, settings.positionOpts).hide().slideDown(settings.showSpeed).find('.menu:eq(0)').css({ visibility: 'visible' });
			
			menuOpen = true;		
			
			// assign events to menu & child items
			menu.parent().click(this.kill);
			jQuery(document).click(this.kill);
			
			if (settings.itemHover) {
				menu.find('li').hover(
					function(){
						jQuery(this).siblings().removeClass(settings.itemHover);
						jQuery(this).addClass(settings.itemHover);
					},
					function(){ jQuery(this).removeClass(settings.itemHover); }
				);
			};	// end if (settings.itemHover) 
			
			//click events when categories are accepted values
			var that = this;
			if (settings.selectCategories) {				
				jQuery('.ddMenu li a').not('.'+settings.nextMenuLink).click(function(){
					alert('You chose '+jQuery(this).text());
					that.kill();
					return false;
					//other actions could go here
				});
			}
			else {
				jQuery('.ddMenu li a').not('.menuIndicator').click(function(){
					alert('You chose '+jQuery(this).text());
					that.kill();
					return false;
					//other actions could go here
				});
			};			
			
		}; // end if (settings.content) 
	}; // end this.create()
	
	this.kill = function(){
		menu.parent().remove();
		if (menuLink.is('.'+settings.callerOnState)) { menuLink.removeClass(settings.callerOnState); };
		menuOpen = false;
	};
	
	return this;	
};


Menu.prototype.drilldown = function(menu, settings) {
	var breadcrumb = jQuery('<ul class="ddBreadcrumb clearfix" style="display: none;"></ul>');
	var ddmenu = jQuery('<div class="ddMenu"></div>');
	
	menu.css({ overflow: 'hidden' }).children().eq(0).wrap(ddmenu);
	menu.prepend(breadcrumb);
	
	var listHeights = [];
	menu.find('.ddMenu').find('ul').each(function(i){
	 	listHeights[i] = jQuery(this).height();	 
	 });
	listHeights.sort(sortBigToSmall);
	menu.find('.ddMenu').find('ul').css({ height: listHeights[0] });
	
	// apply scrollbar to the menu if it exceeds max height
	if (listHeights[0] > settings.maxHeight) {
		menu.find('.ddMenu').addClass('scrollNeeded').css({ height: settings.maxHeight, overflow: 'auto', 'overflow-x': 'hidden' }).find('ul').css({ width: (settings.width-15).pxToEm()});
	}
	else {
		menu.find('.ddMenu').css({ height: listHeights[0] }).find('ul').css({ width: settings.width });
	};
	
	menu.find('.ddMenu li a').each(function(){
		if (!jQuery(this).next().is('.'+settings.nextMenuLink)) {
			jQuery(this).addClass('singleLink');
		};
	});
	
	var showNextLevel = function(el) {
		var thisLink = jQuery(el);
		var thisList = jQuery(el).parents('ul:eq(0)');
		var nextList = jQuery(el).next();
		var thisListId = thisList.attr('id');
		
		//add all categories link
		if (breadcrumb.find('li').size()<1){
			var allCrumb = jQuery('<li class="all"><a href="#">'+settings.topLinkText+'</a></li>');
			allCrumb.click(function(){
				menu.find('ul').not('ul.menu, .ddBreadcrumb').css({ visibility: 'hidden' });
				breadcrumb.empty().hide();
				return false;		
			});
			breadcrumb.append(allCrumb);
		};		
		
		var addNewCrumb = function() {
			var crumbText;
			if (thisLink.prev().is('a')) { crumbText = thisLink.prev().html(); }
			else { crumbText = thisLink.html(); };
		
			var newCrumb = jQuery('<li class="currentCrumb" style="display: none;"><a href="javascript://" class="crumb">'+crumbText+'</a></li>');
			jQuery('.currentCrumb').removeClass('currentCrumb');
			breadcrumb.append(newCrumb);
			newCrumb.show();

			newCrumb.find('a').click(function(){
				if(jQuery(this).parent().is('.currentCrumb')){
					alert('You chose '+jQuery(this).text());
					//jQuery('.menuBtn').children(':last').text(jQuery(this).text());
					menu.kill();
					//other actions could go here
					return false;
				}
				else {
					nextList.find('ul').css({ visibility: 'hidden' });									
					jQuery(this).parent().nextAll().css({ visibility: 'hidden' }).slideUp(settings.crossSpeed, function(){jQuery(this).remove();});
					jQuery(this).parent().addClass('currentCrumb');
					return false;
				}
			});
		};
		
		// if the breadcrumb container is hidden, show it and add the first crumb
		if (breadcrumb.css('display') == 'none') {
			breadcrumb.slideDown();
			addNewCrumb();
		}
		else { addNewCrumb(); };
		
		// show the next list
		nextList.css({
			visibility: 'visible',
			left: settings.width
		}).animate({ left: 0 }, settings.crossSpeed);
	};
	// end showNextLevel
	
	// when category links are not selectable (only link to next level)
	if (!settings.selectCategories) {
		menu.find('.ddMenu li a').each(function(){
			if (jQuery(this).next().is('ul')) { 
				jQuery(this).addClass('menuIndicator').click(function(){
					showNextLevel(this);
					return false;
				});
			};
		});
	};	
	
	menu.find('.'+settings.nextMenuLink).click(function(){
		showNextLevel(this);
		return false;
	});		
};


//======================= Script:   /js/jquery position js ()===========================
/*-------------------------------------------------------------------- 
Scripts for positioning overlaid components: menus, tooltips, overlays, loading indicators, etc.
Version: 1.0, 01.18.2008

By: Maggie Costello Wachs (maggie@filamentgroup.com)
	http://www.filamentgroup.com
		
Copyright (c) 2007 Filament Group
Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)

Dependencies:
	jQuery library
	utilities.js
	
Requirements:
	- the object is absolutely positioned with CSS
	
Parameters (defaults noted with * where applicable):
	@referrer = the link (or other element) used to show the overlaid object 
	@settings = can override four of the Position defaults:
		- posX/Y: where the top left corner of the object should be positioned in relation to its referrer.
				X: left*, center, right
				Y: top, center, bottom*
		- offsetX/Y: the number of pixels to be offset from the x or y position.  Can be a positive or negative number.
		- directionH/V: where the entire menu should appear in relation to its referrer.
				Horizontal: left*, right
				Vertical: up, down*
		- detectH/V: detect the viewport horizontally / vertically
		- linkToFront: copy the menu link and place it on top of the menu (visual effect)
--------------------------------------------------------------------*/

jQuery.fn.positionObject = function(referrer, settings) { 
	var settings = jQuery.extend({
		posX: 'left', 
		posY: 'bottom',
		offsetX: 0,
		offsetY: 0,
		directionH: 'right',
		directionV: 'down', 
		detectH: true, // do horizontal collision detection  
		detectV: true, // do vertical collision detection
		linkToFront: false
	}, settings);

	var el = jQuery(this);
	var referrer = referrer;
	var dims = {
		elW: el.width(),
		elH: el.height(),
		refX: referrer.offset().left,
		refY: referrer.offset().top,
		refW: referrer.getTotalWidth(),
		refH: referrer.getTotalHeight()
	};	
	var xVal, yVal;
	
	el.insertPositionHelper(dims);
	
	// get X pos
	switch(settings.posX) {
		case 'left': 	xVal = 0; 
			break;				
		case 'center': xVal = dims.refW / 2;
			break;				
		case 'right': xVal = dims.refW;
			break;
	};
	
	// get Y pos
	switch(settings.posY) {
		case 'top': 	yVal = 0;
			break;				
		case 'center': yVal = dims.refH / 2;
			break;				
		case 'bottom': yVal = dims.refH;
			break;
	};
	
	// add the offsets (zero by default)
	xVal += settings.offsetX;
	yVal += settings.offsetY;
	
	// position the object vertically
	if (settings.directionV == 'up') {
		el.css({ top: 'auto', bottom: yVal });
		if (settings.detectV && !fitVertical(el)) {
			el.css({ bottom: 'auto', top: yVal });
		}
	} 
	else {
		el.css({ bottom: 'auto', top: yVal });
		if (settings.detectV && !fitVertical(el)) {
			el.css({ top: 'auto', bottom: yVal });
		}
	};
	
	// and horizontally
	if (settings.directionH == 'left') {
		el.css({ left: 'auto', right: xVal });
		if (settings.detectH && !fitHorizontal(el)) {
			el.css({ right: 'auto', left: xVal });
		}
	} 
	else {
		el.css({ right: 'auto', left: xVal });
		if (settings.detectH && !fitHorizontal(el)) {
			el.css({ left: 'auto', right: xVal });
		}
	};
	
	// if specified, clone the referring element and position it so that it appears on top of the menu
	if (settings.linkToFront) {
		referrer.clone().addClass('linkClone').css({
			position: 'absolute', 
			top: 0, 
			right: 'auto', 
			bottom: 'auto', 
			left: 0, 
			width: referrer.width(), 
			height: referrer.height()
		}).insertAfter(el);
	};

	return jQuery(this);
};

jQuery.fn.insertPositionHelper = function(dims) {
	var el = jQuery(this);
	var dims = dims;
	var helper = jQuery('<div class="positionHelper"></div>');
	helper.css({ left: dims.refX, top: dims.refY, width: dims.refW, height: dims.refH });
	el.wrap(helper);
	return jQuery(this);
};


//======================= Script:   /js/jquery toXML js ()===========================
/* JQuery plug-in by Mark Gibson to serialize an element into an XML string, used to get outerHTML of an element
	found at http://dev.jquery.com/wiki/Plugins/toXML and added by ndg on 11/11/08

	Syntax:  var xmlString = jQuery('#something').toXML();

	 Note: Doesn't work in IE(6)  

jQuery.fn.toXML = function () {
    var out = '';
    if (this.length > 0) {
        if (typeof XMLSerializer == 'function' ||
            typeof XMLSerializer == 'object')
        {
            var xs = new XMLSerializer();
            this.each(function() {
                out += xs.serializeToString(this);
            });
        } else if (this[0].xml !== undefined) {
            this.each(function() {
                out += this.xml;
            });
        } else {
            // TODO: Manually serialize DOM here,
            // for browsers that support neither
            // of two methods above.
        }
    }
    return out;
};
*/

jQuery.fn.toXML = function () 
{
	var toXML = function(node)
	{
		var out = '';
		var attributes = '';
		var content = '';
		
		out += '<' + node.nodeName;
		if (node.childNodes)
		{
			for (var i = 0; i < node.childNodes.length; i++)
			{
				switch(node.childNodes[i].nodeType)
				{
					case 1:     // ELEMENT_NODE
						content += toXML(node.childNodes[i]);
						break;
					case 2:     // ATTRIBUTE_NODE
						attributes += ' ' + node.childNodes[i].nodeName  + '="' 
							      + node.childNodes[i].nodeValue + '"';
						break;
					case 3:     // TEXT_NODE
					case 4:     // CDATA_SECTION_NODE
					case 5:     // ENTITY_REFERENCE_NODE
					case 6:     // ENTITY_NODE
					case 7:     // PROCESSING_INSTRUCTION_NODE
					case 8:     // COMMENT_NODE
					case 9:     // DOCUMENT_NODE
					case 10:    // DOCUMENT_TYPE_NODE
					case 11:    // DOCUMENT_FRAGMENT_NODE
					case 12:    // NOTATION_NODE
						content += node.childNodes[i].nodeValue;
						break;
				}
			}
		}
		out += attributes;
		
		if (content.length > 0)
		{
			out += '>' + content;
			out += '</' + node.tagName + '>';
		}
		else
		{
			out += '/>';
		}
		
		return out;
	}
	
	var out = '';
	if (this.length > 0) {
		if (typeof XMLSerializer == 'function' ||
		typeof XMLSerializer == 'object')
		{
			var xs = new XMLSerializer();
			this.each(function() { out += xs.serializeToString(this); });
		} 
		else if (this[0].xml !== undefined) 
		{
			this.each(function() { out += this.xml; });
		}
		else 
		{
			if (this.length > 0)
			{
				this.each( function() { out += toXML(this); } );
			}
		}
	}
	return out;
};


//======================= Script:   /js/jquery ui core tabs packed js ()===========================
;(function($){jQuery.ui={plugin:{add:function(module,option,set){var proto=jQuery.ui[module].prototype;for(var i in set){proto.plugins[i]=proto.plugins[i]||[];proto.plugins[i].push([option,set[i]]);}},call:function(instance,name,args){var set=instance.plugins[name];if(!set){return;}
for(var i=0;i<set.length;i++){if(instance.options[set[i][0]]){set[i][1].apply(instance.element,args);}}}},cssCache:{},css:function(name){if(jQuery.ui.cssCache[name]){return jQuery.ui.cssCache[name];}
var tmp=jQuery('<div class="ui-gen">').addClass(name).css({position:'absolute',top:'-5000px',left:'-5000px',display:'block'}).appendTo('body');jQuery.ui.cssCache[name]=!!((!(/auto|default/).test(tmp.css('cursor'))||(/^[1-9]/).test(tmp.css('height'))||(/^[1-9]/).test(tmp.css('width'))||!(/none/).test(tmp.css('backgroundImage'))||!(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor'))));try{jQuery('body').get(0).removeChild(tmp.get(0));}catch(e){}
return jQuery.ui.cssCache[name];},disableSelection:function(el){jQuery(el).attr('unselectable','on').css('MozUserSelect','none');},enableSelection:function(el){jQuery(el).attr('unselectable','off').css('MozUserSelect','');},hasScroll:function(e,a){var scroll=/top/.test(a||"top")?'scrollTop':'scrollLeft',has=false;if(e[scroll]>0)return true;e[scroll]=1;has=e[scroll]>0?true:false;e[scroll]=0;return has;}};var _remove=jQuery.fn.remove;jQuery.fn.remove=function(){jQuery("*",this).add(this).triggerHandler("remove");return _remove.apply(this,arguments);};function getter(namespace,plugin,method){var methods=$[namespace][plugin].getter||[];methods=(typeof methods=="string"?methods.split(/,?\s+/):methods);return(jQuery.inArray(method,methods)!=-1);}
jQuery.widget=function(name,prototype){var namespace=name.split(".")[0];name=name.split(".")[1];jQuery.fn[name]=function(options){var isMethodCall=(typeof options=='string'),args=Array.prototype.slice.call(arguments,1);if(isMethodCall&&getter(namespace,name,options)){var instance=jQuery.data(this[0],name);return(instance?instance[options].apply(instance,args):undefined);}
return this.each(function(){var instance=jQuery.data(this,name);if(isMethodCall&&instance&&jQuery.isFunction(instance[options])){instance[options].apply(instance,args);}else if(!isMethodCall){jQuery.data(this,name,new $[namespace][name](this,options));}});};$[namespace][name]=function(element,options){var self=this;this.widgetName=name;this.widgetBaseClass=namespace+'-'+name;this.options=jQuery.extend({},jQuery.widget.defaults,$[namespace][name].defaults,options);this.element=jQuery(element).bind('setData.'+name,function(e,key,value){return self.setData(key,value);}).bind('getData.'+name,function(e,key){return self.getData(key);}).bind('remove',function(){return self.destroy();});this.init();};$[namespace][name].prototype=jQuery.extend({},jQuery.widget.prototype,prototype);};jQuery.widget.prototype={init:function(){},destroy:function(){this.element.removeData(this.widgetName);},getData:function(key){return this.options[key];},setData:function(key,value){this.options[key]=value;if(key=='disabled'){this.element[value?'addClass':'removeClass'](this.widgetBaseClass+'-disabled');}},enable:function(){this.setData('disabled',false);},disable:function(){this.setData('disabled',true);}};jQuery.widget.defaults={disabled:false};jQuery.ui.mouse={mouseInit:function(){var self=this;this.element.bind('mousedown.'+this.widgetName,function(e){return self.mouseDown(e);});if(jQuery.browser.msie){this._mouseUnselectable=this.element.attr('unselectable');this.element.attr('unselectable','on');}
this.started=false;},mouseDestroy:function(){this.element.unbind('.'+this.widgetName);(jQuery.browser.msie&&this.element.attr('unselectable',this._mouseUnselectable));},mouseDown:function(e){(this._mouseStarted&&this.mouseUp(e));this._mouseDownEvent=e;var self=this,btnIsLeft=(e.which==1),elIsCancel=(typeof this.options.cancel=="string"?jQuery(e.target).parents().add(e.target).filter(this.options.cancel).length:false);if(!btnIsLeft||elIsCancel||!this.mouseCapture(e)){return true;}
this._mouseDelayMet=!this.options.delay;if(!this._mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){self._mouseDelayMet=true;},this.options.delay);}
if(this.mouseDistanceMet(e)&&this.mouseDelayMet(e)){this._mouseStarted=(this.mouseStart(e)!==false);if(!this._mouseStarted){e.preventDefault();return true;}}
this._mouseMoveDelegate=function(e){return self.mouseMove(e);};this._mouseUpDelegate=function(e){return self.mouseUp(e);};jQuery(document).bind('mousemove.'+this.widgetName,this._mouseMoveDelegate).bind('mouseup.'+this.widgetName,this._mouseUpDelegate);return false;},mouseMove:function(e){if(jQuery.browser.msie&&!e.button){return this.mouseUp(e);}
if(this._mouseStarted){this.mouseDrag(e);return false;}
if(this.mouseDistanceMet(e)&&this.mouseDelayMet(e)){this._mouseStarted=(this.mouseStart(this._mouseDownEvent,e)!==false);(this._mouseStarted?this.mouseDrag(e):this.mouseUp(e));}
return!this._mouseStarted;},mouseUp:function(e){jQuery(document).unbind('mousemove.'+this.widgetName,this._mouseMoveDelegate).unbind('mouseup.'+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this.mouseStop(e);}
return false;},mouseDistanceMet:function(e){return(Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance);},mouseDelayMet:function(e){return this._mouseDelayMet;},mouseStart:function(e){},mouseDrag:function(e){},mouseStop:function(e){},mouseCapture:function(e){return true;}};jQuery.ui.mouse.defaults={cancel:null,distance:1,delay:0};})(jQuery);(function($){jQuery.widget("ui.tabs",{init:function(){this.options.event+='.tabs';this.tabify(true);},setData:function(key,value){if((/^selected/).test(key))
this.select(value);else{this.options[key]=value;this.tabify();}},length:function(){return this.$tabs.length;},tabId:function(a){return a.title&&a.title.replace(/\s/g,'_').replace(/[^A-Za-z0-9\-_:\.]/g,'')||this.options.idPrefix+jQuery.data(a);},ui:function(tab,panel){return{options:this.options,tab:tab,panel:panel,index:this.$tabs.index(tab)};},tabify:function(init){this.$lis=jQuery('li:has(a[href])',this.element);this.$tabs=this.$lis.map(function(){return jQuery('a',this)[0];});this.$panels=jQuery([]);var self=this,o=this.options;this.$tabs.each(function(i,a){if(a.hash&&a.hash.replace('#',''))
self.$panels=self.$panels.add(a.hash);else if(jQuery(a).attr('href')!='#'){jQuery.data(a,'href.tabs',a.href);jQuery.data(a,'load.tabs',a.href);var id=self.tabId(a);a.href='#'+id;var $panel=jQuery('#'+id);if(!$panel.length){$panel=jQuery(o.panelTemplate).attr('id',id).addClass(o.panelClass).insertAfter(self.$panels[i-1]||self.element);$panel.data('destroy.tabs',true);}
self.$panels=self.$panels.add($panel);}
else
o.disabled.push(i+1);});if(init){this.element.addClass(o.navClass);this.$panels.each(function(){var $this=jQuery(this);$this.addClass(o.panelClass);});if(o.selected===undefined){if(location.hash){this.$tabs.each(function(i,a){if(a.hash==location.hash){o.selected=i;if(jQuery.browser.msie||jQuery.browser.opera){var $toShow=jQuery(location.hash),toShowId=$toShow.attr('id');$toShow.attr('id','');setTimeout(function(){$toShow.attr('id',toShowId);},500);}
scrollTo(0,0);return false;}});}
else if(o.cookie){var index=parseInt(jQuery.cookie('ui-tabs'+jQuery.data(self.element)),10);if(index&&self.$tabs[index])
o.selected=index;}
else if(self.$lis.filter('.'+o.selectedClass).length)
o.selected=self.$lis.index(self.$lis.filter('.'+o.selectedClass)[0]);}
o.selected=o.selected===null||o.selected!==undefined?o.selected:0;o.disabled=jQuery.unique(o.disabled.concat(jQuery.map(this.$lis.filter('.'+o.disabledClass),function(n,i){return self.$lis.index(n);}))).sort();if(jQuery.inArray(o.selected,o.disabled)!=-1)
o.disabled.splice(jQuery.inArray(o.selected,o.disabled),1);this.$panels.addClass(o.hideClass);this.$lis.removeClass(o.selectedClass);if(o.selected!==null){this.$panels.eq(o.selected).show().removeClass(o.hideClass);this.$lis.eq(o.selected).addClass(o.selectedClass);var onShow=function(){jQuery(self.element).triggerHandler('tabsshow',[self.fakeEvent('tabsshow'),self.ui(self.$tabs[o.selected],self.$panels[o.selected])],o.show);};if(jQuery.data(this.$tabs[o.selected],'load.tabs'))
this.load(o.selected,onShow);else
onShow();}
jQuery(window).bind('unload',function(){self.$tabs.unbind('.tabs');self.$lis=self.$tabs=self.$panels=null;});}
for(var i=0,li;li=this.$lis[i];i++)
jQuery(li)[jQuery.inArray(i,o.disabled)!=-1&&!jQuery(li).hasClass(o.selectedClass)?'addClass':'removeClass'](o.disabledClass);if(o.cache===false)
this.$tabs.removeData('cache.tabs');var hideFx,showFx,baseFx={'min-width':0,duration:1},baseDuration='normal';if(o.fx&&o.fx.constructor==Array)
hideFx=o.fx[0]||baseFx,showFx=o.fx[1]||baseFx;else
hideFx=showFx=o.fx||baseFx;var resetCSS={display:'',overflow:'',height:''};if(!jQuery.browser.msie)
resetCSS.opacity='';function hideTab(clicked,$hide,$show){$hide.animate(hideFx,hideFx.duration||baseDuration,function(){$hide.addClass(o.hideClass).css(resetCSS);if(jQuery.browser.msie&&hideFx.opacity)
$hide[0].style.filter='';if($show)
showTab(clicked,$show,$hide);});}
function showTab(clicked,$show,$hide){if(showFx===baseFx)
$show.css('display','block');$show.animate(showFx,showFx.duration||baseDuration,function(){$show.removeClass(o.hideClass).css(resetCSS);if(jQuery.browser.msie&&showFx.opacity)
$show[0].style.filter='';jQuery(self.element).triggerHandler('tabsshow',[self.fakeEvent('tabsshow'),self.ui(clicked,$show[0])],o.show);});}
function switchTab(clicked,$li,$hide,$show){$li.addClass(o.selectedClass).siblings().removeClass(o.selectedClass);hideTab(clicked,$hide,$show);}
this.$tabs.unbind('.tabs').bind(o.event,function(){var $li=jQuery(this).parents('li:eq(0)'),$hide=self.$panels.filter(':visible'),$show=jQuery(this.hash);if(($li.hasClass(o.selectedClass)&&!o.unselect)||$li.hasClass(o.disabledClass)||jQuery(this).hasClass(o.loadingClass)||jQuery(self.element).triggerHandler('tabsselect',[self.fakeEvent('tabsselect'),self.ui(this,$show[0])],o.select)===false){this.blur();return false;}
self.options.selected=self.$tabs.index(this);if(o.unselect){if($li.hasClass(o.selectedClass)){self.options.selected=null;$li.removeClass(o.selectedClass);self.$panels.stop();hideTab(this,$hide);this.blur();return false;}else if(!$hide.length){self.$panels.stop();var a=this;self.load(self.$tabs.index(this),function(){$li.addClass(o.selectedClass).addClass(o.unselectClass);showTab(a,$show);});this.blur();return false;}}
if(o.cookie)
jQuery.cookie('ui-tabs'+jQuery.data(self.element),self.options.selected,o.cookie);self.$panels.stop();if($show.length){var a=this;self.load(self.$tabs.index(this),$hide.length?function(){switchTab(a,$li,$hide,$show);}:function(){$li.addClass(o.selectedClass);showTab(a,$show);});}else
throw'jQuery UI Tabs: Mismatching fragment identifier.';if(jQuery.browser.msie)
this.blur();return false;});if(!(/^click/).test(o.event))
this.$tabs.bind('click.tabs',function(){return false;});},add:function(url,label,index){if(index==undefined)
index=this.$tabs.length;var o=this.options;var $li=jQuery(o.tabTemplate.replace(/#\{href\}/g,url).replace(/#\{label\}/g,label));$li.data('destroy.tabs',true);var id=url.indexOf('#')==0?url.replace('#',''):this.tabId(jQuery('a:first-child',$li)[0]);var $panel=jQuery('#'+id);if(!$panel.length){$panel=jQuery(o.panelTemplate).attr('id',id).addClass(o.hideClass).data('destroy.tabs',true);}
$panel.addClass(o.panelClass);if(index>=this.$lis.length){$li.appendTo(this.element);$panel.appendTo(this.element[0].parentNode);}else{$li.insertBefore(this.$lis[index]);$panel.insertBefore(this.$panels[index]);}
o.disabled=jQuery.map(o.disabled,function(n,i){return n>=index?++n:n});this.tabify();if(this.$tabs.length==1){$li.addClass(o.selectedClass);$panel.removeClass(o.hideClass);var href=jQuery.data(this.$tabs[0],'load.tabs');if(href)
this.load(index,href);}
this.element.triggerHandler('tabsadd',[this.fakeEvent('tabsadd'),this.ui(this.$tabs[index],this.$panels[index])],o.add);},remove:function(index){var o=this.options,$li=this.$lis.eq(index).remove(),$panel=this.$panels.eq(index).remove();if($li.hasClass(o.selectedClass)&&this.$tabs.length>1)
this.select(index+(index+1<this.$tabs.length?1:-1));o.disabled=jQuery.map(jQuery.grep(o.disabled,function(n,i){return n!=index;}),function(n,i){return n>=index?--n:n});this.tabify();this.element.triggerHandler('tabsremove',[this.fakeEvent('tabsremove'),this.ui($li.find('a')[0],$panel[0])],o.remove);},enable:function(index){var o=this.options;if(jQuery.inArray(index,o.disabled)==-1)
return;var $li=this.$lis.eq(index).removeClass(o.disabledClass);if(jQuery.browser.safari){$li.css('display','inline-block');setTimeout(function(){$li.css('display','block');},0);}
o.disabled=jQuery.grep(o.disabled,function(n,i){return n!=index;});this.element.triggerHandler('tabsenable',[this.fakeEvent('tabsenable'),this.ui(this.$tabs[index],this.$panels[index])],o.enable);},disable:function(index){var self=this,o=this.options;if(index!=o.selected){this.$lis.eq(index).addClass(o.disabledClass);o.disabled.push(index);o.disabled.sort();this.element.triggerHandler('tabsdisable',[this.fakeEvent('tabsdisable'),this.ui(this.$tabs[index],this.$panels[index])],o.disable);}},select:function(index){if(typeof index=='string')
index=this.$tabs.index(this.$tabs.filter('[href$='+index+']')[0]);this.$tabs.eq(index).trigger(this.options.event);},load:function(index,callback){var self=this,o=this.options,$a=this.$tabs.eq(index),a=$a[0],bypassCache=callback==undefined||callback===false,url=$a.data('load.tabs');callback=callback||function(){};if(!url||!bypassCache&&jQuery.data(a,'cache.tabs')){callback();return;}
var inner=function(parent){var $parent=jQuery(parent),$inner=$parent.find('*:last');return $inner.length&&$inner.is(':not(img)')&&$inner||$parent;};var cleanup=function(){self.$tabs.filter('.'+o.loadingClass).removeClass(o.loadingClass).each(function(){if(o.spinner)
inner(this).parent().html(inner(this).data('label.tabs'));});self.xhr=null;};if(o.spinner){var label=inner(a).html();inner(a).wrapInner('<em></em>').find('em').data('label.tabs',label).html(o.spinner);}
var ajaxOptions=jQuery.extend({},o.ajaxOptions,{url:url,success:function(r,s){jQuery(a.hash).html(r);cleanup();if(o.cache)
jQuery.data(a,'cache.tabs',true);jQuery(self.element).triggerHandler('tabsload',[self.fakeEvent('tabsload'),self.ui(self.$tabs[index],self.$panels[index])],o.load);o.ajaxOptions.success&&o.ajaxOptions.success(r,s);callback();}});if(this.xhr){this.xhr.abort();cleanup();}
$a.addClass(o.loadingClass);setTimeout(function(){self.xhr=jQuery.ajax(ajaxOptions);},0);},url:function(index,url){this.$tabs.eq(index).removeData('cache.tabs').data('load.tabs',url);},destroy:function(){var o=this.options;this.element.unbind('.tabs').removeClass(o.navClass).removeData('tabs');this.$tabs.each(function(){var href=jQuery.data(this,'href.tabs');if(href)
this.href=href;var $this=jQuery(this).unbind('.tabs');jQuery.each(['href','load','cache'],function(i,prefix){$this.removeData(prefix+'.tabs');});});this.$lis.add(this.$panels).each(function(){if(jQuery.data(this,'destroy.tabs'))
jQuery(this).remove();else
jQuery(this).removeClass([o.selectedClass,o.unselectClass,o.disabledClass,o.panelClass,o.hideClass].join(' '));});},fakeEvent:function(type){return jQuery.event.fix({type:type,target:this.element[0]});}});jQuery.ui.tabs.defaults={unselect:false,event:'click',disabled:[],cookie:null,spinner:'Loading&#8230;',cache:false,idPrefix:'ui-tabs-',ajaxOptions:{},fx:null,tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>',panelTemplate:'<div></div>',navClass:'ui-tabs-nav',selectedClass:'ui-tabs-selected',unselectClass:'ui-tabs-unselect',disabledClass:'ui-tabs-disabled',panelClass:'ui-tabs-panel',hideClass:'ui-tabs-hide',loadingClass:'ui-tabs-loading'};jQuery.ui.tabs.getter="length";jQuery.extend(jQuery.ui.tabs.prototype,{rotation:null,rotate:function(ms,continuing){continuing=continuing||false;var self=this,t=this.options.selected;function start(){self.rotation=setInterval(function(){t=++t<self.$tabs.length?t:0;self.select(t);},ms);}
function stop(e){if(!e||e.clientX){clearInterval(self.rotation);}}
if(ms){start();if(!continuing)
this.$tabs.bind(this.options.event,stop);else
this.$tabs.bind(this.options.event,function(){stop();t=self.options.selected;start();});}
else{stop();this.$tabs.unbind(this.options.event,stop);}}});})(jQuery);


//======================= Script:   /js/app_plug js ()===========================
	
/*
	6/18/08: jev3a@virginia.edu
	
	This is for adding thl applications in an iframe. It is called by setting an a href to:
	 	
		#iframe=url&div_id=<div id>&css_url=<css url>
	
	@param	url		required	the url that should be the source of the iframe
	@param	div_id	optional	the id of the div or other element that should be emptied and replaced with the iframe
								defaults to the div_id set in thlplug below
	@param	css_url	optional	the absolute url of the stylesheet to use with the iframed document 
								defaults to the first stylesheet of the parent page
								you can also set a default stylesheet below in the css_url proprety of thlplug
	
	Example: <a href="#iframe=http://staging.tmb.thlib.org/categories/119/children&div_id=content"></a>
	
	Dependencies: 1) jquery; 2) For history management, it depends on class_external.js; 3) there are some obliquely relevant functions in fn.js
	
	TODO: break off functions from class_external.js and add them here, so that there is minimal code there
*/

	//var env_tmb = env_mms = 'http://localhost:3000' ;
	var env_tmb = 'http://staging.tmb.thlib.org' ;
	var env_mms = 'http://staging.mms.thlib.org' ;
	
	jQuery(document).ready(function() {
		ActivateAppLinks.init() ;
		GetCSS() ;	// grab stylesheet from parent document as default; has to be here because needs both doc and thlplug to have loaded
	}) ;

	var ActivateAppLinks = {
		
		EnableKillers: function() { //this is to kill cookies associated with apps in iframes.		
			var apps = new Array( 
				"http://staging.tmb.thlib.org" ,
				"http://tmb.thlib.org" ,
				"http://staging.mms.thlib.org" ,
				"http://mms.thlib.org"
			);
	
			var i = apps.length - 1 ; do {
				arg = "body a[href^=" + apps[i] + "]" ;
				/* jQuery( arg ).click( function() {
					KillFrameCookies( jQuery( arg ) ) ; //handle issue for same domain, if cookie names are known
				}) */
		
				//for different domains, send cookie destroy message
				link = jQuery( arg ).attr("href") ;
				jQuery( arg ).attr("href" , link + "?frame=destroy" ) ; //TODO: look for query string first and append arg if found
			} while ( i-- ) ;
			
		} ,
		
		EnableIframeLinks: function() { // this activates all links that start with #iframe		
			jQuery( "a[href*=#iframe]" ).click(function() {				
				thlplug.swap( this.href ) ;
			})			
		} ,
		
		init: function() {
			this.EnableKillers() ;
			this.EnableIframeLinks() ;
		}
		
	} ;
	
	function GetCSS() {
		var link_href = jQuery( "link[rel^=stylesheet]" ).attr("href") ;
		jQuery('body').append('<div style=\'display:none\'>' + link_href + '</div>');
		var new_href = '' ;
		if ( link_href.indexOf('http://') == -1 ) {
			var zhost = window.location.hostname ;
			if ( zhost.indexOf('places') == -1 ) { // temp fix for places dictionary ror app
				new_href = window.location.protocol + "//" + window.location.hostname ;
			} else {
				new_href = "http://staging.thlib.org/" ;
			}
		}
		new_href += link_href ;
		thlplug.css_url = new_href ;
	}


	var thlplug = {
		
		div_id: "content" , 		// should be set in url of #iframe href (see above example), but defaults to this value
		css_url: "" , 				// first priority for this is in href (see above example), then here, then first <link> stylesheet in parent doc
		iframe_id: "thl_app" ,		// id to use for iframe
		bookmark_arg: "iframe=" , 	// the arg used after hash to trigger this plug-in (this is not globally referenced -- needs to be put in more global loc)
		iframe_html: "<iframe id='{id}' name='{id}' src='{src}' width='{x}' height='{y}' frameborder='0' scrolling='no' style='border:0pt; margin:0px; padding:0pt; overflow-x:hidden; overflow-y:hidden'></iframe>" ,	// html comprising actual iframe
		content_old: '' ,			// storage for content that iframe replaces
		
		// replaces iframe_html with real values
		do_subs: function( data ) {
			dims = this.dims_get( this.iframe_tokens['iframe'] ) ;
			data = data.replace( /{id}/g , this.iframe_id ) ; 
			if(data.indexOf("{src}") > -1) {
				data = data.replace( /{src}/ , this.app_url) ; 
			} else {
				data = data.replace( /src=\'[^?]+/ , "src='" + this.iframe_tokens['iframe']) ;
			}
			data = data.replace( /{x}/ , dims.x ) ;
			data = data.replace( /{y}/ , dims.y ) ;
			return data ;
		},
		
		// calculates dims based on size of iframe parent and content requirements (set in dims_load)
		dims_get: function( url ) {
			var dim = new Object() ;
			if ( obj = this.dim_arr[url] ) {
				dim.y = obj.y > 0 ? this.target_div.y + ( obj.y - this.target_div.y ) + 10 : this.target_div.y ; // add 10 pixels as bottom buffer
				dim.x = obj.x > 0 ? this.target_div.x + ( obj.x - this.target_div.x ) : this.target_div.x ;
			} else { //the url has not been loaded into this.dim_arr in the dims_load method, so default to container dimensions
				dim.y = this.target_div.y ;
				dim.x = this.target_div.x ;
			}
			return dim ;
		},
		
		// for setting the iframe dimensions to appropriate values based on what url is being loaded (shaky solution at best)
		// a 0 value does not actually mean 0, but defaults to the container element width
		// a better way to do this might be to have the app provide dynamic dims in json format, but that risks perfomance
		dims_load: function() {
			this.dim_arr = new Array() ;
			this.dim_arr[env_tmb + '/categories/119/children'] = { y: 1043 , x: 0 } ; 
			this.dim_arr[env_mms + '/media_collection_associations?collection_id=22'] = { y: 577 , x: 0 } ;
		},
		
		// called when this page first loads
		init: function() {
			this.dims_load() ;
		},

		// remove old iframe to make way for new
		kill_old: function() {
			if ( this.target_div  ) {
				this.target_div.html( this.content_old ) ;
				this.status = "off" ;
			}
		},
	
		// this is the main function, swapping out old content for iframe
		swap: function( iframe_data ) {
			// see above for what iframe_data should look like
						
			this.kill_old() ; 								// kill previous iterations; need to refine if doing multiple iframes per page
			
			this.status = "on" ; 							// for swap_undo (when someone uses nav buttons back to pre-iframe page)

			iframe_tokens = this.tokenize( iframe_data ) ;	// take iframe hash and parse out info
			
			this.div_id = !iframe_tokens["div_id"] ? this.div_id : iframe_tokens["div_id"] ;		// resort to div_id default if not in iframe hash
			this.css_url = !iframe_tokens["css_url"] ? this.css_url : iframe_tokens["css_url"] ;	// resort to css_url default if not in iframe hash
			this.parent_url = iframe_tokens["parent_url"] ; // get parent_url from iframe hash

			this.target_div = jQuery( '#' + this.div_id ) ;		// get dimensions of iframe parent
			this.target_div.x = this.target_div.width() ;
			this.target_div.y = this.target_div.height() ;
			
			if (this.content_old == '') { this.content_old = this.target_div.html() }	// store old content
			this.app_url = 									// construct url for iframe src
				iframe_tokens["iframe"] + 					// main url
				( iframe_tokens["iframe"].indexOf("?") > -1 ? "&" : "?" ) + // check for ? already in url; TODO: create an "add_arg" function for all this
				"css_url=" + this.css_url + 				
				"&parent_url=" + iframe_tokens["parent_url"] + 
				"&x=" + this.target_div.x + 
				"&y=" + this.target_div.y
			;
			
			this.iframe_html = this.do_subs( this.iframe_html ) ; // take the iframe html template and swap in real values
			
			// add a back to top link because we have to have extra space at bottom to accommodate unknown iframe content height
			var scroll_link = "<div style=\"position:relative;vertical-align:bottom;text-align:center\"><a href=\"javascript:self.scrollTo(0,0)\">Back to Top</a></div>" ;
			
			this.target_div.html( this.iframe_html + scroll_link ) ; 		// write the html into the target div
			this.iframe_obj = document.getElementById( this.iframe_id ) ;	// get the new dom element for future reference (necessary?)
		
		},
		
		// when a user clicks the back nav button to go to the pre-iframe content
		swap_undo: function() {
			this.kill_old() ;
			this.target_div.show() ;			
		},
		
		// for parsing iframe hash and adding parent url if necessary (could save resources here by having different params instead of one url)
		tokenize: function( data ) {			
			
			this.iframe_tokens = new Array() ;

			iframe_regex = new RegExp( this.bookmark_arg + "(((?!&div_id|&css_url?=).)+)" ) ; //extracts everything between iframe= and div_id|css_url|$
			frame_arr = data.match(iframe_regex) ;
			this.iframe_tokens['iframe'] = frame_arr[1] ;

			data_split = data.match(/([^=&#]+)=([^&]*)/g) ; //returns in an array each arg=val after # 

			var i = data_split.length - 1 ; do {
				if ( i > 0 ) {	// don't extract iframe= here because url may have its own args that shouldn't be split, which is why we did it separately above
					zitem = data_split[i] ;
					arg_arr = zitem.split("=") ;
					arg = arg_arr[0] ;
					this.iframe_tokens[arg] = arg_arr[1] ;
				}
			} while ( i-- ) ;
			
			parent_data = window.location.href.split("#") ;
			this.iframe_tokens["parent_url"] = parent_data[0] ;
			
			return this.iframe_tokens ;

		}


	};
	
	// initialize plugin when page loads 
	thlplug.init() ;



//======================= Script:   /js/jqModal js ()===========================
/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 * $Version: 03/01/2009 +r14
 */
(function($) {
jQuery.fn.jqm=function(o){
var olc = (jQuery.browser.msie)?"jqmOverlay ieOverlay": "jqmOverlay";
var p={
overlay: 50,
overlayClass: olc,
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=jQuery.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:jQuery.extend(p,jQuery.jqm.params,o),a:F,w:jQuery(this).addClass('jqmID'+s),s:s};
if(p.trigger)jQuery(this).jqmAddTrigger(p.trigger);
});};

jQuery.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
jQuery.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
jQuery.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;jQuery.jqm.open(this._jqm,t);});};
jQuery.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;jQuery.jqm.close(this._jqm,t)});};

jQuery.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=jQuery('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])L('bind');A.push(s);}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=F;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
 if(ie6){jQuery('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?jQuery(r,h.w):jQuery(r),u=(u.substr(0,1) == '@')?jQuery(t).attr(u.substring(1)):u;
  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose(jQuery(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose(jQuery(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	
 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
 if(A[0]){A.pop();if(!A[0])L('unbind');}
 if(h.c.toTop&&h.o)jQuery('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=jQuery.jqm.hash,A=[],ie6=jQuery.browser.msie&&(jQuery.browser.version == "6.0"),F=false,
i=jQuery('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!jQuery('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{jQuery(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){jQuery()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!jQuery(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;jQuery(t).each(function() {
 if(!this[c]){this[c]=[];jQuery(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery);
