/*
 * 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,{}));

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };

/**
 * Set the variable that indicates if JavaScript behaviors should be applied
 */
Drupal.jsEnabled = document.getElementsByTagName && document.createElement && document.createTextNode && document.documentElement && document.getElementById;

/**
 * Attach all registered behaviors to a page element.
 *
 * Behaviors are event-triggered actions that attach to page elements, enhancing
 * default non-Javascript UIs. Behaviors are registered in the Drupal.behaviors
 * object as follows:
 * @code
 *    Drupal.behaviors.behaviorName = function () {
 *      ...
 *    };
 * @endcode
 *
 * Drupal.attachBehaviors is added below to the jQuery ready event and so
 * runs on initial page load. Developers implementing AHAH/AJAX in their
 * solutions should also call this function after new page content has been
 * loaded, feeding in an element to be processed, in order to attach all
 * behaviors to the new content.
 *
 * Behaviors should use a class in the form behaviorName-processed to ensure
 * the behavior is attached only once to a given element. (Doing so enables
 * the reprocessing of given elements, which may be needed on occasion despite
 * the ability to limit behavior attachment to a particular element.)
 *
 * @param context
 *   An element to attach behaviors to. If none is given, the document element
 *   is used.
 */
Drupal.attachBehaviors = function(context) {
  context = context || document;
  if (Drupal.jsEnabled) {
    // Execute all of them.
    jQuery.each(Drupal.behaviors, function() {
      this(context);
    });
  }
};

/**
 * Encode special characters in a plain-text string for display as HTML.
 */
Drupal.checkPlain = function(str) {
  str = String(str);
  var replace = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' };
  for (var character in replace) {
    var regex = new RegExp(character, 'g');
    str = str.replace(regex, replace[character]);
  }
  return str;
};

/**
 * Translate strings to the page language or a given language.
 *
 * See the documentation of the server-side t() function for further details.
 *
 * @param str
 *   A string containing the English string to translate.
 * @param args
 *   An object of replacements pairs to make after translation. Incidences
 *   of any key in this array are replaced with the corresponding value.
 *   Based on the first character of the key, the value is escaped and/or themed:
 *    - !variable: inserted as is
 *    - @variable: escape plain text to HTML (Drupal.checkPlain)
 *    - %variable: escape text and theme as a placeholder for user-submitted
 *      content (checkPlain + Drupal.theme('placeholder'))
 * @return
 *   The translated string.
 */
Drupal.t = function(str, args) {
  // Fetch the localized version of the string.
  if (Drupal.locale.strings && Drupal.locale.strings[str]) {
    str = Drupal.locale.strings[str];
  }

  if (args) {
    // Transform arguments before inserting them
    for (var key in args) {
      switch (key.charAt(0)) {
        // Escaped only
        case '@':
          args[key] = Drupal.checkPlain(args[key]);
        break;
        // Pass-through
        case '!':
          break;
        // Escaped and placeholder
        case '%':
        default:
          args[key] = Drupal.theme('placeholder', args[key]);
          break;
      }
      str = str.replace(key, args[key]);
    }
  }
  return str;
};

/**
 * Format a string containing a count of items.
 *
 * This function ensures that the string is pluralized correctly. Since Drupal.t() is
 * called by this function, make sure not to pass already-localized strings to it.
 *
 * See the documentation of the server-side format_plural() function for further details.
 *
 * @param count
 *   The item count to display.
 * @param singular
 *   The string for the singular case. Please make sure it is clear this is
 *   singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
 *   Do not use @count in the singular string.
 * @param plural
 *   The string for the plural case. Please make sure it is clear this is plural,
 *   to ease translation. Use @count in place of the item count, as in "@count
 *   new comments".
 * @param args
 *   An object of replacements pairs to make after translation. Incidences
 *   of any key in this array are replaced with the corresponding value.
 *   Based on the first character of the key, the value is escaped and/or themed:
 *    - !variable: inserted as is
 *    - @variable: escape plain text to HTML (Drupal.checkPlain)
 *    - %variable: escape text and theme as a placeholder for user-submitted
 *      content (checkPlain + Drupal.theme('placeholder'))
 *   Note that you do not need to include @count in this array.
 *   This replacement is done automatically for the plural case.
 * @return
 *   A translated string.
 */
Drupal.formatPlural = function(count, singular, plural, args) {
  var args = args || {};
  args['@count'] = count;
  // Determine the index of the plural form.
  var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1);

  if (index == 0) {
    return Drupal.t(singular, args);
  }
  else if (index == 1) {
    return Drupal.t(plural, args);
  }
  else {
    args['@count['+ index +']'] = args['@count'];
    delete args['@count'];
    return Drupal.t(plural.replace('@count', '@count['+ index +']'));
  }
};

/**
 * Generate the themed representation of a Drupal object.
 *
 * All requests for themed output must go through this function. It examines
 * the request and routes it to the appropriate theme function. If the current
 * theme does not provide an override function, the generic theme function is
 * called.
 *
 * For example, to retrieve the HTML that is output by theme_placeholder(text),
 * call Drupal.theme('placeholder', text).
 *
 * @param func
 *   The name of the theme function to call.
 * @param ...
 *   Additional arguments to pass along to the theme function.
 * @return
 *   Any data the theme function returns. This could be a plain HTML string,
 *   but also a complex object.
 */
Drupal.theme = function(func) {
  for (var i = 1, args = []; i < arguments.length; i++) {
    args.push(arguments[i]);
  }

  return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
};

/**
 * Parse a JSON response.
 *
 * The result is either the JSON object, or an object with 'status' 0 and 'data' an error message.
 */
Drupal.parseJson = function (data) {
  if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) {
    return { status: 0, data: data.length ? data : Drupal.t('Unspecified error') };
  }
  return eval('(' + data + ');');
};

/**
 * Freeze the current body height (as minimum height). Used to prevent
 * unnecessary upwards scrolling when doing DOM manipulations.
 */
Drupal.freezeHeight = function () {
  Drupal.unfreezeHeight();
  var div = document.createElement('div');
  $(div).css({
    position: 'absolute',
    top: '0px',
    left: '0px',
    width: '1px',
    height: $('body').css('height')
  }).attr('id', 'freeze-height');
  $('body').append(div);
};

/**
 * Unfreeze the body height
 */
Drupal.unfreezeHeight = function () {
  $('#freeze-height').remove();
};

/**
 * Wrapper around encodeURIComponent() which avoids Apache quirks (equivalent of
 * drupal_urlencode() in PHP). This function should only be used on paths, not
 * on query string arguments.
 */
Drupal.encodeURIComponent = function (item, uri) {
  uri = uri || location.href;
  item = encodeURIComponent(item).replace(/%2F/g, '/');
  return (uri.indexOf('?q=') != -1) ? item : item.replace(/%26/g, '%2526').replace(/%23/g, '%2523').replace(/\/\//g, '/%252F');
};

/**
 * Get the text selection in a textarea.
 */
Drupal.getSelection = function (element) {
  if (typeof(element.selectionStart) != 'number' && document.selection) {
    // The current selection
    var range1 = document.selection.createRange();
    var range2 = range1.duplicate();
    // Select all text.
    range2.moveToElementText(element);
    // Now move 'dummy' end point to end point of original range.
    range2.setEndPoint('EndToEnd', range1);
    // Now we can calculate start and end points.
    var start = range2.text.length - range1.text.length;
    var end = start + range1.text.length;
    return { 'start': start, 'end': end };
  }
  return { 'start': element.selectionStart, 'end': element.selectionEnd };
};

/**
 * Build an error message from ahah response.
 */
Drupal.ahahError = function(xmlhttp, uri) {
  if (xmlhttp.status == 200) {
    if (jQuery.trim($(xmlhttp.responseText).text())) {
      var message = Drupal.t("An error occurred. \n@uri\n@text", {'@uri': uri, '@text': xmlhttp.responseText });
    }
    else {
      var message = Drupal.t("An error occurred. \n@uri\n(no information available).", {'@uri': uri, '@text': xmlhttp.responseText });
    }
  }
  else {
    var message = Drupal.t("An HTTP error @status occurred. \n@uri", {'@uri': uri, '@status': xmlhttp.status });
  }
  return message;
}

// Global Killswitch on the <html> element
if (Drupal.jsEnabled) {
  // Global Killswitch on the <html> element
  $(document.documentElement).addClass('js');
  // 'js enabled' cookie
  document.cookie = 'has_js=1; path=/';
  // Attach all behaviors.
  $(document).ready(function() {
    Drupal.attachBehaviors(this);
  });
}

/**
 * The default themes.
 */
Drupal.theme.prototype = {

  /**
   * Formats text for emphasized display in a placeholder inside a sentence.
   *
   * @param str
   *   The text to format (plain-text).
   * @return
   *   The formatted text (html).
   */
  placeholder: function(str) {
    return '<em>' + Drupal.checkPlain(str) + '</em>';
  }
};
;
Drupal.locale = { 'pluralFormula': function($n) { return Number(($n!=1)); }, 'strings': { "Anonymous": "Gäst", "Select all rows in this table": "Markera alla rader i tabellen", "Deselect all rows in this table": "Avmarkera alla rader i tabellen", "Not published": "Inte publicerad", "Drag to re-order": "Drag för att ordna om", "Changes made in this table will not be saved until the form is submitted.": "Ändringar som görs i denna tabell sparas inte förrän formuläret skickas.", "The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.": "Den valda filen %filename kan inte laddas upp. Endast filer med följande ändelser är tillåtna: %extensions.", "Automatic alias": "Automatiskt alias", "Alias: @alias": "Alias: @alias", "No alias": "Inga alias", "New revision": "Ny version", "No revision": "Inga versioner", "By @name on @date": "Av @name @date", "By @name": "Av @name", "Sticky on top of lists": "Klistrad överst i listan", "Not in menu": "Ej i meny" } };;
Drupal.behaviors.spamspan=function(_1){$("span."+Drupal.settings.spamspan.m,_1).each(function(_2){var _3=($("span."+Drupal.settings.spamspan.u,this).text()+"@"+$("span."+Drupal.settings.spamspan.d,this).text()).replace(/\s+/g,"").replace(/\[dot\]/g,".");var _4=$("span."+Drupal.settings.spamspan.h,this).text().replace(/^ ?\((.*)\) ?$/,"$1");var _5=$.map(_4.split(/, /),function(n,i){return (n.replace(/: /,"="));});var _6=$("span."+Drupal.settings.spamspan.t,this).text().replace(/^ \((.*)\)$/,"$1");var _7="mailto:"+encodeURIComponent(_3);var _8=_5.join("&");_7+=_8?("?"+_8):"";$(this).after($("<a></a>").attr("href",_7).html(_6?_6:_3).addClass("spamspan")).remove();});};;
/*
 * jQuery Cycle Plugin (with Transition Definitions)
 * Examples and documentation at: http://jquery.malsup.com/cycle/
 * Copyright (c) 2007-2010 M. Alsup
 * Version: 2.88 (08-JUN-2010)
 * Dual licensed under the MIT and GPL licenses.
 * http://jquery.malsup.com/license.html
 * Requires: jQuery v1.2.6 or later
 */
(function($){var ver="2.88";if($.support==undefined){$.support={opacity:!($.browser.msie)};}function debug(s){if($.fn.cycle.debug){log(s);}}function log(){if(window.console&&window.console.log){window.console.log("[cycle] "+Array.prototype.join.call(arguments," "));}}$.fn.cycle=function(options,arg2){var o={s:this.selector,c:this.context};if(this.length===0&&options!="stop"){if(!$.isReady&&o.s){log("DOM not ready, queuing slideshow");$(function(){$(o.s,o.c).cycle(options,arg2);});return this;}log("terminating; zero elements found by selector"+($.isReady?"":" (DOM not ready)"));return this;}return this.each(function(){var opts=handleArguments(this,options,arg2);if(opts===false){return;}opts.updateActivePagerLink=opts.updateActivePagerLink||$.fn.cycle.updateActivePagerLink;if(this.cycleTimeout){clearTimeout(this.cycleTimeout);}this.cycleTimeout=this.cyclePause=0;var $cont=$(this);var $slides=opts.slideExpr?$(opts.slideExpr,this):$cont.children();var els=$slides.get();if(els.length<2){log("terminating; too few slides: "+els.length);return;}var opts2=buildOptions($cont,$slides,els,opts,o);if(opts2===false){return;}var startTime=opts2.continuous?10:getTimeout(els[opts2.currSlide],els[opts2.nextSlide],opts2,!opts2.rev);if(startTime){startTime+=(opts2.delay||0);if(startTime<10){startTime=10;}debug("first timeout: "+startTime);this.cycleTimeout=setTimeout(function(){go(els,opts2,0,(!opts2.rev&&!opts.backwards));},startTime);}});};function handleArguments(cont,options,arg2){if(cont.cycleStop==undefined){cont.cycleStop=0;}if(options===undefined||options===null){options={};}if(options.constructor==String){switch(options){case"destroy":case"stop":var opts=$(cont).data("cycle.opts");if(!opts){return false;}cont.cycleStop++;if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);}cont.cycleTimeout=0;$(cont).removeData("cycle.opts");if(options=="destroy"){destroy(opts);}return false;case"toggle":cont.cyclePause=(cont.cyclePause===1)?0:1;checkInstantResume(cont.cyclePause,arg2,cont);return false;case"pause":cont.cyclePause=1;return false;case"resume":cont.cyclePause=0;checkInstantResume(false,arg2,cont);return false;case"prev":case"next":var opts=$(cont).data("cycle.opts");if(!opts){log('options not found, "prev/next" ignored');return false;}$.fn.cycle[options](opts);return false;default:options={fx:options};}return options;}else{if(options.constructor==Number){var num=options;options=$(cont).data("cycle.opts");if(!options){log("options not found, can not advance slide");return false;}if(num<0||num>=options.elements.length){log("invalid slide index: "+num);return false;}options.nextSlide=num;if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);cont.cycleTimeout=0;}if(typeof arg2=="string"){options.oneTimeFx=arg2;}go(options.elements,options,1,num>=options.currSlide);return false;}}return options;function checkInstantResume(isPaused,arg2,cont){if(!isPaused&&arg2===true){var options=$(cont).data("cycle.opts");if(!options){log("options not found, can not resume");return false;}if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);cont.cycleTimeout=0;}go(options.elements,options,1,(!opts.rev&&!opts.backwards));}}}function removeFilter(el,opts){if(!$.support.opacity&&opts.cleartype&&el.style.filter){try{el.style.removeAttribute("filter");}catch(smother){}}}function destroy(opts){if(opts.next){$(opts.next).unbind(opts.prevNextEvent);}if(opts.prev){$(opts.prev).unbind(opts.prevNextEvent);}if(opts.pager||opts.pagerAnchorBuilder){$.each(opts.pagerAnchors||[],function(){this.unbind().remove();});}opts.pagerAnchors=null;if(opts.destroy){opts.destroy(opts);}}function buildOptions($cont,$slides,els,options,o){var opts=$.extend({},$.fn.cycle.defaults,options||{},$.metadata?$cont.metadata():$.meta?$cont.data():{});if(opts.autostop){opts.countdown=opts.autostopCount||els.length;}var cont=$cont[0];$cont.data("cycle.opts",opts);opts.$cont=$cont;opts.stopCount=cont.cycleStop;opts.elements=els;opts.before=opts.before?[opts.before]:[];opts.after=opts.after?[opts.after]:[];opts.after.unshift(function(){opts.busy=0;});if(!$.support.opacity&&opts.cleartype){opts.after.push(function(){removeFilter(this,opts);});}if(opts.continuous){opts.after.push(function(){go(els,opts,0,(!opts.rev&&!opts.backwards));});}saveOriginalOpts(opts);if(!$.support.opacity&&opts.cleartype&&!opts.cleartypeNoBg){clearTypeFix($slides);}if($cont.css("position")=="static"){$cont.css("position","relative");}if(opts.width){$cont.width(opts.width);}if(opts.height&&opts.height!="auto"){$cont.height(opts.height);}if(opts.startingSlide){opts.startingSlide=parseInt(opts.startingSlide);}else{if(opts.backwards){opts.startingSlide=els.length-1;}}if(opts.random){opts.randomMap=[];for(var i=0;i<els.length;i++){opts.randomMap.push(i);}opts.randomMap.sort(function(a,b){return Math.random()-0.5;});opts.randomIndex=1;opts.startingSlide=opts.randomMap[1];}else{if(opts.startingSlide>=els.length){opts.startingSlide=0;}}opts.currSlide=opts.startingSlide||0;var first=opts.startingSlide;$slides.css({position:"absolute",top:0,left:0}).hide().each(function(i){var z;if(opts.backwards){z=first?i<=first?els.length+(i-first):first-i:els.length-i;}else{z=first?i>=first?els.length-(i-first):first-i:els.length-i;}$(this).css("z-index",z);});$(els[first]).css("opacity",1).show();removeFilter(els[first],opts);if(opts.fit&&opts.width){$slides.width(opts.width);}if(opts.fit&&opts.height&&opts.height!="auto"){$slides.height(opts.height);}var reshape=opts.containerResize&&!$cont.innerHeight();if(reshape){var maxw=0,maxh=0;for(var j=0;j<els.length;j++){var $e=$(els[j]),e=$e[0],w=$e.outerWidth(),h=$e.outerHeight();if(!w){w=e.offsetWidth||e.width||$e.attr("width");}if(!h){h=e.offsetHeight||e.height||$e.attr("height");}maxw=w>maxw?w:maxw;maxh=h>maxh?h:maxh;}if(maxw>0&&maxh>0){$cont.css({width:maxw+"px",height:maxh+"px"});}}if(opts.pause){$cont.hover(function(){this.cyclePause++;},function(){this.cyclePause--;});}if(supportMultiTransitions(opts)===false){return false;}var requeue=false;options.requeueAttempts=options.requeueAttempts||0;$slides.each(function(){var $el=$(this);this.cycleH=(opts.fit&&opts.height)?opts.height:($el.height()||this.offsetHeight||this.height||$el.attr("height")||0);this.cycleW=(opts.fit&&opts.width)?opts.width:($el.width()||this.offsetWidth||this.width||$el.attr("width")||0);if($el.is("img")){var loadingIE=($.browser.msie&&this.cycleW==28&&this.cycleH==30&&!this.complete);var loadingFF=($.browser.mozilla&&this.cycleW==34&&this.cycleH==19&&!this.complete);var loadingOp=($.browser.opera&&((this.cycleW==42&&this.cycleH==19)||(this.cycleW==37&&this.cycleH==17))&&!this.complete);var loadingOther=(this.cycleH==0&&this.cycleW==0&&!this.complete);if(loadingIE||loadingFF||loadingOp||loadingOther){if(o.s&&opts.requeueOnImageNotLoaded&&++options.requeueAttempts<100){log(options.requeueAttempts," - img slide not loaded, requeuing slideshow: ",this.src,this.cycleW,this.cycleH);setTimeout(function(){$(o.s,o.c).cycle(options);},opts.requeueTimeout);requeue=true;return false;}else{log("could not determine size of image: "+this.src,this.cycleW,this.cycleH);}}}return true;});if(requeue){return false;}opts.cssBefore=opts.cssBefore||{};opts.animIn=opts.animIn||{};opts.animOut=opts.animOut||{};$slides.not(":eq("+first+")").css(opts.cssBefore);if(opts.cssFirst){$($slides[first]).css(opts.cssFirst);}if(opts.timeout){opts.timeout=parseInt(opts.timeout);if(opts.speed.constructor==String){opts.speed=$.fx.speeds[opts.speed]||parseInt(opts.speed);}if(!opts.sync){opts.speed=opts.speed/2;}var buffer=opts.fx=="shuffle"?500:250;while((opts.timeout-opts.speed)<buffer){opts.timeout+=opts.speed;}}if(opts.easing){opts.easeIn=opts.easeOut=opts.easing;}if(!opts.speedIn){opts.speedIn=opts.speed;}if(!opts.speedOut){opts.speedOut=opts.speed;}opts.slideCount=els.length;opts.currSlide=opts.lastSlide=first;if(opts.random){if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{if(opts.backwards){opts.nextSlide=opts.startingSlide==0?(els.length-1):opts.startingSlide-1;}else{opts.nextSlide=opts.startingSlide>=(els.length-1)?0:opts.startingSlide+1;}}if(!opts.multiFx){var init=$.fn.cycle.transitions[opts.fx];if($.isFunction(init)){init($cont,$slides,opts);}else{if(opts.fx!="custom"&&!opts.multiFx){log("unknown transition: "+opts.fx,"; slideshow terminating");return false;}}}var e0=$slides[first];if(opts.before.length){opts.before[0].apply(e0,[e0,e0,opts,true]);}if(opts.after.length>1){opts.after[1].apply(e0,[e0,e0,opts,true]);}if(opts.next){$(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,opts.rev?-1:1);});}if(opts.prev){$(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,opts.rev?1:-1);});}if(opts.pager||opts.pagerAnchorBuilder){buildPager(els,opts);}exposeAddSlide(opts,els);return opts;}function saveOriginalOpts(opts){opts.original={before:[],after:[]};opts.original.cssBefore=$.extend({},opts.cssBefore);opts.original.cssAfter=$.extend({},opts.cssAfter);opts.original.animIn=$.extend({},opts.animIn);opts.original.animOut=$.extend({},opts.animOut);$.each(opts.before,function(){opts.original.before.push(this);});$.each(opts.after,function(){opts.original.after.push(this);});}function supportMultiTransitions(opts){var i,tx,txs=$.fn.cycle.transitions;if(opts.fx.indexOf(",")>0){opts.multiFx=true;opts.fxs=opts.fx.replace(/\s*/g,"").split(",");for(i=0;i<opts.fxs.length;i++){var fx=opts.fxs[i];tx=txs[fx];if(!tx||!txs.hasOwnProperty(fx)||!$.isFunction(tx)){log("discarding unknown transition: ",fx);opts.fxs.splice(i,1);i--;}}if(!opts.fxs.length){log("No valid transitions named; slideshow terminating.");return false;}}else{if(opts.fx=="all"){opts.multiFx=true;opts.fxs=[];for(p in txs){tx=txs[p];if(txs.hasOwnProperty(p)&&$.isFunction(tx)){opts.fxs.push(p);}}}}if(opts.multiFx&&opts.randomizeEffects){var r1=Math.floor(Math.random()*20)+30;for(i=0;i<r1;i++){var r2=Math.floor(Math.random()*opts.fxs.length);opts.fxs.push(opts.fxs.splice(r2,1)[0]);}debug("randomized fx sequence: ",opts.fxs);}return true;}function exposeAddSlide(opts,els){opts.addSlide=function(newSlide,prepend){var $s=$(newSlide),s=$s[0];if(!opts.autostopCount){opts.countdown++;}els[prepend?"unshift":"push"](s);if(opts.els){opts.els[prepend?"unshift":"push"](s);}opts.slideCount=els.length;$s.css("position","absolute");$s[prepend?"prependTo":"appendTo"](opts.$cont);if(prepend){opts.currSlide++;opts.nextSlide++;}if(!$.support.opacity&&opts.cleartype&&!opts.cleartypeNoBg){clearTypeFix($s);}if(opts.fit&&opts.width){$s.width(opts.width);}if(opts.fit&&opts.height&&opts.height!="auto"){$slides.height(opts.height);}s.cycleH=(opts.fit&&opts.height)?opts.height:$s.height();s.cycleW=(opts.fit&&opts.width)?opts.width:$s.width();$s.css(opts.cssBefore);if(opts.pager||opts.pagerAnchorBuilder){$.fn.cycle.createPagerAnchor(els.length-1,s,$(opts.pager),els,opts);}if($.isFunction(opts.onAddSlide)){opts.onAddSlide($s);}else{$s.hide();}};}$.fn.cycle.resetState=function(opts,fx){fx=fx||opts.fx;opts.before=[];opts.after=[];opts.cssBefore=$.extend({},opts.original.cssBefore);opts.cssAfter=$.extend({},opts.original.cssAfter);opts.animIn=$.extend({},opts.original.animIn);opts.animOut=$.extend({},opts.original.animOut);opts.fxFn=null;$.each(opts.original.before,function(){opts.before.push(this);});$.each(opts.original.after,function(){opts.after.push(this);});var init=$.fn.cycle.transitions[fx];if($.isFunction(init)){init(opts.$cont,$(opts.elements),opts);}};function go(els,opts,manual,fwd){if(manual&&opts.busy&&opts.manualTrump){debug("manualTrump in go(), stopping active transition");$(els).stop(true,true);opts.busy=false;}if(opts.busy){debug("transition active, ignoring new tx request");return;}var p=opts.$cont[0],curr=els[opts.currSlide],next=els[opts.nextSlide];if(p.cycleStop!=opts.stopCount||p.cycleTimeout===0&&!manual){return;}if(!manual&&!p.cyclePause&&!opts.bounce&&((opts.autostop&&(--opts.countdown<=0))||(opts.nowrap&&!opts.random&&opts.nextSlide<opts.currSlide))){if(opts.end){opts.end(opts);}return;}var changed=false;if((manual||!p.cyclePause)&&(opts.nextSlide!=opts.currSlide)){changed=true;var fx=opts.fx;curr.cycleH=curr.cycleH||$(curr).height();curr.cycleW=curr.cycleW||$(curr).width();next.cycleH=next.cycleH||$(next).height();next.cycleW=next.cycleW||$(next).width();if(opts.multiFx){if(opts.lastFx==undefined||++opts.lastFx>=opts.fxs.length){opts.lastFx=0;}fx=opts.fxs[opts.lastFx];opts.currFx=fx;}if(opts.oneTimeFx){fx=opts.oneTimeFx;opts.oneTimeFx=null;}$.fn.cycle.resetState(opts,fx);if(opts.before.length){$.each(opts.before,function(i,o){if(p.cycleStop!=opts.stopCount){return;}o.apply(next,[curr,next,opts,fwd]);});}var after=function(){$.each(opts.after,function(i,o){if(p.cycleStop!=opts.stopCount){return;}o.apply(next,[curr,next,opts,fwd]);});};debug("tx firing; currSlide: "+opts.currSlide+"; nextSlide: "+opts.nextSlide);opts.busy=1;if(opts.fxFn){opts.fxFn(curr,next,opts,after,fwd,manual&&opts.fastOnEvent);}else{if($.isFunction($.fn.cycle[opts.fx])){$.fn.cycle[opts.fx](curr,next,opts,after,fwd,manual&&opts.fastOnEvent);}else{$.fn.cycle.custom(curr,next,opts,after,fwd,manual&&opts.fastOnEvent);}}}if(changed||opts.nextSlide==opts.currSlide){opts.lastSlide=opts.currSlide;if(opts.random){opts.currSlide=opts.nextSlide;if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];if(opts.nextSlide==opts.currSlide){opts.nextSlide=(opts.currSlide==opts.slideCount-1)?0:opts.currSlide+1;}}else{if(opts.backwards){var roll=(opts.nextSlide-1)<0;if(roll&&opts.bounce){opts.backwards=!opts.backwards;opts.nextSlide=1;opts.currSlide=0;}else{opts.nextSlide=roll?(els.length-1):opts.nextSlide-1;opts.currSlide=roll?0:opts.nextSlide+1;}}else{var roll=(opts.nextSlide+1)==els.length;if(roll&&opts.bounce){opts.backwards=!opts.backwards;opts.nextSlide=els.length-2;opts.currSlide=els.length-1;}else{opts.nextSlide=roll?0:opts.nextSlide+1;opts.currSlide=roll?els.length-1:opts.nextSlide-1;}}}}if(changed&&opts.pager){opts.updateActivePagerLink(opts.pager,opts.currSlide,opts.activePagerClass);}var ms=0;if(opts.timeout&&!opts.continuous){ms=getTimeout(els[opts.currSlide],els[opts.nextSlide],opts,fwd);}else{if(opts.continuous&&p.cyclePause){ms=10;}}if(ms>0){p.cycleTimeout=setTimeout(function(){go(els,opts,0,(!opts.rev&&!opts.backwards));},ms);}}$.fn.cycle.updateActivePagerLink=function(pager,currSlide,clsName){$(pager).each(function(){$(this).children().removeClass(clsName).eq(currSlide).addClass(clsName);});};function getTimeout(curr,next,opts,fwd){if(opts.timeoutFn){var t=opts.timeoutFn.call(curr,curr,next,opts,fwd);while((t-opts.speed)<250){t+=opts.speed;}debug("calculated timeout: "+t+"; speed: "+opts.speed);if(t!==false){return t;}}return opts.timeout;}$.fn.cycle.next=function(opts){advance(opts,opts.rev?-1:1);};$.fn.cycle.prev=function(opts){advance(opts,opts.rev?1:-1);};function advance(opts,val){var els=opts.elements;var p=opts.$cont[0],timeout=p.cycleTimeout;if(timeout){clearTimeout(timeout);p.cycleTimeout=0;}if(opts.random&&val<0){opts.randomIndex--;if(--opts.randomIndex==-2){opts.randomIndex=els.length-2;}else{if(opts.randomIndex==-1){opts.randomIndex=els.length-1;}}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{if(opts.random){opts.nextSlide=opts.randomMap[opts.randomIndex];}else{opts.nextSlide=opts.currSlide+val;if(opts.nextSlide<0){if(opts.nowrap){return false;}opts.nextSlide=els.length-1;}else{if(opts.nextSlide>=els.length){if(opts.nowrap){return false;}opts.nextSlide=0;}}}}var cb=opts.onPrevNextEvent||opts.prevNextClick;if($.isFunction(cb)){cb(val>0,opts.nextSlide,els[opts.nextSlide]);}go(els,opts,1,val>=0);return false;}function buildPager(els,opts){var $p=$(opts.pager);$.each(els,function(i,o){$.fn.cycle.createPagerAnchor(i,o,$p,els,opts);});opts.updateActivePagerLink(opts.pager,opts.startingSlide,opts.activePagerClass);}$.fn.cycle.createPagerAnchor=function(i,el,$p,els,opts){var a;if($.isFunction(opts.pagerAnchorBuilder)){a=opts.pagerAnchorBuilder(i,el);debug("pagerAnchorBuilder("+i+", el) returned: "+a);}else{a='<a href="#">'+(i+1)+"</a>";}if(!a){return;}var $a=$(a);if($a.parents("body").length===0){var arr=[];if($p.length>1){$p.each(function(){var $clone=$a.clone(true);$(this).append($clone);arr.push($clone[0]);});$a=$(arr);}else{$a.appendTo($p);}}opts.pagerAnchors=opts.pagerAnchors||[];opts.pagerAnchors.push($a);$a.bind(opts.pagerEvent,function(e){e.preventDefault();opts.nextSlide=i;var p=opts.$cont[0],timeout=p.cycleTimeout;if(timeout){clearTimeout(timeout);p.cycleTimeout=0;}var cb=opts.onPagerEvent||opts.pagerClick;if($.isFunction(cb)){cb(opts.nextSlide,els[opts.nextSlide]);}go(els,opts,1,opts.currSlide<i);});if(!/^click/.test(opts.pagerEvent)&&!opts.allowPagerClickBubble){$a.bind("click.cycle",function(){return false;});}if(opts.pauseOnPagerHover){$a.hover(function(){opts.$cont[0].cyclePause++;},function(){opts.$cont[0].cyclePause--;});}};$.fn.cycle.hopsFromLast=function(opts,fwd){var hops,l=opts.lastSlide,c=opts.currSlide;if(fwd){hops=c>l?c-l:opts.slideCount-l;}else{hops=c<l?l-c:l+opts.slideCount-c;}return hops;};function clearTypeFix($slides){debug("applying clearType background-color hack");function hex(s){s=parseInt(s).toString(16);return s.length<2?"0"+s:s;}function getBg(e){for(;e&&e.nodeName.toLowerCase()!="html";e=e.parentNode){var v=$.css(e,"background-color");if(v.indexOf("rgb")>=0){var rgb=v.match(/\d+/g);return"#"+hex(rgb[0])+hex(rgb[1])+hex(rgb[2]);}if(v&&v!="transparent"){return v;}}return"#ffffff";}$slides.each(function(){$(this).css("background-color",getBg(this));});}$.fn.cycle.commonReset=function(curr,next,opts,w,h,rev){$(opts.elements).not(curr).hide();opts.cssBefore.opacity=1;opts.cssBefore.display="block";if(w!==false&&next.cycleW>0){opts.cssBefore.width=next.cycleW;}if(h!==false&&next.cycleH>0){opts.cssBefore.height=next.cycleH;}opts.cssAfter=opts.cssAfter||{};opts.cssAfter.display="none";$(curr).css("zIndex",opts.slideCount+(rev===true?1:0));$(next).css("zIndex",opts.slideCount+(rev===true?0:1));};$.fn.cycle.custom=function(curr,next,opts,cb,fwd,speedOverride){var $l=$(curr),$n=$(next);var speedIn=opts.speedIn,speedOut=opts.speedOut,easeIn=opts.easeIn,easeOut=opts.easeOut;$n.css(opts.cssBefore);if(speedOverride){if(typeof speedOverride=="number"){speedIn=speedOut=speedOverride;}else{speedIn=speedOut=1;}easeIn=easeOut=null;}var fn=function(){$n.animate(opts.animIn,speedIn,easeIn,cb);};$l.animate(opts.animOut,speedOut,easeOut,function(){if(opts.cssAfter){$l.css(opts.cssAfter);}if(!opts.sync){fn();}});if(opts.sync){fn();}};$.fn.cycle.transitions={fade:function($cont,$slides,opts){$slides.not(":eq("+opts.currSlide+")").css("opacity",0);opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts);opts.cssBefore.opacity=0;});opts.animIn={opacity:1};opts.animOut={opacity:0};opts.cssBefore={top:0,left:0};}};$.fn.cycle.ver=function(){return ver;};$.fn.cycle.defaults={fx:"fade",timeout:4000,timeoutFn:null,continuous:0,speed:1000,speedIn:null,speedOut:null,next:null,prev:null,onPrevNextEvent:null,prevNextEvent:"click.cycle",pager:null,onPagerEvent:null,pagerEvent:"click.cycle",allowPagerClickBubble:false,pagerAnchorBuilder:null,before:null,after:null,end:null,easing:null,easeIn:null,easeOut:null,shuffle:null,animIn:null,animOut:null,cssBefore:null,cssAfter:null,fxFn:null,height:"auto",startingSlide:0,sync:1,random:0,fit:0,containerResize:1,pause:0,pauseOnPagerHover:0,autostop:0,autostopCount:0,delay:0,slideExpr:null,cleartype:!$.support.opacity,cleartypeNoBg:false,nowrap:0,fastOnEvent:0,randomizeEffects:1,rev:0,manualTrump:true,requeueOnImageNotLoaded:true,requeueTimeout:250,activePagerClass:"activeSlide",updateActivePagerLink:null,backwards:false};})(jQuery);
/*
 * jQuery Cycle Plugin Transition Definitions
 * This script is a plugin for the jQuery Cycle Plugin
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 * Copyright (c) 2007-2010 M. Alsup
 * Version:	 2.72
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function($){$.fn.cycle.transitions.none=function($cont,$slides,opts){opts.fxFn=function(curr,next,opts,after){$(next).show();$(curr).hide();after();};};$.fn.cycle.transitions.scrollUp=function($cont,$slides,opts){$cont.css("overflow","hidden");opts.before.push($.fn.cycle.commonReset);var h=$cont.height();opts.cssBefore={top:h,left:0};opts.cssFirst={top:0};opts.animIn={top:0};opts.animOut={top:-h};};$.fn.cycle.transitions.scrollDown=function($cont,$slides,opts){$cont.css("overflow","hidden");opts.before.push($.fn.cycle.commonReset);var h=$cont.height();opts.cssFirst={top:0};opts.cssBefore={top:-h,left:0};opts.animIn={top:0};opts.animOut={top:h};};$.fn.cycle.transitions.scrollLeft=function($cont,$slides,opts){$cont.css("overflow","hidden");opts.before.push($.fn.cycle.commonReset);var w=$cont.width();opts.cssFirst={left:0};opts.cssBefore={left:w,top:0};opts.animIn={left:0};opts.animOut={left:0-w};};$.fn.cycle.transitions.scrollRight=function($cont,$slides,opts){$cont.css("overflow","hidden");opts.before.push($.fn.cycle.commonReset);var w=$cont.width();opts.cssFirst={left:0};opts.cssBefore={left:-w,top:0};opts.animIn={left:0};opts.animOut={left:w};};$.fn.cycle.transitions.scrollHorz=function($cont,$slides,opts){$cont.css("overflow","hidden").width();opts.before.push(function(curr,next,opts,fwd){$.fn.cycle.commonReset(curr,next,opts);opts.cssBefore.left=fwd?(next.cycleW-1):(1-next.cycleW);opts.animOut.left=fwd?-curr.cycleW:curr.cycleW;});opts.cssFirst={left:0};opts.cssBefore={top:0};opts.animIn={left:0};opts.animOut={top:0};};$.fn.cycle.transitions.scrollVert=function($cont,$slides,opts){$cont.css("overflow","hidden");opts.before.push(function(curr,next,opts,fwd){$.fn.cycle.commonReset(curr,next,opts);opts.cssBefore.top=fwd?(1-next.cycleH):(next.cycleH-1);opts.animOut.top=fwd?curr.cycleH:-curr.cycleH;});opts.cssFirst={top:0};opts.cssBefore={left:0};opts.animIn={top:0};opts.animOut={left:0};};$.fn.cycle.transitions.slideX=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$(opts.elements).not(curr).hide();$.fn.cycle.commonReset(curr,next,opts,false,true);opts.animIn.width=next.cycleW;});opts.cssBefore={left:0,top:0,width:0};opts.animIn={width:"show"};opts.animOut={width:0};};$.fn.cycle.transitions.slideY=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$(opts.elements).not(curr).hide();$.fn.cycle.commonReset(curr,next,opts,true,false);opts.animIn.height=next.cycleH;});opts.cssBefore={left:0,top:0,height:0};opts.animIn={height:"show"};opts.animOut={height:0};};$.fn.cycle.transitions.shuffle=function($cont,$slides,opts){var i,w=$cont.css("overflow","visible").width();$slides.css({left:0,top:0});opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,true,true,true);});if(!opts.speedAdjusted){opts.speed=opts.speed/2;opts.speedAdjusted=true;}opts.random=0;opts.shuffle=opts.shuffle||{left:-w,top:15};opts.els=[];for(i=0;i<$slides.length;i++){opts.els.push($slides[i]);}for(i=0;i<opts.currSlide;i++){opts.els.push(opts.els.shift());}opts.fxFn=function(curr,next,opts,cb,fwd){var $el=fwd?$(curr):$(next);$(next).css(opts.cssBefore);var count=opts.slideCount;$el.animate(opts.shuffle,opts.speedIn,opts.easeIn,function(){var hops=$.fn.cycle.hopsFromLast(opts,fwd);for(var k=0;k<hops;k++){fwd?opts.els.push(opts.els.shift()):opts.els.unshift(opts.els.pop());}if(fwd){for(var i=0,len=opts.els.length;i<len;i++){$(opts.els[i]).css("z-index",len-i+count);}}else{var z=$(curr).css("z-index");$el.css("z-index",parseInt(z)+1+count);}$el.animate({left:0,top:0},opts.speedOut,opts.easeOut,function(){$(fwd?this:curr).hide();if(cb){cb();}});});};opts.cssBefore={display:"block",opacity:1,top:0,left:0};};$.fn.cycle.transitions.turnUp=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,true,false);opts.cssBefore.top=next.cycleH;opts.animIn.height=next.cycleH;});opts.cssFirst={top:0};opts.cssBefore={left:0,height:0};opts.animIn={top:0};opts.animOut={height:0};};$.fn.cycle.transitions.turnDown=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,true,false);opts.animIn.height=next.cycleH;opts.animOut.top=curr.cycleH;});opts.cssFirst={top:0};opts.cssBefore={left:0,top:0,height:0};opts.animOut={height:0};};$.fn.cycle.transitions.turnLeft=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,false,true);opts.cssBefore.left=next.cycleW;opts.animIn.width=next.cycleW;});opts.cssBefore={top:0,width:0};opts.animIn={left:0};opts.animOut={width:0};};$.fn.cycle.transitions.turnRight=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,false,true);opts.animIn.width=next.cycleW;opts.animOut.left=curr.cycleW;});opts.cssBefore={top:0,left:0,width:0};opts.animIn={left:0};opts.animOut={width:0};};$.fn.cycle.transitions.zoom=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,false,false,true);opts.cssBefore.top=next.cycleH/2;opts.cssBefore.left=next.cycleW/2;opts.animIn={top:0,left:0,width:next.cycleW,height:next.cycleH};opts.animOut={width:0,height:0,top:curr.cycleH/2,left:curr.cycleW/2};});opts.cssFirst={top:0,left:0};opts.cssBefore={width:0,height:0};};$.fn.cycle.transitions.fadeZoom=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,false,false);opts.cssBefore.left=next.cycleW/2;opts.cssBefore.top=next.cycleH/2;opts.animIn={top:0,left:0,width:next.cycleW,height:next.cycleH};});opts.cssBefore={width:0,height:0};opts.animOut={opacity:0};};$.fn.cycle.transitions.blindX=function($cont,$slides,opts){var w=$cont.css("overflow","hidden").width();opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts);opts.animIn.width=next.cycleW;opts.animOut.left=curr.cycleW;});opts.cssBefore={left:w,top:0};opts.animIn={left:0};opts.animOut={left:w};};$.fn.cycle.transitions.blindY=function($cont,$slides,opts){var h=$cont.css("overflow","hidden").height();opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts);opts.animIn.height=next.cycleH;opts.animOut.top=curr.cycleH;});opts.cssBefore={top:h,left:0};opts.animIn={top:0};opts.animOut={top:h};};$.fn.cycle.transitions.blindZ=function($cont,$slides,opts){var h=$cont.css("overflow","hidden").height();var w=$cont.width();opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts);opts.animIn.height=next.cycleH;opts.animOut.top=curr.cycleH;});opts.cssBefore={top:h,left:w};opts.animIn={top:0,left:0};opts.animOut={top:h,left:w};};$.fn.cycle.transitions.growX=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,false,true);opts.cssBefore.left=this.cycleW/2;opts.animIn={left:0,width:this.cycleW};opts.animOut={left:0};});opts.cssBefore={width:0,top:0};};$.fn.cycle.transitions.growY=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,true,false);opts.cssBefore.top=this.cycleH/2;opts.animIn={top:0,height:this.cycleH};opts.animOut={top:0};});opts.cssBefore={height:0,left:0};};$.fn.cycle.transitions.curtainX=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,false,true,true);opts.cssBefore.left=next.cycleW/2;opts.animIn={left:0,width:this.cycleW};opts.animOut={left:curr.cycleW/2,width:0};});opts.cssBefore={top:0,width:0};};$.fn.cycle.transitions.curtainY=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,true,false,true);opts.cssBefore.top=next.cycleH/2;opts.animIn={top:0,height:next.cycleH};opts.animOut={top:curr.cycleH/2,height:0};});opts.cssBefore={left:0,height:0};};$.fn.cycle.transitions.cover=function($cont,$slides,opts){var d=opts.direction||"left";var w=$cont.css("overflow","hidden").width();var h=$cont.height();opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts);if(d=="right"){opts.cssBefore.left=-w;}else{if(d=="up"){opts.cssBefore.top=h;}else{if(d=="down"){opts.cssBefore.top=-h;}else{opts.cssBefore.left=w;}}}});opts.animIn={left:0,top:0};opts.animOut={opacity:1};opts.cssBefore={top:0,left:0};};$.fn.cycle.transitions.uncover=function($cont,$slides,opts){var d=opts.direction||"left";var w=$cont.css("overflow","hidden").width();var h=$cont.height();opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,true,true,true);if(d=="right"){opts.animOut.left=w;}else{if(d=="up"){opts.animOut.top=-h;}else{if(d=="down"){opts.animOut.top=h;}else{opts.animOut.left=-w;}}}});opts.animIn={left:0,top:0};opts.animOut={opacity:1};opts.cssBefore={top:0,left:0};};$.fn.cycle.transitions.toss=function($cont,$slides,opts){var w=$cont.css("overflow","visible").width();var h=$cont.height();opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,true,true,true);if(!opts.animOut.left&&!opts.animOut.top){opts.animOut={left:w*2,top:-h/2,opacity:0};}else{opts.animOut.opacity=0;}});opts.cssBefore={left:0,top:0};opts.animIn={left:0};};$.fn.cycle.transitions.wipe=function($cont,$slides,opts){var w=$cont.css("overflow","hidden").width();var h=$cont.height();opts.cssBefore=opts.cssBefore||{};var clip;if(opts.clip){if(/l2r/.test(opts.clip)){clip="rect(0px 0px "+h+"px 0px)";}else{if(/r2l/.test(opts.clip)){clip="rect(0px "+w+"px "+h+"px "+w+"px)";}else{if(/t2b/.test(opts.clip)){clip="rect(0px "+w+"px 0px 0px)";}else{if(/b2t/.test(opts.clip)){clip="rect("+h+"px "+w+"px "+h+"px 0px)";}else{if(/zoom/.test(opts.clip)){var top=parseInt(h/2);var left=parseInt(w/2);clip="rect("+top+"px "+left+"px "+top+"px "+left+"px)";}}}}}}opts.cssBefore.clip=opts.cssBefore.clip||clip||"rect(0px 0px 0px 0px)";var d=opts.cssBefore.clip.match(/(\d+)/g);var t=parseInt(d[0]),r=parseInt(d[1]),b=parseInt(d[2]),l=parseInt(d[3]);opts.before.push(function(curr,next,opts){if(curr==next){return;}var $curr=$(curr),$next=$(next);$.fn.cycle.commonReset(curr,next,opts,true,true,false);opts.cssAfter.display="block";var step=1,count=parseInt((opts.speedIn/13))-1;(function f(){var tt=t?t-parseInt(step*(t/count)):0;var ll=l?l-parseInt(step*(l/count)):0;var bb=b<h?b+parseInt(step*((h-b)/count||1)):h;var rr=r<w?r+parseInt(step*((w-r)/count||1)):w;$next.css({clip:"rect("+tt+"px "+rr+"px "+bb+"px "+ll+"px)"});(step++<=count)?setTimeout(f,13):$curr.css("display","none");})();});opts.cssBefore={display:"block",opacity:1,top:0,left:0};opts.animIn={left:0};opts.animOut={left:0};};})(jQuery);;
// $Id: views_slideshow.js,v 1.1.2.1.2.39 2010/07/01 03:29:08 redndahead Exp $

/**
 *  @file
 *  A simple jQuery SingleFrame Div Slideshow Rotator.
 */

/**
 * This will set our initial behavior, by starting up each individual slideshow.
 */
Drupal.behaviors.viewsSlideshowSingleFrame = function (context) {
  $('.views_slideshow_singleframe_main:not(.viewsSlideshowSingleFrame-processed)', context).addClass('viewsSlideshowSingleFrame-processed').each(function() {
    var fullId = '#' + $(this).attr('id');
    var settings = Drupal.settings.viewsSlideshowSingleFrame[fullId];
    settings.targetId = '#' + $(fullId + " :first").attr('id');
    settings.paused = false;

    settings.opts = {
      speed:settings.speed,
      timeout:parseInt(settings.timeout),
      delay:parseInt(settings.delay),
      sync:settings.sync==1,
      random:settings.random==1,
      pause:false,
      allowPagerClickBubble:(settings.pager_hover==1 || settings.pager_click_to_page),
      prev:(settings.controls > 0)?'#views_slideshow_singleframe_prev_' + settings.vss_id:null,
      next:(settings.controls > 0)?'#views_slideshow_singleframe_next_' + settings.vss_id:null,
      pager:(settings.pager > 0)?'#views_slideshow_singleframe_pager_' + settings.vss_id:null,
      nowrap:parseInt(settings.nowrap),
      pagerAnchorBuilder: function(idx, slide) {
        var classes = 'pager-item pager-num-' + (idx+1);
        if (idx == 0) {
          classes += ' first';
        }
        if ($(slide).siblings().length == idx) {
          classes += ' last';
        }

        if (idx % 2) {
          classes += ' odd';
        }
        else {
          classes += ' even';
        }
        
        var theme = 'viewsSlideshowPager' + settings.pager_type;
        return Drupal.theme.prototype[theme] ? Drupal.theme(theme, classes, idx, slide, settings) : '';
      },
      after:function(curr, next, opts) {
        // Used for Image Counter.
        if (settings.image_count) {
          $('#views_slideshow_singleframe_image_count_' + settings.vss_id + ' span.num').html(opts.currSlide + 1);
          $('#views_slideshow_singleframe_image_count_' + settings.vss_id + ' span.total').html(opts.slideCount);
        }
      },
      before:function(curr, next, opts) {
        // Remember last slide.
        if (settings.remember_slide) {
          createCookie(settings.vss_id, opts.currSlide + 1, settings.remember_slide_days);
        }

        // Make variable height.
        if (settings.fixed_height == 0) {
          //get the height of the current slide
          var $ht = $(this).height();
          //set the container's height to that of the current slide
          $(this).parent().animate({height: $ht});
        }
      },
      cleartype:(settings.ie.cleartype == 'true')? true : false,
      cleartypeNoBg:(settings.ie.cleartypenobg == 'true')? true : false
    }
    
    // Set the starting slide if we are supposed to remember the slide
    if (settings.remember_slide) {
      var startSlide = readCookie(settings.vss_id);
      if (startSlide == null) {
        startSlide = 0;
      }
      settings.opts.startingSlide =  startSlide;
    }

    if (settings.pager_hover == 1) {
      settings.opts.pagerEvent = 'mouseover';
      settings.opts.pauseOnPagerHover = true;
    }

    if (settings.effect == 'none') {
      settings.opts.speed = 1;
    }
    else {
      settings.opts.fx = settings.effect;
    }

    // Pause on hover.
    if (settings.pause == 1) {
      $('#views_slideshow_singleframe_teaser_section_' + settings.vss_id).hover(function() {
        $(settings.targetId).cycle('pause');
      }, function() {
        if (settings.paused == false) {
          $(settings.targetId).cycle('resume');
        }
      });
    }

    // Pause on clicking of the slide.
    if (settings.pause_on_click == 1) {
      $('#views_slideshow_singleframe_teaser_section_' + settings.vss_id).click(function() { 
        viewsSlideshowSingleFramePause(settings);
      });
    }

    // Add additional settings.
		if (settings.advanced != "\n") {
      var advanced = settings.advanced.split("\n");
      for (i=0; i<advanced.length; i++) {
        var prop = '';
        var value = '';
        var property = advanced[i].split(":");
        for (j=0; j<property.length; j++) {
          if (j == 0) {
            prop = property[j];
          }
          else if (j == 1) {
            value = property[j];
          }
          else {
            value += ":" + property[j];
          }
        }

        // Need to evaluate so true, false and numerics aren't a string.
        if (value == 'true' || value == 'false' || IsNumeric(value)) {
          value = eval(value);
        }
        else {
          // Parse strings into functions.
          var func = value.match(/function\s*\((.*?)\)\s*\{(.*)\}/i);
          if (func) {
            value = new Function(func[1].match(/(\w+)/g), func[2]);
          }
        }
	
        // Call both functions if prop was set previously.
        if (typeof(value) == "function" && prop in settings.opts) {
          var callboth = function(before_func, new_func) {
            return function() {
              before_func.apply(null, arguments);
              new_func.apply(null, arguments);
            };
          };
          settings.opts[prop] = callboth(settings.opts[prop], value);
        }
        else {
          settings.opts[prop] = value;
        }
      }
    }
    
    $(settings.targetId).cycle(settings.opts);

    // Start Paused
    if (settings.start_paused) {
      viewsSlideshowSingleFramePause(settings);
    }
    
    // Pause if hidden.
    if (settings.pause_when_hidden) {
      var checkPause = function(settings) {
        // If the slideshow is visible and it is paused then resume.
        // otherwise if the slideshow is not visible and it is not paused then
        // pause it.
        var visible = viewsSlideshowSingleFrameIsVisible(settings.targetId, settings.pause_when_hidden_type, settings.amount_allowed_visible);
        if (visible && settings.paused) {
          viewsSlideshowSingleFrameResume(settings);
        }
        else if (!visible && !settings.paused) {
          viewsSlideshowSingleFramePause(settings);
        }
      }
     
      // Check when scrolled.
      $(window).scroll(function() {
       checkPause(settings);
      });
      
      // Check when the window is resized.
      $(window).resize(function() {
        checkPause(settings);
      });
    }

    // Show image count for people who have js enabled.
    $('#views_slideshow_singleframe_image_count_' + settings.vss_id).show();

    if (settings.controls > 0) {
      // Show controls for people who have js enabled browsers.
      $('#views_slideshow_singleframe_controls_' + settings.vss_id).show();
      
      $('#views_slideshow_singleframe_playpause_' + settings.vss_id).click(function(e) {
      	if (settings.paused) {
      	  viewsSlideshowSingleFrameResume(settings);
      	}
      	else {
      	  viewsSlideshowSingleFramePause(settings);
      	}
        e.preventDefault();
      });
    }
  });
}

// Pause the slideshow 
viewsSlideshowSingleFramePause = function (settings) {
  //make Resume translatable
  var resume = Drupal.t('Resume');

  $(settings.targetId).cycle('pause');
  if (settings.controls > 0) {
    $('#views_slideshow_singleframe_playpause_' + settings.vss_id)
      .addClass('views_slideshow_singleframe_play')
      .addClass('views_slideshow_play')
      .removeClass('views_slideshow_singleframe_pause')
      .removeClass('views_slideshow_pause')
      .text(resume);
  }
  settings.paused = true;
}

// Resume the slideshow
viewsSlideshowSingleFrameResume = function (settings) {
  $(settings.targetId).cycle('resume');
  if (settings.controls > 0) {
    $('#views_slideshow_singleframe_playpause_' + settings.vss_id)
      .addClass('views_slideshow_singleframe_pause')
      .addClass('views_slideshow_pause')
      .removeClass('views_slideshow_singleframe_play')
      .removeClass('views_slideshow_play')
      .text('Pause');
  }
  settings.paused = false;
}

Drupal.theme.prototype.viewsSlideshowPagerThumbnails = function (classes, idx, slide, settings) {
  var href = '#';
  if (settings.pager_click_to_page) {
    href = $(slide).find('a').attr('href');
  }
  return '<div class="' + classes + '"><a href="' + href + '"><img src="' + $(slide).find('img').attr('src') + '" /></a></div>';
}

Drupal.theme.prototype.viewsSlideshowPagerNumbered = function (classes, idx, slide, settings) {
  var href = '#';
  if (settings.pager_click_to_page) {
    href = $(slide).find('a').attr('href');
  }
  return '<div class="' + classes + '"><a href="' + href + '">' + (idx+1) + '</a></div>';
}

// Verify that the value is a number.
function IsNumeric(sText) {
  var ValidChars = "0123456789";
  var IsNumber=true;
  var Char;

  for (var i=0; i < sText.length && IsNumber == true; i++) { 
    Char = sText.charAt(i); 
    if (ValidChars.indexOf(Char) == -1) {
      IsNumber = false;
    }
  }
  return IsNumber;
}

/**
 * Cookie Handling Functions
 */
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else {
    var expires = "";
  }
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) {
      return c.substring(nameEQ.length,c.length);
    }
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}

/**
 * Checks to see if the slide is visible enough.
 * elem = element to check.
 * type = The way to calculate how much is visible.
 * amountVisible = amount that should be visible. Either in percent or px. If
 *                it's not defined then all of the slide must be visible.
 *
 * Returns true or false
 */
function viewsSlideshowSingleFrameIsVisible(elem, type, amountVisible) {
  // Get the top and bottom of the window;
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();
  var docViewLeft = $(window).scrollLeft();
  var docViewRight = docViewLeft + $(window).width();

  // Get the top, bottom, and height of the slide;
  var elemTop = $(elem).offset().top;
  var elemHeight = $(elem).height();
  var elemBottom = elemTop + elemHeight;
  var elemLeft = $(elem).offset().left;
  var elemWidth = $(elem).width();
  var elemRight = elemLeft + elemWidth;
  var elemArea = elemHeight * elemWidth;
  
  // Calculate what's hiding in the slide.
  var missingLeft = 0;
  var missingRight = 0;
  var missingTop = 0;
  var missingBottom = 0;
  
  // Find out how much of the slide is missing from the left.
  if (elemLeft < docViewLeft) {
    missingLeft = docViewLeft - elemLeft;
  }

  // Find out how much of the slide is missing from the right.
  if (elemRight > docViewRight) {
    missingRight = elemRight - docViewRight;
  }
  
  // Find out how much of the slide is missing from the top.
  if (elemTop < docViewTop) {
    missingTop = docViewTop - elemTop;
  }

  // Find out how much of the slide is missing from the bottom.
  if (elemBottom > docViewBottom) {
    missingBottom = elemBottom - docViewBottom;
  }
  
  // If there is no amountVisible defined then check to see if the whole slide
  // is visible.
  if (type == 'full') {
    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
    && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop)
    && (elemLeft >= docViewLeft) && (elemRight <= docViewRight)
    && (elemLeft <= docViewRight) && (elemRight >= docViewLeft));
  }
  else if(type == 'vertical') {
    var verticalShowing = elemHeight - missingTop - missingBottom;
    
    // If user specified a percentage then find out if the current shown percent
    // is larger than the allowed percent.
    // Otherwise check to see if the amount of px shown is larger than the
    // allotted amount.
    if (amountVisible.indexOf('%')) {
      return (((verticalShowing/elemHeight)*100) >= parseInt(amountVisible));
    }
    else {
      return (verticalShowing >= parseInt(amountVisible));
    }
  }
  else if(type == 'horizontal') {
    var horizontalShowing = elemWidth - missingLeft - missingRight;
    
    // If user specified a percentage then find out if the current shown percent
    // is larger than the allowed percent.
    // Otherwise check to see if the amount of px shown is larger than the
    // allotted amount.
    if (amountVisible.indexOf('%')) {
      return (((horizontalShowing/elemWidth)*100) >= parseInt(amountVisible));
    }
    else {
      return (horizontalShowing >= parseInt(amountVisible));
    }
  }
  else if(type == 'area') {
    var areaShowing = (elemWidth - missingLeft - missingRight) * (elemHeight - missingTop - missingBottom);
    
    // If user specified a percentage then find out if the current shown percent
    // is larger than the allowed percent.
    // Otherwise check to see if the amount of px shown is larger than the
    // allotted amount.
    if (amountVisible.indexOf('%')) {
      return (((areaShowing/elemArea)*100) >= parseInt(amountVisible));
    }
    else {
      return (areaShowing >= parseInt(amountVisible));
    }
  }
}

;
/*!
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function($) {
    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name">
     *   <div class="jcarousel-container">
     *     <div class="jcarousel-clip">
     *       <ul class="jcarousel-list">
     *         <li class="jcarousel-item-1">First item</li>
     *         <li class="jcarousel-item-2">Second item</li>
     *       </ul>
     *     </div>
     *     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *     <div class="jcarousel-next"></div>
     *   </div>
     * </div>
     *
     * @method jcarousel
     * @return jQuery
     * @param o {Hash|String} A set of key/value pairs to set as configuration properties or a method name to call on a formerly created instance.
     */
    $.fn.jcarousel = function(o) {
        if (typeof o == 'string') {
            var instance = $(this).data('jcarousel'), args = Array.prototype.slice.call(arguments, 1);
            return instance[o].apply(instance, args);
        } else
            return this.each(function() {
                $(this).data('jcarousel', new $jc(this, o));
            });
    };

    // Default configuration properties.
    var defaults = {
        vertical: false,
        rtl: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 3,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        buttonNextHTML: '<div></div>',
        buttonPrevHTML: '<div></div>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null,
        itemFallbackDimension: null
    }, windowLoaded = false;

    $(window).bind('load.jcarousel', function() { windowLoaded = true; })

    /**
     * The jCarousel object.
     *
     * @constructor
     * @class jcarousel
     * @param e {HTMLElement} The element to create the carousel for.
     * @param o {Object} A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked     = false;

        this.container  = null;
        this.clip       = null;
        this.list       = null;
        this.buttonNext = null;
        this.buttonPrev = null;

        // Only set if not explicitly passed as option
        if (!o || o.rtl === undefined)
            this.options.rtl = ($(e).attr('dir') || $('html').attr('dir') || '').toLowerCase() == 'rtl';

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? (this.options.rtl ? 'right' : 'left') : 'top';

        // Extract skin class
        var skin = '', split = e.className.split(' ');

        for (var i = 0; i < split.length; i++) {
            if (split[i].indexOf('jcarousel-skin') != -1) {
                $(e).removeClass(split[i]);
                skin = split[i];
                break;
            }
        }

        if (e.nodeName.toUpperCase() == 'UL' || e.nodeName.toUpperCase() == 'OL') {
            this.list = $(e);
            this.container = this.list.parent();

            if (this.container.hasClass('jcarousel-clip')) {
                if (!this.container.parent().hasClass('jcarousel-container'))
                    this.container = this.container.wrap('<div></div>');

                this.container = this.container.parent();
            } else if (!this.container.hasClass('jcarousel-container'))
                this.container = this.list.wrap('<div></div>').parent();
        } else {
            this.container = $(e);
            this.list = this.container.find('ul,ol').eq(0);
        }

        if (skin != '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1)
            this.container.wrap('<div class=" '+ skin + '"></div>');

        this.clip = this.list.parent();

        if (!this.clip.length || !this.clip.hasClass('jcarousel-clip'))
            this.clip = this.list.wrap('<div></div>').parent();

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.size() == 0 && this.options.buttonNextHTML != null)
            this.buttonNext = this.clip.after(this.options.buttonNextHTML).next();

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.size() == 0 && this.options.buttonPrevHTML != null)
            this.buttonPrev = this.clip.after(this.options.buttonPrevHTML).next();

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.clip.addClass(this.className('jcarousel-clip')).css({
            overflow: 'hidden',
            position: 'relative'
        });
        this.list.addClass(this.className('jcarousel-list')).css({
            overflow: 'hidden',
            position: 'relative',
            top: 0,
            margin: 0,
            padding: 0
        }).css((this.options.rtl ? 'right' : 'left'), 0);
        this.container.addClass(this.className('jcarousel-container')).css({
            position: 'relative'
        });
        if (!this.options.vertical && this.options.rtl)
            this.container.addClass('jcarousel-direction-rtl').attr('dir', 'rtl');

        var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.size() > 0) {
            var wh = 0, i = this.options.offset;
            li.each(function() {
                self.format(this, i++);
                wh += self.dimension(this, di);
            });

            this.list.css(this.wh, (wh + 100) + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size === undefined)
                this.options.size = li.size();
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };
        this.funcResize = function() { self.reload(); };

        if (this.options.initCallback != null)
            this.options.initCallback(this, 'init');

        if (!windowLoaded && $.browser.safari) {
            this.buttons(false, false);
            $(window).bind('load.jcarousel', function() { self.setup(); });
        } else
            this.setup();
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.5'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @method setup
         * @return undefined
         */
        setup: function() {
            this.first     = null;
            this.last      = null;
            this.prevFirst = null;
            this.prevLast  = null;
            this.animating = false;
            this.timer     = null;
            this.tail      = null;
            this.inTail    = false;

            if (this.locked)
                return;

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);

            $(window).unbind('resize.jcarousel', this.funcResize).bind('resize.jcarousel', this.funcResize);
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @method reset
         * @return undefined
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '10px');

            if (this.options.initCallback != null)
                this.options.initCallback(this, 'reset');

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @method reload
         * @return undefined
         */
        reload: function() {
            if (this.tail != null && this.inTail)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback != null)
                this.options.reloadCallback(this);

            if (this.options.visible != null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                this.list.children('li').each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first)
                        lt = wh;
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @method lock
         * @return undefined
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @method unlock
         * @return undefined
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @method size
         * @return undefined
         * @param s {Number} The size of the carousel.
         */
        size: function(s) {
            if (s != undefined) {
                this.options.size = s;
                if (!this.locked)
                    this.buttons();
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @method get
         * @return bool
         * @param i {Number} The index of the (first) element.
         * @param i2 {Number} The index of the last element.
         */
        has: function(i, i2) {
            if (i2 == undefined || !i2)
                i2 = i;

            if (this.options.size !== null && i2 > this.options.size)
                i2 = this.options.size;

            for (var j = i; j <= i2; j++) {
                var e = this.get(j);
                if (!e.length || e.hasClass('jcarousel-item-placeholder'))
                    return false;
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @method get
         * @return jQuery
         * @param i {Number} The index of the element.
         */
        get: function(i) {
            return $('.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @method add
         * @return jQuery
         * @param i {Number} The index of the element.
         * @param s {String} The innerHTML of the element.
         */
        add: function(i, s) {
            var e = this.get(i), old = 0, n = $(s);

            if (e.length == 0) {
                var c, e = this.create(i), j = $jc.intval(i);
                while (c = this.get(--j)) {
                    if (j <= 0 || c.length) {
                        j <= 0 ? this.list.prepend(e) : c.after(e);
                        break;
                    }
                }
            } else
                old = this.dimension(e);

            if (n.get(0).nodeName.toUpperCase() == 'LI') {
                e.replaceWith(n);
                e = n;
            } else
                e.empty().append(s);

            this.format(e.removeClass(this.className('jcarousel-item-placeholder')), i);

            var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @method remove
         * @return undefined
         * @param i {Number} The index of the element.
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last))
                return;

            var d = this.dimension(e);

            if (i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },

        /**
         * Moves the carousel forwards.
         *
         * @method next
         * @return undefined
         */
        next: function() {
            this.stopAuto();

            if (this.tail != null && !this.inTail)
                this.scrollTail(false);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size != null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
        },

        /**
         * Moves the carousel backwards.
         *
         * @method prev
         * @return undefined
         */
        prev: function() {
            this.stopAuto();

            if (this.tail != null && this.inTail)
                this.scrollTail(true);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size != null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @method scrollTail
         * @return undefined
         * @param b {Boolean} Whether scroll the tail back or forward.
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail)
                return;

            var pos  = $jc.intval(this.list.css(this.lt));

            !b ? pos -= this.tail : pos += this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @method scroll
         * @return undefined
         * @param i {Number} The index of the element to scoll to.
         * @param a {Boolean} Flag indicating whether to perform animation.
         */
        scroll: function(i, a) {
            if (this.locked || this.animating)
                return;

            this.animate(this.pos(i), a);
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @method pos
         * @return {Number}
         * @param i {Number} The index of the element to scoll to.
         */
        pos: function(i) {
            var pos  = $jc.intval(this.list.css(this.lt));

            if (this.locked || this.animating)
                return pos;

            if (this.options.wrap != 'circular')
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);

            var back = this.first > i;

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0, g;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);

                    if (this.first != null && this.options.wrap == 'circular' && this.options.size !== null && (j <= 0 || j > this.options.size)) {
                        g = this.get(this.index(j));
                        if (g.length)
                            e = this.add(j, g.clone(true));
                    }
                }

                c = e;
                d = this.dimension(e);

                if (p)
                    l += d;

                if (this.first != null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size == null || j <= this.options.size))))
                    pos = back ? pos + d : pos - d;
            }

            // Calculate visible items
            var clipping = this.clipping();
            var cache = [];
            var visible = 0, j = i, v = 0;
            var c = this.get(i - 1);

            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    c.length == 0 ? this.list.prepend(e) : c[back ? 'before' : 'after' ](e);

                    if (this.first != null && this.options.wrap == 'circular' && this.options.size !== null && (j <= 0 || j > this.options.size)) {
                        g = this.get(this.index(j));
                        if (g.length)
                            e = this.add(j, g.clone(true));
                    }
                }

                c = e;
                var d = this.dimension(e);
                if (d == 0) {
                    throw new Error('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                }

                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size)
                    cache.push(e);
                else if (p)
                    l += d;

                v += d;

                if (v >= clipping)
                    break;

                j++;
            }

             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++)
                cache[x].remove();

            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');

                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }

            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size)
                last = this.options.size;

            if (j > last) {
                visible = 0, j = last, v = 0;
                while (++visible) {
                    var e = this.get(j--);
                    if (!e.length)
                        break;
                    v += this.dimension(e);
                    if (v >= clipping)
                        break;
                }
            }

            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1)
                first = 1;

            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }

            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.margin(this.get(last), !this.options.vertical ? 'marginRight' : 'marginBottom');
                if ((v - m) > clipping)
                    this.tail = v - clipping - m;
            }

            // Adjust position
            while (i-- > first)
                pos += this.dimension(this.get(i));

            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },

        /**
         * Animates the carousel to a certain position.
         *
         * @method animate
         * @return undefined
         * @param p {Number} Position to scroll to.
         * @param a {Boolean} Flag indicating whether to perform animation.
         */
        animate: function(p, a) {
            if (this.locked || this.animating)
                return;

            this.animating = true;

            var self = this;
            var scrolled = function() {
                self.animating = false;

                if (p == 0)
                    self.list.css(self.lt,  0);

                if (self.options.wrap == 'circular' || self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size == null || self.last < self.options.size)
                    self.startAuto();

                self.buttons();
                self.notify('onAfterAnimation');

                // This function removes items which are appended automatically for circulation.
                // This prevents the list from growing infinitely.
                if (self.options.wrap == 'circular' && self.options.size !== null)
                    for (var i = self.prevFirst; i <= self.prevLast; i++)
                        if (i !== null && !(i >= self.first && i <= self.last) && (i < 1 || i > self.options.size))
                            self.remove(i);
            };

            this.notify('onBeforeAnimation');

            // Animate
            if (!this.options.animation || a == false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? (this.options.rtl ? {'right': p} : {'left': p}) : {'top': p};
                this.list.animate(o, this.options.animation, this.options.easing, scrolled);
            }
        },

        /**
         * Starts autoscrolling.
         *
         * @method auto
         * @return undefined
         * @param s {Number} Seconds to periodically autoscroll the content.
         */
        startAuto: function(s) {
            if (s != undefined)
                this.options.auto = s;

            if (this.options.auto == 0)
                return this.stopAuto();

            if (this.timer != null)
                return;

            var self = this;
            this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },

        /**
         * Stops autoscrolling.
         *
         * @method stopAuto
         * @return undefined
         */
        stopAuto: function() {
            if (this.timer == null)
                return;

            clearTimeout(this.timer);
            this.timer = null;
        },

        /**
         * Sets the states of the prev/next buttons.
         *
         * @method buttons
         * @return undefined
         */
        buttons: function(n, p) {
            if (n == undefined || n == null) {
                var n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size == null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size != null && this.last >= this.options.size)
                    n = this.tail != null && !this.inTail;
            }

            if (p == undefined || p == null) {
                var p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size != null && this.first == 1)
                    p = this.tail != null && this.inTail;
            }

            var self = this;

            this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent + '.jcarousel', this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
            this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent + '.jcarousel', this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

            if (this.options.buttonNextCallback != null && this.buttonNext.data('jcarouselstate') != n) {
                this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); }).data('jcarouselstate', n);
            }

            if (this.options.buttonPrevCallback != null && (this.buttonPrev.data('jcarouselstate') != p)) {
                this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); }).data('jcarouselstate', p);
            }
        },

        /**
         * Notify callback of a specified event.
         *
         * @method notify
         * @return undefined
         * @param evt {String} The event name
         */
        notify: function(evt) {
            var state = this.prevFirst == null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

            // Load items
            this.callback('itemLoadCallback', evt, state);

            if (this.prevFirst !== this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }

            if (this.prevLast !== this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }

            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },

        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == undefined || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation'))
                return;

            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

            if (!$.isFunction(callback))
                return;

            var self = this;

            if (i1 === undefined)
                callback(self, state, evt);
            else if (i2 === undefined)
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            else {
                for (var i = i1; i <= i2; i++)
                    if (i !== null && !(i >= i3 && i <= i4))
                        this.get(i).each(function() { callback(self, this, i, state, evt); });
            }
        },

        create: function(i) {
            return this.format('<li></li>', i);
        },

        format: function(e, i) {
            var e = $(e), split = e.get(0).className.split(' ');
            for (var j = 0; j < split.length; j++) {
                if (split[j].indexOf('jcarousel-') != -1) {
                    e.removeClass(split[j]);
                }
            }
            e.addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i)).css({
                'float': (this.options.rtl ? 'right' : 'left'),
                'list-style': 'none'
            }).attr('jcarouselindex', i);
            return e;
        },

        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },

        dimension: function(e, d) {
            var el = e.jquery != undefined ? e[0] : e;

            var old = !this.options.vertical ?
                (el.offsetWidth || $jc.intval(this.options.itemFallbackDimension)) + $jc.margin(el, 'marginLeft') + $jc.margin(el, 'marginRight') :
                (el.offsetHeight || $jc.intval(this.options.itemFallbackDimension)) + $jc.margin(el, 'marginTop') + $jc.margin(el, 'marginBottom');

            if (d == undefined || old == d)
                return old;

            var w = !this.options.vertical ?
                d - $jc.margin(el, 'marginLeft') - $jc.margin(el, 'marginRight') :
                d - $jc.margin(el, 'marginTop') - $jc.margin(el, 'marginBottom');

            $(el).css(this.wh, w + 'px');

            return this.dimension(el);
        },

        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },

        index: function(i, s) {
            if (s == undefined)
                s = this.options.size;

            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });

    $jc.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @method defaults
         * @return {Object}
         * @param d {Object} A set of key/value pairs to set as configuration properties.
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        },

        margin: function(e, p) {
            if (!e)
                return 0;

            var el = e.jquery != undefined ? e[0] : e;

            if (p == 'marginRight' && $.browser.safari) {
                var old = {'display': 'block', 'float': 'none', 'width': 'auto'}, oWidth, oWidth2;

                $.swap(el, old, function() { oWidth = el.offsetWidth; });

                old['marginRight'] = 0;
                $.swap(el, old, function() { oWidth2 = el.offsetWidth; });

                return oWidth2 - oWidth;
            }

            return $jc.intval($.css(el, p));
        },

        intval: function(v) {
            v = parseInt(v);
            return isNaN(v) ? 0 : v;
        }
    });

})(jQuery);
;

/**
 * @file
 * A simple jQuery JCarouselThumbs Div Slideshow Rotator.
 */

/**
 * This will set our initial behavior, by starting up each individual slideshow.
 */
Drupal.behaviors.viewsSlideshowJCarouselThumbs = function (context) {
  $('.views_slideshow_jcarouselthumbs_main:not(.viewsSlideshowJCarouselThumbs-processed)', context).addClass('viewsSlideshowJCarouselThumbs-processed').each(function() {
    var fullId = '#' + $(this).attr('id');
    var settings = Drupal.settings.viewsSlideshowJCarouselThumbs[fullId];
    settings.targetId = '#' + $(fullId + " :first").attr('id');
    settings.paused = false;

    settings.opts = {
      speed:settings.speed,
      timeout:parseInt(settings.timeout),
      delay:parseInt(settings.delay),
      sync:settings.sync==1,
      random:settings.random==1,
      pause:false,
      pager:(settings.pager_event == 'hoverIntent') ? null : '#views_slideshow_breakout_teasers_' + settings.id,
      nowrap:parseInt(settings.nowrap),
      pagerAnchorBuilder:(settings.pager_event == 'hoverIntent') ? null : function(idx, slide) { 
        return '#views_slideshow_jcarouselthumbs_div_breakout_teaser_' + settings.id + '_' + idx; 
      },
      after:function(curr, next, opts) {
        // Used for Image Counter.
        if (settings.image_count) {
          $('#views_slideshow_jcarouselthumbs_image_count_' + settings.id + ' span.num').html(opts.currSlide + 1);
          $('#views_slideshow_jcarouselthumbs_image_count_' + settings.id + ' span.total').html(opts.slideCount);
        }
      },
      before:function(current, next) {
        if (settings.fixed_height == 0) {
          //get the height of the current slide
          var $ht = $(this).height();
          //set the container's height to that of the current slide
          $(this).parent().animate({height: $ht});
        }
        var currId = (currId=$(current).attr('id')).substring(currId.lastIndexOf('_')+1)
        var nextId = (nextId=$(next).attr('id')).substring(nextId.lastIndexOf('_')+1)
        $('#views_slideshow_jcarouselthumbs_div_breakout_teaser_' + settings.id + '_' + currId).removeClass('activeSlide');
        $('#views_slideshow_jcarouselthumbs_div_breakout_teaser_' + settings.id + '_' + nextId).addClass('activeSlide');

        //scroll the carousel if necessary        
        var temp = $('#views_slideshow_jcarouselthumbs_div_breakout_teaser_' + settings.id + '_' + nextId);
        var doScroll = false;
        var pos = temp.position();
        var clip = $('#views_slideshow_jcarouselthumbs_breakout_teasers_' + settings.id + ' .jcarousel-clip');
        var posTarget =  $('#views_slideshow_jcarouselthumbs_breakout_teasers_' + settings.id + " .carousel-target");

        if (settings.jcarousel_settings.vertical) {
          var offsetTop = pos.top;
          var itemHeight = temp.height();
          var clipHeight = clip.height();
          var clipTop = posTarget.position().top * -1;
          doScroll = (offsetTop + itemHeight > clipHeight + clipTop|| offsetTop < clipTop)
        } else {
          var offsetLeft = pos.left;
          var itemWidth = temp.width();
          var clipWidth = clip.width();
          var clipLeft = posTarget.position().left * -1;
          doScroll = (offsetLeft + itemWidth > clipWidth + clipLeft || offsetLeft < clipLeft)
        }

        if (doScroll) {
          settings.carousel.scroll(parseInt(nextId)+1,true)
        }
      },
      pagerEvent: (settings.pager_event == 'hoverIntent') ? null : settings.pager_event,
      prev:(settings.controls > 0)?'#views_slideshow_jcarouselthumbs_prev_' + settings.id:null,
      next:(settings.controls > 0)?'#views_slideshow_jcarouselthumbs_next_' + settings.id:null,
      cleartype:eval(settings.ie.cleartype),
      cleartypeNoBg:eval(settings.ie.cleartypenobg)
    };

    if (settings.effect == 'none') {
      settings.opts.speed = 1;
    }
    else {
      settings.opts.fx = settings.effect;
    }
    var jcarousel_settings = {};
    jcarousel_settings.scroll = eval(settings.scroll);
    if (settings.jcarousel_advanced.length > 0 && settings.jcarousel_advanced != "\n") {
      viewsSlideshowAdvancedSettings(settings.jcarousel_advanced, jcarousel_settings);
    }

    settings.jcarousel_settings = jcarousel_settings;

    $('#views_slideshow_jcarouselthumbs_breakout_teasers_' + settings.id + " .carousel-target").jcarousel(
      $.extend({
        initCallback:function(c) {
          settings.carousel = c;
          $(c.buttonNext).click(function() {
            viewsSlideshowJCarouselThumbsPause(settings);
          });
          $(c.buttonPrev).click(function() {
            viewsSlideshowJCarouselThumbsPause(settings);
          });
        }
      }, jcarousel_settings));		

    // Pause on hover.
    if (settings.pause == 1) {
      $('#views_slideshow_jcarouselthumbs_teaser_section_' + settings.id).hover(function() {
        $(settings.targetId).cycle('pause');
      }, function() {
        if (settings.paused == false) {
          $(settings.targetId).cycle('resume');
        }
      });
    }

    // Pause on clicking of the slide.
    if (settings.pause_on_click == 1) {
      $('#views_slideshow_jcarouselthumbs_teaser_section_' + settings.id).click(function() { 
        viewsSlideshowJCarouselThumbsPause(settings);
      });
    }

    // Add additional settings.
    if (settings.advanced.length > 0 && settings.advanced != "\n") {
      viewsSlideshowAdvancedSettings(settings.advanced, settings.opts);
    }

    $(settings.targetId).cycle(settings.opts);

    // Show image count for people who have js enabled.
    $('#views_slideshow_jcarouselthumbs_image_count_' + settings.id).show();


    $('#views_slideshow_jcarouselthumbs_breakout_teasers_' + settings.id + ' .views_slideshow_jcarouselthumbs_div_breakout_teaser').each(function(i,obj) {
      if (settings.pager_event == 'hoverIntent') {
        $(obj).hoverIntent(
          function() {
            $('.views_slideshow_jcarouselthumbs_div_breakout_teaser').removeClass('activeSlide');
            var id = $(this).attr('id');
            id = parseInt(id.substring(id.lastIndexOf('_')+1));
            $(settings.targetId).cycle(id);
            $('#views_slideshow_jcarouselthumbs_div_breakout_teaser_' + settings.id + '_' + id).addClass('activeSlide');
            viewsSlideshowJCarouselThumbsPause(settings);
          },
          function() {
            var id = $(this).attr('id');
            settings.opts.startingSlide = parseInt(id.substring(id.lastIndexOf('_')+1));
            $(settings.targetId).cycle(settings.opts);
          }
        );
      } else {
        $(obj).bind(settings.pager_event, function(e) {
          viewsSlideshowJCarouselThumbsPause(settings);
        });
      }
    });


    if (settings.controls > 0) {
      // Show controls for people who have js enabled browsers.
      $('#views_slideshow_jcarouselthumbs_controls_' + settings.id).show();

      $('#views_slideshow_jcarouselthumbs_playpause_' + settings.id).click(function(e) {
        if (settings.paused) {
          viewsSlideshowJCarouselThumbsResume(settings);
        }
        else {
          viewsSlideshowJCarouselThumbsPause(settings);
        }
        e.preventDefault();
      });
    }
  });
}

viewsSlideshowAdvancedSettings = function(settings, opts) {
  var advanced = settings.split("\n");
  for (var i=0; i<advanced.length; i++) {
    var prop = '';
    var value = '';
    var property = advanced[i].split(":");
    for (j=0; j<property.length; j++) {
      if (j == 0) {
        prop = property[j];
      }
      else if (j == 1) {
        value = property[j];
      }
      else {
        value += ":" + property[j];
      }
    }

    // Need to evaluate so true, false and numerics aren't a string.
    if (value == 'true' || value == 'false' || IsNumeric(value)) {
      value = eval(value);
    }
    else {
      // Parse strings into functions.
      var func = value.match(/function\s*\((.*?)\)\s*\{(.*)\}/i);
      if (func) {
        value = new Function(func[1].match(/(\w+)/g), func[2]);
      }
    }

    // Call both functions if prop was set previously.
    if (typeof(value) == "function" && prop in opts) {
      var callboth = function(before_func, new_func) {
        return function() {
          before_func.apply(null, arguments);
          new_func.apply(null, arguments);
        };
      };
      opts[prop] = callboth(opts[prop], value);
    }
    else {
      opts[prop] = value;
    }
  }
  return opts;
}

// Pause the slideshow 
viewsSlideshowJCarouselThumbsPause = function (settings) {
  $(settings.targetId).cycle('pause');
  if (settings.controls > 0) {
    $('#views_slideshow_jcarouselthumbs_playpause_' + settings.id)
      .addClass('views_slideshow_jcarouselthumbs_play')
      .addClass('views_slideshow_play')
      .removeClass('views_slideshow_jcarouselthumbs_pause')
      .removeClass('views_slideshow_pause')
      .text('Resume');
  }
  settings.paused = true;
}

// Resume the slideshow
viewsSlideshowJCarouselThumbsResume = function (settings) {
  $(settings.targetId).cycle('resume');
  if (settings.controls > 0) {
    $('#views_slideshow_jcarouselthumbs_playpause_' + settings.id)
      .addClass('views_slideshow_jcarouselthumbs_pause')
      .addClass('views_slideshow_pause')
      .removeClass('views_slideshow_jcarouselthumbs_play')
      .removeClass('views_slideshow_play')
      .text('Pause');
  }
  settings.paused = false;
}

// Verify that the value is a number.
function IsNumeric(sText) {
  var ValidChars = "0123456789";
  var IsNumber=true;
  var Char;

  for (i=0; i < sText.length && IsNumber == true; i++) { 
    Char = sText.charAt(i); 
    if (ValidChars.indexOf(Char) == -1) {
      IsNumber = false;
    }
  }
  return IsNumber;
}
;
// $Id: extlink.js,v 1.4.2.12 2010/05/26 01:25:56 quicksketch Exp $
(function ($) {

function extlinkAttach(context) {
  // Strip the host name down, removing ports, subdomains, or www.
  var pattern = /^(([^\/:]+?\.)*)([^\.:]{4,})((\.[a-z]{1,4})*)(:[0-9]{1,5})?$/;
  var host = window.location.host.replace(pattern, '$3$4');
  var subdomain = window.location.host.replace(pattern, '$1');

  // Determine what subdomains are considered internal.
  if (Drupal.settings.extlink.extSubdomains) {
    var subdomains = "([^/]*\\.)?";
  }
  else if (subdomain == 'www.' || subdomain == '') {
    var subdomains = "(www\\.)?";
  }
  else {
    var subdomains = subdomain.replace(".", "\\.");
  }

  // Build regular expressions that define an internal link.
  var internal_link = new RegExp("^https?://" + subdomains + host, "i");

  // Extra internal link matching.
  var extInclude = false;
  if (Drupal.settings.extlink.extInclude) {
    extInclude = new RegExp(Drupal.settings.extlink.extInclude.replace(/\\/, '\\'));
  }

  // Extra external link matching.
  var extExclude = false;
  if (Drupal.settings.extlink.extExclude) {
    extExclude = new RegExp(Drupal.settings.extlink.extExclude.replace(/\\/, '\\'));
  }

  // Find all links which are NOT internal and begin with http (as opposed
  // to ftp://, javascript:, etc. other kinds of links.
  // When operating on the 'this' variable, the host has been appended to
  // all links by the browser, even local ones.
  // In jQuery 1.1 and higher, we'd use a filter method here, but it is not
  // available in jQuery 1.0 (Drupal 5 default).
  var external_links = new Array();
  var mailto_links = new Array();
  $("a:not(." + Drupal.settings.extlink.extClass + ", ." + Drupal.settings.extlink.mailtoClass + ")", context).each(function(el) {
    try {
      var url = this.href.toLowerCase();
      if (url.indexOf('http') == 0 && (!url.match(internal_link) || (extInclude && url.match(extInclude))) && !(extExclude && url.match(extExclude))) {
        external_links.push(this);
      }
      else if (url.indexOf('mailto:') == 0) {
        mailto_links.push(this);
      }
    }
    // IE7 throws errors often when dealing with irregular links, such as:
    // <a href="node/10"></a> Empty tags.
    // <a href="http://user:pass@example.com">example</a> User:pass syntax.
    catch(error) {
      return false;
    }
  });

  if (Drupal.settings.extlink.extClass) {
    // Apply the "ext" class to all links not containing images.
    if (parseFloat($().jquery) < 1.2) {
      $(external_links).not('[img]').addClass(Drupal.settings.extlink.extClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.extClass + '></span>'); });
    }
    else {
      $(external_links).not($(external_links).find('img').parents('a')).addClass(Drupal.settings.extlink.extClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.extClass + '></span>'); });
    }
  }

  if (Drupal.settings.extlink.mailtoClass) {
    // Apply the "mailto" class to all mailto links not containing images.
    if (parseFloat($().jquery) < 1.2) {
      $(mailto_links).not('[img]').addClass(Drupal.settings.extlink.mailtoClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.mailtoClass + '></span>'); });
    }
    else {
      $(mailto_links).not($(mailto_links).find('img').parents('a')).addClass(Drupal.settings.extlink.mailtoClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.mailtoClass + '></span>'); });
    }
  }

  if (Drupal.settings.extlink.extTarget) {
    // Apply the target attribute to all links.
    $(external_links).attr('target', Drupal.settings.extlink.extTarget);
  }

  if (Drupal.settings.extlink.extAlert) {
    // Add pop-up click-through dialog.
    $(external_links).click(function(e) {
     return confirm(Drupal.settings.extlink.extAlertText);
    });
  }

  // Work around for Internet Explorer box model problems.
  if (($.support && !($.support.boxModel === undefined) && !$.support.boxModel) || ($.browser.msie && parseInt($.browser.version) <= 7)) {
    $('span.ext, span.mailto').css('display', 'inline-block');
  }
}

Drupal.behaviors.extlink = function(context) {
  extlinkAttach(context);
}

})(jQuery);
;
// $Id: ajax-responder.js,v 1.18.2.24 2010/08/27 22:09:48 merlinofchaos Exp $
/**
 * @file
 *
 * CTools flexible AJAX responder object.
 */

(function ($) {
  Drupal.CTools = Drupal.CTools || {};
  Drupal.CTools.AJAX = Drupal.CTools.AJAX || {};
  Drupal.CTools.AJAX.commands = Drupal.CTools.AJAX.commands || {};
  Drupal.CTools.AJAX.commandCache = Drupal.CTools.AJAX.comandCache || {} ;
  Drupal.CTools.AJAX.scripts = {};
  Drupal.CTools.AJAX.css = {};

  /**
   * Success callback for an ajax request.
   *
   * This function expects to receive a packet of data from a JSON object
   * which is essentially a list of commands. Each commands must have a
   * 'command' setting and this setting must resolve to a function in the
   * Drupal.CTools.AJAX.commands space.
   */
  Drupal.CTools.AJAX.respond = function(data) {
    for (i in data) {
      if (data[i]['command'] && Drupal.CTools.AJAX.commands[data[i]['command']]) {
        Drupal.CTools.AJAX.commands[data[i]['command']](data[i]);
      }
    }
  };

  /**
   * Grab the response from the server and store it.
   */
  Drupal.CTools.AJAX.warmCache = function () {
    // Store this expression for a minor speed improvement.
    $this = $(this);
    var old_url = $this.attr('href');
    // If we are currently fetching, or if we have fetched this already which is
    // ideal for things like pagers, where the previous page might already have
    // been seen in the cache.
    if ($this.hasClass('ctools-fetching') || Drupal.CTools.AJAX.commandCache[old_url]) {
      return false;
    }

    // Grab all the links that match this url and add the fetching class.
    // This allows the caching system to grab each url once and only once
    // instead of grabbing the url once per <a>.
    var $objects = $('a[href=' + old_url + ']')
    $objects.addClass('ctools-fetching');
    try {
      url = old_url.replace(/\/nojs(\/|$)/g, '/ajax$1');
      $.ajax({
        type: "POST",
        url: url,
        data: { 'js': 1, 'ctools_ajax': 1},
        global: true,
        success: function (data) {
          Drupal.CTools.AJAX.commandCache[old_url] = data;
          $objects.addClass('ctools-cache-warmed').trigger('ctools-cache-warm', [data]);
        },
        complete: function() {
          $objects.removeClass('ctools-fetching');
        },
        dataType: 'json'
      });
    }
    catch (err) {
      $objects.removeClass('ctools-fetching');
      return false;
    }

    return false;
  };

  /**
   * Cachable click handler to fetch the commands out of the cache or from url.
   */
  Drupal.CTools.AJAX.clickAJAXCacheLink = function () {
    $this = $(this);
    if ($this.hasClass('ctools-fetching')) {
      $this.bind('ctools-cache-warm', function (event, data) {
        Drupal.CTools.AJAX.respond(data);
      });
      return false;
    }
    else {
      if ($this.hasClass('ctools-cache-warmed') && Drupal.CTools.AJAX.commandCache[$this.attr('href')]) {
        Drupal.CTools.AJAX.respond(Drupal.CTools.AJAX.commandCache[$this.attr('href')]);
        return false;
      }
      else {
        return Drupal.CTools.AJAX.clickAJAXLink.apply(this);
      }
    }
  };

  /**
   * Generic replacement click handler to open the modal with the destination
   * specified by the href of the link.
   */
  Drupal.CTools.AJAX.clickAJAXLink = function() {
    if ($(this).hasClass('ctools-ajaxing')) {
      return false;
    }

    var url = $(this).attr('href');
    var object = $(this);
    $(this).addClass('ctools-ajaxing');
    try {
      url = url.replace(/\/nojs(\/|$)/g, '/ajax$1');
      $.ajax({
        type: "POST",
        url: url,
        data: { 'js': 1, 'ctools_ajax': 1},
        global: true,
        success: Drupal.CTools.AJAX.respond,
        error: function(xhr) {
          Drupal.CTools.AJAX.handleErrors(xhr, url);
        },
        complete: function() {
          $('.ctools-ajaxing').removeClass('ctools-ajaxing');
        },
        dataType: 'json'
      });
    }
    catch (err) {
      alert("An error occurred while attempting to process " + url);
      $('.ctools-ajaxing').removeClass('ctools-ajaxing');
      return false;
    }

    return false;
  };

  /**
   * Generic replacement click handler to open the modal with the destination
   * specified by the href of the link.
   */
  Drupal.CTools.AJAX.clickAJAXButton = function() {
    if ($(this).hasClass('ctools-ajaxing')) {
      return false;
    }

    // Put our button in.
    this.form.clk = this;

    var url = Drupal.CTools.AJAX.findURL(this);
    $(this).addClass('ctools-ajaxing');
    var object = $(this);
    try {
      if (url) {
        url = url.replace(/\/nojs(\/|$)/g, '/ajax$1');
        $.ajax({
          type: "POST",
          url: url,
          data: { 'js': 1, 'ctools_ajax': 1},
          global: true,
          success: Drupal.CTools.AJAX.respond,
          error: function(xhr) {
            Drupal.CTools.AJAX.handleErrors(xhr, url);
          },
          complete: function() {
            $('.ctools-ajaxing').removeClass('ctools-ajaxing');
          },
          dataType: 'json'
        });
      }
      else {
        var form = this.form;
        url = $(form).attr('action');
        setTimeout(function() { Drupal.CTools.AJAX.ajaxSubmit(form, url); }, 1);
      }
    }
    catch (err) {
      alert("An error occurred while attempting to process " + url);
      $(this).removeClass('ctools-ajaxing');
      return false;
    }
    return false;
  };

  /**
   * Event handler to submit an AJAX form.
   *
   * Using a secondary event ensures that our form submission is last, which
   * is needed when submitting wysiwyg controlled forms, for example.
   */
  Drupal.CTools.AJAX.ajaxSubmit = function (form, url) {
    $form = $(form);

    if ($form.hasClass('ctools-ajaxing')) {
      return false;
    }

    $form.addClass('ctools-ajaxing');

    try {
      url = url.replace(/\/nojs(\/|$)/g, '/ajax$1');

      var ajaxOptions = {
        type: 'POST',
        url: url,
        data: { 'js': 1, 'ctools_ajax': 1},
        global: true,
        success: Drupal.CTools.AJAX.respond,
        error: function(xhr) {
          Drupal.CTools.AJAX.handleErrors(xhr, url);
        },
        complete: function() {
          $('.ctools-ajaxing').removeClass('ctools-ajaxing');
          $('div.ctools-ajaxing-temporary').remove();
        },
        dataType: 'json'
      };

      // If the form requires uploads, use an iframe instead and add data to
      // the submit to support this and use the proper response.
      if ($form.attr('enctype') == 'multipart/form-data') {
        $form.append('<input type="hidden" name="ctools_multipart" value="1">');
        ajaxIframeOptions = {
          success: Drupal.CTools.AJAX.iFrameJsonRespond,
          iframe: true
        };
        ajaxOptions = $.extend(ajaxOptions, ajaxIframeOptions);
      }

      $form.ajaxSubmit(ajaxOptions);
    }
    catch (err) {
      alert("An error occurred while attempting to process " + url);
      $('.ctools-ajaxing').removeClass('ctools-ajaxing');
      $('div.ctools-ajaxing-temporary').remove();
      return false;
    }
  };

  /**
   * Wrapper for handling JSON responses from an iframe submission
   */
  Drupal.CTools.AJAX.iFrameJsonRespond = function(data) {
    var myJson = eval(data);
    Drupal.CTools.AJAX.respond(myJson);
  }

  /**
   * Display error in a more fashion way
   */
  Drupal.CTools.AJAX.handleErrors = function(xhr, path) {
    var error_text = '';

    if ((xhr.status == 500 && xhr.responseText) || xhr.status == 200) {
      error_text = xhr.responseText;

      // Replace all &lt; and &gt; by < and >
      error_text = error_text.replace("/&(lt|gt);/g", function (m, p) {
        return (p == "lt")? "<" : ">";
      });

      // Now, replace all html tags by empty spaces
      error_text = error_text.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,"");

      // Fix end lines
      error_text = error_text.replace(/[\n]+\s+/g,"\n");
    }
    else if (xhr.status == 500) {
      error_text = xhr.status + ': ' + Drupal.t("Internal server error. Please see server or PHP logs for error information.");
    }
    else {
      error_text = xhr.status + ': ' + xhr.statusText;
    }

    alert(Drupal.t("An error occurred at @path.\n\nError Description: @error", {'@path': path, '@error': error_text}));
  }

  /**
   * Generic replacement for change handler to execute ajax method.
   */
  Drupal.CTools.AJAX.changeAJAX = function () {
    if ($(this).hasClass('ctools-ajaxing')) {
      return false;
    }

    var url = Drupal.CTools.AJAX.findURL(this);
    $(this).addClass('ctools-ajaxing');
    var object = $(this);
    var form_id = $(object).parents('form').get(0).id;
    try {
      if (url) {
        url = url.replace(/\/nojs(\/|$)/g, '/ajax$1');
        $.ajax({
          type: "POST",
          url: url,
          data: {'ctools_changed': $(this).val(), 'js': 1, 'ctools_ajax': 1 },
          global: true,
          success: Drupal.CTools.AJAX.respond,
          error: function(xhr) {
            Drupal.CTools.AJAX.handleErrors(xhr, url);
          },
          complete: function() {
            $('.ctools-ajaxing').removeClass('ctools-ajaxing');
            if ($(object).hasClass('ctools-ajax-submit-onchange')) {
              $('form#' + form_id).submit();
            }
          },
          dataType: 'json'
        });
      }
      else {
        if ($(object).hasClass('ctools-ajax-submit-onchange')) {
          $('form#' + form_id).submit();
        }
        return false;
      }
    }
    catch (err) {
      alert("An error occurred while attempting to process " + url);
      $('.ctools-ajaxing').removeClass('ctools-ajaxing');
      return false;
    }
    return false;
  };

  /**
   * Find a URL for an AJAX button.
   *
   * The URL for this gadget will be composed of the values of items by
   * taking the ID of this item and adding -url and looking for that
   * class. They need to be in the form in order since we will
   * concat them all together using '/'.
   */
  Drupal.CTools.AJAX.findURL = function(item) {
    var url = '';
    var url_class = '.' + $(item).attr('id') + '-url';
    $(url_class).each(
      function() {
        if (url && $(this).val()) {
          url += '/';
        }
        url += $(this).val();
      });
    return url;
  };

  Drupal.CTools.AJAX.getPath = function (link) {
    if (!link) {
      return;
    }

    var index = link.indexOf('?');
    if (index != -1) {
      link = link.substr(0, index);
    }

    return link;
  }

  Drupal.CTools.AJAX.commands.prepend = function(data) {
    $(data.selector).prepend(data.data);
    Drupal.attachBehaviors($(data.selector));
  };

  Drupal.CTools.AJAX.commands.append = function(data) {
    $(data.selector).append(data.data);
    Drupal.attachBehaviors($(data.selector));
  };

  Drupal.CTools.AJAX.commands.replace = function(data) {
    $(data.selector).replaceWith(data.data);
    Drupal.attachBehaviors($(data.selector));
  };

  Drupal.CTools.AJAX.commands.after = function(data) {
    var object = $(data.data);
    $(data.selector).after(object);
    Drupal.attachBehaviors(object);
  };

  Drupal.CTools.AJAX.commands.before = function(data) {
    var object = $(data.data);
    $(data.selector).before(object);
    Drupal.attachBehaviors(object);
  };

  Drupal.CTools.AJAX.commands.html = function(data) {
    $(data.selector).html(data.data);
    Drupal.attachBehaviors($(data.selector));
  };

  Drupal.CTools.AJAX.commands.remove = function(data) {
    $(data.selector).remove();
  };

  Drupal.CTools.AJAX.commands.changed = function(data) {
    if (!$(data.selector).hasClass('changed')) {
      $(data.selector).addClass('changed');
      if (data.star) {
        $(data.selector).find(data.star).append(' <span class="star">*</span> ');
      }
    }
  };

  Drupal.CTools.AJAX.commands.alert = function(data) {
    alert(data.text, data.title);
  };

  Drupal.CTools.AJAX.commands.css = function(data) {
  /*
    if (data.selector && data.selector.contains('* html ')) {
      // This indicates an IE hack and we should only do it if we are IE.
      if (!jQuery.browser.msie) {
        return;
      }
      data.selector = data.selector.replace('* html ', '');
    }
  */
    $(data.selector).css(data.argument);
  };

  Drupal.CTools.AJAX.commands.css_files = function(data) {
    // Build a list of css files already loaded:
    $('link:not(.ctools-temporary-css)').each(function () {
      if ($(this).attr('type') == 'text/css') {
        var link = Drupal.CTools.AJAX.getPath($(this).attr('href'));
        if (link) {
          Drupal.CTools.AJAX.css[link] = $(this).attr('href');
        }
      }
    });

    var html = '';
    for (i in data.argument) {
      var link = Drupal.CTools.AJAX.getPath(data.argument[i].file);
      if (!Drupal.CTools.AJAX.css[link]) {
        html += '<link class="ctools-temporary-css" type="text/css" rel="stylesheet" media="' + data.argument[i].media +
          '" href="' + data.argument[i].file + '" />';
      }
    }

    if (html) {
      $('link.ctools-temporary-css').remove();
      $('body').append($(html));
    }
  };

  Drupal.CTools.AJAX.commands.settings = function(data) {
    $.extend(Drupal.settings, data.argument);
  };

  Drupal.CTools.AJAX.commands.scripts = function(data) {
    // Build a list of scripts already loaded:
    var scripts = {};
    $('script').each(function () {
      var link = Drupal.CTools.AJAX.getPath($(this).attr('src'));
      if (link) {
        Drupal.CTools.AJAX.scripts[link] = $(this).attr('src');
      }
    });

    var html = '';
    var head = document.getElementsByTagName('head')[0];
    for (i in data.argument) {
      var link = Drupal.CTools.AJAX.getPath(data.argument[i]);
      if (!Drupal.CTools.AJAX.scripts[link]) {
        Drupal.CTools.AJAX.scripts[link] = link;
        // Use this to actually get the script tag into the dom, which is
        // needed for scripts that self-reference to determine paths.
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = data.argument[i];
        head.appendChild(script);
        html += '<script type="text/javascript" src="' + data.argument[i] + '"></script>';
      }
    }

    if (html) {
      $('body').append($(html));
    }
  };

  Drupal.CTools.AJAX.commands.data = function(data) {
    $(data.selector).data(data.name, data.value);
  };

  Drupal.CTools.AJAX.commands.attr = function(data) {
    $(data.selector).attr(data.name, data.value);
  };

  Drupal.CTools.AJAX.commands.restripe = function(data) {
    // :even and :odd are reversed because jquery counts from 0 and
    // we count from 1, so we're out of sync.
    $('tbody tr:not(:hidden)', $(data.selector))
      .removeClass('even')
      .removeClass('odd')
      .filter(':even')
        .addClass('odd')
      .end()
      .filter(':odd')
        .addClass('even');
  };

  Drupal.CTools.AJAX.commands.redirect = function(data) {
    if (data.delay > 0) {
      setTimeout(function () {
        location.href = data.url;
      }, data.delay);
    }
    else {
      location.href = data.url;
    }
  };

  Drupal.CTools.AJAX.commands.reload = function(data) {
    location.reload();
  };

  Drupal.CTools.AJAX.commands.submit = function(data) {
    $(data.selector).submit();
  }


  /**
   * Bind links that will open modals to the appropriate function.
   */
  Drupal.behaviors.CToolsAJAX = function(context) {
    // Bind links

    // Note that doing so in this order means that the two classes can be
    // used together safely.
    $('a.ctools-use-ajax-cache:not(.ctools-use-ajax-processed)', context)
      .addClass('ctools-use-ajax-processed')
      .click(Drupal.CTools.AJAX.clickAJAXCacheLink)
      .each(function () {
        Drupal.CTools.AJAX.warmCache.apply(this);
      });

    $('a.ctools-use-ajax:not(.ctools-use-ajax-processed)', context)
      .addClass('ctools-use-ajax-processed')
      .click(Drupal.CTools.AJAX.clickAJAXLink);


    // Bind buttons
    $('input.ctools-use-ajax:not(.ctools-use-ajax-processed), button.ctools-use-ajax:not(.ctools-use-ajax-processed)', context)
      .addClass('ctools-use-ajax-processed')
      .click(Drupal.CTools.AJAX.clickAJAXButton);

    // Bind select
    $('select, input:text, input:radio, input:checkbox', context)
       .filter('.ctools-use-ajax-onchange:not(.ctools-use-ajax-processed)')
       .addClass('ctools-use-ajax-processed')
       .change(Drupal.CTools.AJAX.changeAJAX);

    // Add information about loaded CSS and JS files.
    if (Drupal.settings.CToolsAJAX && Drupal.settings.CToolsAJAX.css) {
      $.extend(Drupal.CTools.AJAX.css, Drupal.settings.CToolsAJAX.css);
    }
    if (Drupal.settings.CToolsAJAX && Drupal.settings.CToolsAJAX.scripts) {
      $.extend(Drupal.CTools.AJAX.scripts, Drupal.settings.CToolsAJAX.scripts);
    }
  };
})(jQuery);
;
// $Id: boxes.js,v 1.2.2.4 2010/08/05 20:16:28 yhahn Exp $

Drupal.behaviors.boxes = function(context) {
  Drupal.CTools.AJAX.commands.getBlock = function(data) {
    $.ajax({
      type: "GET",
      url: data.url,
      data: { 'boxes_delta': data.delta },
      global: true,
      success: Drupal.CTools.AJAX.respond,
      error: function(xhr) {
        Drupal.CTools.AJAX.handleErrors(xhr, url);
      },
      dataType: 'json'
    });
  };
  $('div.boxes-box-controls a:not(.boxes-processed)')
    .addClass('boxes-processed')
    .click(function() {
      var box = $(this).parents('.boxes-box');
      if (box.is('.boxes-box-editing')) {
        box.removeClass('boxes-box-editing').find('.box-editor').remove().end().find('.boxes-box-content').show();
      }
      else {
        // Show editing form - the form itself gets loaded via CTools ajax..
        box.find('.boxes-box-content').hide().end().addClass('boxes-box-editing').append('<div class="box-editor"><div class="swirly"></div></div>');
      }
      return false;
    });
  $('.boxes-ajax').click(function() {
      if ($(this).hasClass('boxes-ajaxing')) {
        return false;
      }
      // Put our button in.
      this.form.clk = this;
      var object = $(this), form = this.form, url = $(form).attr('action');
      $(this).addClass('boxes-ajaxing').parents('.box-editor').html('<div class="swirly"></div>').end();
      $(form).ajaxSubmit({
        type: "POST",
        url: url,
        data: { 'js': 1, 'ctools_ajax': 1 },
        global: true,
        success: Drupal.CTools.AJAX.respond,
        error: function(xhr) {
          Drupal.CTools.AJAX.handleErrors(xhr, url);
        },
        complete: function() {
          object.removeClass('boxes-ajaxing');
        },
        dataType: 'json'
      });
      return false;
  });

  Drupal.CTools.AJAX.commands.preReplaceContextBlock = function(data) {
    Drupal.settings.boxes = Drupal.settings.boxes || {};
    var e = $('#' + data.id + ' a.context-block:first').clone();
    Drupal.settings.boxes[data.id] =  e;
  };

  Drupal.CTools.AJAX.commands.postReplaceContextBlock = function(data) {
    $('#' + data.id).append(Drupal.settings.boxes[data.id]);
    $('form.context-editor.context-editing').each(function() {
      var id = $(this).attr('id');
      if (Drupal.contextBlockEditor[id]) {
        Drupal.contextBlockEditor[id].initBlocks($('#' + data.id));
      }
    });
  };
};

;

/*
 * jQuery Form Plugin
 * version: 2.01 (10/31/2007)
 * @requires jQuery v1.1 or later
 *
 * Examples at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
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}('(5($){$.7.1j=5(o){2(P o==\'5\')o={L:o};o=$.2h({1h:4.X(\'2i\')||1E.2u.3D(),I:4.X(\'2g\')||\'29\'},o||{});3 p={};$.M.N(\'R.2P.2L\',[4,o,p]);2(p.1Q)6 4;3 a=4.1z(o.2r);2(o.V){H(3 n 3u o.V)a.C({z:n,A:o.V[n]})}2(o.28&&o.28(a,4,o)===E)6 4;$.M.N(\'R.K.36\',[a,4,o,p]);2(p.1Q)6 4;3 q=$.1x(a);2(o.I.31()==\'29\'){o.1h+=(o.1h.2Z(\'?\')>=0?\'&\':\'?\')+q;o.V=B}8 o.V=q;3 r=4,U=[];2(o.1r)U.C(5(){r.1r()});2(o.1o)U.C(5(){r.1o()});2(!o.18&&o.14){3 u=o.L||5(){};U.C(5(a){2(4.1N)$(o.14).X("1M",a).1N().D(u,1L);8 $(o.14).2t(a).D(u,1L)})}8 2(o.L)U.C(o.L);o.L=5(a,b){H(3 i=0,F=U.G;i<F;i++)U[i](a,b,r)};3 v=$(\'19:3v\',4).15();3 w=E;H(3 j=0;j<v.G;j++)2(v[j])w=T;2(o.2f||w){2($.1i.3o&&o.2a)$.3l(o.2a,1l);8 1l()}8 $.3h(o);$.M.N(\'R.K.3f\',[4,o]);6 4;5 1l(){3 d=r[0];3 f=$.2h({},$.39,o);3 h=\'35\'+$.7.1j.1a++;3 i=$(\'<2f 33="\'+h+\'" z="\'+h+\'" />\');3 j=i[0];3 k=$.1i.20&&1E.20.30()<9;2($.1i.1X||k)j.2Y=\'2W:E;1w.2U("");\';i.2S({2R:\'2Q\',23:\'-24\',1R:\'-24\'});3 l={Z:B,1b:B,2K:0,2J:\'n/a\',2H:5(){},2F:5(){},2E:5(){}};3 g=f.2B;2(g&&!$.1O++)$.M.N("2x");2(g)$.M.N("2w",[l,f]);3 m=0;3 n=0;1f(5(){i.2v(\'1n\');j.1K?j.1K(\'1J\',12):j.2s(\'1I\',12,E);3 a=d.1H?\'1H\':\'2q\';3 t=r.X(\'14\');r.X({14:h,2g:\'3C\',2i:f.1h});d[a]=\'3B/R-V\';2(f.1G)1f(5(){n=T;12()},f.1G);d.K();r.X(\'14\',t)},10);5 12(){2(m++)6;j.2o?j.2o(\'1J\',12):j.3A(\'1I\',12,E);3 a=T;3z{2(n)3x\'1G\';3 b,O;O=j.2n?j.2n.1w:j.2l?j.2l:j.1w;l.Z=O.1n?O.1n.1M:B;l.1b=O.2k?O.2k:O;2(f.18==\'2j\'||f.18==\'3s\'){3 c=O.1D(\'1C\')[0];b=c?c.A:l.Z;2(f.18==\'2j\')3r("V = "+b);8 $.3q(b)}8 2(f.18==\'2m\'){b=l.1b;2(!b&&l.Z!=B)b=2d(l.Z)}8{b=l.Z}}3p(e){a=E;$.3n(f,l,\'2b\',e)}2(a){f.L(b,\'L\');2(g)$.M.N("3m",[l,f])}2(g)$.M.N("3k",[l,f]);2(g&&!--$.1O)$.M.N("3j");2(f.27)f.27(l,a?\'L\':\'2b\');1f(5(){i.3i();l.1b=B},3g)};5 2d(s,a){2(1E.26){a=25 26(\'3d.3c\');a.3b=\'E\';a.3a(s)}8 a=(25 38()).37(s,\'1A/2m\');6(a&&a.22&&a.22.1e!=\'34\')?a:B}}};$.7.1j.1a=0;$.7.W=5(a){6 4.21().K(1m).D(5(){4.1u=$.7.W.1a++;$.7.W.1t[4.1u]=a;$(":K,19:Y",4).1Z(1s)})};$.7.W.1a=1;$.7.W.1t={};5 1s(e){3 a=4.R;a.Q=4;2(4.I==\'Y\'){2(e.1Y!=S){a.11=e.1Y;a.16=e.2X}8 2(P $.7.1U==\'5\'){3 b=$(4).1U();a.11=e.1V-b.1R;a.16=e.1W-b.23}8{a.11=e.1V-4.2V;a.16=e.1W-4.32}}1f(5(){a.Q=a.11=a.16=B},10)};5 1m(){3 a=4.1u;3 b=$.7.W.1t[a];$(4).1j(b);6 E};$.7.21=5(){4.1T(\'K\',1m);6 4.D(5(){$(":K,19:Y",4).1T(\'1Z\',1s)})};$.7.1z=5(b){3 a=[];2(4.G==0)6 a;3 c=4[0];3 d=b?c.1D(\'*\'):c.2T;2(!d)6 a;H(3 i=0,F=d.G;i<F;i++){3 e=d[i];3 n=e.z;2(!n)1v;2(b&&c.Q&&e.I=="Y"){2(!e.1d&&c.Q==e)a.C({z:n+\'.x\',A:c.11},{z:n+\'.y\',A:c.16});1v}3 v=$.15(e,T);2(v&&v.1c==1g){H(3 j=0,1S=v.G;j<1S;j++)a.C({z:n,A:v[j]})}8 2(v!==B&&P v!=\'S\')a.C({z:n,A:v})}2(!b&&c.Q){3 f=c.1D("19");H(3 i=0,F=f.G;i<F;i++){3 g=f[i];3 n=g.z;2(n&&!g.1d&&g.I=="Y"&&c.Q==g)a.C({z:n+\'.x\',A:c.11},{z:n+\'.y\',A:c.16})}}6 a};$.7.2O=5(a){6 $.1x(4.1z(a))};$.7.2N=5(b){3 a=[];4.D(5(){3 n=4.z;2(!n)6;3 v=$.15(4,b);2(v&&v.1c==1g){H(3 i=0,F=v.G;i<F;i++)a.C({z:n,A:v[i]})}8 2(v!==B&&P v!=\'S\')a.C({z:4.z,A:v})});6 $.1x(a)};$.7.15=5(a){H(3 b=[],i=0,F=4.G;i<F;i++){3 c=4[i];3 v=$.15(c,a);2(v===B||P v==\'S\'||(v.1c==1g&&!v.G))1v;v.1c==1g?$.3e(b,v):b.C(v)}6 b};$.15=5(b,c){3 n=b.z,t=b.I,13=b.1e.1F();2(P c==\'S\')c=T;2(c&&(!n||b.1d||t==\'17\'||t==\'2M\'||(t==\'1q\'||t==\'1B\')&&!b.1p||(t==\'K\'||t==\'Y\')&&b.R&&b.R.Q!=b||13==\'J\'&&b.1y==-1))6 B;2(13==\'J\'){3 d=b.1y;2(d<0)6 B;3 a=[],1k=b.2I;3 e=(t==\'J-2e\');3 f=(e?d+1:1k.G);H(3 i=(e?d:0);i<f;i++){3 g=1k[i];2(g.2c){3 v=$.1i.1X&&!(g.2G[\'A\'].3t)?g.1A:g.A;2(e)6 v;a.C(v)}}6 a}6 b.A};$.7.1o=5(){6 4.D(5(){$(\'19,J,1C\',4).2p()})};$.7.2p=$.7.2D=5(){6 4.D(5(){3 t=4.I,13=4.1e.1F();2(t==\'1A\'||t==\'3w\'||13==\'1C\')4.A=\'\';8 2(t==\'1q\'||t==\'1B\')4.1p=E;8 2(13==\'J\')4.1y=-1})};$.7.1r=5(){6 4.D(5(){2(P 4.17==\'5\'||(P 4.17==\'2C\'&&!4.17.3y))4.17()})};$.7.2A=5(b){2(b==S)b=T;6 4.D(5(){4.1d=!b})};$.7.J=5(b){2(b==S)b=T;6 4.D(5(){3 t=4.I;2(t==\'1q\'||t==\'1B\')4.1p=b;8 2(4.1e.1F()==\'1P\'){3 a=$(4).2z(\'J\');2(b&&a[0]&&a[0].I==\'J-2e\'){a.2y(\'1P\').J(E)}4.2c=b}})}})(3E);',62,227,'||if|var|this|function|return|fn|else|||||||||||||||||||||||||||name|value|null|push|each|false|max|length|for|type|select|submit|success|event|trigger|doc|typeof|clk|form|undefined|true|callbacks|data|ajaxForm|attr|image|responseText||clk_x|cb|tag|target|fieldValue|clk_y|reset|dataType|input|counter|responseXML|constructor|disabled|tagName|setTimeout|Array|url|browser|ajaxSubmit|ops|fileUpload|submitHandler|body|clearForm|checked|checkbox|resetForm|clickHandler|optionHash|formPluginId|continue|document|param|selectedIndex|formToArray|text|radio|textarea|getElementsByTagName|window|toLowerCase|timeout|encoding|load|onload|attachEvent|arguments|innerHTML|evalScripts|active|option|veto|left|jmax|unbind|offset|pageX|pageY|msie|offsetX|click|opera|ajaxFormUnbind|documentElement|top|1000px|new|ActiveXObject|complete|beforeSubmit|GET|closeKeepAlive|error|selected|toXml|one|iframe|method|extend|action|json|XMLDocument|contentDocument|xml|contentWindow|detachEvent|clearFields|enctype|semantic|addEventListener|html|location|appendTo|ajaxSend|ajaxStart|find|parent|enable|global|object|clearInputs|setRequestHeader|getResponseHeader|attributes|getAllResponseHeaders|options|statusText|status|serialize|button|fieldSerialize|formSerialize|pre|absolute|position|css|elements|write|offsetLeft|javascript|offsetY|src|indexOf|version|toUpperCase|offsetTop|id|parsererror|jqFormIO|validate|parseFromString|DOMParser|ajaxSettings|loadXML|async|XMLDOM|Microsoft|merge|notify|100|ajax|remove|ajaxStop|ajaxComplete|get|ajaxSuccess|handleError|safari|catch|globalEval|eval|script|specified|in|file|password|throw|nodeType|try|removeEventListener|multipart|POST|toString|jQuery'.split('|'),0,{}))
;
Drupal.behaviors.fritzscorner = function() {

  // Event list behavior.
  $(".view-events").each(function() {
    var collapsedHeight = 50;

    $(this).find(".node").each(function() {
      var readmore;
      var node = $(this);
      var content = $(this).find(".content");

      // Create readmore button.
      readmore = $('<div class="readmore"></div>')
        .click(function(e) {
          node.toggleClass("expanded");
          content.slideToggle("fast");
          e.stopPropagation();
        });

      $(this).append(readmore);

      // Make node clickable.
      $(this).click(function(e) {
        if (!node.hasClass("expanded")) {
          readmore.click();
        }
      });
      $(this).find(".title").click(function(e) {
        if (!node.hasClass("expanded")) {
          e.preventDefault();
        }
      });

    });

    // Expand the first two events on the upcoming calendar page.
    if ($(".page-kalender").length > 0) {
      $(this).find(".node:eq(0), .node:eq(1)").each(function() {
        $(this).find(".content").show();
        $(this).addClass("expanded");
      });
    }

  });

  // Make .field-info-value and .views-field-field-image-fid clickable on front main event
  $(".view-front .views-field-field-info-value, .view-front .views-field-field-image-fid").click(function() {
    var href = $(this).siblings(".views-field-title").find("a").attr("href");
    window.location = href;
  });

  // Overlabel on mailchimp signup form
  $("body.not-logged-in .block-mailchimp label").overlabel();

  // Include the animated logo.
  $("#site-name").prepend('<canvas data-processing-sources="/sites/www.fritzscorner.se/themes/fritzscorner/fritz-logo.pde" class="logo"><a href="/" class="logo">&nbsp;</a></canvas>');

  $("#site-name canvas.logo").click(function() {
    window.location.href = $(this).parent().find("a[rel=home]").attr("href");
  });

//  
//  $(".view-events .node").animate({
//       "height": "auto"
//     }, "slow", "easein");
};
;
( function( $ ) {
 
    // plugin definition
    $.fn.overlabel = function( options ) {
 
        // build main options before element iteration
        var opts = $.extend( {}, $.fn.overlabel.defaults, options );
 
        var selection = this.filter( 'label[for]' ).map( function() {
 
            var label = $( this );
            var id = label.attr( 'for' );
            var field = document.getElementById( id );
 
            if ( !field ) return;
 
            // build element specific options
            var o = $.meta ? $.extend( {}, opts, label.data() ) : opts;
 
            label.addClass( o.label_class );
 
            var hide_label = function() { label.css( o.hide_css ) };
            var show_label = function() { this.value || label.css( o.show_css ) };
 
            $( field )
                 .parent().addClass( o.wrapper_class ).end()
                 .focus( hide_label ).blur( show_label ).each( hide_label ).each( show_label );
 
            return this;
 
        } );
 
        return opts.filter ? selection : selection.end();
    };
 
    // publicly accessible defaults
    $.fn.overlabel.defaults = {
 
        label_class:   'overlabel-apply',
        wrapper_class: 'overlabel-wrapper',
        hide_css:      { 'text-indent': '-10000px' },
        show_css:      { 'text-indent': '0px', 'cursor': 'text' },
        filter:        false
 
    };
 
} )( jQuery );;
(function(){var undef;var ajax=function ajax(url){var xhr=new XMLHttpRequest();xhr.open("GET",url,false);xhr.setRequestHeader("If-Modified-Since","Fri, 01 Jan 1960 00:00:00 GMT");xhr.send(null);if(xhr.status!==200&&xhr.status!==0){throw ("XMLHttpRequest failed, status code "+xhr.status)}return xhr.responseText};function fixReplaceByRegExp(){var re=/t/g;if("t".replace(re,"")!==null&&re.exec("t")){return}var _ie_replace=String.prototype.replace;String.prototype.replace=function(searchValue,repaceValue){var result=_ie_replace.apply(this,arguments);if(searchValue instanceof RegExp&&searchValue.global){searchValue.lastIndex=0}return result}}function fixMatchByRegExp(){var re=/t/g;if("t".match(re)!==null&&re.exec("t")){return}var _ie_match=String.prototype.match;String.prototype.match=function(searchValue){var result=_ie_match.apply(this,arguments);if(searchValue instanceof RegExp&&searchValue.global){searchValue.lastIndex=0}return result}}fixReplaceByRegExp();fixMatchByRegExp();(function fixOperaCreateImageData(){try{if(!("createImageData" in CanvasRenderingContext2D.prototype)){CanvasRenderingContext2D.prototype.createImageData=function(sw,sh){return new ImageData(sw,sh)}}}catch(e){}}());var PConstants={X:0,Y:1,Z:2,R:3,G:4,B:5,A:6,U:7,V:8,NX:9,NY:10,NZ:11,EDGE:12,SR:13,SG:14,SB:15,SA:16,SW:17,TX:18,TY:19,TZ:20,VX:21,VY:22,VZ:23,VW:24,AR:25,AG:26,AB:27,DR:3,DG:4,DB:5,DA:6,SPR:28,SPG:29,SPB:30,SHINE:31,ER:32,EG:33,EB:34,BEEN_LIT:35,VERTEX_FIELD_COUNT:36,P2D:1,JAVA2D:1,WEBGL:2,P3D:2,OPENGL:2,PDF:0,DXF:0,OTHER:0,WINDOWS:1,MAXOSX:2,LINUX:3,EPSILON:0.0001,MAX_FLOAT:3.4028235e+38,MIN_FLOAT:-3.4028235e+38,MAX_INT:2147483647,MIN_INT:-2147483648,PI:Math.PI,TWO_PI:2*Math.PI,HALF_PI:Math.PI/2,THIRD_PI:Math.PI/3,QUARTER_PI:Math.PI/4,DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,WHITESPACE:" \t\n\r\f\u00A0",RGB:1,ARGB:2,HSB:3,ALPHA:4,CMYK:5,TIFF:0,TARGA:1,JPEG:2,GIF:3,BLUR:11,GRAY:12,INVERT:13,OPAQUE:14,POSTERIZE:15,THRESHOLD:16,ERODE:17,DILATE:18,REPLACE:0,BLEND:1<<0,ADD:1<<1,SUBTRACT:1<<2,LIGHTEST:1<<3,DARKEST:1<<4,DIFFERENCE:1<<5,EXCLUSION:1<<6,MULTIPLY:1<<7,SCREEN:1<<8,OVERLAY:1<<9,HARD_LIGHT:1<<10,SOFT_LIGHT:1<<11,DODGE:1<<12,BURN:1<<13,ALPHA_MASK:4278190080,RED_MASK:16711680,GREEN_MASK:65280,BLUE_MASK:255,CUSTOM:0,ORTHOGRAPHIC:2,PERSPECTIVE:3,POINT:2,POINTS:2,LINE:4,LINES:4,TRIANGLE:8,TRIANGLES:9,TRIANGLE_STRIP:10,TRIANGLE_FAN:11,QUAD:16,QUADS:16,QUAD_STRIP:17,POLYGON:20,PATH:21,RECT:30,ELLIPSE:31,ARC:32,SPHERE:40,BOX:41,GROUP:0,PRIMITIVE:1,GEOMETRY:3,VERTEX:0,BEZIER_VERTEX:1,CURVE_VERTEX:2,BREAK:3,CLOSESHAPE:4,OPEN:1,CLOSE:2,CORNER:0,CORNERS:1,RADIUS:2,CENTER_RADIUS:2,CENTER:3,DIAMETER:3,CENTER_DIAMETER:3,BASELINE:0,TOP:101,BOTTOM:102,NORMAL:1,NORMALIZED:1,IMAGE:2,MODEL:4,SHAPE:5,SQUARE:"butt",ROUND:"round",PROJECT:"square",MITER:"miter",BEVEL:"bevel",AMBIENT:0,DIRECTIONAL:1,SPOT:3,BACKSPACE:8,TAB:9,ENTER:10,RETURN:13,ESC:27,DELETE:127,CODED:65535,SHIFT:16,CONTROL:17,ALT:18,CAPSLK:20,PGUP:33,PGDN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,INS:45,DEL:46,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,NUMLK:144,ARROW:"default",CROSS:"crosshair",HAND:"pointer",MOVE:"move",TEXT:"text",WAIT:"wait",NOCURSOR:"url('data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='), auto",DISABLE_OPENGL_2X_SMOOTH:1,ENABLE_OPENGL_2X_SMOOTH:-1,ENABLE_OPENGL_4X_SMOOTH:2,ENABLE_NATIVE_FONTS:3,DISABLE_DEPTH_TEST:4,ENABLE_DEPTH_TEST:-4,ENABLE_DEPTH_SORT:5,DISABLE_DEPTH_SORT:-5,DISABLE_OPENGL_ERROR_REPORT:6,ENABLE_OPENGL_ERROR_REPORT:-6,ENABLE_ACCURATE_TEXTURES:7,DISABLE_ACCURATE_TEXTURES:-7,HINT_COUNT:10,SINCOS_LENGTH:parseInt(360/0.5,10),PRECISIONB:15,PRECISIONF:1<<15,PREC_MAXVAL:(1<<15)-1,PREC_ALPHA_SHIFT:24-15,PREC_RED_SHIFT:16-15,NORMAL_MODE_AUTO:0,NORMAL_MODE_SHAPE:1,NORMAL_MODE_VERTEX:2,MAX_LIGHTS:8};function setupTypedArray(name,fallback){if(typeof this[name]!=="function"&&typeof this[name]!=="object"){if(typeof this[fallback]==="function"){this[name]=this[fallback]}else{this[name]=function(obj){if(obj instanceof Array){return obj}else{if(typeof obj==="number"){return new Array(obj)}}}}}}setupTypedArray("Float32Array","WebGLFloatArray");setupTypedArray("Int32Array","WebGLIntArray");setupTypedArray("Uint16Array","WebGLUnsignedShortArray");setupTypedArray("Uint8Array","WebGLUnsignedByteArray");var ArrayList=(function(){function Iterator(array){var index=0;this.hasNext=function(){return index<array.length};this.next=function(){return array[index++]};this.remove=function(){array.splice(index,1)}}function ArrayList(){var array=arguments.length===0?[]:typeof arguments[0]==="number"?new Array(0|arguments[0]):arguments[0];this.get=function(i){return array[i]};this.contains=function(item){return array.indexOf(item)!==-1};this.add=function(){if(arguments.length===1){array.push(arguments[0])}else{if(arguments.length===2){var arg0=arguments[0];if(typeof arg0==="number"){if(arg0>=0&&arg0<=array.length){array.splice(arg0,0,arguments[1])}else{throw (arg0+" is not a valid index")}}else{throw (typeof arg0+" is not a number")}}else{throw ("Please use the proper number of parameters.")}}};this.set=function(){if(arguments.length===2){var arg0=arguments[0];if(typeof arg0==="number"){if(arg0>=0&&arg0<array.length){array.splice(arg0,1,arguments[1])}else{throw (arg0+" is not a valid index.")}}else{throw (typeof arg0+" is not a number")}}else{throw ("Please use the proper number of parameters.")}};this.size=function(){return array.length};this.clear=function(){array.length=0};this.remove=function(i){return array.splice(i,1)[0]};this.isEmpty=function(){return !array.length};this.clone=function(){return new ArrayList(array.slice(0))};this.toArray=function(){return array.slice(0)};this.iterator=function(){return new Iterator(array)}}return ArrayList}());var HashMap=(function(){function virtHashCode(obj){if(obj.constructor===String){var hash=0;for(var i=0;i<obj.length;++i){hash=(hash*31+obj.charCodeAt(i))&4294967295}return hash}else{if(typeof(obj)!=="object"){return obj&4294967295}else{if("hashCode" in obj){return obj.hashCode.call(obj)}else{if(obj.$id===undef){obj.$id=((Math.floor(Math.random()*65536)-32768)<<16)|Math.floor(Math.random()*65536)}return obj.$id}}}}function virtEquals(obj,other){if(obj===null||other===null){return(obj===null)&&(other===null)}else{if(obj.constructor===String){return obj===other}else{if(typeof(obj)!=="object"){return obj===other}else{if("equals" in obj){return obj.equals.call(obj,other)}else{return obj===other}}}}}function HashMap(){if(arguments.length===1&&arguments[0].constructor===HashMap){return arguments[0].clone()}var initialCapacity=arguments.length>0?arguments[0]:16;var loadFactor=arguments.length>1?arguments[1]:0.75;var buckets=new Array(initialCapacity);var count=0;var hashMap=this;function ensureLoad(){if(count<=loadFactor*buckets.length){return}var allEntries=[];for(var i=0;i<buckets.length;++i){if(buckets[i]!==undef){allEntries=allEntries.concat(buckets[i])}}buckets=new Array(buckets.length*2);for(var j=0;j<allEntries.length;++j){var index=virtHashCode(allEntries[j].key)%buckets.length;var bucket=buckets[index];if(bucket===undef){buckets[index]=bucket=[]}bucket.push(allEntries[j])}}function Iterator(conversion,removeItem){var bucketIndex=0;var itemIndex=-1;var endOfBuckets=false;function findNext(){while(!endOfBuckets){++itemIndex;if(bucketIndex>=buckets.length){endOfBuckets=true}else{if(buckets[bucketIndex]===undef||itemIndex>=buckets[bucketIndex].length){itemIndex=-1;++bucketIndex}else{return}}}}this.hasNext=function(){return !endOfBuckets};this.next=function(){var result=conversion(buckets[bucketIndex][itemIndex]);findNext();return result};this.remove=function(){removeItem(this.next());--itemIndex};findNext()}function Set(conversion,isIn,removeItem){this.clear=function(){hashMap.clear()};this.contains=function(o){return isIn(o)};this.containsAll=function(o){var it=o.iterator();while(it.hasNext()){if(!this.contains(it.next())){return false}}return true};this.isEmpty=function(){return hashMap.isEmpty()};this.iterator=function(){return new Iterator(conversion,removeItem)};this.remove=function(o){if(this.contains(o)){removeItem(o);return true}return false};this.removeAll=function(c){var it=c.iterator();var changed=false;while(it.hasNext()){var item=it.next();if(this.contains(item)){removeItem(item);changed=true}}return true};this.retainAll=function(c){var it=this.iterator();var toRemove=[];while(it.hasNext()){var entry=it.next();if(!c.contains(entry)){toRemove.push(entry)}}for(var i=0;i<toRemove.length;++i){removeItem(toRemove[i])}return toRemove.length>0};this.size=function(){return hashMap.size()};this.toArray=function(){var result=new ArrayList(0);var it=this.iterator();while(it.hasNext()){result.push(it.next())}return result}}function Entry(pair){this._isIn=function(map){return map===hashMap&&(pair.removed===undef)};this.equals=function(o){return virtEquals(pair.key,o.getKey())};this.getKey=function(){return pair.key};this.getValue=function(){return pair.value};this.hashCode=function(o){return virtHashCode(pair.key)};this.setValue=function(value){var old=pair.value;pair.value=value;return old}}this.clear=function(){count=0;buckets=new Array(initialCapacity)};this.clone=function(){var map=new HashMap();map.putAll(this);return map};this.containsKey=function(key){var index=virtHashCode(key)%buckets.length;var bucket=buckets[index];if(bucket===undef){return false}for(var i=0;i<bucket.length;++i){if(virtEquals(bucket[i].key,key)){return true}}return false};this.containsValue=function(value){for(var i=0;i<buckets.length;++i){var bucket=buckets[i];if(bucket===undef){continue}for(var j=0;j<bucket.length;++j){if(virtEquals(bucket[j].value,value)){return true}}}return false};this.entrySet=function(){return new Set(function(pair){return new Entry(pair)},function(pair){return pair.constructor===Entry&&pair._isIn(hashMap)},function(pair){return hashMap.remove(pair.getKey())})};this.get=function(key){var index=virtHashCode(key)%buckets.length;var bucket=buckets[index];if(bucket===undef){return null}for(var i=0;i<bucket.length;++i){if(virtEquals(bucket[i].key,key)){return bucket[i].value}}return null};this.isEmpty=function(){return count===0};this.keySet=function(){return new Set(function(pair){return pair.key},function(key){return hashMap.containsKey(key)},function(key){return hashMap.remove(key)})};this.put=function(key,value){var index=virtHashCode(key)%buckets.length;var bucket=buckets[index];if(bucket===undef){++count;buckets[index]=[{key:key,value:value}];ensureLoad();return null}for(var i=0;i<bucket.length;++i){if(virtEquals(bucket[i].key,key)){var previous=bucket[i].value;bucket[i].value=value;return previous}}++count;bucket.push({key:key,value:value});ensureLoad();return null};this.putAll=function(m){var it=m.entrySet().iterator();while(it.hasNext()){var entry=it.next();this.put(entry.getKey(),entry.getValue())}};this.remove=function(key){var index=virtHashCode(key)%buckets.length;var bucket=buckets[index];if(bucket===undef){return null}for(var i=0;i<bucket.length;++i){if(virtEquals(bucket[i].key,key)){--count;var previous=bucket[i].value;bucket[i].removed=true;if(bucket.length>1){bucket.splice(i,1)}else{buckets[index]=undef}return previous}}return null};this.size=function(){return count};this.values=function(){var result=new ArrayList(0);var it=this.entrySet().iterator();while(it.hasNext()){var entry=it.next();result.push(entry.getValue())}return result}}return HashMap}());var PVector=(function(){function PVector(x,y,z){this.x=x||0;this.y=y||0;this.z=z||0}function createPVectorMethod(method){return function(v1,v2){var v=v1.get();v[method](v2);return v}}function createSimplePVectorMethod(method){return function(v1,v2){return v1[method](v2)}}var simplePVMethods="dist dot cross".split(" ");var method=simplePVMethods.length;PVector.angleBetween=function(v1,v2){return Math.acos(v1.dot(v2)/(v1.mag()*v2.mag()))};PVector.prototype={set:function(v,y,z){if(arguments.length===1){this.set(v.x||v[0],v.y||v[1],v.z||v[2])}else{this.x=v;this.y=y;this.z=z}},get:function(){return new PVector(this.x,this.y,this.z)},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},add:function(v,y,z){if(arguments.length===3){this.x+=v;this.y+=y;this.z+=z}else{if(arguments.length===1){this.x+=v.x;this.y+=v.y;this.z+=v.z}}},sub:function(v,y,z){if(arguments.length===3){this.x-=v;this.y-=y;this.z-=z}else{if(arguments.length===1){this.x-=v.x;this.y-=v.y;this.z-=v.z}}},mult:function(v){if(typeof v==="number"){this.x*=v;this.y*=v;this.z*=v}else{if(typeof v==="object"){this.x*=v.x;this.y*=v.y;this.z*=v.z}}},div:function(v){if(typeof v==="number"){this.x/=v;this.y/=v;this.z/=v}else{if(typeof v==="object"){this.x/=v.x;this.y/=v.y;this.z/=v.z}}},dist:function(v){var dx=this.x-v.x,dy=this.y-v.y,dz=this.z-v.z;return Math.sqrt(dx*dx+dy*dy+dz*dz)},dot:function(v,y,z){if(arguments.length===3){return(this.x*v+this.y*y+this.z*z)}else{if(arguments.length===1){return(this.x*v.x+this.y*v.y+this.z*v.z)}}},cross:function(v){return new PVector(this.y*v.z-v.y*this.z,this.z*v.x-v.z*this.x,this.x*v.y-v.x*this.y)},normalize:function(){var m=this.mag();if(m>0){this.div(m)}},limit:function(high){if(this.mag()>high){this.normalize();this.mult(high)}},heading2D:function(){return(-Math.atan2(-this.y,this.x))},toString:function(){return"["+this.x+", "+this.y+", "+this.z+"]"},array:function(){return[this.x,this.y,this.z]}};while(method--){PVector[simplePVMethods[method]]=createSimplePVectorMethod(simplePVMethods[method])}for(method in PVector.prototype){if(PVector.prototype.hasOwnProperty(method)&&!PVector.hasOwnProperty(method)){PVector[method]=createPVectorMethod(method)}}return PVector}());function DefaultScope(){}DefaultScope.prototype=PConstants;var defaultScope=new DefaultScope();defaultScope.ArrayList=ArrayList;defaultScope.HashMap=HashMap;defaultScope.PVector=PVector;var Processing=this.Processing=function Processing(curElement,aCode){if(!(this instanceof Processing)){throw ("called Processing constructor as if it were a function: missing 'new'.")}var p=this;p.externals={canvas:curElement,context:undef,sketch:undef,onblur:function(){},onfocus:function(){}};p.name="Processing.js Instance";p.use3DContext=false;p.focused=true;p.breakShape=false;p.glyphTable={};p.pmouseX=0;p.pmouseY=0;p.mouseX=0;p.mouseY=0;p.mouseButton=0;p.mouseScroll=0;p.mouseClicked=undef;p.mouseDragged=undef;p.mouseMoved=undef;p.mousePressed=undef;p.mouseReleased=undef;p.mouseScrolled=undef;p.key=undef;p.keyCode=undef;p.keyPressed=function(){};p.keyReleased=function(){};p.keyTyped=function(){};p.draw=undef;p.setup=undef;p.__mousePressed=false;p.__keyPressed=false;p.__frameRate=0;p.frameCount=0;p.width=curElement.width-0;p.height=curElement.height-0;p.defineProperty=function(obj,name,desc){if("defineProperty" in Object){Object.defineProperty(obj,name,desc)}else{if(desc.hasOwnProperty("get")){obj.__defineGetter__(name,desc.get)}if(desc.hasOwnProperty("set")){obj.__defineSetter__(name,desc.set)}}};var curContext,curSketch,online=true,doFill=true,fillStyle=[1,1,1,1],currentFillColor=4294967295,isFillDirty=true,doStroke=true,strokeStyle=[0.8,0.8,0.8,1],currentStrokeColor=4294835709,isStrokeDirty=true,lineWidth=1,loopStarted=false,doLoop=true,looping=0,curRectMode=PConstants.CORNER,curEllipseMode=PConstants.CENTER,normalX=0,normalY=0,normalZ=0,normalMode=PConstants.NORMAL_MODE_AUTO,inDraw=false,curFrameRate=60,curCursor=PConstants.ARROW,oldCursor=curElement.style.cursor,curMsPerFrame=1,curShape=PConstants.POLYGON,curShapeCount=0,curvePoints=[],curTightness=0,curveDet=20,curveInited=false,bezDetail=20,colorModeA=255,colorModeX=255,colorModeY=255,colorModeZ=255,pathOpen=false,mouseDragging=false,curColorMode=PConstants.RGB,curTint=null,curTextSize=12,curTextFont="Arial",curTextLeading=14,getLoaded=false,start=new Date().getTime(),timeSinceLastFPS=start,framesSinceLastFPS=0,textcanvas,curveBasisMatrix,curveToBezierMatrix,curveDrawMatrix,bezierDrawMatrix,bezierBasisInverse,bezierBasisMatrix,firstCodedDown=true,firstEDGKeyDown=true,firstEDMKeyDown=true,firstMKeyDown=true,firstGKeyDown=true,gRefire=false,curContextCache={attributes:{},locations:{}},programObject3D,programObject2D,programObjectUnlitShape,boxBuffer,boxNormBuffer,boxOutlineBuffer,rectBuffer,rectNormBuffer,sphereBuffer,lineBuffer,fillBuffer,fillColorBuffer,strokeColorBuffer,pointBuffer,shapeTexVBO,canTex,textTex,curTexture={width:0,height:0},curTextureMode=PConstants.IMAGE,usingTexture=false,textBuffer,textureBuffer,indexBuffer,horizontalTextAlignment=PConstants.LEFT,verticalTextAlignment=PConstants.BASELINE,baselineOffset=0.2,tMode=PConstants.MODEL,originalContext,proxyContext=null,isContextReplaced=false,setPixelsCached,maxPixelsCached=1000,codedKeys=[PConstants.SHIFT,PConstants.CONTROL,PConstants.ALT,PConstants.CAPSLK,PConstants.PGUP,PConstants.PGDN,PConstants.END,PConstants.HOME,PConstants.LEFT,PConstants.UP,PConstants.RIGHT,PConstants.DOWN,PConstants.NUMLK,PConstants.INS,PConstants.F1,PConstants.F2,PConstants.F3,PConstants.F4,PConstants.F5,PConstants.F6,PConstants.F7,PConstants.F8,PConstants.F9,PConstants.F10,PConstants.F11,PConstants.F12];var stylePaddingLeft,stylePaddingTop,styleBorderLeft,styleBorderTop;if(document.defaultView&&document.defaultView.getComputedStyle){stylePaddingLeft=parseInt(document.defaultView.getComputedStyle(curElement,null)["paddingLeft"],10)||0;stylePaddingTop=parseInt(document.defaultView.getComputedStyle(curElement,null)["paddingTop"],10)||0;styleBorderLeft=parseInt(document.defaultView.getComputedStyle(curElement,null)["borderLeftWidth"],10)||0;styleBorderTop=parseInt(document.defaultView.getComputedStyle(curElement,null)["borderTopWidth"],10)||0}var lightCount=0;var sphereDetailV=0,sphereDetailU=0,sphereX=[],sphereY=[],sphereZ=[],sinLUT=new Array(PConstants.SINCOS_LENGTH),cosLUT=new Array(PConstants.SINCOS_LENGTH),sphereVerts,sphereNorms;var cam,cameraInv,forwardTransform,reverseTransform,modelView,modelViewInv,userMatrixStack,inverseCopy,projection,manipulatingCamera=false,frustumMode=false,cameraFOV=60*(Math.PI/180),cameraX=curElement.width/2,cameraY=curElement.height/2,cameraZ=cameraY/Math.tan(cameraFOV/2),cameraNear=cameraZ/10,cameraFar=cameraZ*10,cameraAspect=curElement.width/curElement.height;var vertArray=[],curveVertArray=[],curveVertCount=0,isCurve=false,isBezier=false,firstVert=true;var curShapeMode=PConstants.CORNER;var colors={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};var styleArray=new Array(0);var boxVerts=new Float32Array([0.5,0.5,-0.5,0.5,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5,0.5,-0.5,0.5,0.5,-0.5,0.5,0.5,0.5,-0.5,0.5,0.5,-0.5,-0.5,0.5,-0.5,-0.5,0.5,0.5,-0.5,0.5,0.5,0.5,0.5,0.5,0.5,-0.5,0.5,0.5,0.5,0.5,-0.5,0.5,0.5,-0.5,0.5,0.5,-0.5,-0.5,0.5,0.5,-0.5,0.5,-0.5,-0.5,0.5,-0.5,0.5,-0.5,-0.5,0.5,-0.5,-0.5,0.5,-0.5,-0.5,-0.5,0.5,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5,0.5,-0.5,0.5,0.5,-0.5,0.5,0.5,-0.5,0.5,-0.5,-0.5,-0.5,-0.5,0.5,0.5,0.5,0.5,0.5,-0.5,-0.5,0.5,-0.5,-0.5,0.5,-0.5,-0.5,0.5,0.5,0.5,0.5,0.5]);var boxOutlineVerts=new Float32Array([0.5,0.5,0.5,0.5,-0.5,0.5,0.5,0.5,-0.5,0.5,-0.5,-0.5,-0.5,0.5,-0.5,-0.5,-0.5,-0.5,-0.5,0.5,0.5,-0.5,-0.5,0.5,0.5,0.5,0.5,0.5,0.5,-0.5,0.5,0.5,-0.5,-0.5,0.5,-0.5,-0.5,0.5,-0.5,-0.5,0.5,0.5,-0.5,0.5,0.5,0.5,0.5,0.5,0.5,-0.5,0.5,0.5,-0.5,-0.5,0.5,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5,0.5,-0.5,-0.5,0.5,0.5,-0.5,0.5]);var boxNorms=new Float32Array([0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0]);var rectVerts=new Float32Array([0,0,0,0,1,0,1,1,0,1,0,0]);var rectNorms=new Float32Array([0,0,-1,0,0,-1,0,0,-1,0,0,-1]);var vShaderSrcUnlitShape="varying vec4 frontColor;attribute vec3 aVertex;attribute vec4 aColor;uniform mat4 uView;uniform mat4 uProjection;void main(void) {  frontColor = aColor;  gl_Position = uProjection * uView * vec4(aVertex, 1.0);}";var fShaderSrcUnlitShape="#ifdef GL_ES\nprecision highp float;\n#endif\nvarying vec4 frontColor;void main(void){  gl_FragColor = frontColor;}";var vertexShaderSource2D="varying vec4 frontColor;attribute vec3 Vertex;attribute vec2 aTextureCoord;uniform vec4 color;uniform mat4 model;uniform mat4 view;uniform mat4 projection;uniform float pointSize;varying vec2 vTextureCoord;void main(void) {  gl_PointSize = pointSize;  frontColor = color;  gl_Position = projection * view * model * vec4(Vertex, 1.0);  vTextureCoord = aTextureCoord;}";var fragmentShaderSource2D="#ifdef GL_ES\nprecision highp float;\n#endif\nvarying vec4 frontColor;varying vec2 vTextureCoord;uniform sampler2D uSampler;uniform int picktype;void main(void){  if(picktype == 0){    gl_FragColor = frontColor;  }  else if(picktype == 1){    float alpha = texture2D(uSampler, vTextureCoord).a;    gl_FragColor = vec4(frontColor.rgb*alpha, alpha);\n  }}";var vertexShaderSource3D="varying vec4 frontColor;attribute vec3 Vertex;attribute vec3 Normal;attribute vec4 aColor;attribute vec2 aTexture;varying   vec2 vTexture;uniform vec4 color;uniform bool usingMat;uniform vec3 specular;uniform vec3 mat_emissive;uniform vec3 mat_ambient;uniform vec3 mat_specular;uniform float shininess;uniform mat4 model;uniform mat4 view;uniform mat4 projection;uniform mat4 normalTransform;uniform int lightCount;uniform vec3 falloff;struct Light {  bool dummy;  int type;  vec3 color;  vec3 position;  vec3 direction;  float angle;  vec3 halfVector;  float concentration;};uniform Light lights[8];void AmbientLight( inout vec3 totalAmbient, in vec3 ecPos, in Light light ) {  float d = length( light.position - ecPos );  float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ));  totalAmbient += light.color * attenuation;}void DirectionalLight( inout vec3 col, in vec3 ecPos, inout vec3 spec, in vec3 vertNormal, in Light light ) {  float powerfactor = 0.0;  float nDotVP = max(0.0, dot( vertNormal, light.position ));  float nDotVH = max(0.0, dot( vertNormal, normalize( light.position-ecPos )));  if( nDotVP != 0.0 ){    powerfactor = pow( nDotVH, shininess );  }  col += light.color * nDotVP;  spec += specular * powerfactor;}void PointLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in vec3 eye, in Light light ) {  float powerfactor;   vec3 VP = light.position - ecPos;  float d = length( VP );   VP = normalize( VP );  float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ));  float nDotVP = max( 0.0, dot( vertNormal, VP ));  vec3 halfVector = normalize( VP + eye );  float nDotHV = max( 0.0, dot( vertNormal, halfVector ));  if( nDotVP == 0.0) {    powerfactor = 0.0;  }  else{    powerfactor = pow( nDotHV, shininess );  }  spec += specular * powerfactor * attenuation;  col += light.color * nDotVP * attenuation;}void SpotLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in vec3 eye, in Light light ) {  float spotAttenuation;  float powerfactor;  vec3 VP = light.position - ecPos;   vec3 ldir = normalize( light.direction );  float d = length( VP );  VP = normalize( VP );  float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ) );  float spotDot = dot( VP, ldir );  if( spotDot < cos( light.angle ) ) {    spotAttenuation = pow( spotDot, light.concentration );  }  else{    spotAttenuation = 1.0;  }  attenuation *= spotAttenuation;  float nDotVP = max( 0.0, dot( vertNormal, VP ));  vec3 halfVector = normalize( VP + eye );  float nDotHV = max( 0.0, dot( vertNormal, halfVector ));  if( nDotVP == 0.0 ) {    powerfactor = 0.0;  }  else {    powerfactor = pow( nDotHV, shininess );  }  spec += specular * powerfactor * attenuation;  col += light.color * nDotVP * attenuation;}void main(void) {  vec3 finalAmbient = vec3( 0.0, 0.0, 0.0 );  vec3 finalDiffuse = vec3( 0.0, 0.0, 0.0 );  vec3 finalSpecular = vec3( 0.0, 0.0, 0.0 );  vec4 col = color;  if(color[0] == -1.0){    col = aColor;  }  vec3 norm = vec3( normalTransform * vec4( Normal, 0.0 ) );  vec4 ecPos4 = view * model * vec4(Vertex,1.0);  vec3 ecPos = (vec3(ecPos4))/ecPos4.w;  vec3 eye = vec3( 0.0, 0.0, 1.0 );  if( lightCount == 0 ) {    frontColor = col + vec4(mat_specular,1.0);  }  else {    for( int i = 0; i < lightCount; i++ ) {      if( lights[i].type == 0 ) {        AmbientLight( finalAmbient, ecPos, lights[i] );      }      else if( lights[i].type == 1 ) {        DirectionalLight( finalDiffuse,ecPos, finalSpecular, norm, lights[i] );      }      else if( lights[i].type == 2 ) {        PointLight( finalDiffuse, finalSpecular, norm, ecPos, eye, lights[i] );      }      else if( lights[i].type == 3 ) {        SpotLight( finalDiffuse, finalSpecular, norm, ecPos, eye, lights[i] );      }    }   if( usingMat == false ) {    frontColor = vec4(        vec3(col) * finalAmbient +      vec3(col) * finalDiffuse +      vec3(col) * finalSpecular,      col[3] );   }   else{     frontColor = vec4(        mat_emissive +        (vec3(col) * mat_ambient * finalAmbient) +        (vec3(col) * finalDiffuse) +        (mat_specular * finalSpecular),        col[3] );    }  }  vTexture.xy = aTexture.xy;  gl_Position = projection * view * model * vec4( Vertex, 1.0 );}";var fragmentShaderSource3D="#ifdef GL_ES\nprecision highp float;\n#endif\nvarying vec4 frontColor;uniform sampler2D sampler;uniform bool usingTexture;varying vec2 vTexture;void main(void){  if(usingTexture){    gl_FragColor =  vec4(texture2D(sampler, vTexture.xy));  }  else{    gl_FragColor = frontColor;  }}";function uniformf(cacheId,programObj,varName,varValue){var varLocation=curContextCache.locations[cacheId];if(varLocation===undef){varLocation=curContext.getUniformLocation(programObj,varName);curContextCache.locations[cacheId]=varLocation}if(varLocation!==-1){if(varValue.length===4){curContext.uniform4fv(varLocation,varValue)}else{if(varValue.length===3){curContext.uniform3fv(varLocation,varValue)}else{if(varValue.length===2){curContext.uniform2fv(varLocation,varValue)}else{curContext.uniform1f(varLocation,varValue)}}}}}function uniformi(cacheId,programObj,varName,varValue){var varLocation=curContextCache.locations[cacheId];if(varLocation===undef){varLocation=curContext.getUniformLocation(programObj,varName);curContextCache.locations[cacheId]=varLocation}if(varLocation!==-1){if(varValue.length===4){curContext.uniform4iv(varLocation,varValue)}else{if(varValue.length===3){curContext.uniform3iv(varLocation,varValue)}else{if(varValue.length===2){curContext.uniform2iv(varLocation,varValue)}else{curContext.uniform1i(varLocation,varValue)}}}}}function vertexAttribPointer(cacheId,programObj,varName,size,VBO){var varLocation=curContextCache.attributes[cacheId];if(varLocation===undef){varLocation=curContext.getAttribLocation(programObj,varName);curContextCache.attributes[cacheId]=varLocation}if(varLocation!==-1){curContext.bindBuffer(curContext.ARRAY_BUFFER,VBO);curContext.vertexAttribPointer(varLocation,size,curContext.FLOAT,false,0,0);curContext.enableVertexAttribArray(varLocation)}}function disableVertexAttribPointer(cacheId,programObj,varName){var varLocation=curContextCache.attributes[cacheId];if(varLocation===undef){varLocation=curContext.getAttribLocation(programObj,varName);curContextCache.attributes[cacheId]=varLocation}if(varLocation!==-1){curContext.disableVertexAttribArray(varLocation)}}function uniformMatrix(cacheId,programObj,varName,transpose,matrix){var varLocation=curContextCache.locations[cacheId];if(varLocation===undef){varLocation=curContext.getUniformLocation(programObj,varName);curContextCache.locations[cacheId]=varLocation}if(varLocation!==-1){if(matrix.length===16){curContext.uniformMatrix4fv(varLocation,transpose,matrix)}else{if(matrix.length===9){curContext.uniformMatrix3fv(varLocation,transpose,matrix)}else{curContext.uniformMatrix2fv(varLocation,transpose,matrix)}}}}var imageModeCorner=function imageModeCorner(x,y,w,h,whAreSizes){return{x:x,y:y,w:w,h:h}};var imageModeConvert=imageModeCorner;var imageModeCorners=function imageModeCorners(x,y,w,h,whAreSizes){return{x:x,y:y,w:whAreSizes?w:w-x,h:whAreSizes?h:h-y}};var imageModeCenter=function imageModeCenter(x,y,w,h,whAreSizes){return{x:x-w/2,y:y-h/2,w:w,h:h}};var createProgramObject=function(curContext,vetexShaderSource,fragmentShaderSource){var vertexShaderObject=curContext.createShader(curContext.VERTEX_SHADER);curContext.shaderSource(vertexShaderObject,vetexShaderSource);curContext.compileShader(vertexShaderObject);if(!curContext.getShaderParameter(vertexShaderObject,curContext.COMPILE_STATUS)){throw curContext.getShaderInfoLog(vertexShaderObject)}var fragmentShaderObject=curContext.createShader(curContext.FRAGMENT_SHADER);curContext.shaderSource(fragmentShaderObject,fragmentShaderSource);curContext.compileShader(fragmentShaderObject);if(!curContext.getShaderParameter(fragmentShaderObject,curContext.COMPILE_STATUS)){throw curContext.getShaderInfoLog(fragmentShaderObject)}var programObject=curContext.createProgram();curContext.attachShader(programObject,vertexShaderObject);curContext.attachShader(programObject,fragmentShaderObject);curContext.linkProgram(programObject);if(!curContext.getProgramParameter(programObject,curContext.LINK_STATUS)){throw"Error linking shaders."}return programObject};var charMap={};var Char=p.Character=function Char(chr){if(typeof chr==="string"&&chr.length===1){this.code=chr.charCodeAt(0)}else{this.code=NaN}return(charMap[this.code]===undef)?charMap[this.code]=this:charMap[this.code]};Char.prototype.toString=function(){return String.fromCharCode(this.code)};Char.prototype.valueOf=function(){return this.code};var PShape=p.PShape=function(family){this.family=family||PConstants.GROUP;this.visible=true;this.style=true;this.children=[];this.nameTable=[];this.params=[];this.name="";this.image=null;this.matrix=null;this.kind=null;this.close=null;this.width=null;this.height=null;this.parent=null;this.isVisible=function(){return this.visible};this.setVisible=function(visible){this.visible=visible};this.disableStyle=function(){this.style=false;for(var i=0;i<this.children.length;i++){this.children[i].disableStyle()}};this.enableStyle=function(){this.style=true;for(var i=0;i<this.children.length;i++){this.children[i].enableStyle()}};this.getFamily=function(){return this.family};this.getWidth=function(){return this.width};this.getHeight=function(){return this.height};this.setName=function(name){this.name=name};this.getName=function(){return this.name};this.draw=function(){if(this.visible){this.pre();this.drawImpl();this.post()}};this.drawImpl=function(){if(this.family===PConstants.GROUP){this.drawGroup()}else{if(this.family===PConstants.PRIMITIVE){this.drawPrimitive()}else{if(this.family===PConstants.GEOMETRY){this.drawGeometry()}else{if(this.family===PConstants.PATH){this.drawPath()}}}}};this.drawPath=function(){if(this.vertices.length===0){return}p.beginShape();var i;if(this.vertexCodes.length===0){if(this.vertices[0].length===2){for(i=0;i<this.vertices.length;i++){p.vertex(this.vertices[i][0],this.vertices[i][1])}}else{for(i=0;i<this.vertices.length;i++){p.vertex(this.vertices[i][0],this.vertices[i][1],this.vertices[i][2])}}}else{var index=0;var j;if(this.vertices[0].length===2){for(j=0;j<this.vertexCodes.length;j++){switch(this.vertexCodes[j]){case PConstants.VERTEX:p.vertex(this.vertices[index][0],this.vertices[index][1]);if(this.vertices[index]["moveTo"]===true){vertArray[vertArray.length-1]["moveTo"]=true}else{if(this.vertices[index]["moveTo"]===false){vertArray[vertArray.length-1]["moveTo"]=false}}p.breakShape=false;index++;break;case PConstants.BEZIER_VERTEX:p.bezierVertex(this.vertices[index+0][0],this.vertices[index+0][1],this.vertices[index+1][0],this.vertices[index+1][1],this.vertices[index+2][0],this.vertices[index+2][1]);index+=3;break;case PConstants.CURVE_VERTEX:p.curveVertex(this.vertices[index][0],this.vertices[index][1]);index++;break;case PConstants.BREAK:p.breakShape=true;break}}}else{for(j=0;j<this.vertexCodes.length;j++){switch(this.vertexCodes[j]){case PConstants.VERTEX:p.vertex(this.vertices[index][0],this.vertices[index][1],this.vertices[index][2]);if(this.vertices[index]["moveTo"]===true){vertArray[vertArray.length-1]["moveTo"]=true}else{if(this.vertices[index]["moveTo"]===false){vertArray[vertArray.length-1]["moveTo"]=false}}p.breakShape=false;break;case PConstants.BEZIER_VERTEX:p.bezierVertex(this.vertices[index+0][0],this.vertices[index+0][1],this.vertices[index+0][2],this.vertices[index+1][0],this.vertices[index+1][1],this.vertices[index+1][2],this.vertices[index+2][0],this.vertices[index+2][1],this.vertices[index+2][2]);index+=3;break;case PConstants.CURVE_VERTEX:p.curveVertex(this.vertices[index][0],this.vertices[index][1],this.vertices[index][2]);index++;break;case PConstants.BREAK:p.breakShape=true;break}}}}p.endShape(this.close?PConstants.CLOSE:PConstants.OPEN)};this.drawGeometry=function(){p.beginShape(this.kind);var i;if(this.style){for(i=0;i<this.vertices.length;i++){p.vertex(this.vertices[i])}}else{for(i=0;i<this.vertices.length;i++){var vert=this.vertices[i];if(vert[2]===0){p.vertex(vert[0],vert[1])}else{p.vertex(vert[0],vert[1],vert[2])}}}p.endShape()};this.drawGroup=function(){for(var i=0;i<this.children.length;i++){this.children[i].draw()}};this.drawPrimitive=function(){switch(this.kind){case PConstants.POINT:p.point(this.params[0],this.params[1]);break;case PConstants.LINE:if(this.params.length===4){p.line(this.params[0],this.params[1],this.params[2],this.params[3])}else{p.line(this.params[0],this.params[1],this.params[2],this.params[3],this.params[4],this.params[5])}break;case PConstants.TRIANGLE:p.triangle(this.params[0],this.params[1],this.params[2],this.params[3],this.params[4],this.params[5]);break;case PConstants.QUAD:p.quad(this.params[0],this.params[1],this.params[2],this.params[3],this.params[4],this.params[5],this.params[6],this.params[7]);break;case PConstants.RECT:if(this.image!==null){p.imageMode(PConstants.CORNER);p.image(this.image,this.params[0],this.params[1],this.params[2],this.params[3])}else{p.rectMode(PConstants.CORNER);p.rect(this.params[0],this.params[1],this.params[2],this.params[3])}break;case PConstants.ELLIPSE:p.ellipseMode(PConstants.CORNER);p.ellipse(this.params[0],this.params[1],this.params[2],this.params[3]);break;case PConstants.ARC:p.ellipseMode(PConstants.CORNER);p.arc(this.params[0],this.params[1],this.params[2],this.params[3],this.params[4],this.params[5]);break;case PConstants.BOX:if(this.params.length===1){p.box(this.params[0])}else{p.box(this.params[0],this.params[1],this.params[2])}break;case PConstants.SPHERE:p.sphere(this.params[0]);break}};this.pre=function(){if(this.matrix){p.pushMatrix();curContext.transform(this.matrix.elements[0],this.matrix.elements[3],this.matrix.elements[1],this.matrix.elements[4],this.matrix.elements[2],this.matrix.elements[5])}if(this.style){p.pushStyle();this.styles()}};this.post=function(){if(this.matrix){p.popMatrix()}if(this.style){p.popStyle()}};this.styles=function(){if(this.stroke){p.stroke(this.strokeColor);p.strokeWeight(this.strokeWeight);p.strokeCap(this.strokeCap);p.strokeJoin(this.strokeJoin)}else{p.noStroke()}if(this.fill){p.fill(this.fillColor)}else{p.noFill()}};this.getChild=function(){if(typeof arguments[0]==="number"){return this.children[arguments[0]]}else{var found,i;if(arguments[0]===""||this.name===arguments[0]){return this}else{if(this.nameTable.length>0){for(i=0;i<this.nameTable.length||found;i++){if(this.nameTable[i].getName===arguments[0]){found=this.nameTable[i]}}if(found){return found}}for(i=0;i<this.children.lenth;i++){found=this.children[i].getChild(arguments[0]);if(found){return found}}}return null}};this.getChildCount=function(){return this.children.length};this.addChild=function(child){this.children.push(child);child.parent=this;if(child.getName()!==null){this.addName(child.getName(),child)}};this.addName=function(name,shape){if(this.parent!==null){this.parent.addName(name,shape)}else{this.nameTable.push([name,shape])}};this.translate=function(){if(arguments.length===2){this.checkMatrix(2);this.matrix.translate(arguments[0],arguments[1])}else{this.checkMatrix(3);this.matrix.translate(arguments[0],arguments[1],0)}};this.checkMatrix=function(dimensions){if(this.matrix===null){if(dimensions===2){this.matrix=new p.PMatrix2D()}else{this.matrix=new p.PMatrix3D()}}else{if(dimensions===3&&this.matrix instanceof p.PMatrix2D){this.matrix=new p.PMatrix3D()}}};this.rotateX=function(angle){this.rotate(angle,1,0,0)};this.rotateY=function(angle){this.rotate(angle,0,1,0)};this.rotateZ=function(angle){this.rotate(angle,0,0,1)};this.rotate=function(){if(arguments.length===1){this.checkMatrix(2);this.matrix.rotate(arguments[0])}else{this.checkMatrix(3);this.matrix.rotate(arguments[0],arguments[1],arguments[2],arguments[3])}};this.scale=function(){if(arguments.length===2){this.checkMatrix(2);this.matrix.scale(arguments[0],arguments[1])}else{if(arguments.length===3){this.checkMatrix(2);this.matrix.scale(arguments[0],arguments[1],arguments[2])}else{this.checkMatrix(2);this.matrix.scale(arguments[0])}}};this.resetMatrix=function(){this.checkMatrix(2);this.matrix.reset()};this.applyMatrix=function(matrix){if(arguments.length===1){this.applyMatrix(matrix.elements[0],matrix.elements[1],0,matrix.elements[2],matrix.elements[3],matrix.elements[4],0,matrix.elements[5],0,0,1,0,0,0,0,1)}else{if(arguments.length===6){this.checkMatrix(2);this.matrix.apply(arguments[0],arguments[1],arguments[2],0,arguments[3],arguments[4],arguments[5],0,0,0,1,0,0,0,0,1)}else{if(arguments.length===16){this.checkMatrix(3);this.matrix.apply(arguments[0],arguments[1],arguments[2],arguments[3],arguments[4],arguments[5],arguments[6],arguments[7],arguments[8],arguments[9],arguments[10],arguments[11],arguments[12],arguments[13],arguments[14],arguments[15])}}}}};var PShapeSVG=p.PShapeSVG=function(){p.PShape.call(this);if(arguments.length===1){this.element=arguments[0];this.vertexCodes=[];this.vertices=[];this.opacity=1;this.stroke=false;this.strokeColor=PConstants.ALPHA_MASK;this.strokeWeight=1;this.strokeCap=PConstants.SQUARE;this.strokeJoin=PConstants.MITER;this.strokeGradient=null;this.strokeGradientPaint=null;this.strokeName=null;this.strokeOpacity=1;this.fill=true;this.fillColor=PConstants.ALPHA_MASK;this.fillGradient=null;this.fillGradientPaint=null;this.fillName=null;this.fillOpacity=1;if(this.element.getName()!=="svg"){throw ("root is not <svg>, it's <"+this.element.getName()+">")}}else{if(arguments.length===2){if(typeof arguments[1]==="string"){if(arguments[1].indexOf(".svg")>-1){this.element=new p.XMLElement(null,arguments[1]);this.vertexCodes=[];this.vertices=[];this.opacity=1;this.stroke=false;this.strokeColor=PConstants.ALPHA_MASK;this.strokeWeight=1;this.strokeCap=PConstants.SQUARE;this.strokeJoin=PConstants.MITER;this.strokeGradient="";this.strokeGradientPaint="";this.strokeName="";this.strokeOpacity=1;this.fill=true;this.fillColor=PConstants.ALPHA_MASK;this.fillGradient=null;this.fillGradientPaint=null;this.fillOpacity=1}}else{if(arguments[0]){this.element=arguments[1];this.vertexCodes=arguments[0].vertexCodes.slice();this.vertices=arguments[0].vertices.slice();this.stroke=arguments[0].stroke;this.strokeColor=arguments[0].strokeColor;this.strokeWeight=arguments[0].strokeWeight;this.strokeCap=arguments[0].strokeCap;this.strokeJoin=arguments[0].strokeJoin;this.strokeGradient=arguments[0].strokeGradient;this.strokeGradientPaint=arguments[0].strokeGradientPaint;this.strokeName=arguments[0].strokeName;this.fill=arguments[0].fill;this.fillColor=arguments[0].fillColor;this.fillGradient=arguments[0].fillGradient;this.fillGradientPaint=arguments[0].fillGradientPaint;this.fillName=arguments[0].fillName;this.strokeOpacity=arguments[0].strokeOpacity;this.fillOpacity=arguments[0].fillOpacity;this.opacity=arguments[0].opacity}}}}this.name=this.element.getStringAttribute("id");var displayStr=this.element.getStringAttribute("display","inline");this.visible=displayStr!=="none";var str=this.element.getAttribute("transform");if(str){this.matrix=this.parseMatrix(str)}var viewBoxStr=this.element.getStringAttribute("viewBox");if(viewBoxStr!==null){var viewBox=viewBoxStr.split(" ");this.width=viewBox[2];this.height=viewBox[3]}var unitWidth=this.element.getStringAttribute("width");var unitHeight=this.element.getStringAttribute("height");if(unitWidth!==null){this.width=this.parseUnitSize(unitWidth);this.height=this.parseUnitSize(unitHeight)}else{if((this.width===0)||(this.height===0)){this.width=1;this.height=1;throw ("The width and/or height is not readable in the <svg> tag of this file.")}}this.parseColors(this.element);this.parseChildren(this.element)};PShapeSVG.prototype={parseMatrix:function(str){this.checkMatrix(2);var pieces=[];str.replace(/\s*(\w+)\((.*?)\)/g,function(all){pieces.push(p.trim(all))});if(pieces.length===0){p.println("Transformation:"+str+" is empty");return null}for(var i=0;i<pieces.length;i++){var m=[];pieces[i].replace(/\((.*?)\)/,(function(){return function(all,params){m=params.replace(/,+/g," ").split(/\s+/)}}()));if(pieces[i].indexOf("matrix")!==-1){this.matrix.set(m[0],m[2],m[4],m[1],m[3],m[5])}else{if(pieces[i].indexOf("translate")!==-1){var tx=m[0];var ty=(m.length===2)?m[1]:0;this.matrix.translate(tx,ty)}else{if(pieces[i].indexOf("scale")!==-1){var sx=m[0];var sy=(m.length===2)?m[1]:m[0];this.matrix.scale(sx,sy)}else{if(pieces[i].indexOf("rotate")!==-1){var angle=m[0];if(m.length===1){this.matrix.rotate(p.radians(angle))}else{if(m.length===3){this.matrix.translate(m[1],m[2]);this.matrix.rotate(p.radians(m[0]));this.matrix.translate(-m[1],-m[2])}}}else{if(pieces[i].indexOf("skewX")!==-1){this.matrix.skewX(parseFloat(m[0]))}else{if(pieces[i].indexOf("skewY")!==-1){this.matrix.skewY(m[0])}}}}}}}return this.matrix},parseChildren:function(element){var newelement=element.getChildren();var children=new p.PShape();for(var i=0;i<newelement.length;i++){var kid=this.parseChild(newelement[i]);if(kid){children.addChild(kid)}}this.children.push(children)},getName:function(){return this.name},parseChild:function(elem){var name=elem.getName();var shape;switch(name){case"g":shape=new PShapeSVG(this,elem);break;case"defs":shape=new PShapeSVG(this,elem);break;case"line":shape=new PShapeSVG(this,elem);shape.parseLine();break;case"circle":shape=new PShapeSVG(this,elem);shape.parseEllipse(true);break;case"ellipse":shape=new PShapeSVG(this,elem);shape.parseEllipse(false);break;case"rect":shape=new PShapeSVG(this,elem);shape.parseRect();break;case"polygon":shape=new PShapeSVG(this,elem);shape.parsePoly(true);break;case"polyline":shape=new PShapeSVG(this,elem);shape.parsePoly(false);break;case"path":shape=new PShapeSVG(this,elem);shape.parsePath();break;case"radialGradient":break;case"linearGradient":break;case"text":p.println("Text in SVG files is not currently supported, convert text to outlines instead.");break;case"filter":p.println("Filters are not supported.");break;case"mask":p.println("Masks are not supported.");break;default:p.println("Ignoring  <"+name+"> tag.");break}return shape},parsePath:function(){this.family=PConstants.PATH;this.kind=0;var pathDataChars=[];var c;var pathData=p.trim(this.element.getStringAttribute("d").replace(/[\s,]+/g," "));if(pathData===null){return}pathData=pathData.toCharArray();var cx=0,cy=0,ctrlX=0,ctrlY=0,ctrlX1=0,ctrlX2=0,ctrlY1=0,ctrlY2=0,endX=0,endY=0,ppx=0,ppy=0,px=0,py=0,i=0,j=0,valOf=0;var str="";var tmpArray=[];var flag=false;var lastInstruction;var command;while(i<pathData.length){valOf=pathData[i].valueOf();if((valOf>=65&&valOf<=90)||(valOf>=97&&valOf<=122)){j=i;i++;if(i<pathData.length){tmpArray=[];valOf=pathData[i].valueOf();while(!((valOf>=65&&valOf<=90)||(valOf>=97&&valOf<=100)||(valOf>=102&&valOf<=122))&&flag===false){if(valOf===32){if(str!==""){tmpArray.push(parseFloat(str));str=""}i++}else{if(valOf===45){if(pathData[i-1].valueOf()===101){str+=pathData[i].toString();i++}else{if(str!==""){tmpArray.push(parseFloat(str))}str=pathData[i].toString();i++}}else{str+=pathData[i].toString();i++}}if(i===pathData.length){flag=true}else{valOf=pathData[i].valueOf()}}}if(str!==""){tmpArray.push(parseFloat(str));str=""}command=pathData[j];switch(command.valueOf()){case 77:if(tmpArray.length>=2&&tmpArray.length%2===0){cx=tmpArray[0];cy=tmpArray[1];this.parsePathMoveto(cx,cy);if(tmpArray.length>2){for(j=2;j<tmpArray.length;j+=2){cx=tmpArray[j];cy=tmpArray[j+1];this.parsePathLineto(cx,cy)}}}break;case 109:if(tmpArray.length>=2&&tmpArray.length%2===0){cx+=tmpArray[0];cy+=tmpArray[1];this.parsePathMoveto(cx,cy);if(tmpArray.length>2){for(j=2;j<tmpArray.length;j+=2){cx+=tmpArray[j];cy+=tmpArray[j+1];this.parsePathLineto(cx,cy)}}}break;case 76:if(tmpArray.length>=2&&tmpArray.length%2===0){for(j=0;j<tmpArray.length;j+=2){cx=tmpArray[j];cy=tmpArray[j+1];this.parsePathLineto(cx,cy)}}break;case 108:if(tmpArray.length>=2&&tmpArray.length%2===0){for(j=0;j<tmpArray.length;j+=2){cx+=tmpArray[j];cy+=tmpArray[j+1];this.parsePathLineto(cx,cy)}}break;case 72:for(j=0;j<tmpArray.length;j++){cx=tmpArray[j];this.parsePathLineto(cx,cy)}break;case 104:for(j=0;j<tmpArray.length;j++){cx+=tmpArray[j];this.parsePathLineto(cx,cy)}break;case 86:for(j=0;j<tmpArray.length;j++){cy=tmpArray[j];this.parsePathLineto(cx,cy)}break;case 118:for(j=0;j<tmpArray.length;j++){cy+=tmpArray[j];this.parsePathLineto(cx,cy)}break;case 67:if(tmpArray.length>=6&&tmpArray.length%6===0){for(j=0;j<tmpArray.length;j+=6){ctrlX1=tmpArray[j];ctrlY1=tmpArray[j+1];ctrlX2=tmpArray[j+2];ctrlY2=tmpArray[j+3];endX=tmpArray[j+4];endY=tmpArray[j+5];this.parsePathCurveto(ctrlX1,ctrlY1,ctrlX2,ctrlY2,endX,endY);cx=endX;cy=endY}}break;case 99:if(tmpArray.length>=6&&tmpArray.length%6===0){for(j=0;j<tmpArray.length;j+=6){ctrlX1=cx+tmpArray[j];ctrlY1=cy+tmpArray[j+1];ctrlX2=cx+tmpArray[j+2];ctrlY2=cy+tmpArray[j+3];endX=cx+tmpArray[j+4];endY=cy+tmpArray[j+5];this.parsePathCurveto(ctrlX1,ctrlY1,ctrlX2,ctrlY2,endX,endY);cx=endX;cy=endY}}break;case 83:if(tmpArray.length>=4&&tmpArray.length%4===0){for(j=0;j<tmpArray.length;j+=4){if(lastInstruction.toLowerCase()==="c"||lastInstruction.toLowerCase()==="s"){ppx=this.vertices[this.vertices.length-2][0];ppy=this.vertices[this.vertices.length-2][1];px=this.vertices[this.vertices.length-1][0];py=this.vertices[this.vertices.length-1][1];ctrlX1=px+(px-ppx);ctrlY1=py+(py-ppy)}else{ctrlX1=this.vertices[this.vertices.length-1][0];ctrlY1=this.vertices[this.vertices.length-1][1]}ctrlX2=tmpArray[j];ctrlY2=tmpArray[j+1];endX=tmpArray[j+2];endY=tmpArray[j+3];this.parsePathCurveto(ctrlX1,ctrlY1,ctrlX2,ctrlY2,endX,endY);cx=endX;cy=endY}}break;case 115:if(tmpArray.length>=4&&tmpArray.length%4===0){for(j=0;j<tmpArray.length;j+=4){if(lastInstruction.toLowerCase()==="c"||lastInstruction.toLowerCase()==="s"){ppx=this.vertices[this.vertices.length-2][0];ppy=this.vertices[this.vertices.length-2][1];px=this.vertices[this.vertices.length-1][0];py=this.vertices[this.vertices.length-1][1];ctrlX1=px+(px-ppx);ctrlY1=py+(py-ppy)}else{ctrlX1=this.vertices[this.vertices.length-1][0];ctrlY1=this.vertices[this.vertices.length-1][1]}ctrlX2=cx+tmpArray[j];ctrlY2=cy+tmpArray[j+1];endX=cx+tmpArray[j+2];endY=cy+tmpArray[j+3];this.parsePathCurveto(ctrlX1,ctrlY1,ctrlX2,ctrlY2,endX,endY);cx=endX;cy=endY}}break;case 81:if(tmpArray.length>=4&&tmpArray.length%4===0){for(j=0;j<tmpArray.length;j+=4){ctrlX=tmpArray[j];ctrlY=tmpArray[j+1];endX=tmpArray[j+2];endY=tmpArray[j+3];this.parsePathQuadto(cx,cy,ctrlX,ctrlY,endX,endY);cx=endX;cy=endY}}break;case 113:if(tmpArray.length>=4&&tmpArray.length%4===0){for(j=0;j<tmpArray.length;j+=4){ctrlX=cx+tmpArray[j];ctrlY=cy+tmpArray[j+1];endX=cx+tmpArray[j+2];endY=cy+tmpArray[j+3];this.parsePathQuadto(cx,cy,ctrlX,ctrlY,endX,endY);cx=endX;cy=endY}}break;case 84:if(tmpArray.length>=2&&tmpArray.length%2===0){for(j=0;j<tmpArray.length;j+=2){if(lastInstruction.toLowerCase()==="q"||lastInstruction.toLowerCase()==="t"){ppx=this.vertices[this.vertices.length-2][0];ppy=this.vertices[this.vertices.length-2][1];px=this.vertices[this.vertices.length-1][0];py=this.vertices[this.vertices.length-1][1];ctrlX=px+(px-ppx);ctrlY=py+(py-ppy)}else{ctrlX=cx;ctrlY=cy}endX=tmpArray[j];endY=tmpArray[j+1];this.parsePathQuadto(cx,cy,ctrlX,ctrlY,endX,endY);cx=endX;cy=endY}}break;case 116:if(tmpArray.length>=2&&tmpArray.length%2===0){for(j=0;j<tmpArray.length;j+=2){if(lastInstruction.toLowerCase()==="q"||lastInstruction.toLowerCase()==="t"){ppx=this.vertices[this.vertices.length-2][0];ppy=this.vertices[this.vertices.length-2][1];px=this.vertices[this.vertices.length-1][0];py=this.vertices[this.vertices.length-1][1];ctrlX=px+(px-ppx);ctrlY=py+(py-ppy)}else{ctrlX=cx;ctrlY=cy}endX=cx+tmpArray[j];endY=cy+tmpArray[j+1];this.parsePathQuadto(cx,cy,ctrlX,ctrlY,endX,endY);cx=endX;cy=endY}}break;case 90:case 122:this.close=true;break}lastInstruction=command.toString()}else{i++}}},parsePathQuadto:function(x1,y1,cx,cy,x2,y2){if(this.vertices.length>0){this.parsePathCode(PConstants.BEZIER_VERTEX);this.parsePathVertex(x1+((cx-x1)*2/3),y1+((cy-y1)*2/3));this.parsePathVertex(x2+((cx-x2)*2/3),y2+((cy-y2)*2/3));this.parsePathVertex(x2,y2)}else{throw ("Path must start with M/m")}},parsePathCurveto:function(x1,y1,x2,y2,x3,y3){if(this.vertices.length>0){this.parsePathCode(PConstants.BEZIER_VERTEX);this.parsePathVertex(x1,y1);this.parsePathVertex(x2,y2);this.parsePathVertex(x3,y3)}else{throw ("Path must start with M/m")}},parsePathLineto:function(px,py){if(this.vertices.length>0){this.parsePathCode(PConstants.VERTEX);this.parsePathVertex(px,py);this.vertices[this.vertices.length-1]["moveTo"]=false}else{throw ("Path must start with M/m")}},parsePathMoveto:function(px,py){if(this.vertices.length>0){this.parsePathCode(PConstants.BREAK)}this.parsePathCode(PConstants.VERTEX);this.parsePathVertex(px,py);this.vertices[this.vertices.length-1]["moveTo"]=true},parsePathVertex:function(x,y){var verts=[];verts[0]=x;verts[1]=y;this.vertices.push(verts)},parsePathCode:function(what){this.vertexCodes.push(what)},parsePoly:function(val){this.family=PConstants.PATH;this.close=val;var pointsAttr=p.trim(this.element.getStringAttribute("points").replace(/[,\s]+/g," "));if(pointsAttr!==null){var pointsBuffer=pointsAttr.split(" ");if(pointsBuffer.length%2===0){for(var i=0;i<pointsBuffer.length;i++){var verts=[];verts[0]=pointsBuffer[i];verts[1]=pointsBuffer[++i];this.vertices.push(verts)}}else{p.println("Error parsing polygon points: odd number of coordinates provided")}}},parseRect:function(){this.kind=PConstants.RECT;this.family=PConstants.PRIMITIVE;this.params=[];this.params[0]=this.element.getFloatAttribute("x");this.params[1]=this.element.getFloatAttribute("y");this.params[2]=this.element.getFloatAttribute("width");this.params[3]=this.element.getFloatAttribute("height");if(this.params[2]<0||this.params[3]<0){throw ("svg error: negative width or height found while parsing <rect>")}},parseEllipse:function(val){this.kind=PConstants.ELLIPSE;this.family=PConstants.PRIMITIVE;this.params=[];this.params[0]=this.element.getFloatAttribute("cx")|0;this.params[1]=this.element.getFloatAttribute("cy")|0;var rx,ry;if(val){rx=ry=this.element.getFloatAttribute("r");if(rx<0){throw ("svg error: negative radius found while parsing <circle>")}}else{rx=this.element.getFloatAttribute("rx");ry=this.element.getFloatAttribute("ry");if(rx<0||ry<0){throw ("svg error: negative x-axis radius or y-axis radius found while parsing <ellipse>")}}this.params[0]-=rx;this.params[1]-=ry;this.params[2]=rx*2;this.params[3]=ry*2},parseLine:function(){this.kind=PConstants.LINE;this.family=PConstants.PRIMITIVE;this.params=[];this.params[0]=this.element.getFloatAttribute("x1");this.params[1]=this.element.getFloatAttribute("y1");this.params[2]=this.element.getFloatAttribute("x2");this.params[3]=this.element.getFloatAttribute("y2")},parseColors:function(element){if(element.hasAttribute("opacity")){this.setOpacity(element.getAttribute("opacity"))}if(element.hasAttribute("stroke")){this.setStroke(element.getAttribute("stroke"))}if(element.hasAttribute("stroke-width")){this.setStrokeWeight(element.getAttribute("stroke-width"))}if(element.hasAttribute("stroke-linejoin")){this.setStrokeJoin(element.getAttribute("stroke-linejoin"))}if(element.hasAttribute("stroke-linecap")){this.setStrokeCap(element.getStringAttribute("stroke-linecap"))}if(element.hasAttribute("fill")){this.setFill(element.getStringAttribute("fill"))}if(element.hasAttribute("style")){var styleText=element.getStringAttribute("style");var styleTokens=styleText.toString().split(";");for(var i=0;i<styleTokens.length;i++){var tokens=p.trim(styleTokens[i].split(":"));switch(tokens[0]){case"fill":this.setFill(tokens[1]);break;case"fill-opacity":this.setFillOpacity(tokens[1]);break;case"stroke":this.setStroke(tokens[1]);break;case"stroke-width":this.setStrokeWeight(tokens[1]);break;case"stroke-linecap":this.setStrokeCap(tokens[1]);break;case"stroke-linejoin":this.setStrokeJoin(tokens[1]);break;case"stroke-opacity":this.setStrokeOpacity(tokens[1]);break;case"opacity":this.setOpacity(tokens[1]);break}}}},setFillOpacity:function(opacityText){this.fillOpacity=parseFloat(opacityText);this.fillColor=this.fillOpacity*255<<24|this.fillColor&16777215},setFill:function(fillText){var opacityMask=this.fillColor&4278190080;if(fillText==="none"){this.fill=false}else{if(fillText.indexOf("#")===0){this.fill=true;if(fillText.length===4){fillText=fillText.replace(/#(.)(.)(.)/,"#$1$1$2$2$3$3")}this.fillColor=opacityMask|(parseInt(fillText.substring(1),16))&16777215}else{if(fillText.indexOf("rgb")===0){this.fill=true;this.fillColor=opacityMask|this.parseRGB(fillText)}else{if(fillText.indexOf("url(#")===0){this.fillName=fillText.substring(5,fillText.length-1)}else{if(colors[fillText]){this.fill=true;this.fillColor=opacityMask|(parseInt(colors[fillText].substring(1),16))&16777215}}}}}},setOpacity:function(opacity){this.strokeColor=parseFloat(opacity)*255<<24|this.strokeColor&16777215;this.fillColor=parseFloat(opacity)*255<<24|this.fillColor&16777215},setStroke:function(strokeText){var opacityMask=this.strokeColor&4278190080;if(strokeText==="none"){this.stroke=false}else{if(strokeText.charAt(0)==="#"){this.stroke=true;if(strokeText.length===4){strokeText=strokeText.replace(/#(.)(.)(.)/,"#$1$1$2$2$3$3")}this.strokeColor=opacityMask|(parseInt(strokeText.substring(1),16))&16777215}else{if(strokeText.indexOf("rgb")===0){this.stroke=true;this.strokeColor=opacityMask|this.parseRGB(strokeText)}else{if(strokeText.indexOf("url(#")===0){this.strokeName=strokeText.substring(5,strokeText.length-1)}else{if(colors[strokeText]){this.stroke=true;this.strokeColor=opacityMask|(parseInt(colors[strokeText].substring(1),16))&16777215}}}}}},setStrokeWeight:function(weight){this.strokeWeight=this.parseUnitSize(weight)},setStrokeJoin:function(linejoin){if(linejoin==="miter"){this.strokeJoin=PConstants.MITER}else{if(linejoin==="round"){this.strokeJoin=PConstants.ROUND}else{if(linejoin==="bevel"){this.strokeJoin=PConstants.BEVEL}}}},setStrokeCap:function(linecap){if(linecap==="butt"){this.strokeCap=PConstants.SQUARE}else{if(linecap==="round"){this.strokeCap=PConstants.ROUND}else{if(linecap==="square"){this.strokeCap=PConstants.PROJECT}}}},setStrokeOpacity:function(opacityText){this.strokeOpacity=parseFloat(opacityText);this.strokeColor=this.strokeOpacity*255<<24|this.strokeColor&16777215},parseRGB:function(color){var sub=color.substring(color.indexOf("(")+1,color.indexOf(")"));var values=sub.split(", ");return(values[0]<<16)|(values[1]<<8)|(values[2])},parseUnitSize:function(text){var len=text.length-2;if(len<0){return text}if(text.indexOf("pt")===len){return parseFloat(text.substring(0,len))*1.25}else{if(text.indexOf("pc")===len){return parseFloat(text.substring(0,len))*15}else{if(text.indexOf("mm")===len){return parseFloat(text.substring(0,len))*3.543307}else{if(text.indexOf("cm")===len){return parseFloat(text.substring(0,len))*35.43307}else{if(text.indexOf("in")===len){return parseFloat(text.substring(0,len))*90}else{if(text.indexOf("px")===len){return parseFloat(text.substring(0,len))}else{return parseFloat(text)}}}}}}}};p.shape=function(shape,x,y,width,height){if(arguments.length>=1&&arguments[0]!==null){if(shape.isVisible()){p.pushMatrix();if(curShapeMode===PConstants.CENTER){if(arguments.length===5){p.translate(x-width/2,y-height/2);p.scale(width/shape.getWidth(),height/shape.getHeight())}else{if(arguments.length===3){p.translate(x-shape.getWidth()/2,-shape.getHeight()/2)}else{p.translate(-shape.getWidth()/2,-shape.getHeight()/2)}}}else{if(curShapeMode===PConstants.CORNER){if(arguments.length===5){p.translate(x,y);p.scale(width/shape.getWidth(),height/shape.getHeight())}else{if(arguments.length===3){p.translate(x,y)}}}else{if(curShapeMode===PConstants.CORNERS){if(arguments.length===5){width-=x;height-=y;p.translate(x,y);p.scale(width/shape.getWidth(),height/shape.getHeight())}else{if(arguments.length===3){p.translate(x,y)}}}}}shape.draw();if((arguments.length===1&&curShapeMode===PConstants.CENTER)||arguments.length>1){p.popMatrix()}}}};p.shapeMode=function(mode){curShapeMode=mode};p.loadShape=function(filename){if(arguments.length===1){if(filename.indexOf(".svg")>-1){return new PShapeSVG(null,filename)}}return null};var XMLAttribute=function(fname,n,nameSpace,v,t){this.fullName=fname||"";this.name=n||"";this.namespace=nameSpace||"";this.value=v;this.type=t};XMLAttribute.prototype={getName:function(){return this.name},getFullName:function(){return this.fullName},getNamespace:function(){return this.namespace},getValue:function(){return this.value},getType:function(){return this.type},setValue:function(newval){this.value=newval}};var XMLElement=p.XMLElement=function(){if(arguments.length===4){this.attributes=[];this.children=[];this.fullName=arguments[0]||"";if(arguments[1]){this.name=arguments[1]}else{var index=this.fullName.indexOf(":");if(index>=0){this.name=this.fullName.substring(index+1)}else{this.name=this.fullName}}this.namespace=arguments[1];this.content="";this.lineNr=arguments[3];this.systemID=arguments[2];this.parent=null}else{if((arguments.length===2&&arguments[1].indexOf(".")>-1)){this.attributes=[];this.children=[];this.fullName="";this.name="";this.namespace="";this.content="";this.systemID="";this.lineNr="";this.parent=null;this.parse(arguments[arguments.length-1])}else{if(arguments.length===1&&typeof arguments[0]==="string"){this.attributes=[];this.children=[];this.fullName="";this.name="";this.namespace="";this.content="";this.systemID="";this.lineNr="";this.parent=null;this.parse(arguments[0])}else{this.attributes=[];this.children=[];this.fullName="";this.name="";this.namespace="";this.content="";this.systemID="";this.lineNr="";this.parent=null}}}return this};XMLElement.prototype={parse:function(filename){var xmlDoc;try{if(filename.indexOf(".xml")>-1||filename.indexOf(".svg")>-1){filename=ajax(filename)}xmlDoc=new DOMParser().parseFromString(filename,"text/xml");var elements=xmlDoc.documentElement;if(elements){this.parseChildrenRecursive(null,elements)}else{throw ("Error loading document")}return this}catch(e){throw (e)}},createElement:function(){if(arguments.length===2){return new XMLElement(arguments[0],arguments[1],null,null)}else{return new XMLElement(arguments[0],arguments[1],arguments[2],arguments[3])}},hasAttribute:function(){if(arguments.length===1){return this.getAttribute(arguments[0])!==null}else{if(arguments.length===2){return this.getAttribute(arguments[0],arguments[1])!==null}}},createPCDataElement:function(){return new XMLElement()},equals:function(object){if(typeof object==="Object"){return this.equalsXMLElement(object)}},equalsXMLElement:function(object){if(object instanceof XMLElement){if(this.name!==object.getLocalName()){return false}if(this.attributes.length!==object.getAttributeCount()){return false}for(var i=0;i<this.attributes.length;i++){if(!object.hasAttribute(this.attributes[i].getName(),this.attributes[i].getNamespace())){return false}if(this.attributes[i].getValue()!==object.attributes[i].getValue()){return false}if(this.attributes[i].getType()!==object.attributes[i].getType()){return false}}if(this.children.length!==object.getChildCount()){return false}var child1,child2;for(i=0;i<this.children.length;i++){child1=this.getChildAtIndex(i);child2=object.getChildAtIndex(i);if(!child1.equalsXMLElement(child2)){return false}}return true}},getContent:function(){return this.content},getAttribute:function(){var attribute;if(arguments.length===2){attribute=this.findAttribute(arguments[0]);if(attribute){return attribute.getValue()}else{return arguments[1]}}else{if(arguments.length===1){attribute=this.findAttribute(arguments[0]);if(attribute){return attribute.getValue()}else{return null}}else{if(arguments.length===3){attribute=this.findAttribute(arguments[0],arguments[1]);if(attribute){return attribute.getValue()}else{return arguments[2]}}}}},getStringAttribute:function(){if(arguments.length===1){return this.getAttribute(arguments[0])}else{if(arguments.length===2){return this.getAttribute(arguments[0],arguments[1])}else{return this.getAttribute(arguments[0],arguments[1],arguments[2])}}},getFloatAttribute:function(){if(arguments.length===1){return parseFloat(this.getAttribute(arguments[0],0))}else{if(arguments.length===2){return this.getAttribute(arguments[0],arguments[1])}else{return this.getAttribute(arguments[0],arguments[1],arguments[2])}}},getIntAttribute:function(){if(arguments.length===1){return this.getAttribute(arguments[0],0)}else{if(arguments.length===2){return this.getAttribute(arguments[0],arguments[1])}else{return this.getAttribute(arguments[0],arguments[1],arguments[2])}}},hasChildren:function(){return this.children.length>0},addChild:function(child){if(child!==null){child.parent=this;this.children.push(child)}},insertChild:function(child,index){if(child){if((child.getLocalName()===null)&&(!this.hasChildren())){var lastChild=this.children[this.children.length-1];if(lastChild.getLocalName()===null){lastChild.setContent(lastChild.getContent()+child.getContent());return}}child.parent=this;this.children.splice(index,0,child)}},getChild:function(){if(typeof arguments[0]==="number"){return this.children[arguments[0]]}else{if(arguments[0].indexOf("/")!==-1){this.getChildRecursive(arguments[0].split("/"),0)}else{var kid,kidName;for(var i=0;i<this.getChildCount();i++){kid=this.getChild(i);kidName=kid.getName();if(kidName!==null&&kidName===arguments[0]){return kid}}return null}}},getChildren:function(){if(arguments.length===1){if(typeof arguments[0]==="number"){return this.getChild(arguments[0])}else{if(arguments[0].indexOf("/")!==-1){return this.getChildrenRecursive(arguments[0].split("/"),0)}else{var matches=[];var kid,kidName;for(var i=0;i<this.getChildCount();i++){kid=this.getChild(i);kidName=kid.getName();if(kidName!==null&&kidName===arguments[0]){matches.push(kid)}}return matches}}}else{return this.children}},getChildCount:function(){return this.children.length},getChildRecursive:function(items,offset){var kid,kidName;for(var i=0;i<this.getChildCount();i++){kid=this.getChild(i);kidName=kid.getName();if(kidName!==null&&kidName===items[offset]){if(offset===items.length-1){return kid}else{offset+=1;return kid.getChildRecursive(items,offset)}}}return null},getChildrenRecursive:function(items,offset){if(offset===items.length-1){return this.getChildren(items[offset])}var matches=this.getChildren(items[offset]);var kidMatches;for(var i=0;i<matches.length;i++){kidMatches=matches[i].getChildrenRecursive(items,offset+1)}return kidMatches},parseChildrenRecursive:function(parent,elementpath){var xmlelement,xmlattribute,tmpattrib;if(!parent){this.fullName=elementpath.localName;this.name=elementpath.nodeName;this.content=elementpath.textContent||"";xmlelement=this}else{xmlelement=new XMLElement(elementpath.localName,elementpath.nodeName,"","");xmlelement.content=elementpath.textContent||"";xmlelement.parent=parent}for(var l=0;l<elementpath.attributes.length;l++){tmpattrib=elementpath.attributes[l];xmlattribute=new XMLAttribute(tmpattrib.getname,tmpattrib.nodeName,tmpattrib.namespaceURI,tmpattrib.nodeValue,tmpattrib.nodeType);xmlelement.attributes.push(xmlattribute)}for(var node in elementpath.childNodes){if(elementpath.childNodes[node].nodeType===1){xmlelement.children.push(xmlelement.parseChildrenRecursive(xmlelement,elementpath.childNodes[node]))}}return xmlelement},isLeaf:function(){return !this.hasChildren()},listChildren:function(){var arr=[];for(var i=0;i<this.children.length;i++){arr.push(this.getChild(i).getName())}return arr},removeAttribute:function(name,namespace){this.namespace=namespace||"";for(var i=0;i<this.attributes.length;i++){if(this.attributes[i].getName()===name&&this.attributes[i].getNamespace()===this.namespace){this.attributes.splice(i,1)}}},removeChild:function(child){if(child){for(var i=0;i<this.children.length;i++){if(this.children[i].equalsXMLElement(child)){this.children.splice(i,1)}}}},removeChildAtIndex:function(index){if(this.children.length>index){this.children.splice(index,1)}},findAttribute:function(name,namespace){this.namespace=namespace||"";for(var i=0;i<this.attributes.length;i++){if(this.attributes[i].getName()===name&&this.attributes[i].getNamespace()===this.namespace){return this.attributes[i]}}},setAttribute:function(){var attr;if(arguments.length===3){var index=arguments[0].indexOf(":");var name=arguments[0].substring(index+1);attr=this.findAttribute(name,arguments[1]);if(attr){attr.setValue(arguments[2])}else{attr=new XMLAttribute(arguments[0],name,arguments[1],arguments[2],"CDATA");this.attributes.push(attr)}}else{attr=this.findAttribute(arguments[0]);if(attr){attr.setValue(arguments[1])}else{attr=new XMLAttribute(arguments[0],arguments[0],null,arguments[1],"CDATA");this.attributes.push(attr)}}},setContent:function(content){this.content=content},setName:function(){if(arguments.length===1){this.name=arguments[0];this.fullName=arguments[0];this.namespace=null}else{var index=arguments[0].indexOf(":");if((arguments[1]===null)||(index<0)){this.name=arguments[0]}else{this.name=arguments[0].substring(index+1)}this.fullName=arguments[0];this.namespace=arguments[1]}},getName:function(){return this.fullName},getLocalName:function(){return this.name},getAttributeCount:function(){return this.attributes.length}};var printMatrixHelper=function printMatrixHelper(elements){var big=0;for(var i=0;i<elements.length;i++){if(i!==0){big=Math.max(big,Math.abs(elements[i]))}else{big=Math.abs(elements[i])}}var digits=(big+"").indexOf(".");if(digits===0){digits=1}else{if(digits===-1){digits=(big+"").length}}return digits};var PMatrix2D=p.PMatrix2D=function(){if(arguments.length===0){this.reset()}else{if(arguments.length===1&&arguments[0] instanceof PMatrix2D){this.set(arguments[0].array())}else{if(arguments.length===6){this.set(arguments[0],arguments[1],arguments[2],arguments[3],arguments[4],arguments[5])}}}};PMatrix2D.prototype={set:function(){if(arguments.length===6){var a=arguments;this.set([a[0],a[1],a[2],a[3],a[4],a[5]])}else{if(arguments.length===1&&arguments[0] instanceof PMatrix2D){this.elements=arguments[0].array()}else{if(arguments.length===1&&arguments[0] instanceof Array){this.elements=arguments[0].slice()}}}},get:function(){var outgoing=new PMatrix2D();outgoing.set(this.elements);return outgoing},reset:function(){this.set([1,0,0,0,1,0])},array:function array(){return this.elements.slice()},translate:function(tx,ty){this.elements[2]=tx*this.elements[0]+ty*this.elements[1]+this.elements[2];this.elements[5]=tx*this.elements[3]+ty*this.elements[4]+this.elements[5]},transpose:function(){},mult:function(source,target){var x,y;if(source instanceof PVector){x=source.x;y=source.y;if(!target){target=new PVector()}}else{if(source instanceof Array){x=source[0];y=source[1];if(!target){target=[]}}}if(target instanceof Array){target[0]=this.elements[0]*x+this.elements[1]*y+this.elements[2];target[1]=this.elements[3]*x+this.elements[4]*y+this.elements[5]}else{if(target instanceof PVector){target.x=this.elements[0]*x+this.elements[1]*y+this.elements[2];target.y=this.elements[3]*x+this.elements[4]*y+this.elements[5];target.z=0}}return target},multX:function(x,y){return(x*this.elements[0]+y*this.elements[1]+this.elements[2])},multY:function(x,y){return(x*this.elements[3]+y*this.elements[4]+this.elements[5])},skewX:function(angle){this.apply(1,0,1,angle,0,0)},skewY:function(angle){this.apply(1,0,1,0,angle,0)},determinant:function(){return(this.elements[0]*this.elements[4]-this.elements[1]*this.elements[3])},invert:function(){var d=this.determinant();if(Math.abs(d)>PConstants.MIN_INT){var old00=this.elements[0];var old01=this.elements[1];var old02=this.elements[2];var old10=this.elements[3];var old11=this.elements[4];var old12=this.elements[5];this.elements[0]=old11/d;this.elements[3]=-old10/d;this.elements[1]=-old01/d;this.elements[4]=old00/d;this.elements[2]=(old01*old12-old11*old02)/d;this.elements[5]=(old10*old02-old00*old12)/d;return true}return false},scale:function(sx,sy){if(sx&&!sy){sy=sx}if(sx&&sy){this.elements[0]*=sx;this.elements[1]*=sy;this.elements[3]*=sx;this.elements[4]*=sy}},apply:function(){var source;if(arguments.length===1&&arguments[0] instanceof PMatrix2D){source=arguments[0].array()}else{if(arguments.length===6){source=Array.prototype.slice.call(arguments)}else{if(arguments.length===1&&arguments[0] instanceof Array){source=arguments[0]}}}var result=[0,0,this.elements[2],0,0,this.elements[5]];var e=0;for(var row=0;row<2;row++){for(var col=0;col<3;col++,e++){result[e]+=this.elements[row*3+0]*source[col+0]+this.elements[row*3+1]*source[col+3]}}this.elements=result.slice()},preApply:function(){var source;if(arguments.length===1&&arguments[0] instanceof PMatrix2D){source=arguments[0].array()}else{if(arguments.length===6){source=Array.prototype.slice.call(arguments)}else{if(arguments.length===1&&arguments[0] instanceof Array){source=arguments[0]}}}var result=[0,0,source[2],0,0,source[5]];result[2]=source[2]+this.elements[2]*source[0]+this.elements[5]*source[1];result[5]=source[5]+this.elements[2]*source[3]+this.elements[5]*source[4];result[0]=this.elements[0]*source[0]+this.elements[3]*source[1];result[3]=this.elements[0]*source[3]+this.elements[3]*source[4];result[1]=this.elements[1]*source[0]+this.elements[4]*source[1];result[4]=this.elements[1]*source[3]+this.elements[4]*source[4];this.elements=result.slice()},rotate:function(angle){var c=Math.cos(angle);var s=Math.sin(angle);var temp1=this.elements[0];var temp2=this.elements[1];this.elements[0]=c*temp1+s*temp2;this.elements[1]=-s*temp1+c*temp2;temp1=this.elements[3];temp2=this.elements[4];this.elements[3]=c*temp1+s*temp2;this.elements[4]=-s*temp1+c*temp2},rotateZ:function(angle){this.rotate(angle)},print:function(){var digits=printMatrixHelper(this.elements);var output=""+p.nfs(this.elements[0],digits,4)+" "+p.nfs(this.elements[1],digits,4)+" "+p.nfs(this.elements[2],digits,4)+"\n"+p.nfs(this.elements[3],digits,4)+" "+p.nfs(this.elements[4],digits,4)+" "+p.nfs(this.elements[5],digits,4)+"\n\n";p.println(output)}};var PMatrix3D=p.PMatrix3D=function PMatrix3D(){this.reset()};PMatrix3D.prototype={set:function(){if(arguments.length===16){this.elements=Array.prototype.slice.call(arguments)}else{if(arguments.length===1&&arguments[0] instanceof PMatrix3D){this.elements=arguments[0].array()}else{if(arguments.length===1&&arguments[0] instanceof Array){this.elements=arguments[0].slice()}}}},get:function(){var outgoing=new PMatrix3D();outgoing.set(this.elements);return outgoing},reset:function(){this.set([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])},array:function array(){return this.elements.slice()},translate:function(tx,ty,tz){if(tz===undef){tz=0}this.elements[3]+=tx*this.elements[0]+ty*this.elements[1]+tz*this.elements[2];this.elements[7]+=tx*this.elements[4]+ty*this.elements[5]+tz*this.elements[6];this.elements[11]+=tx*this.elements[8]+ty*this.elements[9]+tz*this.elements[10];this.elements[15]+=tx*this.elements[12]+ty*this.elements[13]+tz*this.elements[14]},transpose:function(){var temp=this.elements.slice();this.elements[0]=temp[0];this.elements[1]=temp[4];this.elements[2]=temp[8];this.elements[3]=temp[12];this.elements[4]=temp[1];this.elements[5]=temp[5];this.elements[6]=temp[9];this.elements[7]=temp[13];this.elements[8]=temp[2];this.elements[9]=temp[6];this.elements[10]=temp[10];this.elements[11]=temp[14];this.elements[12]=temp[3];this.elements[13]=temp[7];this.elements[14]=temp[11];this.elements[15]=temp[15]},mult:function(source,target){var x,y,z,w;if(source instanceof PVector){x=source.x;y=source.y;z=source.z;w=1;if(!target){target=new PVector()}}else{if(source instanceof Array){x=source[0];y=source[1];z=source[2];w=source[3]||1;if(!target||target.length!==3&&target.length!==4){target=[0,0,0]}}}if(target instanceof Array){if(target.length===3){target[0]=this.elements[0]*x+this.elements[1]*y+this.elements[2]*z+this.elements[3];target[1]=this.elements[4]*x+this.elements[5]*y+this.elements[6]*z+this.elements[7];target[2]=this.elements[8]*x+this.elements[9]*y+this.elements[10]*z+this.elements[11]}else{if(target.length===4){target[0]=this.elements[0]*x+this.elements[1]*y+this.elements[2]*z+this.elements[3]*w;target[1]=this.elements[4]*x+this.elements[5]*y+this.elements[6]*z+this.elements[7]*w;target[2]=this.elements[8]*x+this.elements[9]*y+this.elements[10]*z+this.elements[11]*w;target[3]=this.elements[12]*x+this.elements[13]*y+this.elements[14]*z+this.elements[15]*w}}}if(target instanceof PVector){target.x=this.elements[0]*x+this.elements[1]*y+this.elements[2]*z+this.elements[3];target.y=this.elements[4]*x+this.elements[5]*y+this.elements[6]*z+this.elements[7];target.z=this.elements[8]*x+this.elements[9]*y+this.elements[10]*z+this.elements[11]}return target},preApply:function(){var source;if(arguments.length===1&&arguments[0] instanceof PMatrix3D){source=arguments[0].array()}else{if(arguments.length===16){source=Array.prototype.slice.call(arguments)}else{if(arguments.length===1&&arguments[0] instanceof Array){source=arguments[0]}}}var result=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];var e=0;for(var row=0;row<4;row++){for(var col=0;col<4;col++,e++){result[e]+=this.elements[col+0]*source[row*4+0]+this.elements[col+4]*source[row*4+1]+this.elements[col+8]*source[row*4+2]+this.elements[col+12]*source[row*4+3]}}this.elements=result.slice()},apply:function(){var source;if(arguments.length===1&&arguments[0] instanceof PMatrix3D){source=arguments[0].array()}else{if(arguments.length===16){source=Array.prototype.slice.call(arguments)}else{if(arguments.length===1&&arguments[0] instanceof Array){source=arguments[0]}}}var result=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];var e=0;for(var row=0;row<4;row++){for(var col=0;col<4;col++,e++){result[e]+=this.elements[row*4+0]*source[col+0]+this.elements[row*4+1]*source[col+4]+this.elements[row*4+2]*source[col+8]+this.elements[row*4+3]*source[col+12]}}this.elements=result.slice()},rotate:function(angle,v0,v1,v2){if(!v1){this.rotateZ(angle)}else{var c=p.cos(angle);var s=p.sin(angle);var t=1-c;this.apply((t*v0*v0)+c,(t*v0*v1)-(s*v2),(t*v0*v2)+(s*v1),0,(t*v0*v1)+(s*v2),(t*v1*v1)+c,(t*v1*v2)-(s*v0),0,(t*v0*v2)-(s*v1),(t*v1*v2)+(s*v0),(t*v2*v2)+c,0,0,0,0,1)}},invApply:function(){if(inverseCopy===undef){inverseCopy=new PMatrix3D()}var a=arguments;inverseCopy.set(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10],a[11],a[12],a[13],a[14],a[15]);if(!inverseCopy.invert()){return false}this.preApply(inverseCopy);return true},rotateX:function(angle){var c=p.cos(angle);var s=p.sin(angle);this.apply([1,0,0,0,0,c,-s,0,0,s,c,0,0,0,0,1])},rotateY:function(angle){var c=p.cos(angle);var s=p.sin(angle);this.apply([c,0,s,0,0,1,0,0,-s,0,c,0,0,0,0,1])},rotateZ:function(angle){var c=Math.cos(angle);var s=Math.sin(angle);this.apply([c,-s,0,0,s,c,0,0,0,0,1,0,0,0,0,1])},scale:function(sx,sy,sz){if(sx&&!sy&&!sz){sy=sz=sx}else{if(sx&&sy&&!sz){sz=1}}if(sx&&sy&&sz){this.elements[0]*=sx;this.elements[1]*=sy;this.elements[2]*=sz;this.elements[4]*=sx;this.elements[5]*=sy;this.elements[6]*=sz;this.elements[8]*=sx;this.elements[9]*=sy;this.elements[10]*=sz;this.elements[12]*=sx;this.elements[13]*=sy;this.elements[14]*=sz}},skewX:function(angle){var t=Math.tan(angle);this.apply(1,t,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},skewY:function(angle){var t=Math.tan(angle);this.apply(1,0,0,0,t,1,0,0,0,0,1,0,0,0,0,1)},multX:function(x,y,z,w){if(!z){return this.elements[0]*x+this.elements[1]*y+this.elements[3]}else{if(!w){return this.elements[0]*x+this.elements[1]*y+this.elements[2]*z+this.elements[3]}else{return this.elements[0]*x+this.elements[1]*y+this.elements[2]*z+this.elements[3]*w}}},multY:function(x,y,z,w){if(!z){return this.elements[4]*x+this.elements[5]*y+this.elements[7]}else{if(!w){return this.elements[4]*x+this.elements[5]*y+this.elements[6]*z+this.elements[7]}else{return this.elements[4]*x+this.elements[5]*y+this.elements[6]*z+this.elements[7]*w}}},multZ:function(x,y,z,w){if(!w){return this.elements[8]*x+this.elements[9]*y+this.elements[10]*z+this.elements[11]}else{return this.elements[8]*x+this.elements[9]*y+this.elements[10]*z+this.elements[11]*w}},multW:function(x,y,z,w){if(!w){return this.elements[12]*x+this.elements[13]*y+this.elements[14]*z+this.elements[15]}else{return this.elements[12]*x+this.elements[13]*y+this.elements[14]*z+this.elements[15]*w}},invert:function(){var fA0=this.elements[0]*this.elements[5]-this.elements[1]*this.elements[4];var fA1=this.elements[0]*this.elements[6]-this.elements[2]*this.elements[4];var fA2=this.elements[0]*this.elements[7]-this.elements[3]*this.elements[4];var fA3=this.elements[1]*this.elements[6]-this.elements[2]*this.elements[5];var fA4=this.elements[1]*this.elements[7]-this.elements[3]*this.elements[5];var fA5=this.elements[2]*this.elements[7]-this.elements[3]*this.elements[6];var fB0=this.elements[8]*this.elements[13]-this.elements[9]*this.elements[12];var fB1=this.elements[8]*this.elements[14]-this.elements[10]*this.elements[12];var fB2=this.elements[8]*this.elements[15]-this.elements[11]*this.elements[12];var fB3=this.elements[9]*this.elements[14]-this.elements[10]*this.elements[13];var fB4=this.elements[9]*this.elements[15]-this.elements[11]*this.elements[13];var fB5=this.elements[10]*this.elements[15]-this.elements[11]*this.elements[14];var fDet=fA0*fB5-fA1*fB4+fA2*fB3+fA3*fB2-fA4*fB1+fA5*fB0;if(Math.abs(fDet)<=1e-9){return false}var kInv=[];kInv[0]=+this.elements[5]*fB5-this.elements[6]*fB4+this.elements[7]*fB3;kInv[4]=-this.elements[4]*fB5+this.elements[6]*fB2-this.elements[7]*fB1;kInv[8]=+this.elements[4]*fB4-this.elements[5]*fB2+this.elements[7]*fB0;kInv[12]=-this.elements[4]*fB3+this.elements[5]*fB1-this.elements[6]*fB0;kInv[1]=-this.elements[1]*fB5+this.elements[2]*fB4-this.elements[3]*fB3;kInv[5]=+this.elements[0]*fB5-this.elements[2]*fB2+this.elements[3]*fB1;kInv[9]=-this.elements[0]*fB4+this.elements[1]*fB2-this.elements[3]*fB0;kInv[13]=+this.elements[0]*fB3-this.elements[1]*fB1+this.elements[2]*fB0;kInv[2]=+this.elements[13]*fA5-this.elements[14]*fA4+this.elements[15]*fA3;kInv[6]=-this.elements[12]*fA5+this.elements[14]*fA2-this.elements[15]*fA1;kInv[10]=+this.elements[12]*fA4-this.elements[13]*fA2+this.elements[15]*fA0;kInv[14]=-this.elements[12]*fA3+this.elements[13]*fA1-this.elements[14]*fA0;kInv[3]=-this.elements[9]*fA5+this.elements[10]*fA4-this.elements[11]*fA3;kInv[7]=+this.elements[8]*fA5-this.elements[10]*fA2+this.elements[11]*fA1;kInv[11]=-this.elements[8]*fA4+this.elements[9]*fA2-this.elements[11]*fA0;kInv[15]=+this.elements[8]*fA3-this.elements[9]*fA1+this.elements[10]*fA0;var fInvDet=1/fDet;kInv[0]*=fInvDet;kInv[1]*=fInvDet;kInv[2]*=fInvDet;kInv[3]*=fInvDet;kInv[4]*=fInvDet;kInv[5]*=fInvDet;kInv[6]*=fInvDet;kInv[7]*=fInvDet;kInv[8]*=fInvDet;kInv[9]*=fInvDet;kInv[10]*=fInvDet;kInv[11]*=fInvDet;kInv[12]*=fInvDet;kInv[13]*=fInvDet;kInv[14]*=fInvDet;kInv[15]*=fInvDet;this.elements=kInv.slice();return true},toString:function(){var str="";for(var i=0;i<15;i++){str+=this.elements[i]+", "}str+=this.elements[15];return str},print:function(){var digits=printMatrixHelper(this.elements);var output=""+p.nfs(this.elements[0],digits,4)+" "+p.nfs(this.elements[1],digits,4)+" "+p.nfs(this.elements[2],digits,4)+" "+p.nfs(this.elements[3],digits,4)+"\n"+p.nfs(this.elements[4],digits,4)+" "+p.nfs(this.elements[5],digits,4)+" "+p.nfs(this.elements[6],digits,4)+" "+p.nfs(this.elements[7],digits,4)+"\n"+p.nfs(this.elements[8],digits,4)+" "+p.nfs(this.elements[9],digits,4)+" "+p.nfs(this.elements[10],digits,4)+" "+p.nfs(this.elements[11],digits,4)+"\n"+p.nfs(this.elements[12],digits,4)+" "+p.nfs(this.elements[13],digits,4)+" "+p.nfs(this.elements[14],digits,4)+" "+p.nfs(this.elements[15],digits,4)+"\n\n";p.println(output)},invTranslate:function(tx,ty,tz){this.preApply(1,0,0,-tx,0,1,0,-ty,0,0,1,-tz,0,0,0,1)},invRotateX:function(angle){var c=Math.cos(-angle);var s=Math.sin(-angle);this.preApply([1,0,0,0,0,c,-s,0,0,s,c,0,0,0,0,1])},invRotateY:function(angle){var c=Math.cos(-angle);var s=Math.sin(-angle);this.preApply([c,0,s,0,0,1,0,0,-s,0,c,0,0,0,0,1])},invRotateZ:function(angle){var c=Math.cos(-angle);var s=Math.sin(-angle);this.preApply([c,-s,0,0,s,c,0,0,0,0,1,0,0,0,0,1])},invScale:function(x,y,z){this.preApply([1/x,0,0,0,0,1/y,0,0,0,0,1/z,0,0,0,0,1])}};var PMatrixStack=p.PMatrixStack=function PMatrixStack(){this.matrixStack=[]};PMatrixStack.prototype.load=function load(){var tmpMatrix;if(p.use3DContext){tmpMatrix=new PMatrix3D()}else{tmpMatrix=new PMatrix2D()}if(arguments.length===1){tmpMatrix.set(arguments[0])}else{tmpMatrix.set(arguments)}this.matrixStack.push(tmpMatrix)};PMatrixStack.prototype.push=function push(){this.matrixStack.push(this.peek())};PMatrixStack.prototype.pop=function pop(){return this.matrixStack.pop()};PMatrixStack.prototype.peek=function peek(){var tmpMatrix;if(p.use3DContext){tmpMatrix=new PMatrix3D()}else{tmpMatrix=new PMatrix2D()}tmpMatrix.set(this.matrixStack[this.matrixStack.length-1]);return tmpMatrix};PMatrixStack.prototype.mult=function mult(matrix){this.matrixStack[this.matrixStack.length-1].apply(matrix)};p.split=function(str,delim){return str.split(delim)};p.splitTokens=function(str,tokens){if(arguments.length===1){tokens="\n\t\r\f "}tokens="["+tokens+"]";var ary=[];var index=0;var pos=str.search(tokens);while(pos>=0){if(pos===0){str=str.substring(1)}else{ary[index]=str.substring(0,pos);index++;str=str.substring(pos)}pos=str.search(tokens)}if(str.length>0){ary[index]=str}if(ary.length===0){ary=undef}return ary};p.append=function(array,element){array[array.length]=element;return array};p.concat=function(array1,array2){return array1.concat(array2)};p.sort=function(array,numElem){var ret=[];if(array.length>0){var elemsToCopy=numElem>0?numElem:array.length;for(var i=0;i<elemsToCopy;i++){ret.push(array[i])}if(typeof array[0]==="string"){ret.sort()}else{ret.sort(function(a,b){return a-b})}if(numElem>0){for(var j=ret.length;j<array.length;j++){ret.push(array[j])}}}return ret};p.splice=function(array,value,index){if(value.length===0){return array}if(value instanceof Array){for(var i=0,j=index;i<value.length;j++,i++){array.splice(j,0,value[i])}}else{array.splice(index,0,value)}return array};p.subset=function(array,offset,length){if(arguments.length===2){return array.slice(offset,array.length-offset)}else{if(arguments.length===3){return array.slice(offset,offset+length)}}};p.join=function(array,seperator){return array.join(seperator)};p.shorten=function(ary){var newary=[];var len=ary.length;for(var i=0;i<len;i++){newary[i]=ary[i]}newary.pop();return newary};p.expand=function(ary,newSize){var temp=ary.slice(0);if(arguments.length===1){temp.length=ary.length*2;return temp}else{if(arguments.length===2){temp.length=newSize;return temp}}};p.arrayCopy=function(){var src,srcPos=0,dest,destPos=0,length;if(arguments.length===2){src=arguments[0];dest=arguments[1];length=src.length}else{if(arguments.length===3){src=arguments[0];dest=arguments[1];length=arguments[2]}else{if(arguments.length===5){src=arguments[0];srcPos=arguments[1];dest=arguments[2];destPos=arguments[3];length=arguments[4]}}}for(var i=srcPos,j=destPos;i<length+srcPos;i++,j++){if(dest[j]!==undef){dest[j]=src[i]}else{throw"array index out of bounds exception"}}};p.reverse=function(array){return array.reverse()};p.mix=function(a,b,f){return a+(((b-a)*f)>>8)};p.peg=function(n){return(n<0)?0:((n>255)?255:n)};p.modes={replace:function(c1,c2){return c2},blend:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|p.mix(c1&PConstants.RED_MASK,c2&PConstants.RED_MASK,f)&PConstants.RED_MASK|p.mix(c1&PConstants.GREEN_MASK,c2&PConstants.GREEN_MASK,f)&PConstants.GREEN_MASK|p.mix(c1&PConstants.BLUE_MASK,c2&PConstants.BLUE_MASK,f))},add:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|Math.min(((c1&PConstants.RED_MASK)+((c2&PConstants.RED_MASK)>>8)*f),PConstants.RED_MASK)&PConstants.RED_MASK|Math.min(((c1&PConstants.GREEN_MASK)+((c2&PConstants.GREEN_MASK)>>8)*f),PConstants.GREEN_MASK)&PConstants.GREEN_MASK|Math.min((c1&PConstants.BLUE_MASK)+(((c2&PConstants.BLUE_MASK)*f)>>8),PConstants.BLUE_MASK))},subtract:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|Math.max(((c1&PConstants.RED_MASK)-((c2&PConstants.RED_MASK)>>8)*f),PConstants.GREEN_MASK)&PConstants.RED_MASK|Math.max(((c1&PConstants.GREEN_MASK)-((c2&PConstants.GREEN_MASK)>>8)*f),PConstants.BLUE_MASK)&PConstants.GREEN_MASK|Math.max((c1&PConstants.BLUE_MASK)-(((c2&PConstants.BLUE_MASK)*f)>>8),0))},lightest:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|Math.max(c1&PConstants.RED_MASK,((c2&PConstants.RED_MASK)>>8)*f)&PConstants.RED_MASK|Math.max(c1&PConstants.GREEN_MASK,((c2&PConstants.GREEN_MASK)>>8)*f)&PConstants.GREEN_MASK|Math.max(c1&PConstants.BLUE_MASK,((c2&PConstants.BLUE_MASK)*f)>>8))},darkest:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|p.mix(c1&PConstants.RED_MASK,Math.min(c1&PConstants.RED_MASK,((c2&PConstants.RED_MASK)>>8)*f),f)&PConstants.RED_MASK|p.mix(c1&PConstants.GREEN_MASK,Math.min(c1&PConstants.GREEN_MASK,((c2&PConstants.GREEN_MASK)>>8)*f),f)&PConstants.GREEN_MASK|p.mix(c1&PConstants.BLUE_MASK,Math.min(c1&PConstants.BLUE_MASK,((c2&PConstants.BLUE_MASK)*f)>>8),f))},difference:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;var ar=(c1&PConstants.RED_MASK)>>16;var ag=(c1&PConstants.GREEN_MASK)>>8;var ab=(c1&PConstants.BLUE_MASK);var br=(c2&PConstants.RED_MASK)>>16;var bg=(c2&PConstants.GREEN_MASK)>>8;var bb=(c2&PConstants.BLUE_MASK);var cr=(ar>br)?(ar-br):(br-ar);var cg=(ag>bg)?(ag-bg):(bg-ag);var cb=(ab>bb)?(ab-bb):(bb-ab);return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|(p.peg(ar+(((cr-ar)*f)>>8))<<16)|(p.peg(ag+(((cg-ag)*f)>>8))<<8)|(p.peg(ab+(((cb-ab)*f)>>8))))},exclusion:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;var ar=(c1&PConstants.RED_MASK)>>16;var ag=(c1&PConstants.GREEN_MASK)>>8;var ab=(c1&PConstants.BLUE_MASK);var br=(c2&PConstants.RED_MASK)>>16;var bg=(c2&PConstants.GREEN_MASK)>>8;var bb=(c2&PConstants.BLUE_MASK);var cr=ar+br-((ar*br)>>7);var cg=ag+bg-((ag*bg)>>7);var cb=ab+bb-((ab*bb)>>7);return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|(p.peg(ar+(((cr-ar)*f)>>8))<<16)|(p.peg(ag+(((cg-ag)*f)>>8))<<8)|(p.peg(ab+(((cb-ab)*f)>>8))))},multiply:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;var ar=(c1&PConstants.RED_MASK)>>16;var ag=(c1&PConstants.GREEN_MASK)>>8;var ab=(c1&PConstants.BLUE_MASK);var br=(c2&PConstants.RED_MASK)>>16;var bg=(c2&PConstants.GREEN_MASK)>>8;var bb=(c2&PConstants.BLUE_MASK);var cr=(ar*br)>>8;var cg=(ag*bg)>>8;var cb=(ab*bb)>>8;return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|(p.peg(ar+(((cr-ar)*f)>>8))<<16)|(p.peg(ag+(((cg-ag)*f)>>8))<<8)|(p.peg(ab+(((cb-ab)*f)>>8))))},screen:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;var ar=(c1&PConstants.RED_MASK)>>16;var ag=(c1&PConstants.GREEN_MASK)>>8;var ab=(c1&PConstants.BLUE_MASK);var br=(c2&PConstants.RED_MASK)>>16;var bg=(c2&PConstants.GREEN_MASK)>>8;var bb=(c2&PConstants.BLUE_MASK);var cr=255-(((255-ar)*(255-br))>>8);var cg=255-(((255-ag)*(255-bg))>>8);var cb=255-(((255-ab)*(255-bb))>>8);return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|(p.peg(ar+(((cr-ar)*f)>>8))<<16)|(p.peg(ag+(((cg-ag)*f)>>8))<<8)|(p.peg(ab+(((cb-ab)*f)>>8))))},hard_light:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;var ar=(c1&PConstants.RED_MASK)>>16;var ag=(c1&PConstants.GREEN_MASK)>>8;var ab=(c1&PConstants.BLUE_MASK);var br=(c2&PConstants.RED_MASK)>>16;var bg=(c2&PConstants.GREEN_MASK)>>8;var bb=(c2&PConstants.BLUE_MASK);var cr=(br<128)?((ar*br)>>7):(255-(((255-ar)*(255-br))>>7));var cg=(bg<128)?((ag*bg)>>7):(255-(((255-ag)*(255-bg))>>7));var cb=(bb<128)?((ab*bb)>>7):(255-(((255-ab)*(255-bb))>>7));return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|(p.peg(ar+(((cr-ar)*f)>>8))<<16)|(p.peg(ag+(((cg-ag)*f)>>8))<<8)|(p.peg(ab+(((cb-ab)*f)>>8))))},soft_light:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;var ar=(c1&PConstants.RED_MASK)>>16;var ag=(c1&PConstants.GREEN_MASK)>>8;var ab=(c1&PConstants.BLUE_MASK);var br=(c2&PConstants.RED_MASK)>>16;var bg=(c2&PConstants.GREEN_MASK)>>8;var bb=(c2&PConstants.BLUE_MASK);var cr=((ar*br)>>7)+((ar*ar)>>8)-((ar*ar*br)>>15);var cg=((ag*bg)>>7)+((ag*ag)>>8)-((ag*ag*bg)>>15);var cb=((ab*bb)>>7)+((ab*ab)>>8)-((ab*ab*bb)>>15);return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|(p.peg(ar+(((cr-ar)*f)>>8))<<16)|(p.peg(ag+(((cg-ag)*f)>>8))<<8)|(p.peg(ab+(((cb-ab)*f)>>8))))},overlay:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;var ar=(c1&PConstants.RED_MASK)>>16;var ag=(c1&PConstants.GREEN_MASK)>>8;var ab=(c1&PConstants.BLUE_MASK);var br=(c2&PConstants.RED_MASK)>>16;var bg=(c2&PConstants.GREEN_MASK)>>8;var bb=(c2&PConstants.BLUE_MASK);var cr=(ar<128)?((ar*br)>>7):(255-(((255-ar)*(255-br))>>7));var cg=(ag<128)?((ag*bg)>>7):(255-(((255-ag)*(255-bg))>>7));var cb=(ab<128)?((ab*bb)>>7):(255-(((255-ab)*(255-bb))>>7));return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|(p.peg(ar+(((cr-ar)*f)>>8))<<16)|(p.peg(ag+(((cg-ag)*f)>>8))<<8)|(p.peg(ab+(((cb-ab)*f)>>8))))},dodge:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;var ar=(c1&PConstants.RED_MASK)>>16;var ag=(c1&PConstants.GREEN_MASK)>>8;var ab=(c1&PConstants.BLUE_MASK);var br=(c2&PConstants.RED_MASK)>>16;var bg=(c2&PConstants.GREEN_MASK)>>8;var bb=(c2&PConstants.BLUE_MASK);var cr=(br===255)?255:p.peg((ar<<8)/(255-br));var cg=(bg===255)?255:p.peg((ag<<8)/(255-bg));var cb=(bb===255)?255:p.peg((ab<<8)/(255-bb));return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|(p.peg(ar+(((cr-ar)*f)>>8))<<16)|(p.peg(ag+(((cg-ag)*f)>>8))<<8)|(p.peg(ab+(((cb-ab)*f)>>8))))},burn:function(c1,c2){var f=(c2&PConstants.ALPHA_MASK)>>>24;var ar=(c1&PConstants.RED_MASK)>>16;var ag=(c1&PConstants.GREEN_MASK)>>8;var ab=(c1&PConstants.BLUE_MASK);var br=(c2&PConstants.RED_MASK)>>16;var bg=(c2&PConstants.GREEN_MASK)>>8;var bb=(c2&PConstants.BLUE_MASK);var cr=(br===0)?0:255-p.peg(((255-ar)<<8)/br);var cg=(bg===0)?0:255-p.peg(((255-ag)<<8)/bg);var cb=(bb===0)?0:255-p.peg(((255-ab)<<8)/bb);return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|(p.peg(ar+(((cr-ar)*f)>>8))<<16)|(p.peg(ag+(((cg-ag)*f)>>8))<<8)|(p.peg(ab+(((cb-ab)*f)>>8))))}};function color$4(aValue1,aValue2,aValue3,aValue4){var r,g,b,a;if(curColorMode===PConstants.HSB){var rgb=p.color.toRGB(aValue1,aValue2,aValue3);r=rgb[0];g=rgb[1];b=rgb[2]}else{r=Math.round(255*(aValue1/colorModeX));g=Math.round(255*(aValue2/colorModeY));b=Math.round(255*(aValue3/colorModeZ))}a=Math.round(255*(aValue4/colorModeA));r=(r>255)?255:r;g=(g>255)?255:g;b=(b>255)?255:b;a=(a>255)?255:a;return(a<<24)&PConstants.ALPHA_MASK|(r<<16)&PConstants.RED_MASK|(g<<8)&PConstants.GREEN_MASK|b&PConstants.BLUE_MASK}function color$2(aValue1,aValue2){var a;if(aValue1&PConstants.ALPHA_MASK){a=Math.round(255*(aValue2/colorModeA));a=(a>255)?255:a;return aValue1-(aValue1&PConstants.ALPHA_MASK)+((a<<24)&PConstants.ALPHA_MASK)}else{if(curColorMode===PConstants.RGB){return color$4(aValue1,aValue1,aValue1,aValue2)}else{if(curColorMode===PConstants.HSB){return color$4(0,0,(aValue1/colorModeX)*colorModeZ,aValue2)}}}}function color$1(aValue1){if(aValue1<=colorModeX&&aValue1>=0){if(curColorMode===PConstants.RGB){return color$4(aValue1,aValue1,aValue1,colorModeA)}else{if(curColorMode===PConstants.HSB){return color$4(0,0,(aValue1/colorModeX)*colorModeZ,colorModeA)}}}else{if(aValue1){return aValue1}}}p.color=function color(aValue1,aValue2,aValue3,aValue4){if(aValue1!==undef&&aValue2!==undef&&aValue3!==undef&&aValue4!==undef){return color$4(aValue1,aValue2,aValue3,aValue4)}else{if(aValue1!==undef&&aValue2!==undef&&aValue3!==undef){return color$4(aValue1,aValue2,aValue3,colorModeA)}else{if(aValue1!==undef&&aValue2!==undef){return color$2(aValue1,aValue2)}else{if(typeof aValue1==="number"){return color$1(aValue1)}else{return color$4(colorModeX,colorModeY,colorModeZ,colorModeA)}}}}};p.color.toString=function(colorInt){return"rgba("+((colorInt&PConstants.RED_MASK)>>>16)+","+((colorInt&PConstants.GREEN_MASK)>>>8)+","+((colorInt&PConstants.BLUE_MASK))+","+((colorInt&PConstants.ALPHA_MASK)>>>24)/255+")"};p.color.toInt=function(r,g,b,a){return(a<<24)&PConstants.ALPHA_MASK|(r<<16)&PConstants.RED_MASK|(g<<8)&PConstants.GREEN_MASK|b&PConstants.BLUE_MASK};p.color.toArray=function(colorInt){return[(colorInt&PConstants.RED_MASK)>>>16,(colorInt&PConstants.GREEN_MASK)>>>8,colorInt&PConstants.BLUE_MASK,(colorInt&PConstants.ALPHA_MASK)>>>24]};p.color.toGLArray=function(colorInt){return[((colorInt&PConstants.RED_MASK)>>>16)/255,((colorInt&PConstants.GREEN_MASK)>>>8)/255,(colorInt&PConstants.BLUE_MASK)/255,((colorInt&PConstants.ALPHA_MASK)>>>24)/255]};p.color.toRGB=function(h,s,b){h=(h>colorModeX)?colorModeX:h;s=(s>colorModeY)?colorModeY:s;b=(b>colorModeZ)?colorModeZ:b;h=(h/colorModeX)*360;s=(s/colorModeY)*100;b=(b/colorModeZ)*100;var br=Math.round(b/100*255);if(s===0){return[br,br,br]}else{var hue=h%360;var f=hue%60;var p=Math.round((b*(100-s))/10000*255);var q=Math.round((b*(6000-s*f))/600000*255);var t=Math.round((b*(6000-s*(60-f)))/600000*255);switch(Math.floor(hue/60)){case 0:return[br,t,p];case 1:return[q,br,p];case 2:return[p,br,t];case 3:return[p,q,br];case 4:return[t,p,br];case 5:return[br,p,q]}}};p.color.toHSB=function(colorInt){var red,green,blue;red=((colorInt&PConstants.RED_MASK)>>>16)/255;green=((colorInt&PConstants.GREEN_MASK)>>>8)/255;blue=(colorInt&PConstants.BLUE_MASK)/255;var max=p.max(p.max(red,green),blue),min=p.min(p.min(red,green),blue),hue,saturation;if(min===max){return[0,0,max]}else{saturation=(max-min)/max;if(red===max){hue=(green-blue)/(max-min)}else{if(green===max){hue=2+((blue-red)/(max-min))}else{hue=4+((red-green)/(max-min))}}hue/=6;if(hue<0){hue+=1}else{if(hue>1){hue-=1}}}return[hue*colorModeX,saturation*colorModeY,max*colorModeZ]};p.brightness=function(colInt){return p.color.toHSB(colInt)[2]};p.saturation=function(colInt){return p.color.toHSB(colInt)[1]};p.hue=function(colInt){return p.color.toHSB(colInt)[0]};var verifyChannel=function verifyChannel(aColor){if(aColor.constructor===Array){return aColor}else{return p.color(aColor)}};p.red=function(aColor){return((aColor&PConstants.RED_MASK)>>>16)/255*colorModeX};p.green=function(aColor){return((aColor&PConstants.GREEN_MASK)>>>8)/255*colorModeY};p.blue=function(aColor){return(aColor&PConstants.BLUE_MASK)/255*colorModeZ};p.alpha=function(aColor){return((aColor&PConstants.ALPHA_MASK)>>>24)/255*colorModeA};p.lerpColor=function lerpColor(c1,c2,amt){var colorBits1=p.color(c1);var r1=(colorBits1&PConstants.RED_MASK)>>>16;var g1=(colorBits1&PConstants.GREEN_MASK)>>>8;var b1=(colorBits1&PConstants.BLUE_MASK);var a1=((colorBits1&PConstants.ALPHA_MASK)>>>24)/colorModeA;var colorBits2=p.color(c2);var r2=(colorBits2&PConstants.RED_MASK)>>>16;var g2=(colorBits2&PConstants.GREEN_MASK)>>>8;var b2=(colorBits2&PConstants.BLUE_MASK);var a2=((colorBits2&PConstants.ALPHA_MASK)>>>24)/colorModeA;var r=parseInt(p.lerp(r1,r2,amt),10);var g=parseInt(p.lerp(g1,g2,amt),10);var b=parseInt(p.lerp(b1,b2,amt),10);var a=parseFloat(p.lerp(a1,a2,amt)*colorModeA);return p.color.toInt(r,g,b,a)};p.defaultColor=function(aValue1,aValue2,aValue3){var tmpColorMode=curColorMode;curColorMode=PConstants.RGB;var c=p.color(aValue1/255*colorModeX,aValue2/255*colorModeY,aValue3/255*colorModeZ);curColorMode=tmpColorMode;return c};p.colorMode=function colorMode(){curColorMode=arguments[0];if(arguments.length>1){colorModeX=arguments[1];colorModeY=arguments[2]||arguments[1];colorModeZ=arguments[3]||arguments[1];colorModeA=arguments[4]||arguments[1]}};p.blendColor=function(c1,c2,mode){var color=0;switch(mode){case PConstants.REPLACE:color=p.modes.replace(c1,c2);break;case PConstants.BLEND:color=p.modes.blend(c1,c2);break;case PConstants.ADD:color=p.modes.add(c1,c2);break;case PConstants.SUBTRACT:color=p.modes.subtract(c1,c2);break;case PConstants.LIGHTEST:color=p.modes.lightest(c1,c2);break;case PConstants.DARKEST:color=p.modes.darkest(c1,c2);break;case PConstants.DIFFERENCE:color=p.modes.difference(c1,c2);break;case PConstants.EXCLUSION:color=p.modes.exclusion(c1,c2);break;case PConstants.MULTIPLY:color=p.modes.multiply(c1,c2);break;case PConstants.SCREEN:color=p.modes.screen(c1,c2);break;case PConstants.HARD_LIGHT:color=p.modes.hard_light(c1,c2);break;case PConstants.SOFT_LIGHT:color=p.modes.soft_light(c1,c2);break;case PConstants.OVERLAY:color=p.modes.overlay(c1,c2);break;case PConstants.DODGE:color=p.modes.dodge(c1,c2);break;case PConstants.BURN:color=p.modes.burn(c1,c2);break}return color};function saveContext(){curContext.save()}function restoreContext(){curContext.restore();isStrokeDirty=true;isFillDirty=true}p.printMatrix=function printMatrix(){modelView.print()};p.translate=function translate(x,y,z){if(p.use3DContext){forwardTransform.translate(x,y,z);reverseTransform.invTranslate(x,y,z)}else{curContext.translate(x,y)}};p.scale=function scale(x,y,z){if(p.use3DContext){forwardTransform.scale(x,y,z);reverseTransform.invScale(x,y,z)}else{curContext.scale(x,y||x)}};p.pushMatrix=function pushMatrix(){if(p.use3DContext){userMatrixStack.load(modelView)}else{saveContext()}};p.popMatrix=function popMatrix(){if(p.use3DContext){modelView.set(userMatrixStack.pop())}else{restoreContext()}};p.resetMatrix=function resetMatrix(){if(p.use3DContext){forwardTransform.reset();reverseTransform.reset()}else{curContext.setTransform(1,0,0,1,0,0)}};p.applyMatrix=function applyMatrix(){var a=arguments;if(!p.use3DContext){for(var cnt=a.length;cnt<16;cnt++){a[cnt]=0}a[10]=a[15]=1}forwardTransform.apply(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10],a[11],a[12],a[13],a[14],a[15]);reverseTransform.invApply(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10],a[11],a[12],a[13],a[14],a[15])};p.rotateX=function(angleInRadians){forwardTransform.rotateX(angleInRadians);reverseTransform.invRotateX(angleInRadians)};p.rotateZ=function(angleInRadians){forwardTransform.rotateZ(angleInRadians);reverseTransform.invRotateZ(angleInRadians)};p.rotateY=function(angleInRadians){forwardTransform.rotateY(angleInRadians);reverseTransform.invRotateY(angleInRadians)};p.rotate=function rotate(angleInRadians){if(p.use3DContext){forwardTransform.rotateZ(angleInRadians);reverseTransform.invRotateZ(angleInRadians)}else{curContext.rotate(angleInRadians)}};p.pushStyle=function pushStyle(){saveContext();p.pushMatrix();var newState={doFill:doFill,currentFillColor:currentFillColor,doStroke:doStroke,currentStrokeColor:currentStrokeColor,curTint:curTint,curRectMode:curRectMode,curColorMode:curColorMode,colorModeX:colorModeX,colorModeZ:colorModeZ,colorModeY:colorModeY,colorModeA:colorModeA,curTextFont:curTextFont,curTextSize:curTextSize};styleArray.push(newState)};p.popStyle=function popStyle(){var oldState=styleArray.pop();if(oldState){restoreContext();p.popMatrix();doFill=oldState.doFill;currentFillColor=oldState.currentFillColor;doStroke=oldState.doStroke;currentStrokeColor=oldState.currentStrokeColor;curTint=oldState.curTint;curRectMode=oldState.curRectmode;curColorMode=oldState.curColorMode;colorModeX=oldState.colorModeX;colorModeZ=oldState.colorModeZ;colorModeY=oldState.colorModeY;colorModeA=oldState.colorModeA;curTextFont=oldState.curTextFont;curTextSize=oldState.curTextSize}else{throw"Too many popStyle() without enough pushStyle()"}};p.year=function year(){return new Date().getFullYear()};p.month=function month(){return new Date().getMonth()+1};p.day=function day(){return new Date().getDate()};p.hour=function hour(){return new Date().getHours()};p.minute=function minute(){return new Date().getMinutes()};p.second=function second(){return new Date().getSeconds()};p.millis=function millis(){return new Date().getTime()-start};p.redraw=function redraw(){var sec=(new Date().getTime()-timeSinceLastFPS)/1000;framesSinceLastFPS++;var fps=framesSinceLastFPS/sec;if(sec>0.5){timeSinceLastFPS=new Date().getTime();framesSinceLastFPS=0;p.__frameRate=fps}p.frameCount++;inDraw=true;if(p.use3DContext){curContext.clear(curContext.DEPTH_BUFFER_BIT);curContextCache={attributes:{},locations:{}};p.noLights();p.lightFalloff(1,0,0);p.shininess(1);p.ambient(255,255,255);p.specular(0,0,0);p.camera();p.draw()}else{saveContext();p.draw();restoreContext()}inDraw=false};p.noLoop=function noLoop(){doLoop=false;loopStarted=false;clearInterval(looping)};p.loop=function loop(){if(loopStarted){return}looping=window.setInterval(function(){try{if(document.hasFocus instanceof Function){p.focused=document.hasFocus()}p.redraw()}catch(e_loop){window.clearInterval(looping);throw e_loop}},curMsPerFrame);doLoop=true;loopStarted=true};p.frameRate=function frameRate(aRate){curFrameRate=aRate;curMsPerFrame=1000/curFrameRate;if(doLoop){p.noLoop();p.loop()}};var eventHandlers=[];p.exit=function exit(){window.clearInterval(looping);Processing.removeInstance(p.externals.canvas.id);for(var lib in Processing.lib){if(Processing.lib.hasOwnProperty(lib)){if(Processing.lib[lib].hasOwnProperty("detach")){Processing.lib[lib].detach(p)}}}for(var i=0,ehl=eventHandlers.length;i<ehl;i++){var elem=eventHandlers[i][0],type=eventHandlers[i][1],fn=eventHandlers[i][2];if(elem.removeEventListener){elem.removeEventListener(type,fn,false)}else{if(elem.detachEvent){elem.detachEvent("on"+type,fn)}}}};p.cursor=function cursor(){if(arguments.length>1||(arguments.length===1&&arguments[0] instanceof p.PImage)){var image=arguments[0],x,y;if(arguments.length>=3){x=arguments[1];y=arguments[2];if(x<0||y<0||y>=image.height||x>=image.width){throw"x and y must be non-negative and less than the dimensions of the image"}}else{x=image.width>>>1;y=image.height>>>1}var imageDataURL=image.toDataURL();var style='url("'+imageDataURL+'") '+x+" "+y+", default";curCursor=curElement.style.cursor=style}else{if(arguments.length===1){var mode=arguments[0];curCursor=curElement.style.cursor=mode}else{curCursor=curElement.style.cursor=oldCursor}}};p.noCursor=function noCursor(){curCursor=curElement.style.cursor=PConstants.NOCURSOR};p.link=function(href,target){if(target!==undef){window.open(href,target)}else{window.location=href}};p.beginDraw=function beginDraw(){};p.endDraw=function endDraw(){};p.Import=function Import(lib){};var contextMenu=function(e){e.preventDefault();e.stopPropagation()};p.disableContextMenu=function disableContextMenu(){curElement.addEventListener("contextmenu",contextMenu,false)};p.enableContextMenu=function enableContextMenu(){curElement.removeEventListener("contextmenu",contextMenu,false)};p.status=function(text){window.status=text};function decToBin(value,numBitsInValue){var mask=1;mask=mask<<(numBitsInValue-1);var str="";for(var i=0;i<numBitsInValue;i++){str+=(mask&value)?"1":"0";mask=mask>>>1}return str}p.binary=function(num,numBits){var numBitsInValue=32;if(typeof num==="number"){if(numBits){numBitsInValue=numBits}return decToBin(num,numBitsInValue)}if(num instanceof Char){num=num.toString().charCodeAt(0);if(numBits){numBitsInValue=32}else{numBitsInValue=16}}var str=decToBin(num,numBitsInValue);if(numBits){str=str.substr(-numBits)}return str};p.unbinary=function unbinary(binaryString){var binaryPattern=new RegExp("^[0|1]{8}$");var addUp=0;var i;if(binaryString instanceof Array){var values=[];for(i=0;i<binaryString.length;i++){values[i]=p.unbinary(binaryString[i])}return values}else{if(isNaN(binaryString)){throw"NaN_Err"}else{if(arguments.length===1||binaryString.length===8){if(binaryPattern.test(binaryString)){for(i=0;i<8;i++){addUp+=(Math.pow(2,i)*parseInt(binaryString.charAt(7-i),10))}return addUp+""}else{throw"notBinary: the value passed into unbinary was not an 8 bit binary number"}}else{throw"longErr"}}}};function nfCoreScalar(value,plus,minus,leftDigits,rightDigits,group){var sign=(value<0)?minus:plus;var autoDetectDecimals=rightDigits===0;var rightDigitsOfDefault=(rightDigits===undef||rightDigits<0)?0:rightDigits;var absValue=Math.abs(value);if(autoDetectDecimals){rightDigitsOfDefault=1;absValue*=10;while(Math.abs(Math.round(absValue)-absValue)>0.000001&&rightDigitsOfDefault<7){++rightDigitsOfDefault;absValue*=10}}else{if(rightDigitsOfDefault!==0){absValue*=Math.pow(10,rightDigitsOfDefault)}}var number,doubled=absValue*2;if(Math.floor(absValue)===absValue){number=absValue}else{if(Math.floor(doubled)===doubled){var floored=Math.floor(absValue);number=floored+(floored%2)}else{number=Math.round(absValue)}}var buffer="";var totalDigits=leftDigits+rightDigitsOfDefault;while(totalDigits>0||number>0){totalDigits--;buffer=""+(number%10)+buffer;number=Math.floor(number/10)}if(group!==undef){var i=buffer.length-3-rightDigitsOfDefault;while(i>0){buffer=buffer.substring(0,i)+group+buffer.substring(i);i-=3}}if(rightDigitsOfDefault>0){return sign+buffer.substring(0,buffer.length-rightDigitsOfDefault)+"."+buffer.substring(buffer.length-rightDigitsOfDefault,buffer.length)}else{return sign+buffer}}function nfCore(value,plus,minus,leftDigits,rightDigits,group){if(value instanceof Array){var arr=[];for(var i=0,len=value.length;i<len;i++){arr.push(nfCoreScalar(value[i],plus,minus,leftDigits,rightDigits,group))}return arr}else{return nfCoreScalar(value,plus,minus,leftDigits,rightDigits,group)}}p.nf=function(value,leftDigits,rightDigits){return nfCore(value,"","-",leftDigits,rightDigits)};p.nfs=function(value,leftDigits,rightDigits){return nfCore(value," ","-",leftDigits,rightDigits)};p.nfp=function(value,leftDigits,rightDigits){return nfCore(value,"+","-",leftDigits,rightDigits)};p.nfc=function(value,leftDigits,rightDigits){return nfCore(value,"","-",leftDigits,rightDigits,",")};var decimalToHex=function decimalToHex(d,padding){padding=(padding===undef||padding===null)?padding=8:padding;if(d<0){d=4294967295+d+1}var hex=Number(d).toString(16).toUpperCase();while(hex.length<padding){hex="0"+hex}if(hex.length>=padding){hex=hex.substring(hex.length-padding,hex.length)}return hex};p.hex=function hex(value,len){if(arguments.length===1){if(value instanceof Char){len=4}else{len=8}}return decimalToHex(value,len)};function unhexScalar(hex){var value=parseInt("0x"+hex,16);if(value>2147483647){value-=4294967296}return value}p.unhex=function(hex){if(hex instanceof Array){var arr=[];for(var i=0;i<hex.length;i++){arr.push(unhexScalar(hex[i]))}return arr}else{return unhexScalar(hex)}};p.loadStrings=function loadStrings(filename){if(localStorage[filename]){return localStorage[filename].split("\n")}var filecontent=ajax(filename);if(typeof filecontent!=="string"||filecontent===""){return[]}filecontent=filecontent.replace(/(\r\n?)/g,"\n").replace(/\n$/,"");return filecontent.split("\n")};p.saveStrings=function saveStrings(filename,strings){localStorage[filename]=strings.join("\n")};p.loadBytes=function loadBytes(url,strings){var string=ajax(url);var ret=[];for(var i=0;i<string.length;i++){ret.push(string.charCodeAt(i))}return ret};p.matchAll=function matchAll(aString,aRegExp){var results=[],latest;var regexp=new RegExp(aRegExp,"g");while((latest=regexp.exec(aString))!==null){results.push(latest);if(latest[0].length===0){++regexp.lastIndex}}return results.length>0?results:null};String.prototype.replaceAll=function(re,replace){return this.replace(new RegExp(re,"g"),replace)};String.prototype.equals=function equals(str){return this.valueOf()===str.valueOf()};String.prototype.toCharArray=function(){var chars=this.split("");for(var i=chars.length-1;i>=0;i--){chars[i]=new Char(chars[i])}return chars};p.match=function(str,regexp){return str.match(regexp)};var logBuffer=[];p.console=window.console||Processing.logger;p.println=function println(message){var bufferLen=logBuffer.length;if(bufferLen){Processing.logger.log(logBuffer.join(""));logBuffer.length=0}if(arguments.length===0&&bufferLen===0){Processing.logger.log("")}else{if(arguments.length!==0){Processing.logger.log(message)}}};p.print=function print(message){logBuffer.push(message)};p.str=function str(val){if(val instanceof Array){var arr=[];for(var i=0;i<val.length;i++){arr.push(val[i]+"")}return arr}else{return(val+"")}};p.trim=function(str){if(str instanceof Array){var arr=[];for(var i=0;i<str.length;i++){arr.push(str[i].replace(/^\s*/,"").replace(/\s*$/,"").replace(/\r*$/,""))}return arr}else{return str.replace(/^\s*/,"").replace(/\s*$/,"").replace(/\r*$/,"")}};function booleanScalar(val){if(typeof val==="number"){return val!==0}else{if(typeof val==="boolean"){return val}else{if(typeof val==="string"){return val.toLowerCase()==="true"}else{if(val instanceof Char){return val.code===49||val.code===84||val.code===116}}}}}p["boolean"]=function(val){if(val instanceof Array){var ret=[];for(var i=0;i<val.length;i++){ret.push(booleanScalar(val[i]))}return ret}else{return booleanScalar(val)}};p["byte"]=function(aNumber){if(aNumber instanceof Array){var bytes=[];for(var i=0;i<aNumber.length;i++){bytes.push((0-(aNumber[i]&128))|(aNumber[i]&127))}return bytes}else{return(0-(aNumber&128))|(aNumber&127)}};p["char"]=function(key){if(typeof key==="number"){return new Char(String.fromCharCode(key&65535))}else{if(key instanceof Array){var ret=[];for(var i=0;i<key.length;i++){ret.push(new Char(String.fromCharCode(key[i]&65535)))}return ret}else{throw"char() may receive only one argument of type int, byte, int[], or byte[]."}}};function floatScalar(val){if(typeof val==="number"){return val}else{if(typeof val==="boolean"){return val?1:0}else{if(typeof val==="string"){return parseFloat(val)}else{if(val instanceof Char){return val.code}}}}}p["float"]=function(val){if(val instanceof Array){var ret=[];for(var i=0;i<val.length;i++){ret.push(floatScalar(val[i]))}return ret}else{return floatScalar(val)}};function intScalar(val){if(typeof val==="number"){return val&4294967295}else{if(typeof val==="boolean"){return val?1:0}else{if(typeof val==="string"){var number=parseInt(val,10);return number&4294967295}else{if(val instanceof Char){return val.code}}}}}p["int"]=function(val){if(val instanceof Array){var ret=[];for(var i=0;i<val.length;i++){if(typeof val[i]==="string"&&!/^\s*[+\-]?\d+\s*$/.test(val[i])){ret.push(0)}else{ret.push(intScalar(val[i]))}}return ret}else{return intScalar(val)}};p.__int_cast=function(val){return 0|val};p.abs=Math.abs;p.ceil=Math.ceil;p.constrain=function(aNumber,aMin,aMax){return aNumber>aMax?aMax:aNumber<aMin?aMin:aNumber};p.dist=function(){var dx,dy,dz;if(arguments.length===4){dx=arguments[0]-arguments[2];dy=arguments[1]-arguments[3];return Math.sqrt(dx*dx+dy*dy)}else{if(arguments.length===6){dx=arguments[0]-arguments[3];dy=arguments[1]-arguments[4];dz=arguments[2]-arguments[5];return Math.sqrt(dx*dx+dy*dy+dz*dz)}}};p.exp=Math.exp;p.floor=Math.floor;p.lerp=function(value1,value2,amt){return((value2-value1)*amt)+value1};p.log=Math.log;p.mag=function(a,b,c){if(arguments.length===2){return Math.sqrt(a*a+b*b)}else{if(arguments.length===3){return Math.sqrt(a*a+b*b+c*c)}}};p.map=function(value,istart,istop,ostart,ostop){return ostart+(ostop-ostart)*((value-istart)/(istop-istart))};p.max=function(){if(arguments.length===2){return arguments[0]<arguments[1]?arguments[1]:arguments[0]}else{var numbers=arguments.length===1?arguments[0]:arguments;if(!("length" in numbers&&numbers.length>0)){throw"Non-empty array is expected"}var max=numbers[0],count=numbers.length;for(var i=1;i<count;++i){if(max<numbers[i]){max=numbers[i]}}return max}};p.min=function(){if(arguments.length===2){return arguments[0]<arguments[1]?arguments[0]:arguments[1]}else{var numbers=arguments.length===1?arguments[0]:arguments;if(!("length" in numbers&&numbers.length>0)){throw"Non-empty array is expected"}var min=numbers[0],count=numbers.length;for(var i=1;i<count;++i){if(min>numbers[i]){min=numbers[i]}}return min}};p.norm=function(aNumber,low,high){return(aNumber-low)/(high-low)};p.pow=Math.pow;p.round=Math.round;p.sq=function(aNumber){return aNumber*aNumber};p.sqrt=Math.sqrt;p.acos=Math.acos;p.asin=Math.asin;p.atan=Math.atan;p.atan2=Math.atan2;p.cos=Math.cos;p.degrees=function(aAngle){return(aAngle*180)/Math.PI};p.radians=function(aAngle){return(aAngle/180)*Math.PI};p.sin=Math.sin;p.tan=Math.tan;var currentRandom=Math.random;p.random=function random(){if(arguments.length===0){return currentRandom()}else{if(arguments.length===1){return currentRandom()*arguments[0]}else{var aMin=arguments[0],aMax=arguments[1];return currentRandom()*(aMax-aMin)+aMin}}};function Marsaglia(i1,i2){var z=i1||362436069,w=i2||521288629;var nextInt=function(){z=(36969*(z&65535)+(z>>>16))&4294967295;w=(18000*(w&65535)+(w>>>16))&4294967295;return(((z&65535)<<16)|(w&65535))&4294967295};this.nextDouble=function(){var i=nextInt()/4294967296;return i<0?1+i:i};this.nextInt=nextInt}Marsaglia.createRandomized=function(){var now=new Date();return new Marsaglia((now/60000)&4294967295,now&4294967295)};p.randomSeed=function(seed){currentRandom=(new Marsaglia(seed)).nextDouble};p.Random=function(seed){var haveNextNextGaussian=false,nextNextGaussian,random;this.nextGaussian=function(){if(haveNextNextGaussian){haveNextNextGaussian=false;return nextNextGaussian}else{var v1,v2,s;do{v1=2*random()-1;v2=2*random()-1;s=v1*v1+v2*v2}while(s>=1||s===0);var multiplier=Math.sqrt(-2*Math.log(s)/s);nextNextGaussian=v2*multiplier;haveNextNextGaussian=true;return v1*multiplier}};random=(seed===undef)?Math.random:(new Marsaglia(seed)).nextDouble};function PerlinNoise(seed){var rnd=seed!==undef?new Marsaglia(seed):Marsaglia.createRandomized();var i,j;var perm=new Array(512);for(i=0;i<256;++i){perm[i]=i}for(i=0;i<256;++i){var t=perm[j=rnd.nextInt()&255];perm[j]=perm[i];perm[i]=t}for(i=0;i<256;++i){perm[i+256]=perm[i]}function grad3d(i,x,y,z){var h=i&15;var u=h<8?x:y,v=h<4?y:h===12||h===14?x:z;return((h&1)===0?u:-u)+((h&2)===0?v:-v)}function grad2d(i,x,y){var v=(i&1)===0?x:y;return(i&2)===0?-v:v}function grad1d(i,x){return(i&1)===0?-x:x}function lerp(t,a,b){return a+t*(b-a)}this.noise3d=function(x,y,z){var X=Math.floor(x)&255,Y=Math.floor(y)&255,Z=Math.floor(z)&255;x-=Math.floor(x);y-=Math.floor(y);z-=Math.floor(z);var fx=(3-2*x)*x*x,fy=(3-2*y)*y*y,fz=(3-2*z)*z*z;var p0=perm[X]+Y,p00=perm[p0]+Z,p01=perm[p0+1]+Z,p1=perm[X+1]+Y,p10=perm[p1]+Z,p11=perm[p1+1]+Z;return lerp(fz,lerp(fy,lerp(fx,grad3d(perm[p00],x,y,z),grad3d(perm[p10],x-1,y,z)),lerp(fx,grad3d(perm[p01],x,y-1,z),grad3d(perm[p11],x-1,y-1,z))),lerp(fy,lerp(fx,grad3d(perm[p00+1],x,y,z-1),grad3d(perm[p10+1],x-1,y,z-1)),lerp(fx,grad3d(perm[p01+1],x,y-1,z-1),grad3d(perm[p11+1],x-1,y-1,z-1))))};this.noise2d=function(x,y){var X=Math.floor(x)&255,Y=Math.floor(y)&255;x-=Math.floor(x);y-=Math.floor(y);var fx=(3-2*x)*x*x,fy=(3-2*y)*y*y;var p0=perm[X]+Y,p1=perm[X+1]+Y;return lerp(fy,lerp(fx,grad2d(perm[p0],x,y),grad2d(perm[p1],x-1,y)),lerp(fx,grad2d(perm[p0+1],x,y-1),grad2d(perm[p1+1],x-1,y-1)))};this.noise1d=function(x){var X=Math.floor(x)&255;x-=Math.floor(x);var fx=(3-2*x)*x*x;return lerp(fx,grad1d(perm[X],x),grad1d(perm[X+1],x-1))}}var noiseProfile={generator:undef,octaves:4,fallout:0.5,seed:undef};p.noise=function(x,y,z){if(noiseProfile.generator===undef){noiseProfile.generator=new PerlinNoise(noiseProfile.seed)}var generator=noiseProfile.generator;var effect=1,k=1,sum=0;for(var i=0;i<noiseProfile.octaves;++i){effect*=noiseProfile.fallout;switch(arguments.length){case 1:sum+=effect*(1+generator.noise1d(k*x))/2;break;case 2:sum+=effect*(1+generator.noise2d(k*x,k*y))/2;break;case 3:sum+=effect*(1+generator.noise3d(k*x,k*y,k*z))/2;break}k*=2}return sum};p.noiseDetail=function(octaves,fallout){noiseProfile.octaves=octaves;if(fallout!==undef){noiseProfile.fallout=fallout}};p.noiseSeed=function(seed){noiseProfile.seed=seed;noiseProfile.generator=undef};var refreshBackground=function(){if(!curSketch.options.isTransparent){if(p.use3DContext){curContext.clearColor(204/255,204/255,204/255,1);curContext.clear(curContext.COLOR_BUFFER_BIT|curContext.DEPTH_BUFFER_BIT)}else{curContext.fillStyle="rgb(204, 204, 204)";curContext.fillRect(0,0,p.width,p.height);isFillDirty=true}}};p.size=function size(aWidth,aHeight,aMode){if(aMode&&(aMode===PConstants.WEBGL)){try{if(curElement.width!==aWidth||curElement.height!==aHeight){curElement.setAttribute("width",aWidth);curElement.setAttribute("height",aHeight)}curContext=curElement.getContext("experimental-webgl");p.use3DContext=true;canTex=curContext.createTexture();textTex=curContext.createTexture()}catch(e_size){Processing.debug(e_size)}if(!curContext){throw"WebGL context is not supported on this browser."}else{for(var i=0;i<PConstants.SINCOS_LENGTH;i++){sinLUT[i]=p.sin(i*(PConstants.PI/180)*0.5);cosLUT[i]=p.cos(i*(PConstants.PI/180)*0.5)}curContext.viewport(0,0,curElement.width,curElement.height);curContext.enable(curContext.DEPTH_TEST);curContext.enable(curContext.BLEND);curContext.blendFunc(curContext.SRC_ALPHA,curContext.ONE_MINUS_SRC_ALPHA);refreshBackground();programObject2D=createProgramObject(curContext,vertexShaderSource2D,fragmentShaderSource2D);curContext.useProgram(programObject2D);p.strokeWeight(1);programObject3D=createProgramObject(curContext,vertexShaderSource3D,fragmentShaderSource3D);programObjectUnlitShape=createProgramObject(curContext,vShaderSrcUnlitShape,fShaderSrcUnlitShape);curContext.useProgram(programObject3D);uniformi("usingTexture3d",programObject3D,"usingTexture",usingTexture);p.lightFalloff(1,0,0);p.shininess(1);p.ambient(255,255,255);p.specular(0,0,0);boxBuffer=curContext.createBuffer();curContext.bindBuffer(curContext.ARRAY_BUFFER,boxBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,boxVerts,curContext.STATIC_DRAW);boxNormBuffer=curContext.createBuffer();curContext.bindBuffer(curContext.ARRAY_BUFFER,boxNormBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,boxNorms,curContext.STATIC_DRAW);boxOutlineBuffer=curContext.createBuffer();curContext.bindBuffer(curContext.ARRAY_BUFFER,boxOutlineBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,boxOutlineVerts,curContext.STATIC_DRAW);rectBuffer=curContext.createBuffer();curContext.bindBuffer(curContext.ARRAY_BUFFER,rectBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,rectVerts,curContext.STATIC_DRAW);rectNormBuffer=curContext.createBuffer();curContext.bindBuffer(curContext.ARRAY_BUFFER,rectNormBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,rectNorms,curContext.STATIC_DRAW);sphereBuffer=curContext.createBuffer();lineBuffer=curContext.createBuffer();fillBuffer=curContext.createBuffer();fillColorBuffer=curContext.createBuffer();strokeColorBuffer=curContext.createBuffer();shapeTexVBO=curContext.createBuffer();pointBuffer=curContext.createBuffer();curContext.bindBuffer(curContext.ARRAY_BUFFER,pointBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array([0,0,0]),curContext.STATIC_DRAW);textBuffer=curContext.createBuffer();curContext.bindBuffer(curContext.ARRAY_BUFFER,textBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),curContext.STATIC_DRAW);textureBuffer=curContext.createBuffer();curContext.bindBuffer(curContext.ARRAY_BUFFER,textureBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array([0,0,1,0,1,1,0,1]),curContext.STATIC_DRAW);indexBuffer=curContext.createBuffer();curContext.bindBuffer(curContext.ELEMENT_ARRAY_BUFFER,indexBuffer);curContext.bufferData(curContext.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,2,3,0]),curContext.STATIC_DRAW);cam=new PMatrix3D();cameraInv=new PMatrix3D();forwardTransform=new PMatrix3D();reverseTransform=new PMatrix3D();modelView=new PMatrix3D();modelViewInv=new PMatrix3D();projection=new PMatrix3D();p.camera();p.perspective();forwardTransform=modelView;reverseTransform=modelViewInv;userMatrixStack=new PMatrixStack();curveBasisMatrix=new PMatrix3D();curveToBezierMatrix=new PMatrix3D();curveDrawMatrix=new PMatrix3D();bezierDrawMatrix=new PMatrix3D();bezierBasisInverse=new PMatrix3D();bezierBasisMatrix=new PMatrix3D();bezierBasisMatrix.set(-1,3,-3,1,3,-6,3,0,-3,3,0,0,1,0,0,0)}p.stroke(0);p.fill(255)}else{if(curContext===undef){curContext=curElement.getContext("2d");p.use3DContext=false;userMatrixStack=new PMatrixStack();modelView=new PMatrix2D()}}var props={fillStyle:curContext.fillStyle,strokeStyle:curContext.strokeStyle,lineCap:curContext.lineCap,lineJoin:curContext.lineJoin};if(curElement.style.length>0){curElement.style.removeProperty("width");curElement.style.removeProperty("height")}curElement.width=p.width=aWidth||100;curElement.height=p.height=aHeight||100;for(var j in props){if(props){curContext[j]=props[j]}}refreshBackground();maxPixelsCached=Math.max(1000,aWidth*aHeight*0.05);p.externals.context=curContext;p.toImageData=function(){if(!p.use3DContext){return curContext.getImageData(0,0,this.width,this.height)}else{var c=document.createElement("canvas");var ctx=c.getContext("2d");var obj=ctx.createImageData(this.width,this.height);var uBuff=new Uint8Array(this.width*this.height*4);curContext.readPixels(0,0,this.width,this.height,curContext.RGBA,curContext.UNSIGNED_BYTE,uBuff);for(var i=0;i<uBuff.length;i++){obj.data[i]=uBuff[(this.height-1-Math.floor(i/4/this.width))*this.width*4+(i%(this.width*4))]}return obj}}};p.ambientLight=function(r,g,b,x,y,z){if(p.use3DContext){if(lightCount===PConstants.MAX_LIGHTS){throw"can only create "+PConstants.MAX_LIGHTS+" lights"}var pos=new PVector(x,y,z);var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.mult(pos,pos);curContext.useProgram(programObject3D);uniformf("lights.color.3d."+lightCount,programObject3D,"lights["+lightCount+"].color",[r/255,g/255,b/255]);uniformf("lights.position.3d."+lightCount,programObject3D,"lights["+lightCount+"].position",pos.array());uniformi("lights.type.3d."+lightCount,programObject3D,"lights["+lightCount+"].type",0);uniformi("lightCount3d",programObject3D,"lightCount",++lightCount)}};p.directionalLight=function(r,g,b,nx,ny,nz){if(p.use3DContext){if(lightCount===PConstants.MAX_LIGHTS){throw"can only create "+PConstants.MAX_LIGHTS+" lights"}curContext.useProgram(programObject3D);var dir=[nx,ny,nz,1e-7];var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.mult(dir,dir);uniformf("lights.color.3d."+lightCount,programObject3D,"lights["+lightCount+"].color",[r/255,g/255,b/255]);uniformf("lights.position.3d."+lightCount,programObject3D,"lights["+lightCount+"].position",[-dir[0],-dir[1],-dir[2]]);uniformi("lights.type.3d."+lightCount,programObject3D,"lights["+lightCount+"].type",1);uniformi("lightCount3d",programObject3D,"lightCount",++lightCount)}};p.lightFalloff=function lightFalloff(constant,linear,quadratic){if(p.use3DContext){curContext.useProgram(programObject3D);uniformf("falloff3d",programObject3D,"falloff",[constant,linear,quadratic])}};p.lightSpecular=function lightSpecular(r,g,b){if(p.use3DContext){curContext.useProgram(programObject3D);uniformf("specular3d",programObject3D,"specular",[r/255,g/255,b/255])}};p.lights=function lights(){p.ambientLight(128,128,128);p.directionalLight(128,128,128,0,0,-1);p.lightFalloff(1,0,0);p.lightSpecular(0,0,0)};p.pointLight=function(r,g,b,x,y,z){if(p.use3DContext){if(lightCount===PConstants.MAX_LIGHTS){throw"can only create "+PConstants.MAX_LIGHTS+" lights"}var pos=new PVector(x,y,z);var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.mult(pos,pos);curContext.useProgram(programObject3D);uniformf("lights.color.3d."+lightCount,programObject3D,"lights["+lightCount+"].color",[r/255,g/255,b/255]);uniformf("lights.position.3d."+lightCount,programObject3D,"lights["+lightCount+"].position",pos.array());uniformi("lights.type.3d."+lightCount,programObject3D,"lights["+lightCount+"].type",2);uniformi("lightCount3d",programObject3D,"lightCount",++lightCount)}};p.noLights=function noLights(){if(p.use3DContext){lightCount=0;curContext.useProgram(programObject3D);uniformi("lightCount3d",programObject3D,"lightCount",lightCount)}};p.spotLight=function spotLight(r,g,b,x,y,z,nx,ny,nz,angle,concentration){if(p.use3DContext){if(lightCount===PConstants.MAX_LIGHTS){throw"can only create "+PConstants.MAX_LIGHTS+" lights"}curContext.useProgram(programObject3D);var pos=new PVector(x,y,z);var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.mult(pos,pos);var dir=[nx,ny,nz,1e-7];view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.mult(dir,dir);uniformf("lights.color.3d."+lightCount,programObject3D,"lights["+lightCount+"].color",[r/255,g/255,b/255]);uniformf("lights.position.3d."+lightCount,programObject3D,"lights["+lightCount+"].position",pos.array());uniformf("lights.direction.3d."+lightCount,programObject3D,"lights["+lightCount+"].direction",[dir[0],dir[1],dir[2]]);uniformf("lights.concentration.3d."+lightCount,programObject3D,"lights["+lightCount+"].concentration",concentration);uniformf("lights.angle.3d."+lightCount,programObject3D,"lights["+lightCount+"].angle",angle);uniformi("lights.type.3d."+lightCount,programObject3D,"lights["+lightCount+"].type",3);uniformi("lightCount3d",programObject3D,"lightCount",++lightCount)}};p.beginCamera=function beginCamera(){if(manipulatingCamera){throw ("You cannot call beginCamera() again before calling endCamera()")}else{manipulatingCamera=true;forwardTransform=cameraInv;reverseTransform=cam}};p.endCamera=function endCamera(){if(!manipulatingCamera){throw ("You cannot call endCamera() before calling beginCamera()")}else{modelView.set(cam);modelViewInv.set(cameraInv);forwardTransform=modelView;reverseTransform=modelViewInv;manipulatingCamera=false}};p.camera=function camera(eyeX,eyeY,eyeZ,centerX,centerY,centerZ,upX,upY,upZ){if(arguments.length===0){cameraX=curElement.width/2;cameraY=curElement.height/2;cameraZ=cameraY/Math.tan(cameraFOV/2);eyeX=cameraX;eyeY=cameraY;eyeZ=cameraZ;centerX=cameraX;centerY=cameraY;centerZ=0;upX=0;upY=1;upZ=0}var z=new PVector(eyeX-centerX,eyeY-centerY,eyeZ-centerZ);var y=new PVector(upX,upY,upZ);var transX,transY,transZ;z.normalize();var x=PVector.cross(y,z);y=PVector.cross(z,x);x.normalize();y.normalize();cam.set(x.x,x.y,x.z,0,y.x,y.y,y.z,0,z.x,z.y,z.z,0,0,0,0,1);cam.translate(-eyeX,-eyeY,-eyeZ);cameraInv.reset();cameraInv.invApply(x.x,x.y,x.z,0,y.x,y.y,y.z,0,z.x,z.y,z.z,0,0,0,0,1);cameraInv.translate(eyeX,eyeY,eyeZ);modelView.set(cam);modelViewInv.set(cameraInv)};p.perspective=function perspective(fov,aspect,near,far){if(arguments.length===0){cameraY=curElement.height/2;cameraZ=cameraY/Math.tan(cameraFOV/2);cameraNear=cameraZ/10;cameraFar=cameraZ*10;cameraAspect=curElement.width/curElement.height;fov=cameraFOV;aspect=cameraAspect;near=cameraNear;far=cameraFar}var yMax,yMin,xMax,xMin;yMax=near*Math.tan(fov/2);yMin=-yMax;xMax=yMax*aspect;xMin=yMin*aspect;p.frustum(xMin,xMax,yMin,yMax,near,far)};p.frustum=function frustum(left,right,bottom,top,near,far){frustumMode=true;projection=new PMatrix3D();projection.set((2*near)/(right-left),0,(right+left)/(right-left),0,0,(2*near)/(top-bottom),(top+bottom)/(top-bottom),0,0,0,-(far+near)/(far-near),-(2*far*near)/(far-near),0,0,-1,0)};p.ortho=function ortho(left,right,bottom,top,near,far){if(arguments.length===0){left=0;right=p.width;bottom=0;top=p.height;near=-10;far=10}var x=2/(right-left);var y=2/(top-bottom);var z=-2/(far-near);var tx=-(right+left)/(right-left);var ty=-(top+bottom)/(top-bottom);var tz=-(far+near)/(far-near);projection=new PMatrix3D();projection.set(x,0,0,tx,0,y,0,ty,0,0,z,tz,0,0,0,1);frustumMode=false};p.printProjection=function(){projection.print()};p.printCamera=function(){cam.print()};p.box=function(w,h,d){if(p.use3DContext){if(!h||!d){h=d=w}var model=new PMatrix3D();model.scale(w,h,d);var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.transpose();var proj=new PMatrix3D();proj.set(projection);proj.transpose();if(doFill===true){curContext.useProgram(programObject3D);disableVertexAttribPointer("aTexture3d",programObject3D,"aTexture");uniformMatrix("model3d",programObject3D,"model",false,model.array());uniformMatrix("view3d",programObject3D,"view",false,view.array());uniformMatrix("projection3d",programObject3D,"projection",false,proj.array());curContext.enable(curContext.POLYGON_OFFSET_FILL);curContext.polygonOffset(1,1);uniformf("color3d",programObject3D,"color",fillStyle);var v=new PMatrix3D();v.set(view);var m=new PMatrix3D();m.set(model);v.mult(m);var normalMatrix=new PMatrix3D();normalMatrix.set(v);normalMatrix.invert();normalMatrix.transpose();uniformMatrix("normalTransform3d",programObject3D,"normalTransform",false,normalMatrix.array());vertexAttribPointer("vertex3d",programObject3D,"Vertex",3,boxBuffer);vertexAttribPointer("normal3d",programObject3D,"Normal",3,boxNormBuffer);vertexAttribPointer("aColor3d",programObject3D,"aColor",3,boxNormBuffer);curContext.drawArrays(curContext.TRIANGLES,0,boxVerts.length/3);curContext.disable(curContext.POLYGON_OFFSET_FILL)}if(lineWidth>0&&doStroke){curContext.useProgram(programObject2D);uniformMatrix("model2d",programObject2D,"model",false,model.array());uniformMatrix("view2d",programObject2D,"view",false,view.array());uniformMatrix("projection2d",programObject2D,"projection",false,proj.array());uniformf("color2d",programObject2D,"color",strokeStyle);uniformi("picktype2d",programObject2D,"picktype",0);vertexAttribPointer("vertex2d",programObject2D,"Vertex",3,boxOutlineBuffer);disableVertexAttribPointer("aTextureCoord2d",programObject2D,"aTextureCoord");curContext.lineWidth(lineWidth);curContext.drawArrays(curContext.LINES,0,boxOutlineVerts.length/3)}}};var initSphere=function(){var i;sphereVerts=[];for(i=0;i<sphereDetailU;i++){sphereVerts.push(0);sphereVerts.push(-1);sphereVerts.push(0);sphereVerts.push(sphereX[i]);sphereVerts.push(sphereY[i]);sphereVerts.push(sphereZ[i])}sphereVerts.push(0);sphereVerts.push(-1);sphereVerts.push(0);sphereVerts.push(sphereX[0]);sphereVerts.push(sphereY[0]);sphereVerts.push(sphereZ[0]);var v1,v11,v2;var voff=0;for(i=2;i<sphereDetailV;i++){v1=v11=voff;voff+=sphereDetailU;v2=voff;for(var j=0;j<sphereDetailU;j++){sphereVerts.push(parseFloat(sphereX[v1]));sphereVerts.push(parseFloat(sphereY[v1]));sphereVerts.push(parseFloat(sphereZ[v1++]));sphereVerts.push(parseFloat(sphereX[v2]));sphereVerts.push(parseFloat(sphereY[v2]));sphereVerts.push(parseFloat(sphereZ[v2++]))}v1=v11;v2=voff;sphereVerts.push(parseFloat(sphereX[v1]));sphereVerts.push(parseFloat(sphereY[v1]));sphereVerts.push(parseFloat(sphereZ[v1]));sphereVerts.push(parseFloat(sphereX[v2]));sphereVerts.push(parseFloat(sphereY[v2]));sphereVerts.push(parseFloat(sphereZ[v2]))}for(i=0;i<sphereDetailU;i++){v2=voff+i;sphereVerts.push(parseFloat(sphereX[v2]));sphereVerts.push(parseFloat(sphereY[v2]));sphereVerts.push(parseFloat(sphereZ[v2]));sphereVerts.push(0);sphereVerts.push(1);sphereVerts.push(0)}sphereVerts.push(parseFloat(sphereX[voff]));sphereVerts.push(parseFloat(sphereY[voff]));sphereVerts.push(parseFloat(sphereZ[voff]));sphereVerts.push(0);sphereVerts.push(1);sphereVerts.push(0);curContext.bindBuffer(curContext.ARRAY_BUFFER,sphereBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array(sphereVerts),curContext.STATIC_DRAW)};p.sphereDetail=function sphereDetail(ures,vres){var i;if(arguments.length===1){ures=vres=arguments[0]}if(ures<3){ures=3}if(vres<2){vres=2}if((ures===sphereDetailU)&&(vres===sphereDetailV)){return}var delta=PConstants.SINCOS_LENGTH/ures;var cx=new Array(ures);var cz=new Array(ures);for(i=0;i<ures;i++){cx[i]=cosLUT[parseInt((i*delta)%PConstants.SINCOS_LENGTH,10)];cz[i]=sinLUT[parseInt((i*delta)%PConstants.SINCOS_LENGTH,10)]}var vertCount=ures*(vres-1)+2;var currVert=0;sphereX=new Array(vertCount);sphereY=new Array(vertCount);sphereZ=new Array(vertCount);var angle_step=(PConstants.SINCOS_LENGTH*0.5)/vres;var angle=angle_step;for(i=1;i<vres;i++){var curradius=sinLUT[parseInt(angle%PConstants.SINCOS_LENGTH,10)];var currY=-cosLUT[parseInt(angle%PConstants.SINCOS_LENGTH,10)];for(var j=0;j<ures;j++){sphereX[currVert]=cx[j]*curradius;sphereY[currVert]=currY;sphereZ[currVert++]=cz[j]*curradius}angle+=angle_step}sphereDetailU=ures;sphereDetailV=vres;initSphere()};p.sphere=function(){if(p.use3DContext){var sRad=arguments[0],c;if((sphereDetailU<3)||(sphereDetailV<2)){p.sphereDetail(30)}var model=new PMatrix3D();model.scale(sRad,sRad,sRad);var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.transpose();var proj=new PMatrix3D();proj.set(projection);proj.transpose();if(doFill===true){var v=new PMatrix3D();v.set(view);var m=new PMatrix3D();m.set(model);v.mult(m);var normalMatrix=new PMatrix3D();normalMatrix.set(v);normalMatrix.invert();normalMatrix.transpose();curContext.useProgram(programObject3D);disableVertexAttribPointer("aTexture3d",programObject3D,"aTexture");uniformMatrix("model3d",programObject3D,"model",false,model.array());uniformMatrix("view3d",programObject3D,"view",false,view.array());uniformMatrix("projection3d",programObject3D,"projection",false,proj.array());uniformMatrix("normalTransform3d",programObject3D,"normalTransform",false,normalMatrix.array());vertexAttribPointer("vertex3d",programObject3D,"Vertex",3,sphereBuffer);vertexAttribPointer("normal3d",programObject3D,"Normal",3,sphereBuffer);vertexAttribPointer("aColor3d",programObject3D,"aColor",3,sphereBuffer);curContext.enable(curContext.POLYGON_OFFSET_FILL);curContext.polygonOffset(1,1);uniformf("color3d",programObject3D,"color",fillStyle);curContext.drawArrays(curContext.TRIANGLE_STRIP,0,sphereVerts.length/3);curContext.disable(curContext.POLYGON_OFFSET_FILL)}if(lineWidth>0&&doStroke){curContext.useProgram(programObject2D);uniformMatrix("model2d",programObject2D,"model",false,model.array());uniformMatrix("view2d",programObject2D,"view",false,view.array());uniformMatrix("projection2d",programObject2D,"projection",false,proj.array());vertexAttribPointer("vertex2d",programObject2D,"Vertex",3,sphereBuffer);disableVertexAttribPointer("aTextureCoord2d",programObject2D,"aTextureCoord");uniformf("color2d",programObject2D,"color",strokeStyle);uniformi("picktype2d",programObject2D,"picktype",0);curContext.lineWidth(lineWidth);curContext.drawArrays(curContext.LINE_STRIP,0,sphereVerts.length/3)}}};p.modelX=function modelX(x,y,z){var mv=modelView.array();var ci=cameraInv.array();var ax=mv[0]*x+mv[1]*y+mv[2]*z+mv[3];var ay=mv[4]*x+mv[5]*y+mv[6]*z+mv[7];var az=mv[8]*x+mv[9]*y+mv[10]*z+mv[11];var aw=mv[12]*x+mv[13]*y+mv[14]*z+mv[15];var ox=ci[0]*ax+ci[1]*ay+ci[2]*az+ci[3]*aw;var ow=ci[12]*ax+ci[13]*ay+ci[14]*az+ci[15]*aw;return(ow!==0)?ox/ow:ox};p.modelY=function modelY(x,y,z){var mv=modelView.array();var ci=cameraInv.array();var ax=mv[0]*x+mv[1]*y+mv[2]*z+mv[3];var ay=mv[4]*x+mv[5]*y+mv[6]*z+mv[7];var az=mv[8]*x+mv[9]*y+mv[10]*z+mv[11];var aw=mv[12]*x+mv[13]*y+mv[14]*z+mv[15];var oy=ci[4]*ax+ci[5]*ay+ci[6]*az+ci[7]*aw;var ow=ci[12]*ax+ci[13]*ay+ci[14]*az+ci[15]*aw;return(ow!==0)?oy/ow:oy};p.modelZ=function modelZ(x,y,z){var mv=modelView.array();var ci=cameraInv.array();var ax=mv[0]*x+mv[1]*y+mv[2]*z+mv[3];var ay=mv[4]*x+mv[5]*y+mv[6]*z+mv[7];var az=mv[8]*x+mv[9]*y+mv[10]*z+mv[11];var aw=mv[12]*x+mv[13]*y+mv[14]*z+mv[15];var oz=ci[8]*ax+ci[9]*ay+ci[10]*az+ci[11]*aw;var ow=ci[12]*ax+ci[13]*ay+ci[14]*az+ci[15]*aw;return(ow!==0)?oz/ow:oz};p.ambient=function ambient(){var a=arguments;if(p.use3DContext){curContext.useProgram(programObject3D);uniformi("usingMat3d",programObject3D,"usingMat",true);if(a.length===1){if(typeof a[0]==="string"){var c=a[0].slice(5,-1).split(",");uniformf("mat_ambient3d",programObject3D,"mat_ambient",[c[0]/255,c[1]/255,c[2]/255])}else{uniformf("mat_ambient3d",programObject3D,"mat_ambient",[a[0]/255,a[0]/255,a[0]/255])}}else{uniformf("mat_ambient3d",programObject3D,"mat_ambient",[a[0]/255,a[1]/255,a[2]/255])}}};p.emissive=function emissive(){var a=arguments;if(p.use3DContext){curContext.useProgram(programObject3D);uniformi("usingMat3d",programObject3D,"usingMat",true);if(a.length===1){if(typeof a[0]==="string"){var c=a[0].slice(5,-1).split(",");uniformf("mat_emissive3d",programObject3D,"mat_emissive",[c[0]/255,c[1]/255,c[2]/255])}else{uniformf("mat_emissive3d",programObject3D,"mat_emissive",[a[0]/255,a[0]/255,a[0]/255])}}else{uniformf("mat_emissive3d",programObject3D,"mat_emissive",[a[0]/255,a[1]/255,a[2]/255])}}};p.shininess=function shininess(shine){if(p.use3DContext){curContext.useProgram(programObject3D);uniformi("usingMat3d",programObject3D,"usingMat",true);uniformf("shininess3d",programObject3D,"shininess",shine)}};p.specular=function specular(){var c=p.color.apply(this,arguments);if(p.use3DContext){curContext.useProgram(programObject3D);uniformi("usingMat3d",programObject3D,"usingMat",true);uniformf("mat_specular3d",programObject3D,"mat_specular",p.color.toGLArray(c).slice(0,3))}};p.screenX=function screenX(x,y,z){var mv=modelView.array();var pj=projection.array();var ax=mv[0]*x+mv[1]*y+mv[2]*z+mv[3];var ay=mv[4]*x+mv[5]*y+mv[6]*z+mv[7];var az=mv[8]*x+mv[9]*y+mv[10]*z+mv[11];var aw=mv[12]*x+mv[13]*y+mv[14]*z+mv[15];var ox=pj[0]*ax+pj[1]*ay+pj[2]*az+pj[3]*aw;var ow=pj[12]*ax+pj[13]*ay+pj[14]*az+pj[15]*aw;if(ow!==0){ox/=ow}return p.width*(1+ox)/2};p.screenY=function screenY(x,y,z){var mv=modelView.array();var pj=projection.array();var ax=mv[0]*x+mv[1]*y+mv[2]*z+mv[3];var ay=mv[4]*x+mv[5]*y+mv[6]*z+mv[7];var az=mv[8]*x+mv[9]*y+mv[10]*z+mv[11];var aw=mv[12]*x+mv[13]*y+mv[14]*z+mv[15];var oy=pj[4]*ax+pj[5]*ay+pj[6]*az+pj[7]*aw;var ow=pj[12]*ax+pj[13]*ay+pj[14]*az+pj[15]*aw;if(ow!==0){oy/=ow}return p.height*(1+oy)/2};p.screenZ=function screenZ(x,y,z){var mv=modelView.array();var pj=projection.array();var ax=mv[0]*x+mv[1]*y+mv[2]*z+mv[3];var ay=mv[4]*x+mv[5]*y+mv[6]*z+mv[7];var az=mv[8]*x+mv[9]*y+mv[10]*z+mv[11];var aw=mv[12]*x+mv[13]*y+mv[14]*z+mv[15];var oz=pj[8]*ax+pj[9]*ay+pj[10]*az+pj[11]*aw;var ow=pj[12]*ax+pj[13]*ay+pj[14]*az+pj[15]*aw;if(ow!==0){oz/=ow}return(oz+1)/2};p.fill=function fill(){var color=p.color(arguments[0],arguments[1],arguments[2],arguments[3]);if(color===currentFillColor&&doFill){return}doFill=true;currentFillColor=color;if(p.use3DContext){fillStyle=p.color.toGLArray(color)}else{isFillDirty=true}};function executeContextFill(){if(doFill){if(isFillDirty){curContext.fillStyle=p.color.toString(currentFillColor);isFillDirty=false}curContext.fill()}}p.noFill=function noFill(){doFill=false};p.stroke=function stroke(){var color=p.color(arguments[0],arguments[1],arguments[2],arguments[3]);if(color===currentStrokeColor&&doStroke){return}doStroke=true;currentStrokeColor=color;if(p.use3DContext){strokeStyle=p.color.toGLArray(color)}else{isStrokeDirty=true}};function executeContextStroke(){if(doStroke){if(isStrokeDirty){curContext.strokeStyle=p.color.toString(currentStrokeColor);isStrokeDirty=false}curContext.stroke()}}p.noStroke=function noStroke(){doStroke=false};p.strokeWeight=function strokeWeight(w){lineWidth=w;if(p.use3DContext){curContext.useProgram(programObject2D);uniformf("pointSize2d",programObject2D,"pointSize",w)}else{curContext.lineWidth=w}};p.strokeCap=function strokeCap(value){curContext.lineCap=value};p.strokeJoin=function strokeJoin(value){curContext.lineJoin=value};p.smooth=function(){curElement.style.setProperty("image-rendering","optimizeQuality","important");if(!p.use3DContext&&"mozImageSmoothingEnabled" in curContext){curContext.mozImageSmoothingEnabled=true}};p.noSmooth=function(){curElement.style.setProperty("image-rendering","optimizeSpeed","important");if(!p.use3DContext&&"mozImageSmoothingEnabled" in curContext){curContext.mozImageSmoothingEnabled=false}};function colorBlendWithAlpha(c1,c2,k){var f=0|(k*((c2&PConstants.ALPHA_MASK)>>>24));return(Math.min(((c1&PConstants.ALPHA_MASK)>>>24)+f,255)<<24|p.mix(c1&PConstants.RED_MASK,c2&PConstants.RED_MASK,f)&PConstants.RED_MASK|p.mix(c1&PConstants.GREEN_MASK,c2&PConstants.GREEN_MASK,f)&PConstants.GREEN_MASK|p.mix(c1&PConstants.BLUE_MASK,c2&PConstants.BLUE_MASK,f))}p.point=function point(x,y,z){if(p.use3DContext){var model=new PMatrix3D();model.translate(x,y,z||0);model.transpose();var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.transpose();var proj=new PMatrix3D();proj.set(projection);proj.transpose();curContext.useProgram(programObject2D);uniformMatrix("model2d",programObject2D,"model",false,model.array());uniformMatrix("view2d",programObject2D,"view",false,view.array());uniformMatrix("projection2d",programObject2D,"projection",false,proj.array());if(lineWidth>0&&doStroke){uniformf("color2d",programObject2D,"color",strokeStyle);uniformi("picktype2d",programObject2D,"picktype",0);vertexAttribPointer("vertex2d",programObject2D,"Vertex",3,pointBuffer);disableVertexAttribPointer("aTextureCoord2d",programObject2D,"aTextureCoord");curContext.drawArrays(curContext.POINTS,0,1)}}else{if(doStroke){if(curSketch.options.crispLines){var alphaOfPointWeight=Math.PI/4;var c=p.get(x,y);p.set(x,y,colorBlendWithAlpha(c,currentStrokeColor,alphaOfPointWeight))}else{if(lineWidth>1){curContext.fillStyle=p.color.toString(currentStrokeColor);isFillDirty=true;curContext.beginPath();curContext.arc(x,y,lineWidth/2,0,PConstants.TWO_PI,false);curContext.fill();curContext.closePath()}else{curContext.fillStyle=p.color.toString(currentStrokeColor);curContext.fillRect(Math.round(x),Math.round(y),1,1);isFillDirty=true}}}}};p.beginShape=function beginShape(type){curShape=type;curvePoints=[];vertArray=[]};p.vertex=function vertex(){var vert=[];if(firstVert){firstVert=false}if(arguments.length===4){vert[0]=arguments[0];vert[1]=arguments[1];vert[2]=0;vert[3]=arguments[2];vert[4]=arguments[3]}else{vert[0]=arguments[0];vert[1]=arguments[1];vert[2]=arguments[2]||0;vert[3]=arguments[3]||0;vert[4]=arguments[4]||0}vert.isVert=true;if(p.use3DContext){vert[5]=fillStyle[0];vert[6]=fillStyle[1];vert[7]=fillStyle[2];vert[8]=fillStyle[3];vert[9]=strokeStyle[0];vert[10]=strokeStyle[1];vert[11]=strokeStyle[2];vert[12]=strokeStyle[3];vert[13]=normalX;vert[14]=normalY;vert[15]=normalZ}else{vert[5]=currentFillColor;vert[6]=currentStrokeColor}vertArray.push(vert)};var point3D=function point3D(vArray,cArray){var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.transpose();var proj=new PMatrix3D();proj.set(projection);proj.transpose();curContext.useProgram(programObjectUnlitShape);uniformMatrix("uViewUS",programObjectUnlitShape,"uView",false,view.array());uniformMatrix("uProjectionUS",programObjectUnlitShape,"uProjection",false,proj.array());vertexAttribPointer("aVertexUS",programObjectUnlitShape,"aVertex",3,pointBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array(vArray),curContext.STREAM_DRAW);vertexAttribPointer("aColorUS",programObjectUnlitShape,"aColor",4,fillColorBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array(cArray),curContext.STREAM_DRAW);curContext.drawArrays(curContext.POINTS,0,vArray.length/3)};var line3D=function line3D(vArray,mode,cArray){var ctxMode;if(mode==="LINES"){ctxMode=curContext.LINES}else{if(mode==="LINE_LOOP"){ctxMode=curContext.LINE_LOOP}else{ctxMode=curContext.LINE_STRIP}}var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.transpose();var proj=new PMatrix3D();proj.set(projection);proj.transpose();curContext.useProgram(programObjectUnlitShape);uniformMatrix("uViewUS",programObjectUnlitShape,"uView",false,view.array());uniformMatrix("uProjectionUS",programObjectUnlitShape,"uProjection",false,proj.array());vertexAttribPointer("aVertexUS",programObjectUnlitShape,"aVertex",3,lineBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array(vArray),curContext.STREAM_DRAW);vertexAttribPointer("aColorUS",programObjectUnlitShape,"aColor",4,strokeColorBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array(cArray),curContext.STREAM_DRAW);curContext.lineWidth(lineWidth);curContext.drawArrays(ctxMode,0,vArray.length/3)};var fill3D=function fill3D(vArray,mode,cArray,tArray){var ctxMode;if(mode==="TRIANGLES"){ctxMode=curContext.TRIANGLES}else{if(mode==="TRIANGLE_FAN"){ctxMode=curContext.TRIANGLE_FAN}else{ctxMode=curContext.TRIANGLE_STRIP}}var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.transpose();var proj=new PMatrix3D();proj.set(projection);proj.transpose();curContext.useProgram(programObject3D);uniformMatrix("model3d",programObject3D,"model",false,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);uniformMatrix("view3d",programObject3D,"view",false,view.array());uniformMatrix("projection3d",programObject3D,"projection",false,proj.array());curContext.enable(curContext.POLYGON_OFFSET_FILL);curContext.polygonOffset(1,1);uniformf("color3d",programObject3D,"color",[-1,0,0,0]);vertexAttribPointer("vertex3d",programObject3D,"Vertex",3,fillBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array(vArray),curContext.STREAM_DRAW);vertexAttribPointer("aColor3d",programObject3D,"aColor",4,fillColorBuffer);curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array(cArray),curContext.STREAM_DRAW);disableVertexAttribPointer("normal3d",programObject3D,"Normal");var i;if(usingTexture){if(curTextureMode===PConstants.IMAGE){for(i=0;i<tArray.length;i+=2){tArray[i]=tArray[i]/curTexture.width;tArray[i+1]/=curTexture.height}}for(i=0;i<tArray.length;i+=2){if(tArray[i+0]>1){tArray[i+0]-=(tArray[i+0]-1)}if(tArray[i+1]>1){tArray[i+1]-=(tArray[i+1]-1)}}uniformi("usingTexture3d",programObject3D,"usingTexture",usingTexture);vertexAttribPointer("aTexture3d",programObject3D,"aTexture",2,shapeTexVBO);curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array(tArray),curContext.STREAM_DRAW)}curContext.drawArrays(ctxMode,0,vArray.length/3);curContext.disable(curContext.POLYGON_OFFSET_FILL)};p.endShape=function endShape(mode){var closeShape=mode===PConstants.CLOSE;var lineVertArray=[];var fillVertArray=[];var colorVertArray=[];var strokeVertArray=[];var texVertArray=[];firstVert=true;var i,j,k;var last=vertArray.length-1;for(i=0;i<vertArray.length;i++){for(j=0;j<3;j++){fillVertArray.push(vertArray[i][j])}}for(i=0;i<vertArray.length;i++){for(j=5;j<9;j++){colorVertArray.push(vertArray[i][j])}}for(i=0;i<vertArray.length;i++){for(j=9;j<13;j++){strokeVertArray.push(vertArray[i][j])}}for(i=0;i<vertArray.length;i++){texVertArray.push(vertArray[i][3]);texVertArray.push(vertArray[i][4])}if(closeShape){fillVertArray.push(vertArray[0][0]);fillVertArray.push(vertArray[0][1]);fillVertArray.push(vertArray[0][2]);for(i=5;i<9;i++){colorVertArray.push(vertArray[0][i])}for(i=9;i<13;i++){strokeVertArray.push(vertArray[0][i])}texVertArray.push(vertArray[0][3]);texVertArray.push(vertArray[0][4])}if(isCurve&&curShape===PConstants.POLYGON||isCurve&&curShape===undef){if(p.use3DContext){lineVertArray=fillVertArray;if(doStroke){line3D(lineVertArray,null,strokeVertArray)}if(doFill){fill3D(fillVertArray,null,colorVertArray)}}else{if(vertArray.length>3){var b=[],s=1-curTightness;curContext.beginPath();curContext.moveTo(vertArray[1][0],vertArray[1][1]);for(i=1;(i+2)<vertArray.length;i++){b[0]=[vertArray[i][0],vertArray[i][1]];b[1]=[vertArray[i][0]+(s*vertArray[i+1][0]-s*vertArray[i-1][0])/6,vertArray[i][1]+(s*vertArray[i+1][1]-s*vertArray[i-1][1])/6];b[2]=[vertArray[i+1][0]+(s*vertArray[i][0]-s*vertArray[i+2][0])/6,vertArray[i+1][1]+(s*vertArray[i][1]-s*vertArray[i+2][1])/6];b[3]=[vertArray[i+1][0],vertArray[i+1][1]];curContext.bezierCurveTo(b[1][0],b[1][1],b[2][0],b[2][1],b[3][0],b[3][1])}if(closeShape){curContext.lineTo(vertArray[0][0],vertArray[0][1])}executeContextFill();executeContextStroke();curContext.closePath()}}}else{if(isBezier&&curShape===PConstants.POLYGON||isBezier&&curShape===undef){if(p.use3DContext){lineVertArray=fillVertArray;lineVertArray.splice(lineVertArray.length-3);strokeVertArray.splice(strokeVertArray.length-4);if(doStroke){line3D(lineVertArray,null,strokeVertArray)}if(doFill){fill3D(fillVertArray,"TRIANGLES",colorVertArray)}}else{curContext.beginPath();for(i=0;i<vertArray.length;i++){if(vertArray[i]["isVert"]===true){if(vertArray[i]["moveTo"]===true){curContext.moveTo(vertArray[i][0],vertArray[i][1])}else{if(vertArray[i]["moveTo"]===false){curContext.lineTo(vertArray[i][0],vertArray[i][1])}else{curContext.moveTo(vertArray[i][0],vertArray[i][1])}}}else{curContext.bezierCurveTo(vertArray[i][0],vertArray[i][1],vertArray[i][2],vertArray[i][3],vertArray[i][4],vertArray[i][5])}}if(closeShape){curContext.lineTo(vertArray[0][0],vertArray[0][1])}executeContextFill();executeContextStroke();curContext.closePath()}}else{if(p.use3DContext){if(curShape===PConstants.POINTS){for(i=0;i<vertArray.length;i++){for(j=0;j<3;j++){lineVertArray.push(vertArray[i][j])}}point3D(lineVertArray,strokeVertArray)}else{if(curShape===PConstants.LINES){for(i=0;i<vertArray.length;i++){for(j=0;j<3;j++){lineVertArray.push(vertArray[i][j])}}for(i=0;i<vertArray.length;i++){for(j=5;j<9;j++){colorVertArray.push(vertArray[i][j])}}line3D(lineVertArray,"LINES",strokeVertArray)}else{if(curShape===PConstants.TRIANGLES){if(vertArray.length>2){for(i=0;(i+2)<vertArray.length;i+=3){fillVertArray=[];texVertArray=[];lineVertArray=[];colorVertArray=[];strokeVertArray=[];for(j=0;j<3;j++){for(k=0;k<3;k++){lineVertArray.push(vertArray[i+j][k]);fillVertArray.push(vertArray[i+j][k])}}for(j=0;j<3;j++){for(k=3;k<5;k++){texVertArray.push(vertArray[i+j][k])}}for(j=0;j<3;j++){for(k=5;k<9;k++){colorVertArray.push(vertArray[i+j][k]);strokeVertArray.push(vertArray[i+j][k+4])}}if(doStroke){line3D(lineVertArray,"LINE_LOOP",strokeVertArray)}if(doFill||usingTexture){fill3D(fillVertArray,"TRIANGLES",colorVertArray,texVertArray)}}}}else{if(curShape===PConstants.TRIANGLE_STRIP){if(vertArray.length>2){for(i=0;(i+2)<vertArray.length;i++){lineVertArray=[];fillVertArray=[];strokeVertArray=[];colorVertArray=[];texVertArray=[];for(j=0;j<3;j++){for(k=0;k<3;k++){lineVertArray.push(vertArray[i+j][k]);fillVertArray.push(vertArray[i+j][k])}}for(j=0;j<3;j++){for(k=3;k<5;k++){texVertArray.push(vertArray[i+j][k])}}for(j=0;j<3;j++){for(k=5;k<9;k++){strokeVertArray.push(vertArray[i+j][k+4]);colorVertArray.push(vertArray[i+j][k])}}if(doFill||usingTexture){fill3D(fillVertArray,"TRIANGLE_STRIP",colorVertArray,texVertArray)}if(doStroke){line3D(lineVertArray,"LINE_LOOP",strokeVertArray)}}}}else{if(curShape===PConstants.TRIANGLE_FAN){if(vertArray.length>2){for(i=0;i<3;i++){for(j=0;j<3;j++){lineVertArray.push(vertArray[i][j])}}for(i=0;i<3;i++){for(j=9;j<13;j++){strokeVertArray.push(vertArray[i][j])}}if(doStroke){line3D(lineVertArray,"LINE_LOOP",strokeVertArray)}for(i=2;(i+1)<vertArray.length;i++){lineVertArray=[];strokeVertArray=[];lineVertArray.push(vertArray[0][0]);lineVertArray.push(vertArray[0][1]);lineVertArray.push(vertArray[0][2]);strokeVertArray.push(vertArray[0][9]);strokeVertArray.push(vertArray[0][10]);strokeVertArray.push(vertArray[0][11]);strokeVertArray.push(vertArray[0][12]);for(j=0;j<2;j++){for(k=0;k<3;k++){lineVertArray.push(vertArray[i+j][k])}}for(j=0;j<2;j++){for(k=9;k<13;k++){strokeVertArray.push(vertArray[i+j][k])}}if(doStroke){line3D(lineVertArray,"LINE_STRIP",strokeVertArray)}}if(doFill||usingTexture){fill3D(fillVertArray,"TRIANGLE_FAN",colorVertArray,texVertArray)}}}else{if(curShape===PConstants.QUADS){for(i=0;(i+3)<vertArray.length;i+=4){lineVertArray=[];for(j=0;j<4;j++){for(k=0;k<3;k++){lineVertArray.push(vertArray[i+j][k])}}if(doStroke){line3D(lineVertArray,"LINE_LOOP",strokeVertArray)}if(doFill){fillVertArray=[];colorVertArray=[];texVertArray=[];for(j=0;j<3;j++){fillVertArray.push(vertArray[i][j])}for(j=5;j<9;j++){colorVertArray.push(vertArray[i][j])}for(j=0;j<3;j++){fillVertArray.push(vertArray[i+1][j])}for(j=5;j<9;j++){colorVertArray.push(vertArray[i+1][j])}for(j=0;j<3;j++){fillVertArray.push(vertArray[i+3][j])}for(j=5;j<9;j++){colorVertArray.push(vertArray[i+3][j])}for(j=0;j<3;j++){fillVertArray.push(vertArray[i+2][j])}for(j=5;j<9;j++){colorVertArray.push(vertArray[i+2][j])}if(usingTexture){texVertArray.push(vertArray[i+0][3]);texVertArray.push(vertArray[i+0][4]);texVertArray.push(vertArray[i+1][3]);texVertArray.push(vertArray[i+1][4]);texVertArray.push(vertArray[i+3][3]);texVertArray.push(vertArray[i+3][4]);texVertArray.push(vertArray[i+2][3]);texVertArray.push(vertArray[i+2][4])}fill3D(fillVertArray,"TRIANGLE_STRIP",colorVertArray,texVertArray)}}}else{if(curShape===PConstants.QUAD_STRIP){var tempArray=[];if(vertArray.length>3){for(i=0;i<2;i++){for(j=0;j<3;j++){lineVertArray.push(vertArray[i][j])}}for(i=0;i<2;i++){for(j=9;j<13;j++){strokeVertArray.push(vertArray[i][j])}}line3D(lineVertArray,"LINE_STRIP",strokeVertArray);if(vertArray.length>4&&vertArray.length%2>0){tempArray=fillVertArray.splice(fillVertArray.length-3);vertArray.pop()}for(i=0;(i+3)<vertArray.length;i+=2){lineVertArray=[];strokeVertArray=[];for(j=0;j<3;j++){lineVertArray.push(vertArray[i+1][j])}for(j=0;j<3;j++){lineVertArray.push(vertArray[i+3][j])}for(j=0;j<3;j++){lineVertArray.push(vertArray[i+2][j])}for(j=0;j<3;j++){lineVertArray.push(vertArray[i+0][j])}for(j=9;j<13;j++){strokeVertArray.push(vertArray[i+1][j])}for(j=9;j<13;j++){strokeVertArray.push(vertArray[i+3][j])}for(j=9;j<13;j++){strokeVertArray.push(vertArray[i+2][j])}for(j=9;j<13;j++){strokeVertArray.push(vertArray[i+0][j])}if(doStroke){line3D(lineVertArray,"LINE_STRIP",strokeVertArray)}}if(doFill||usingTexture){fill3D(fillVertArray,"TRIANGLE_LIST",colorVertArray,texVertArray)}}}else{if(vertArray.length===1){for(j=0;j<3;j++){lineVertArray.push(vertArray[0][j])}for(j=9;j<13;j++){strokeVertArray.push(vertArray[0][j])}point3D(lineVertArray,strokeVertArray)}else{for(i=0;i<vertArray.length;i++){for(j=0;j<3;j++){lineVertArray.push(vertArray[i][j])}for(j=5;j<9;j++){strokeVertArray.push(vertArray[i][j])}}if(closeShape){line3D(lineVertArray,"LINE_LOOP",strokeVertArray)}else{line3D(lineVertArray,"LINE_STRIP",strokeVertArray)}if(doFill||usingTexture){fill3D(fillVertArray,"TRIANGLE_FAN",colorVertArray,texVertArray)}}}}}}}}}usingTexture=false;curContext.useProgram(programObject3D);uniformi("usingTexture3d",programObject3D,"usingTexture",usingTexture)}else{if(curShape===PConstants.POINTS){for(i=0;i<vertArray.length;i++){if(doStroke){p.stroke(vertArray[i][6])}p.point(vertArray[i][0],vertArray[i][1])}}else{if(curShape===PConstants.LINES){for(i=0;(i+1)<vertArray.length;i+=2){if(doStroke){p.stroke(vertArray[i+1][6])}p.line(vertArray[i][0],vertArray[i][1],vertArray[i+1][0],vertArray[i+1][1])}}else{if(curShape===PConstants.TRIANGLES){for(i=0;(i+2)<vertArray.length;i+=3){curContext.beginPath();curContext.moveTo(vertArray[i][0],vertArray[i][1]);curContext.lineTo(vertArray[i+1][0],vertArray[i+1][1]);curContext.lineTo(vertArray[i+2][0],vertArray[i+2][1]);curContext.lineTo(vertArray[i][0],vertArray[i][1]);if(doFill){p.fill(vertArray[i+2][5]);executeContextFill()}if(doStroke){p.stroke(vertArray[i+2][6]);executeContextStroke()}curContext.closePath()}}else{if(curShape===PConstants.TRIANGLE_STRIP){for(i=0;(i+1)<vertArray.length;i++){curContext.beginPath();curContext.moveTo(vertArray[i+1][0],vertArray[i+1][1]);curContext.lineTo(vertArray[i][0],vertArray[i][1]);if(doStroke){p.stroke(vertArray[i+1][6])}if(doFill){p.fill(vertArray[i+1][5])}if(i+2<vertArray.length){curContext.lineTo(vertArray[i+2][0],vertArray[i+2][1]);if(doStroke){p.stroke(vertArray[i+2][6])}if(doFill){p.fill(vertArray[i+2][5])}}executeContextFill();executeContextStroke();curContext.closePath()}}else{if(curShape===PConstants.TRIANGLE_FAN){if(vertArray.length>2){curContext.beginPath();curContext.moveTo(vertArray[0][0],vertArray[0][1]);curContext.lineTo(vertArray[1][0],vertArray[1][1]);curContext.lineTo(vertArray[2][0],vertArray[2][1]);if(doFill){p.fill(vertArray[2][5]);executeContextFill()}if(doStroke){p.stroke(vertArray[2][6]);executeContextStroke()}curContext.closePath();for(i=3;i<vertArray.length;i++){curContext.beginPath();curContext.moveTo(vertArray[0][0],vertArray[0][1]);curContext.lineTo(vertArray[i-1][0],vertArray[i-1][1]);curContext.lineTo(vertArray[i][0],vertArray[i][1]);if(doFill){p.fill(vertArray[i][5]);executeContextFill()}if(doStroke){p.stroke(vertArray[i][6]);executeContextStroke()}curContext.closePath()}}}else{if(curShape===PConstants.QUADS){for(i=0;(i+3)<vertArray.length;i+=4){curContext.beginPath();curContext.moveTo(vertArray[i][0],vertArray[i][1]);for(j=1;j<4;j++){curContext.lineTo(vertArray[i+j][0],vertArray[i+j][1])}curContext.lineTo(vertArray[i][0],vertArray[i][1]);if(doFill){p.fill(vertArray[i+3][5]);executeContextFill()}if(doStroke){p.stroke(vertArray[i+3][6]);executeContextStroke()}curContext.closePath()}}else{if(curShape===PConstants.QUAD_STRIP){if(vertArray.length>3){for(i=0;(i+1)<vertArray.length;i+=2){curContext.beginPath();if(i+3<vertArray.length){curContext.moveTo(vertArray[i+2][0],vertArray[i+2][1]);curContext.lineTo(vertArray[i][0],vertArray[i][1]);curContext.lineTo(vertArray[i+1][0],vertArray[i+1][1]);curContext.lineTo(vertArray[i+3][0],vertArray[i+3][1]);if(doFill){p.fill(vertArray[i+3][5])}if(doStroke){p.stroke(vertArray[i+3][6])}}else{curContext.moveTo(vertArray[i][0],vertArray[i][1]);curContext.lineTo(vertArray[i+1][0],vertArray[i+1][1])}executeContextFill();executeContextStroke();curContext.closePath()}}}else{curContext.beginPath();curContext.moveTo(vertArray[0][0],vertArray[0][1]);for(i=1;i<vertArray.length;i++){if(vertArray[i]["isVert"]===true){if(vertArray[i]["moveTo"]===true){curContext.moveTo(vertArray[i][0],vertArray[i][1])}else{if(vertArray[i]["moveTo"]===false){curContext.lineTo(vertArray[i][0],vertArray[i][1])}else{curContext.lineTo(vertArray[i][0],vertArray[i][1])}}}}if(closeShape){curContext.lineTo(vertArray[0][0],vertArray[0][1])}executeContextFill();executeContextStroke();curContext.closePath()}}}}}}}}}}isCurve=false;isBezier=false;curveVertArray=[];curveVertCount=0};var splineForward=function(segments,matrix){var f=1/segments;var ff=f*f;var fff=ff*f;matrix.set(0,0,0,1,fff,ff,f,0,6*fff,2*ff,0,0,6*fff,0,0,0)};var curveInit=function(){if(!curveDrawMatrix){curveBasisMatrix=new PMatrix3D();curveDrawMatrix=new PMatrix3D();curveInited=true}var s=curTightness;curveBasisMatrix.set((s-1)/2,(s+3)/2,(-3-s)/2,(1-s)/2,(1-s),(-5-s)/2,(s+2),(s-1)/2,(s-1)/2,0,(1-s)/2,0,0,1,0,0);splineForward(curveDet,curveDrawMatrix);if(!bezierBasisInverse){curveToBezierMatrix=new PMatrix3D()}curveToBezierMatrix.set(curveBasisMatrix);curveToBezierMatrix.preApply(bezierBasisInverse);curveDrawMatrix.apply(curveBasisMatrix)};p.bezierVertex=function bezierVertex(){isBezier=true;var vert=[];if(firstVert){throw ("vertex() must be used at least once before calling bezierVertex()")}else{if(arguments.length===9){if(p.use3DContext){if(bezierDrawMatrix===undef){bezierDrawMatrix=new PMatrix3D()}var lastPoint=vertArray.length-1;splineForward(bezDetail,bezierDrawMatrix);bezierDrawMatrix.apply(bezierBasisMatrix);var draw=bezierDrawMatrix.array();var x1=vertArray[lastPoint][0],y1=vertArray[lastPoint][1],z1=vertArray[lastPoint][2];var xplot1=draw[4]*x1+draw[5]*arguments[0]+draw[6]*arguments[3]+draw[7]*arguments[6];var xplot2=draw[8]*x1+draw[9]*arguments[0]+draw[10]*arguments[3]+draw[11]*arguments[6];var xplot3=draw[12]*x1+draw[13]*arguments[0]+draw[14]*arguments[3]+draw[15]*arguments[6];var yplot1=draw[4]*y1+draw[5]*arguments[1]+draw[6]*arguments[4]+draw[7]*arguments[7];var yplot2=draw[8]*y1+draw[9]*arguments[1]+draw[10]*arguments[4]+draw[11]*arguments[7];var yplot3=draw[12]*y1+draw[13]*arguments[1]+draw[14]*arguments[4]+draw[15]*arguments[7];var zplot1=draw[4]*z1+draw[5]*arguments[2]+draw[6]*arguments[5]+draw[7]*arguments[8];var zplot2=draw[8]*z1+draw[9]*arguments[2]+draw[10]*arguments[5]+draw[11]*arguments[8];var zplot3=draw[12]*z1+draw[13]*arguments[2]+draw[14]*arguments[5]+draw[15]*arguments[8];for(var j=0;j<bezDetail;j++){x1+=xplot1;xplot1+=xplot2;xplot2+=xplot3;y1+=yplot1;yplot1+=yplot2;yplot2+=yplot3;z1+=zplot1;zplot1+=zplot2;zplot2+=zplot3;p.vertex(x1,y1,z1)}p.vertex(arguments[6],arguments[7],arguments[8])}}else{for(var i=0;i<arguments.length;i++){vert[i]=arguments[i]}vertArray.push(vert);vertArray[vertArray.length-1]["isVert"]=false}}};var executeTexImage2D=function(){var canvas2d=document.createElement("canvas");try{curContext.texImage2D(curContext.TEXTURE_2D,0,curContext.RGBA,curContext.RGBA,curContext.UNSIGNED_BYTE,canvas2d);executeTexImage2D=function(texture){curContext.texImage2D(curContext.TEXTURE_2D,0,curContext.RGBA,curContext.RGBA,curContext.UNSIGNED_BYTE,texture)}}catch(e){executeTexImage2D=function(texture){curContext.texImage2D(curContext.TEXTURE_2D,0,texture,false)}}executeTexImage2D.apply(this,arguments)};p.texture=function(pimage){if(pimage.localName==="canvas"){curContext.bindTexture(curContext.TEXTURE_2D,canTex);executeTexImage2D(pimage);curContext.texParameteri(curContext.TEXTURE_2D,curContext.TEXTURE_MAG_FILTER,curContext.LINEAR);curContext.texParameteri(curContext.TEXTURE_2D,curContext.TEXTURE_MIN_FILTER,curContext.LINEAR);curContext.generateMipmap(curContext.TEXTURE_2D)}else{if(!pimage.__texture){var texture=curContext.createTexture();pimage.__texture=texture;var cvs=document.createElement("canvas");var pot;if(pimage.width&(pimage.width-1)===0){cvs.width=pimage.width}else{pot=1;while(pot<pimage.width){pot*=2}cvs.width=pot}if(pimage.height&(pimage.height-1)===0){cvs.height=pimage.height}else{pot=1;while(pot<pimage.height){pot*=2}cvs.height=pot}var ctx=cvs.getContext("2d");var textureImage=ctx.createImageData(cvs.width,cvs.height);var imgData=pimage.toImageData();for(var i=0;i<cvs.width;i+=1){for(var j=0;j<cvs.height;j+=1){var index=(j*cvs.width+i)*4;textureImage.data[index+0]=imgData.data[index+0];textureImage.data[index+1]=imgData.data[index+1];textureImage.data[index+2]=imgData.data[index+2];textureImage.data[index+3]=255}}ctx.putImageData(textureImage,0,0);pimage.__cvs=cvs;curContext.bindTexture(curContext.TEXTURE_2D,pimage.__texture);curContext.texParameteri(curContext.TEXTURE_2D,curContext.TEXTURE_MIN_FILTER,curContext.LINEAR_MIPMAP_LINEAR);curContext.texParameteri(curContext.TEXTURE_2D,curContext.TEXTURE_MAG_FILTER,curContext.LINEAR);curContext.texParameteri(curContext.TEXTURE_2D,curContext.TEXTURE_WRAP_T,curContext.CLAMP_TO_EDGE);curContext.texParameteri(curContext.TEXTURE_2D,curContext.TEXTURE_WRAP_S,curContext.CLAMP_TO_EDGE);executeTexImage2D(pimage.__cvs);curContext.generateMipmap(curContext.TEXTURE_2D)}else{curContext.bindTexture(curContext.TEXTURE_2D,pimage.__texture)}}curTexture.width=pimage.width;curTexture.height=pimage.height;usingTexture=true;curContext.useProgram(programObject3D);uniformi("usingTexture3d",programObject3D,"usingTexture",usingTexture)};p.textureMode=function(mode){curTextureMode=mode};var curveVertexSegment=function(x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4){var x0=x2;var y0=y2;var z0=z2;var draw=curveDrawMatrix.array();var xplot1=draw[4]*x1+draw[5]*x2+draw[6]*x3+draw[7]*x4;var xplot2=draw[8]*x1+draw[9]*x2+draw[10]*x3+draw[11]*x4;var xplot3=draw[12]*x1+draw[13]*x2+draw[14]*x3+draw[15]*x4;var yplot1=draw[4]*y1+draw[5]*y2+draw[6]*y3+draw[7]*y4;var yplot2=draw[8]*y1+draw[9]*y2+draw[10]*y3+draw[11]*y4;var yplot3=draw[12]*y1+draw[13]*y2+draw[14]*y3+draw[15]*y4;var zplot1=draw[4]*z1+draw[5]*z2+draw[6]*z3+draw[7]*z4;var zplot2=draw[8]*z1+draw[9]*z2+draw[10]*z3+draw[11]*z4;var zplot3=draw[12]*z1+draw[13]*z2+draw[14]*z3+draw[15]*z4;p.vertex(x0,y0,z0);for(var j=0;j<curveDet;j++){x0+=xplot1;xplot1+=xplot2;xplot2+=xplot3;y0+=yplot1;yplot1+=yplot2;yplot2+=yplot3;z0+=zplot1;zplot1+=zplot2;zplot2+=zplot3;p.vertex(x0,y0,z0)}};p.curveVertex=function(x,y,z){isCurve=true;if(p.use3DContext){if(!curveInited){curveInit()}var vert=[];vert[0]=x;vert[1]=y;vert[2]=z;curveVertArray.push(vert);curveVertCount++;if(curveVertCount>3){curveVertexSegment(curveVertArray[curveVertCount-4][0],curveVertArray[curveVertCount-4][1],curveVertArray[curveVertCount-4][2],curveVertArray[curveVertCount-3][0],curveVertArray[curveVertCount-3][1],curveVertArray[curveVertCount-3][2],curveVertArray[curveVertCount-2][0],curveVertArray[curveVertCount-2][1],curveVertArray[curveVertCount-2][2],curveVertArray[curveVertCount-1][0],curveVertArray[curveVertCount-1][1],curveVertArray[curveVertCount-1][2])}}else{p.vertex(x,y,z)}};p.curve=function curve(){if(arguments.length===8){p.beginShape();p.curveVertex(arguments[0],arguments[1]);p.curveVertex(arguments[2],arguments[3]);p.curveVertex(arguments[4],arguments[5]);p.curveVertex(arguments[6],arguments[7]);p.endShape()}else{if(p.use3DContext){p.beginShape();p.curveVertex(arguments[0],arguments[1],arguments[2]);p.curveVertex(arguments[3],arguments[4],arguments[5]);p.curveVertex(arguments[6],arguments[7],arguments[8]);p.curveVertex(arguments[9],arguments[10],arguments[11]);p.endShape()}}};p.curveTightness=function(tightness){curTightness=tightness};p.curveDetail=function curveDetail(detail){curveDet=detail;curveInit()};p.rectMode=function rectMode(aRectMode){curRectMode=aRectMode};p.imageMode=function(mode){switch(mode){case PConstants.CORNER:imageModeConvert=imageModeCorner;break;case PConstants.CORNERS:imageModeConvert=imageModeCorners;break;case PConstants.CENTER:imageModeConvert=imageModeCenter;break;default:throw"Invalid imageMode"}};p.ellipseMode=function ellipseMode(aEllipseMode){curEllipseMode=aEllipseMode};p.arc=function arc(x,y,width,height,start,stop){if(width<=0||stop<start){return}if(curEllipseMode===PConstants.CORNERS){width=width-x;height=height-y}else{if(curEllipseMode===PConstants.RADIUS){x=x-width;y=y-height;width=width*2;height=height*2}else{if(curEllipseMode===PConstants.CENTER){x=x-width/2;y=y-height/2}}}while(start<0){start+=PConstants.TWO_PI;stop+=PConstants.TWO_PI}if(stop-start>PConstants.TWO_PI){start=0;stop=PConstants.TWO_PI}var hr=width/2;var vr=height/2;var centerX=x+hr;var centerY=y+vr;var i,ii,startLUT,stopLUT;if(doFill){var savedStroke=doStroke;doStroke=false;startLUT=0.5+(start/PConstants.TWO_PI)*PConstants.SINCOS_LENGTH;stopLUT=0.5+(stop/PConstants.TWO_PI)*PConstants.SINCOS_LENGTH;p.beginShape();p.vertex(centerX,centerY);for(i=startLUT;i<stopLUT;i++){ii=i%PConstants.SINCOS_LENGTH;if(ii<0){ii+=PConstants.SINCOS_LENGTH}p.vertex(centerX+parseFloat(Math.cos(ii*PConstants.DEG_TO_RAD*0.5))*hr,centerY+parseFloat(Math.sin(ii*PConstants.DEG_TO_RAD*0.5))*vr)}p.endShape(PConstants.CLOSE);doStroke=savedStroke}if(doStroke){var savedFill=doFill;doFill=false;startLUT=0.5+(start/PConstants.TWO_PI)*PConstants.SINCOS_LENGTH;stopLUT=0.5+(stop/PConstants.TWO_PI)*PConstants.SINCOS_LENGTH;p.beginShape();for(i=startLUT;i<stopLUT;i++){ii=i%PConstants.SINCOS_LENGTH;if(ii<0){ii+=PConstants.SINCOS_LENGTH}p.vertex(centerX+parseFloat(Math.cos(ii*PConstants.DEG_TO_RAD*0.5))*hr,centerY+parseFloat(Math.sin(ii*PConstants.DEG_TO_RAD*0.5))*vr)}p.endShape();doFill=savedFill}};p.line=function line(){var x1,y1,z1,x2,y2,z2;if(p.use3DContext){if(arguments.length===6){x1=arguments[0];y1=arguments[1];z1=arguments[2];x2=arguments[3];y2=arguments[4];z2=arguments[5]}else{if(arguments.length===4){x1=arguments[0];y1=arguments[1];z1=0;x2=arguments[2];y2=arguments[3];z2=0}}var lineVerts=[x1,y1,z1,x2,y2,z2];var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.transpose();var proj=new PMatrix3D();proj.set(projection);proj.transpose();if(lineWidth>0&&doStroke){curContext.useProgram(programObject2D);uniformMatrix("model2d",programObject2D,"model",false,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);uniformMatrix("view2d",programObject2D,"view",false,view.array());uniformMatrix("projection2d",programObject2D,"projection",false,proj.array());uniformf("color2d",programObject2D,"color",strokeStyle);uniformi("picktype2d",programObject2D,"picktype",0);curContext.lineWidth(lineWidth);vertexAttribPointer("vertex2d",programObject2D,"Vertex",3,lineBuffer);disableVertexAttribPointer("aTextureCoord2d",programObject2D,"aTextureCoord");curContext.bufferData(curContext.ARRAY_BUFFER,new Float32Array(lineVerts),curContext.STREAM_DRAW);curContext.drawArrays(curContext.LINES,0,2)}}else{x1=arguments[0];y1=arguments[1];x2=arguments[2];y2=arguments[3];if((x1===x2||y1===y2)&&lineWidth<=1&&doStroke&&curSketch.options.crispLines){var temp;if(x1===x2){if(y1>y2){temp=y1;y1=y2;y2=temp}for(var y=y1;y<=y2;++y){p.set(x1,y,currentStrokeColor)}}else{if(x1>x2){temp=x1;x1=x2;x2=temp}for(var x=x1;x<=x2;++x){p.set(x,y1,currentStrokeColor)}}return}if(doStroke){curContext.beginPath();curContext.moveTo(x1||0,y1||0);curContext.lineTo(x2||0,y2||0);executeContextStroke();curContext.closePath()}}};p.bezier=function bezier(){if(arguments.length===8&&!p.use3DContext){p.beginShape();p.vertex(arguments[0],arguments[1]);p.bezierVertex(arguments[2],arguments[3],arguments[4],arguments[5],arguments[6],arguments[7]);p.endShape()}else{if(arguments.length===12&&p.use3DContext){p.beginShape();p.vertex(arguments[0],arguments[1],arguments[2]);p.bezierVertex(arguments[3],arguments[4],arguments[5],arguments[6],arguments[7],arguments[8],arguments[9],arguments[10],arguments[11]);p.endShape()}else{throw ("Please use the proper parameters!")}}};p.bezierDetail=function bezierDetail(detail){bezDetail=detail};p.bezierPoint=function bezierPoint(a,b,c,d,t){return(1-t)*(1-t)*(1-t)*a+3*(1-t)*(1-t)*t*b+3*(1-t)*t*t*c+t*t*t*d};p.bezierTangent=function bezierTangent(a,b,c,d,t){return(3*t*t*(-a+3*b-3*c+d)+6*t*(a-2*b+c)+3*(-a+b))};p.curvePoint=function curvePoint(a,b,c,d,t){return 0.5*((2*b)+(-a+c)*t+(2*a-5*b+4*c-d)*t*t+(-a+3*b-3*c+d)*t*t*t)};p.curveTangent=function curveTangent(a,b,c,d,t){return 0.5*((-a+c)+2*(2*a-5*b+4*c-d)*t+3*(-a+3*b-3*c+d)*t*t)};p.triangle=function triangle(x1,y1,x2,y2,x3,y3){p.beginShape(PConstants.TRIANGLES);p.vertex(x1,y1,0);p.vertex(x2,y2,0);p.vertex(x3,y3,0);p.endShape()};p.quad=function quad(x1,y1,x2,y2,x3,y3,x4,y4){p.beginShape(PConstants.QUADS);p.vertex(x1,y1,0);p.vertex(x2,y2,0);p.vertex(x3,y3,0);p.vertex(x4,y4,0);p.endShape()};p.rect=function rect(x,y,width,height){if(p.use3DContext){var model=new PMatrix3D();model.translate(x,y,0);model.scale(width,height,1);model.transpose();var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.transpose();var proj=new PMatrix3D();proj.set(projection);proj.transpose();if(lineWidth>0&&doStroke){curContext.useProgram(programObject2D);uniformMatrix("model2d",programObject2D,"model",false,model.array());uniformMatrix("view2d",programObject2D,"view",false,view.array());uniformMatrix("projection2d",programObject2D,"projection",false,proj.array());uniformf("color2d",programObject2D,"color",strokeStyle);uniformi("picktype2d",programObject2D,"picktype",0);vertexAttribPointer("vertex2d",programObject2D,"Vertex",3,rectBuffer);disableVertexAttribPointer("aTextureCoord2d",programObject2D,"aTextureCoord");curContext.lineWidth(lineWidth);curContext.drawArrays(curContext.LINE_LOOP,0,rectVerts.length/3)}if(doFill){curContext.useProgram(programObject3D);uniformMatrix("model3d",programObject3D,"model",false,model.array());uniformMatrix("view3d",programObject3D,"view",false,view.array());uniformMatrix("projection3d",programObject3D,"projection",false,proj.array());curContext.enable(curContext.POLYGON_OFFSET_FILL);curContext.polygonOffset(1,1);uniformf("color3d",programObject3D,"color",fillStyle);var v=new PMatrix3D();v.set(view);var m=new PMatrix3D();m.set(model);v.mult(m);var normalMatrix=new PMatrix3D();normalMatrix.set(v);normalMatrix.invert();normalMatrix.transpose();uniformMatrix("normalTransform3d",programObject3D,"normalTransform",false,normalMatrix.array());vertexAttribPointer("vertex3d",programObject3D,"Vertex",3,rectBuffer);vertexAttribPointer("normal3d",programObject3D,"Normal",3,rectNormBuffer);curContext.drawArrays(curContext.TRIANGLE_FAN,0,rectVerts.length/3);curContext.disable(curContext.POLYGON_OFFSET_FILL)}}else{if(!width&&!height){return}if(doStroke&&!doFill&&lineWidth<=1&&curSketch.options.crispLines){var i,x2=x+width-1,y2=y+height-1;for(i=0;i<width;++i){p.set(x+i,y,currentStrokeColor);p.set(x+i,y2,currentStrokeColor)}for(i=0;i<height;++i){p.set(x,y+i,currentStrokeColor);p.set(x2,y+i,currentStrokeColor)}return}curContext.beginPath();var offsetStart=0;var offsetEnd=0;if(curRectMode===PConstants.CORNERS){width-=x;height-=y}if(curRectMode===PConstants.RADIUS){width*=2;height*=2}if(curRectMode===PConstants.CENTER||curRectMode===PConstants.RADIUS){x-=width/2;y-=height/2}curContext.rect(Math.round(x)-offsetStart,Math.round(y)-offsetStart,Math.round(width)+offsetEnd,Math.round(height)+offsetEnd);executeContextFill();executeContextStroke();curContext.closePath()}};p.ellipse=function ellipse(x,y,width,height){x=x||0;y=y||0;if(width<=0&&height<=0){return}if(curEllipseMode===PConstants.RADIUS){width*=2;height*=2}if(curEllipseMode===PConstants.CORNERS){width=width-x;height=height-y}if(curEllipseMode===PConstants.CORNER||curEllipseMode===PConstants.CORNERS){x+=width/2;y+=height/2}var offsetStart=0;if((!p.use3DContext)&&(width===height)){curContext.beginPath();curContext.arc(x-offsetStart,y-offsetStart,width/2,0,PConstants.TWO_PI,false);executeContextFill();executeContextStroke();curContext.closePath()}else{var w=width/2,h=height/2,C=0.5522847498307933;var c_x=C*w,c_y=C*h;if(!p.use3DContext){p.beginShape();p.vertex(x+w,y);p.bezierVertex(x+w,y-c_y,x+c_x,y-h,x,y-h);p.bezierVertex(x-c_x,y-h,x-w,y-c_y,x-w,y);p.bezierVertex(x-w,y+c_y,x-c_x,y+h,x,y+h);p.bezierVertex(x+c_x,y+h,x+w,y+c_y,x+w,y);p.endShape()}else{p.beginShape();p.vertex(x+w,y);p.bezierVertex(x+w,y-c_y,0,x+c_x,y-h,0,x,y-h,0);p.bezierVertex(x-c_x,y-h,0,x-w,y-c_y,0,x-w,y,0);p.bezierVertex(x-w,y+c_y,0,x-c_x,y+h,0,x,y+h,0);p.bezierVertex(x+c_x,y+h,0,x+w,y+c_y,0,x+w,y,0);p.endShape();var xAv=0,yAv=0,i,j;for(i=0;i<vertArray.length;i++){xAv+=vertArray[i][0];yAv+=vertArray[i][1]}xAv/=vertArray.length;yAv/=vertArray.length;var vert=[],fillVertArray=[],colorVertArray=[];vert[0]=xAv;vert[1]=yAv;vert[2]=0;vert[3]=0;vert[4]=0;vert[5]=fillStyle[0];vert[6]=fillStyle[1];vert[7]=fillStyle[2];vert[8]=fillStyle[3];vert[9]=strokeStyle[0];vert[10]=strokeStyle[1];vert[11]=strokeStyle[2];vert[12]=strokeStyle[3];vert[13]=normalX;vert[14]=normalY;vert[15]=normalZ;vertArray.unshift(vert);for(i=0;i<vertArray.length;i++){for(j=0;j<3;j++){fillVertArray.push(vertArray[i][j])}for(j=5;j<9;j++){colorVertArray.push(vertArray[i][j])}}fill3D(fillVertArray,"TRIANGLE_FAN",colorVertArray)}}};p.normal=function normal(nx,ny,nz){if(arguments.length!==3||!(typeof nx==="number"&&typeof ny==="number"&&typeof nz==="number")){throw"normal() requires three numeric arguments."}normalX=nx;normalY=ny;normalZ=nz;if(curShape!==0){if(normalMode===PConstants.NORMAL_MODE_AUTO){normalMode=PConstants.NORMAL_MODE_SHAPE}else{if(normalMode===PConstants.NORMAL_MODE_SHAPE){normalMode=PConstants.NORMAL_MODE_VERTEX}}}};p.save=function save(file,img){if(img!==undef){return window.open(img.toDataURL(),"_blank")}else{return window.open(p.externals.canvas.toDataURL(),"_blank")}};var saveNumber=0;p.saveFrame=function saveFrame(file){if(file===undef){file="screen-####.png"}var frameFilename=file.replace(/#+/,function(all){var s=""+(saveNumber++);while(s.length<all.length){s="0"+s}return s});p.save(frameFilename)};var utilityContext2d=document.createElement("canvas").getContext("2d");var canvasDataCache=[undef,undef,undef];function getCanvasData(obj,w,h){var canvasData=canvasDataCache.shift();if(canvasData===undef){canvasData={};canvasData.canvas=document.createElement("canvas");canvasData.context=canvasData.canvas.getContext("2d")}canvasDataCache.push(canvasData);var canvas=canvasData.canvas,context=canvasData.context,width=w||obj.width,height=h||obj.height;canvas.width=width;canvas.height=height;if(!obj){context.clearRect(0,0,width,height)}else{if("data" in obj){context.putImageData(obj,0,0)}else{context.clearRect(0,0,width,height);context.drawImage(obj,0,0,width,height)}}return canvasData}var PImage=function PImage(aWidth,aHeight,aFormat){this.get=function(x,y,w,h){if(!arguments.length){return p.get(this)}else{if(arguments.length===2){return p.get(x,y,this)}else{if(arguments.length===4){return p.get(x,y,w,h,this)}}}};this.set=function(x,y,c){p.set(x,y,c,this)};this.blend=function(srcImg,x,y,width,height,dx,dy,dwidth,dheight,MODE){if(arguments.length===9){p.blend(this,srcImg,x,y,width,height,dx,dy,dwidth,dheight,this)}else{if(arguments.length===10){p.blend(srcImg,x,y,width,height,dx,dy,dwidth,dheight,MODE,this)}}delete this.sourceImg};this.copy=function(srcImg,sx,sy,swidth,sheight,dx,dy,dwidth,dheight){if(arguments.length===8){p.blend(this,srcImg,sx,sy,swidth,sheight,dx,dy,dwidth,PConstants.REPLACE,this)}else{if(arguments.length===9){p.blend(srcImg,sx,sy,swidth,sheight,dx,dy,dwidth,dheight,PConstants.REPLACE,this)}}delete this.sourceImg};this.filter=function(mode,param){if(arguments.length===2){p.filter(mode,param,this)}else{if(arguments.length===1){p.filter(mode,null,this)}}delete this.sourceImg};this.save=function(file){p.save(file,this)};this.resize=function(w,h){if(this.isRemote){throw"Image is loaded remotely. Cannot resize."}else{if(this.width!==0||this.height!==0){if(w===0&&h!==0){w=Math.floor(this.width/this.height*h)}else{if(h===0&&w!==0){h=Math.floor(this.height/this.width*w)}}var canvas=getCanvasData(this.imageData).canvas;var imageData=getCanvasData(canvas,w,h).context.getImageData(0,0,w,h);this.fromImageData(imageData)}}};this.mask=function(mask){this.__mask=undef;if(mask.constructor.name==="PImage"){if(mask.width===this.width&&mask.height===this.height){this.__mask=mask}else{throw"mask must have the same dimensions as PImage."}}else{if(typeof mask==="object"&&mask.constructor===Array){if(this.pixels.length===mask.length){this.__mask=mask}else{throw"mask array must be the same length as PImage pixels array."}}}};this.pixels={getLength:(function(aImg){if(aImg.isRemote){throw"Image is loaded remotely. Cannot get length."}else{return function(){return aImg.imageData.data.length?aImg.imageData.data.length/4:0}}}(this)),getPixel:(function(aImg){if(aImg.isRemote){throw"Image is loaded remotely. Cannot get pixels."}else{return function(i){var offset=i*4;return p.color.toInt(aImg.imageData.data[offset],aImg.imageData.data[offset+1],aImg.imageData.data[offset+2],aImg.imageData.data[offset+3])}}}(this)),setPixel:(function(aImg){if(aImg.isRemote){throw"Image is loaded remotely. Cannot set pixel."}else{return function(i,c){var offset=i*4;aImg.imageData.data[offset+0]=(c&PConstants.RED_MASK)>>>16;aImg.imageData.data[offset+1]=(c&PConstants.GREEN_MASK)>>>8;aImg.imageData.data[offset+2]=(c&PConstants.BLUE_MASK);aImg.imageData.data[offset+3]=(c&PConstants.ALPHA_MASK)>>>24}}}(this)),set:function(arr){if(this.isRemote){throw"Image is loaded remotely. Cannot set pixels."}else{for(var i=0,aL=arr.length;i<aL;i++){this.setPixel(i,arr[i])}}}};this.loadPixels=function(){};this.updatePixels=function(){};this.toImageData=function(){if(this.isRemote){return this.sourceImg}else{var canvasData=getCanvasData(this.imageData);return canvasData.context.getImageData(0,0,this.width,this.height)}};this.toDataURL=function(){if(this.isRemote){throw"Image is loaded remotely. Cannot create dataURI."}else{var canvasData=getCanvasData(this.imageData);return canvasData.canvas.toDataURL()}};this.fromImageData=function(canvasImg){this.width=canvasImg.width;this.height=canvasImg.height;this.imageData=canvasImg;this.format=PConstants.ARGB};this.fromHTMLImageData=function(htmlImg){var canvasData=getCanvasData(htmlImg);try{var imageData=canvasData.context.getImageData(0,0,htmlImg.width,htmlImg.height);this.fromImageData(imageData)}catch(e){if(htmlImg.width&&htmlImg.height){this.isRemote=true;this.width=htmlImg.width;this.height=htmlImg.height}}this.sourceImg=htmlImg};if(arguments.length===1){this.fromHTMLImageData(arguments[0])}else{if(arguments.length===2||arguments.length===3){this.width=aWidth||1;this.height=aHeight||1;this.imageData=utilityContext2d.createImageData(this.width,this.height);this.format=(aFormat===PConstants.ARGB||aFormat===PConstants.ALPHA)?aFormat:PConstants.RGB}else{this.width=0;this.height=0;this.imageData=utilityContext2d.createImageData(1,1);this.format=PConstants.ARGB}}};p.PImage=PImage;p.createImage=function createImage(w,h,mode){return new PImage(w,h,mode)};p.loadImage=function loadImage(file,type,callback){if(type){file=file+"."+type}if(curSketch.imageCache.images[file]){return new PImage(curSketch.imageCache.images[file])}else{var pimg=new PImage();var img=document.createElement("img");pimg.sourceImg=img;img.onload=(function(aImage,aPImage,aCallback){var image=aImage;var pimg=aPImage;var callback=aCallback;return function(){pimg.fromHTMLImageData(image);pimg.loaded=true;if(callback){callback()}}}(img,pimg,callback));img.src=file;return pimg}};p.requestImage=p.loadImage;function get$0(){var c=new PImage(p.width,p.height,PConstants.RGB);c.fromImageData(curContext.getImageData(0,0,p.width,p.height));return c}function get$2(x,y){var data;if(x<p.width&&x>=0&&y>=0&&y<p.height){if(isContextReplaced){var offset=((0|x)+p.width*(0|y))*4;data=p.imageData.data;return p.color.toInt(data[offset],data[offset+1],data[offset+2],data[offset+3])}data=curContext.getImageData(0|x,0|y,1,1).data;return p.color.toInt(data[0],data[1],data[2],data[3])}else{return 0}}function get$3(x,y,img){if(img.isRemote){throw"Image is loaded remotely. Cannot get x,y."}else{var offset=y*img.width*4+(x*4);return p.color.toInt(img.imageData.data[offset],img.imageData.data[offset+1],img.imageData.data[offset+2],img.imageData.data[offset+3])}}function get$4(x,y,w,h){var c=new PImage(w,h,PConstants.RGB);c.fromImageData(curContext.getImageData(x,y,w,h));return c}function get$5(x,y,w,h,img){if(img.isRemote){throw"Image is loaded remotely. Cannot get x,y,w,h."}else{var c=new PImage(w,h,PConstants.RGB),cData=c.imageData.data,imgWidth=img.width,imgHeight=img.height,imgData=img.imageData.data;var startRow=Math.max(0,-y),startColumn=Math.max(0,-x),stopRow=Math.min(h,imgHeight-y),stopColumn=Math.min(w,imgWidth-x);for(var i=startRow;i<stopRow;++i){var sourceOffset=((y+i)*imgWidth+(x+startColumn))*4;var targetOffset=(i*w+startColumn)*4;for(var j=startColumn;j<stopColumn;++j){cData[targetOffset++]=imgData[sourceOffset++];cData[targetOffset++]=imgData[sourceOffset++];cData[targetOffset++]=imgData[sourceOffset++];cData[targetOffset++]=imgData[sourceOffset++]}}return c}}p.get=function get(x,y,w,h,img){if(arguments.length===2){return get$2(x,y)}else{if(arguments.length===0){return get$0()}else{if(arguments.length===5){return get$5(x,y,w,h,img)}else{if(arguments.length===4){return get$4(x,y,w,h)}else{if(arguments.length===3){return get$3(x,y,w)}else{if(arguments.length===1){return x}}}}}}};p.createGraphics=function createGraphics(w,h,render){var canvas=document.createElement("canvas");var pg=new Processing(canvas);pg.size(w,h,render);pg.canvas=canvas;return pg};function resetContext(){if(isContextReplaced){curContext=originalContext;isContextReplaced=false;p.updatePixels()}}function SetPixelContextWrapper(){function wrapFunction(newContext,name){function wrapper(){resetContext();curContext[name].apply(curContext,arguments)}newContext[name]=wrapper}function wrapProperty(newContext,name){function getter(){resetContext();return curContext[name]}function setter(value){resetContext();curContext[name]=value}p.defineProperty(newContext,name,{get:getter,set:setter})}for(var n in curContext){if(typeof curContext[n]==="function"){wrapFunction(this,n)}else{wrapProperty(this,n)}}}function replaceContext(){if(isContextReplaced){return}p.loadPixels();if(proxyContext===null){originalContext=curContext;proxyContext=new SetPixelContextWrapper()}isContextReplaced=true;curContext=proxyContext;setPixelsCached=0}function set$3(x,y,c){if(x<p.width&&x>=0&&y>=0&&y<p.height){replaceContext();p.pixels.setPixel((0|x)+p.width*(0|y),c);if(++setPixelsCached>maxPixelsCached){resetContext()}}}function set$4(x,y,obj,img){if(img.isRemote){throw"Image is loaded remotely. Cannot set x,y."}else{var c=p.color.toArray(obj);var offset=y*img.width*4+(x*4);var data=img.imageData.data;data[offset]=c[0];data[offset+1]=c[1];data[offset+2]=c[2];data[offset+3]=c[3]}}p.set=function set(x,y,obj,img){var color,oldFill;if(arguments.length===3){if(typeof obj==="number"){set$3(x,y,obj)}else{if(obj instanceof PImage){p.image(obj,x,y)}}}else{if(arguments.length===4){set$4(x,y,obj,img)}}};p.imageData={};p.pixels={getLength:function(){return p.imageData.data.length?p.imageData.data.length/4:0},getPixel:function(i){var offset=i*4;return(p.imageData.data[offset+3]<<24)&4278190080|(p.imageData.data[offset+0]<<16)&16711680|(p.imageData.data[offset+1]<<8)&65280|p.imageData.data[offset+2]&255},setPixel:function(i,c){var offset=i*4;p.imageData.data[offset+0]=(c&16711680)>>>16;p.imageData.data[offset+1]=(c&65280)>>>8;p.imageData.data[offset+2]=(c&255);p.imageData.data[offset+3]=(c&4278190080)>>>24},set:function(arr){for(var i=0,aL=arr.length;i<aL;i++){this.setPixel(i,arr[i])}}};p.loadPixels=function(){p.imageData=curContext.getImageData(0,0,p.width,p.height)};p.updatePixels=function(){if(p.imageData){curContext.putImageData(p.imageData,0,0)}};p.hint=function hint(which){if(which===PConstants.DISABLE_DEPTH_TEST){curContext.disable(curContext.DEPTH_TEST);curContext.depthMask(false);curContext.clear(curContext.DEPTH_BUFFER_BIT)}else{if(which===PConstants.ENABLE_DEPTH_TEST){curContext.enable(curContext.DEPTH_TEST);curContext.depthMask(true)}}};p.background=function background(){var color,a,img;if(typeof arguments[0]==="number"){color=p.color.apply(this,arguments);if(!curSketch.options.isTransparent){color=color|PConstants.ALPHA_MASK}}else{if(arguments.length===1&&arguments[0] instanceof PImage){img=arguments[0];if(!img.pixels||img.width!==p.width||img.height!==p.height){throw"Background image must be the same dimensions as the canvas."}}else{throw"Incorrect background parameters."}}if(p.use3DContext){if(color!==undef){var c=p.color.toGLArray(color);refreshBackground=function(){curContext.clearColor(c[0],c[1],c[2],c[3]);curContext.clear(curContext.COLOR_BUFFER_BIT|curContext.DEPTH_BUFFER_BIT)}}else{refreshBackground=function(){}}}else{if(color!==undef){refreshBackground=function(){saveContext();curContext.setTransform(1,0,0,1,0,0);if(curSketch.options.isTransparent){curContext.clearRect(0,0,p.width,p.height)}curContext.fillStyle=p.color.toString(color);curContext.fillRect(0,0,p.width,p.height);isFillDirty=true;restoreContext()}}else{refreshBackground=function(){saveContext();curContext.setTransform(1,0,0,1,0,0);p.image(img,0,0);restoreContext()}}}refreshBackground()};p.image=function image(img,x,y,w,h){if(img.width>0){var wid=w||img.width;var hgt=h||img.height;if(p.use3DContext){p.beginShape(p.QUADS);p.texture(img.externals.canvas);p.vertex(x,y,0,0,0);p.vertex(x,y+hgt,0,0,hgt);p.vertex(x+wid,y+hgt,0,wid,hgt);p.vertex(x+wid,y,0,wid,0);p.endShape()}else{var bounds=imageModeConvert(x||0,y||0,w||img.width,h||img.height,arguments.length<4);var fastImage=!!img.sourceImg&&curTint===null&&!img.__mask;if(fastImage){var htmlElement=img.sourceImg;curContext.drawImage(htmlElement,0,0,htmlElement.width,htmlElement.height,bounds.x,bounds.y,bounds.w,bounds.h)}else{var obj=img.toImageData();if(img.__mask){var j,size;if(img.__mask.constructor.name==="PImage"){var objMask=img.__mask.toImageData();for(j=2,size=img.width*img.height*4;j<size;j+=4){obj.data[j+1]=objMask.data[j]}}else{for(j=0,size=img.__mask.length;j<size;++j){obj.data[(j<<2)+3]=img.__mask[j]}}}if(curTint!==null){curTint(obj)}curContext.drawImage(getCanvasData(obj).canvas,0,0,img.width,img.height,bounds.x,bounds.y,bounds.w,bounds.h)}}}};p.clear=function clear(x,y,width,height){if(arguments.length===0){curContext.clearRect(0,0,p.width,p.height)}else{curContext.clearRect(x,y,width,height)}};p.tint=function tint(){var tintColor=p.color.apply(this,arguments);var r=p.red(tintColor)/colorModeX;var g=p.green(tintColor)/colorModeY;var b=p.blue(tintColor)/colorModeZ;var a=p.alpha(tintColor)/colorModeA;curTint=function(obj){var data=obj.data,length=4*obj.width*obj.height;for(var i=0;i<length;){data[i++]*=r;data[i++]*=g;data[i++]*=b;data[i++]*=a}}};p.noTint=function noTint(){curTint=null};p.copy=function copy(src,sx,sy,sw,sh,dx,dy,dw,dh){if(arguments.length===8){dh=dw;dw=dy;dy=dx;dx=sh;sh=sw;sw=sy;sy=sx;sx=src;src=p}p.blend(src,sx,sy,sw,sh,dx,dy,dw,dh,PConstants.REPLACE)};p.blend=function blend(src,sx,sy,sw,sh,dx,dy,dw,dh,mode,pimgdest){if(arguments.length===9){mode=dh;dh=dw;dw=dy;dy=dx;dx=sh;sh=sw;sw=sy;sy=sx;sx=src;src=p}var sx2=sx+sw;var sy2=sy+sh;var dx2=dx+dw;var dy2=dy+dh;var dest;if(src.isRemote){throw"Image is loaded remotely. Cannot blend image."}else{if(arguments.length===10||arguments.length===9){p.loadPixels();dest=p}else{if(arguments.length===11&&pimgdest&&pimgdest.imageData){dest=pimgdest}}if(src===p){if(p.intersect(sx,sy,sx2,sy2,dx,dy,dx2,dy2)){p.blit_resize(p.get(sx,sy,sx2-sx,sy2-sy),0,0,sx2-sx-1,sy2-sy-1,dest.imageData.data,dest.width,dest.height,dx,dy,dx2,dy2,mode)}else{p.blit_resize(src,sx,sy,sx2,sy2,dest.imageData.data,dest.width,dest.height,dx,dy,dx2,dy2,mode)}}else{src.loadPixels();p.blit_resize(src,sx,sy,sx2,sy2,dest.imageData.data,dest.width,dest.height,dx,dy,dx2,dy2,mode)}if(arguments.length===10){p.updatePixels()}}};var buildBlurKernel=function buildBlurKernel(r){var radius=p.floor(r*3.5),i,radiusi;radius=(radius<1)?1:((radius<248)?radius:248);if(p.shared.blurRadius!==radius){p.shared.blurRadius=radius;p.shared.blurKernelSize=1+(p.shared.blurRadius<<1);p.shared.blurKernel=new Array(p.shared.blurKernelSize);for(i=0;i<p.shared.blurKernelSize;i++){p.shared.blurKernel[i]=0}for(i=1,radiusi=radius-1;i<radius;i++){p.shared.blurKernel[radius+i]=p.shared.blurKernel[radiusi]=radiusi*radiusi}p.shared.blurKernel[radius]=radius*radius}};var blurARGB=function blurARGB(r,aImg){var sum,cr,cg,cb,ca,c,m;var read,ri,ym,ymi,bk0;var wh=aImg.pixels.getLength();var r2=new Array(wh);var g2=new Array(wh);var b2=new Array(wh);var a2=new Array(wh);var yi=0;var x,y,i;buildBlurKernel(r);for(y=0;y<aImg.height;y++){for(x=0;x<aImg.width;x++){cb=cg=cr=ca=sum=0;read=x-p.shared.blurRadius;if(read<0){bk0=-read;read=0}else{if(read>=aImg.width){break}bk0=0}for(i=bk0;i<p.shared.blurKernelSize;i++){if(read>=aImg.width){break}c=aImg.pixels.getPixel(read+yi);m=p.shared.blurKernel[i];ca+=m*((c&PConstants.ALPHA_MASK)>>>24);cr+=m*((c&PConstants.RED_MASK)>>16);cg+=m*((c&PConstants.GREEN_MASK)>>8);cb+=m*(c&PConstants.BLUE_MASK);sum+=m;read++}ri=yi+x;a2[ri]=ca/sum;r2[ri]=cr/sum;g2[ri]=cg/sum;b2[ri]=cb/sum}yi+=aImg.width}yi=0;ym=-p.shared.blurRadius;ymi=ym*aImg.width;for(y=0;y<aImg.height;y++){for(x=0;x<aImg.width;x++){cb=cg=cr=ca=sum=0;if(ym<0){bk0=ri=-ym;read=x}else{if(ym>=aImg.height){break}bk0=0;ri=ym;read=x+ymi}for(i=bk0;i<p.shared.blurKernelSize;i++){if(ri>=aImg.height){break}m=p.shared.blurKernel[i];ca+=m*a2[read];cr+=m*r2[read];cg+=m*g2[read];cb+=m*b2[read];sum+=m;ri++;read+=aImg.width}aImg.pixels.setPixel(x+yi,((ca/sum)<<24|(cr/sum)<<16|(cg/sum)<<8|(cb/sum)))}yi+=aImg.width;ymi+=aImg.width;ym++}};var dilate=function dilate(isInverted,aImg){var currIdx=0;var maxIdx=aImg.pixels.getLength();var out=new Array(maxIdx);var currRowIdx,maxRowIdx,colOrig,colOut,currLum;var idxRight,idxLeft,idxUp,idxDown,colRight,colLeft,colUp,colDown,lumRight,lumLeft,lumUp,lumDown;if(!isInverted){while(currIdx<maxIdx){currRowIdx=currIdx;maxRowIdx=currIdx+aImg.width;while(currIdx<maxRowIdx){colOrig=colOut=aImg.pixels.getPixel(currIdx);idxLeft=currIdx-1;idxRight=currIdx+1;idxUp=currIdx-aImg.width;idxDown=currIdx+aImg.width;if(idxLeft<currRowIdx){idxLeft=currIdx}if(idxRight>=maxRowIdx){idxRight=currIdx}if(idxUp<0){idxUp=0}if(idxDown>=maxIdx){idxDown=currIdx}colUp=aImg.pixels.getPixel(idxUp);colLeft=aImg.pixels.getPixel(idxLeft);colDown=aImg.pixels.getPixel(idxDown);colRight=aImg.pixels.getPixel(idxRight);currLum=77*(colOrig>>16&255)+151*(colOrig>>8&255)+28*(colOrig&255);lumLeft=77*(colLeft>>16&255)+151*(colLeft>>8&255)+28*(colLeft&255);lumRight=77*(colRight>>16&255)+151*(colRight>>8&255)+28*(colRight&255);lumUp=77*(colUp>>16&255)+151*(colUp>>8&255)+28*(colUp&255);lumDown=77*(colDown>>16&255)+151*(colDown>>8&255)+28*(colDown&255);if(lumLeft>currLum){colOut=colLeft;currLum=lumLeft}if(lumRight>currLum){colOut=colRight;currLum=lumRight}if(lumUp>currLum){colOut=colUp;currLum=lumUp}if(lumDown>currLum){colOut=colDown;currLum=lumDown}out[currIdx++]=colOut}}}else{while(currIdx<maxIdx){currRowIdx=currIdx;maxRowIdx=currIdx+aImg.width;while(currIdx<maxRowIdx){colOrig=colOut=aImg.pixels.getPixel(currIdx);idxLeft=currIdx-1;idxRight=currIdx+1;idxUp=currIdx-aImg.width;idxDown=currIdx+aImg.width;if(idxLeft<currRowIdx){idxLeft=currIdx}if(idxRight>=maxRowIdx){idxRight=currIdx}if(idxUp<0){idxUp=0}if(idxDown>=maxIdx){idxDown=currIdx}colUp=aImg.pixels.getPixel(idxUp);colLeft=aImg.pixels.getPixel(idxLeft);colDown=aImg.pixels.getPixel(idxDown);colRight=aImg.pixels.getPixel(idxRight);currLum=77*(colOrig>>16&255)+151*(colOrig>>8&255)+28*(colOrig&255);lumLeft=77*(colLeft>>16&255)+151*(colLeft>>8&255)+28*(colLeft&255);lumRight=77*(colRight>>16&255)+151*(colRight>>8&255)+28*(colRight&255);lumUp=77*(colUp>>16&255)+151*(colUp>>8&255)+28*(colUp&255);lumDown=77*(colDown>>16&255)+151*(colDown>>8&255)+28*(colDown&255);if(lumLeft<currLum){colOut=colLeft;currLum=lumLeft}if(lumRight<currLum){colOut=colRight;currLum=lumRight}if(lumUp<currLum){colOut=colUp;currLum=lumUp}if(lumDown<currLum){colOut=colDown;currLum=lumDown}out[currIdx++]=colOut}}}aImg.pixels.set(out)};p.filter=function filter(kind,param,aImg){var img,col,lum,i;if(arguments.length===3){aImg.loadPixels();img=aImg}else{p.loadPixels();img=p}if(param===undef){param=null}if(img.isRemote){throw"Image is loaded remotely. Cannot filter image."}else{var imglen=img.pixels.getLength();switch(kind){case PConstants.BLUR:var radius=param||1;blurARGB(radius,img);break;case PConstants.GRAY:if(img.format===PConstants.ALPHA){for(i=0;i<imglen;i++){col=255-img.pixels.getPixel(i);img.pixels.setPixel(i,(4278190080|(col<<16)|(col<<8)|col))}img.format=PConstants.RGB}else{for(i=0;i<imglen;i++){col=img.pixels.getPixel(i);lum=(77*(col>>16&255)+151*(col>>8&255)+28*(col&255))>>8;img.pixels.setPixel(i,((col&PConstants.ALPHA_MASK)|lum<<16|lum<<8|lum))}}break;case PConstants.INVERT:for(i=0;i<imglen;i++){img.pixels.setPixel(i,(img.pixels.getPixel(i)^16777215))}break;case PConstants.POSTERIZE:if(param===null){throw"Use filter(POSTERIZE, int levels) instead of filter(POSTERIZE)"}var levels=p.floor(param);if((levels<2)||(levels>255)){throw"Levels must be between 2 and 255 for filter(POSTERIZE, levels)"}var levels1=levels-1;for(i=0;i<imglen;i++){var rlevel=(img.pixels.getPixel(i)>>16)&255;var glevel=(img.pixels.getPixel(i)>>8)&255;var blevel=img.pixels.getPixel(i)&255;rlevel=(((rlevel*levels)>>8)*255)/levels1;glevel=(((glevel*levels)>>8)*255)/levels1;blevel=(((blevel*levels)>>8)*255)/levels1;img.pixels.setPixel(i,((4278190080&img.pixels.getPixel(i))|(rlevel<<16)|(glevel<<8)|blevel))}break;case PConstants.OPAQUE:for(i=0;i<imglen;i++){img.pixels.setPixel(i,(img.pixels.getPixel(i)|4278190080))}img.format=PConstants.RGB;break;case PConstants.THRESHOLD:if(param===null){param=0.5}if((param<0)||(param>1)){throw"Level must be between 0 and 1 for filter(THRESHOLD, level)"}var thresh=p.floor(param*255);for(i=0;i<imglen;i++){var max=p.max((img.pixels.getPixel(i)&PConstants.RED_MASK)>>16,p.max((img.pixels.getPixel(i)&PConstants.GREEN_MASK)>>8,(img.pixels.getPixel(i)&PConstants.BLUE_MASK)));img.pixels.setPixel(i,((img.pixels.getPixel(i)&PConstants.ALPHA_MASK)|((max<thresh)?0:16777215)))}break;case PConstants.ERODE:dilate(true,img);break;case PConstants.DILATE:dilate(false,img);break}img.updatePixels()}};p.shared={fracU:0,ifU:0,fracV:0,ifV:0,u1:0,u2:0,v1:0,v2:0,sX:0,sY:0,iw:0,iw1:0,ih1:0,ul:0,ll:0,ur:0,lr:0,cUL:0,cLL:0,cUR:0,cLR:0,srcXOffset:0,srcYOffset:0,r:0,g:0,b:0,a:0,srcBuffer:null,blurRadius:0,blurKernelSize:0,blurKernel:null};p.intersect=function intersect(sx1,sy1,sx2,sy2,dx1,dy1,dx2,dy2){var sw=sx2-sx1+1;var sh=sy2-sy1+1;var dw=dx2-dx1+1;var dh=dy2-dy1+1;if(dx1<sx1){dw+=dx1-sx1;if(dw>sw){dw=sw}}else{var w=sw+sx1-dx1;if(dw>w){dw=w}}if(dy1<sy1){dh+=dy1-sy1;if(dh>sh){dh=sh}}else{var h=sh+sy1-dy1;if(dh>h){dh=h}}return !(dw<=0||dh<=0)};p.filter_new_scanline=function filter_new_scanline(){p.shared.sX=p.shared.srcXOffset;p.shared.fracV=p.shared.srcYOffset&PConstants.PREC_MAXVAL;p.shared.ifV=PConstants.PREC_MAXVAL-p.shared.fracV;p.shared.v1=(p.shared.srcYOffset>>PConstants.PRECISIONB)*p.shared.iw;p.shared.v2=Math.min((p.shared.srcYOffset>>PConstants.PRECISIONB)+1,p.shared.ih1)*p.shared.iw};p.filter_bilinear=function filter_bilinear(){p.shared.fracU=p.shared.sX&PConstants.PREC_MAXVAL;p.shared.ifU=PConstants.PREC_MAXVAL-p.shared.fracU;p.shared.ul=(p.shared.ifU*p.shared.ifV)>>PConstants.PRECISIONB;p.shared.ll=(p.shared.ifU*p.shared.fracV)>>PConstants.PRECISIONB;p.shared.ur=(p.shared.fracU*p.shared.ifV)>>PConstants.PRECISIONB;p.shared.lr=(p.shared.fracU*p.shared.fracV)>>PConstants.PRECISIONB;p.shared.u1=(p.shared.sX>>PConstants.PRECISIONB);p.shared.u2=Math.min(p.shared.u1+1,p.shared.iw1);var cULoffset=(p.shared.v1+p.shared.u1)*4;var cURoffset=(p.shared.v1+p.shared.u2)*4;var cLLoffset=(p.shared.v2+p.shared.u1)*4;var cLRoffset=(p.shared.v2+p.shared.u2)*4;p.shared.cUL=p.color.toInt(p.shared.srcBuffer[cULoffset],p.shared.srcBuffer[cULoffset+1],p.shared.srcBuffer[cULoffset+2],p.shared.srcBuffer[cULoffset+3]);p.shared.cUR=p.color.toInt(p.shared.srcBuffer[cURoffset],p.shared.srcBuffer[cURoffset+1],p.shared.srcBuffer[cURoffset+2],p.shared.srcBuffer[cURoffset+3]);p.shared.cLL=p.color.toInt(p.shared.srcBuffer[cLLoffset],p.shared.srcBuffer[cLLoffset+1],p.shared.srcBuffer[cLLoffset+2],p.shared.srcBuffer[cLLoffset+3]);p.shared.cLR=p.color.toInt(p.shared.srcBuffer[cLRoffset],p.shared.srcBuffer[cLRoffset+1],p.shared.srcBuffer[cLRoffset+2],p.shared.srcBuffer[cLRoffset+3]);p.shared.r=((p.shared.ul*((p.shared.cUL&PConstants.RED_MASK)>>16)+p.shared.ll*((p.shared.cLL&PConstants.RED_MASK)>>16)+p.shared.ur*((p.shared.cUR&PConstants.RED_MASK)>>16)+p.shared.lr*((p.shared.cLR&PConstants.RED_MASK)>>16))<<PConstants.PREC_RED_SHIFT)&PConstants.RED_MASK;p.shared.g=((p.shared.ul*(p.shared.cUL&PConstants.GREEN_MASK)+p.shared.ll*(p.shared.cLL&PConstants.GREEN_MASK)+p.shared.ur*(p.shared.cUR&PConstants.GREEN_MASK)+p.shared.lr*(p.shared.cLR&PConstants.GREEN_MASK))>>>PConstants.PRECISIONB)&PConstants.GREEN_MASK;p.shared.b=(p.shared.ul*(p.shared.cUL&PConstants.BLUE_MASK)+p.shared.ll*(p.shared.cLL&PConstants.BLUE_MASK)+p.shared.ur*(p.shared.cUR&PConstants.BLUE_MASK)+p.shared.lr*(p.shared.cLR&PConstants.BLUE_MASK))>>>PConstants.PRECISIONB;p.shared.a=((p.shared.ul*((p.shared.cUL&PConstants.ALPHA_MASK)>>>24)+p.shared.ll*((p.shared.cLL&PConstants.ALPHA_MASK)>>>24)+p.shared.ur*((p.shared.cUR&PConstants.ALPHA_MASK)>>>24)+p.shared.lr*((p.shared.cLR&PConstants.ALPHA_MASK)>>>24))<<PConstants.PREC_ALPHA_SHIFT)&PConstants.ALPHA_MASK;return p.shared.a|p.shared.r|p.shared.g|p.shared.b};p.blit_resize=function blit_resize(img,srcX1,srcY1,srcX2,srcY2,destPixels,screenW,screenH,destX1,destY1,destX2,destY2,mode){var x,y;if(srcX1<0){srcX1=0}if(srcY1<0){srcY1=0}if(srcX2>=img.width){srcX2=img.width-1}if(srcY2>=img.height){srcY2=img.height-1}var srcW=srcX2-srcX1;var srcH=srcY2-srcY1;var destW=destX2-destX1;var destH=destY2-destY1;var smooth=true;if(!smooth){srcW++;srcH++}if(destW<=0||destH<=0||srcW<=0||srcH<=0||destX1>=screenW||destY1>=screenH||srcX1>=img.width||srcY1>=img.height){return}var dx=Math.floor(srcW/destW*PConstants.PRECISIONF);var dy=Math.floor(srcH/destH*PConstants.PRECISIONF);p.shared.srcXOffset=Math.floor(destX1<0?-destX1*dx:srcX1*PConstants.PRECISIONF);p.shared.srcYOffset=Math.floor(destY1<0?-destY1*dy:srcY1*PConstants.PRECISIONF);if(destX1<0){destW+=destX1;destX1=0}if(destY1<0){destH+=destY1;destY1=0}destW=Math.min(destW,screenW-destX1);destH=Math.min(destH,screenH-destY1);var destOffset=destY1*screenW+destX1;var destColor;p.shared.srcBuffer=img.imageData.data;if(smooth){p.shared.iw=img.width;p.shared.iw1=img.width-1;p.shared.ih1=img.height-1;switch(mode){case PConstants.BLEND:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.blend(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.ADD:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.add(destColor,p.filter_bilinear()));destColor=p.color.toArray(p.modes.add(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.SUBTRACT:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.subtract(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.LIGHTEST:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.lightest(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.DARKEST:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.darkest(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.REPLACE:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.filter_bilinear());destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.DIFFERENCE:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.difference(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.EXCLUSION:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.exclusion(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.MULTIPLY:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.multiply(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.SCREEN:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.screen(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.OVERLAY:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.overlay(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.HARD_LIGHT:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.hard_light(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.SOFT_LIGHT:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.soft_light(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.DODGE:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.dodge(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break;case PConstants.BURN:for(y=0;y<destH;y++){p.filter_new_scanline();for(x=0;x<destW;x++){destColor=p.color.toInt(destPixels[(destOffset+x)*4],destPixels[((destOffset+x)*4)+1],destPixels[((destOffset+x)*4)+2],destPixels[((destOffset+x)*4)+3]);destColor=p.color.toArray(p.modes.burn(destColor,p.filter_bilinear()));destPixels[(destOffset+x)*4]=destColor[0];destPixels[(destOffset+x)*4+1]=destColor[1];destPixels[(destOffset+x)*4+2]=destColor[2];destPixels[(destOffset+x)*4+3]=destColor[3];p.shared.sX+=dx}destOffset+=screenW;p.shared.srcYOffset+=dy}break}}};function PFont(name){this.name="sans-serif";if(name!==undef){switch(name){case"sans-serif":case"serif":case"monospace":case"fantasy":case"cursive":this.name=name;break;default:this.name='"'+name+'", sans-serif';break}}this.origName=name}PFont.prototype.width=function(str){if("measureText" in curContext){return curContext.measureText(typeof str==="number"?String.fromCharCode(str):str).width/curTextSize}else{if("mozMeasureText" in curContext){return curContext.mozMeasureText(typeof str==="number"?String.fromCharCode(str):str)/curTextSize}else{return 0}}};PFont.list=function(){return["sans-serif","serif","monospace","fantasy","cursive"]};p.PFont=PFont;p.loadFont=function loadFont(name){if(name===undef||name.indexOf(".svg")===-1){return new PFont(name)}else{var font=p.loadGlyphs(name);return{name:name,glyph:true,units_per_em:font.units_per_em,horiz_adv_x:1/font.units_per_em*font.horiz_adv_x,ascent:font.ascent,descent:font.descent,width:function(str){var width=0;var len=str.length;for(var i=0;i<len;i++){try{width+=parseFloat(p.glyphLook(p.glyphTable[name],str[i]).horiz_adv_x)}catch(e){Processing.debug(e)}}return width/p.glyphTable[name].units_per_em}}}};p.createFont=function(name,size,smooth,charset){if(arguments.length===2){p.textSize(size);return p.loadFont(name)}else{if(arguments.length===3){p.textSize(size);return p.loadFont(name)}else{if(arguments.length===4){p.textSize(size);return p.loadFont(name)}else{throw ("incorrent number of parameters for createFont")}}}};p.textFont=function textFont(font,size){curTextFont=font;if(size){p.textSize(size)}else{curContext.font=curContext.mozTextStyle=curTextSize+"px "+curTextFont.name}};p.textSize=function textSize(size){if(size){curTextSize=size;curContext.font=curContext.mozTextStyle=curTextSize+"px "+curTextFont.name}};p.textAlign=function textAlign(){if(arguments.length===1){horizontalTextAlignment=arguments[0]}else{if(arguments.length===2){horizontalTextAlignment=arguments[0];verticalTextAlignment=arguments[1]}}};p.textWidth=function textWidth(str){if(p.use3DContext){if(textcanvas===undef){textcanvas=document.createElement("canvas")}var oldContext=curContext;curContext=textcanvas.getContext("2d");curContext.font=curContext.mozTextStyle=curTextSize+"px "+curTextFont.name;if("fillText" in curContext){textcanvas.width=curContext.measureText(str).width}else{if("mozDrawText" in curContext){textcanvas.width=curContext.mozMeasureText(str)}}curContext=oldContext;return textcanvas.width}else{curContext.font=curTextSize+"px "+curTextFont.name;if("fillText" in curContext){return curContext.measureText(str).width}else{if("mozDrawText" in curContext){return curContext.mozMeasureText(str)}}}};p.textLeading=function textLeading(leading){curTextLeading=leading};var measureTextCanvas=function(fontFace,fontSize,baseLine,text){this.canvas=document.createElement("canvas");this.canvas.setAttribute("width",fontSize+"px");this.canvas.setAttribute("height",fontSize+"px");this.ctx=this.canvas.getContext("2d");this.ctx.font=fontSize+"pt "+fontFace;this.ctx.fillStyle="black";this.ctx.fillRect(0,0,fontSize,fontSize);this.ctx.fillStyle="white";this.ctx.fillText(text,0,baseLine);this.imageData=this.ctx.getImageData(0,0,fontSize,fontSize);this.get=function(x,y){return this.imageData.data[((y*(this.imageData.width*4))+(x*4))]}};p.textAscent=(function(){var oldTextSize=undef,oldTextFont=undef,ascent=undef,graphics=undef;return function textAscent(){if(oldTextFont!==curTextFont||oldTextSize!==curTextSize){oldTextFont=curTextFont;oldTextSize=curTextSize;var found=false,character="k",colour=p.color(0),top=0,bottom=curTextSize,yLoc=curTextSize/2;graphics=new measureTextCanvas(curTextFont.name,curTextSize,curTextSize,character);while(yLoc!==bottom){for(var xLoc=0;xLoc<curTextSize;xLoc++){if(graphics.get(xLoc,yLoc)!==colour){found=true;xLoc=curTextSize}}if(found){bottom=yLoc;found=false}else{top=yLoc}yLoc=Math.ceil((bottom+top)/2)}ascent=((curTextSize-1)-yLoc)+1;return ascent}else{return ascent}}}());p.textDescent=(function(){var oldTextSize=undef,oldTextFont=undef,descent=undef,graphics=undef;return function textDescent(){if(oldTextFont!==curTextFont||oldTextSize!==curTextSize){oldTextFont=curTextFont;oldTextSize=curTextSize;var found=false,character="p",colour=p.color(0),top=0,bottom=curTextSize,yLoc=curTextSize/2;graphics=new measureTextCanvas(curTextFont.name,curTextSize,0,character);while(yLoc!==bottom){for(var xLoc=0;xLoc<curTextSize;xLoc++){if(graphics.get(xLoc,yLoc)!==colour){found=true;xLoc=curTextSize}}if(found){top=yLoc;found=false}else{bottom=yLoc}yLoc=Math.ceil((bottom+top)/2)}descent=yLoc+1;return descent}else{return descent}}}());p.glyphLook=function glyphLook(font,chr){try{switch(chr){case"1":return font.one;case"2":return font.two;case"3":return font.three;case"4":return font.four;case"5":return font.five;case"6":return font.six;case"7":return font.seven;case"8":return font.eight;case"9":return font.nine;case"0":return font.zero;case" ":return font.space;case"$":return font.dollar;case"!":return font.exclam;case'"':return font.quotedbl;case"#":return font.numbersign;case"%":return font.percent;case"&":return font.ampersand;case"'":return font.quotesingle;case"(":return font.parenleft;case")":return font.parenright;case"*":return font.asterisk;case"+":return font.plus;case",":return font.comma;case"-":return font.hyphen;case".":return font.period;case"/":return font.slash;case"_":return font.underscore;case":":return font.colon;case";":return font.semicolon;case"<":return font.less;case"=":return font.equal;case">":return font.greater;case"?":return font.question;case"@":return font.at;case"[":return font.bracketleft;case"\\":return font.backslash;case"]":return font.bracketright;case"^":return font.asciicircum;case"`":return font.grave;case"{":return font.braceleft;case"|":return font.bar;case"}":return font.braceright;case"~":return font.asciitilde;default:return font[chr]}}catch(e){Processing.debug(e)}};function toP5String(obj){if(obj instanceof String){return obj}else{if(typeof obj==="number"){if(obj===(0|obj)){return obj.toString()}else{return p.nf(obj,0,3)}}else{if(obj===null||obj===undef){return""}else{return obj.toString()}}}}function text$line(str,x,y,z,align){var textWidth=0,xOffset=0;if(!curTextFont.glyph){if(str&&("fillText" in curContext||"mozDrawText" in curContext)){if(isFillDirty){curContext.fillStyle=p.color.toString(currentFillColor);isFillDirty=false}if(align===PConstants.RIGHT||align===PConstants.CENTER){if("fillText" in curContext){textWidth=curContext.measureText(str).width}else{if("mozDrawText" in curContext){textWidth=curContext.mozMeasureText(str)}}if(align===PConstants.RIGHT){xOffset=-textWidth}else{xOffset=-textWidth/2}}if("fillText" in curContext){curContext.fillText(str,x+xOffset,y)}else{if("mozDrawText" in curContext){saveContext();curContext.translate(x+xOffset,y);curContext.mozDrawText(str);restoreContext()}}}}else{var font=p.glyphTable[curTextFont.name];saveContext();curContext.translate(x,y+curTextSize);if(align===PConstants.RIGHT||align===PConstants.CENTER){textWidth=font.width(str);if(align===PConstants.RIGHT){xOffset=-textWidth}else{xOffset=-textWidth/2}}var upem=font.units_per_em,newScale=1/upem*curTextSize;curContext.scale(newScale,newScale);for(var i=0,len=str.length;i<len;i++){try{p.glyphLook(font,str[i]).draw()}catch(e){Processing.debug(e)}}restoreContext()}}function text$line$3d(str,x,y,z,align){if(textcanvas===undef){textcanvas=document.createElement("canvas")}var oldContext=curContext;curContext=textcanvas.getContext("2d");curContext.font=curContext.mozTextStyle=curTextSize+"px "+curTextFont.name;var textWidth=0;if("fillText" in curContext){textWidth=curContext.measureText(str).width}else{if("mozDrawText" in curContext){textWidth=curContext.mozMeasureText(str)}}textcanvas.width=textWidth;textcanvas.height=curTextSize;curContext=textcanvas.getContext("2d");curContext.font=curContext.mozTextStyle=curTextSize+"px "+curTextFont.name;curContext.textBaseline="top";text$line(str,0,0,0,PConstants.LEFT);var aspect=textcanvas.width/textcanvas.height;curContext=oldContext;curContext.bindTexture(curContext.TEXTURE_2D,textTex);executeTexImage2D(textcanvas);curContext.texParameteri(curContext.TEXTURE_2D,curContext.TEXTURE_MAG_FILTER,curContext.LINEAR);curContext.texParameteri(curContext.TEXTURE_2D,curContext.TEXTURE_MIN_FILTER,curContext.LINEAR);curContext.texParameteri(curContext.TEXTURE_2D,curContext.TEXTURE_WRAP_T,curContext.CLAMP_TO_EDGE);curContext.texParameteri(curContext.TEXTURE_2D,curContext.TEXTURE_WRAP_S,curContext.CLAMP_TO_EDGE);var xOffset=0;if(align===PConstants.RIGHT){xOffset=-textWidth}else{if(align===PConstants.CENTER){xOffset=-textWidth/2}}var model=new PMatrix3D();var scalefactor=curTextSize*0.5;model.translate(x+xOffset-scalefactor/2,y-scalefactor,z);model.scale(-aspect*scalefactor,-scalefactor,scalefactor);model.translate(-1,-1,-1);model.transpose();var view=new PMatrix3D();view.scale(1,-1,1);view.apply(modelView.array());view.transpose();var proj=new PMatrix3D();proj.set(projection);proj.transpose();curContext.useProgram(programObject2D);vertexAttribPointer("vertex2d",programObject2D,"Vertex",3,textBuffer);vertexAttribPointer("aTextureCoord2d",programObject2D,"aTextureCoord",2,textureBuffer);uniformi("uSampler2d",programObject2D,"uSampler",[0]);uniformi("picktype2d",programObject2D,"picktype",1);uniformMatrix("model2d",programObject2D,"model",false,model.array());uniformMatrix("view2d",programObject2D,"view",false,view.array());uniformMatrix("projection2d",programObject2D,"projection",false,proj.array());uniformf("color2d",programObject2D,"color",fillStyle);curContext.bindBuffer(curContext.ELEMENT_ARRAY_BUFFER,indexBuffer);curContext.drawElements(curContext.TRIANGLES,6,curContext.UNSIGNED_SHORT,0)}function text$4(str,x,y,z){var lineFunction=p.use3DContext?text$line$3d:text$line;var lines,linesCount;if(str.indexOf("\n")<0){lines=[str];linesCount=1}else{lines=str.split(/\r?\n/g);linesCount=lines.length}var yOffset;if(verticalTextAlignment===PConstants.TOP){yOffset=(1-baselineOffset)*curTextLeading}else{if(verticalTextAlignment===PConstants.CENTER){yOffset=(1-baselineOffset-linesCount/2)*curTextLeading}else{if(verticalTextAlignment===PConstants.BOTTOM){yOffset=(1-baselineOffset-linesCount)*curTextLeading}else{yOffset=0}}}for(var i=0;i<linesCount;++i){var line=lines[i];lineFunction(line,x,y+yOffset,z,horizontalTextAlignment);yOffset+=curTextLeading}}function text$6(str,x,y,width,height,z){if(str.length===0){return}if(curTextSize>height){return}curContext.font=curTextSize+"px "+curTextFont.name;var spaceLoc=null,yOffset=0,lineWidth=0,letterWidth=0,strings=str.split("\n");for(var j=0;j<strings.length;j++){for(var jj=0;jj<strings[j].length;jj++){if("fillText" in curContext){letterWidth=curContext.measureText(strings[j][jj]).width}else{if("mozDrawText" in curContext){letterWidth=curContext.mozMeasureText(strings[j][jj])}}lineWidth+=letterWidth;if(strings[j][jj]===" "){spaceLoc=jj}if(lineWidth>=width&&strings[j][jj]!==" "){if(spaceLoc===null){spaceLoc=jj}strings.splice(j,1,strings[j].substring(0,spaceLoc+1),strings[j].substring(spaceLoc+1));spaceLoc=null}}lineWidth=letterWidth=0}var lineFunction=p.use3DContext?text$line$3d:text$line;var xOffset=0;if(horizontalTextAlignment===PConstants.CENTER){xOffset=width/2}else{if(horizontalTextAlignment===PConstants.RIGHT){xOffset=width}}var boxYOffset1=(1-baselineOffset)*curTextSize,boxYOffset2=0;if(verticalTextAlignment===PConstants.BOTTOM){boxYOffset2=height-(strings.length*curTextLeading)}else{if(verticalTextAlignment===PConstants.CENTER){boxYOffset2=(height-(strings.length*curTextLeading))/2}}for(var il=0,ll=strings.length;il<ll;++il,yOffset+=curTextLeading){if(yOffset+boxYOffset2<0){continue}if(yOffset+boxYOffset2+curTextLeading>height){break}lineFunction(strings[il],x+xOffset,y+yOffset+boxYOffset1+boxYOffset2,z,horizontalTextAlignment)}}p.text=function text(){if(tMode===PConstants.SCREEN){p.pushMatrix();p.resetMatrix();var asc=p.textAscent();var des=p.textDescent();var tWidth=p.textWidth(arguments[0]);var tHeight=asc+des;var font=p.loadFont(curTextFont.origName);var hud=p.createGraphics(tWidth,tHeight);hud.beginDraw();hud.fill(currentFillColor);hud.opaque=false;hud.background(0,0,0,0);hud.textFont(font);hud.textSize(curTextSize);hud.text(arguments[0],0,asc);hud.endDraw();if(arguments.length===5||arguments.length===6){p.image(hud,arguments[1],arguments[2]-asc,arguments[3],arguments[4])}else{p.image(hud,arguments[1],arguments[2]-asc)}p.popMatrix()}else{if(tMode===PConstants.SHAPE){}else{if(arguments.length===3){text$4(toP5String(arguments[0]),arguments[1],arguments[2],0)}else{if(arguments.length===4){text$4(toP5String(arguments[0]),arguments[1],arguments[2],arguments[3])}else{if(arguments.length===5){text$6(toP5String(arguments[0]),arguments[1],arguments[2],arguments[3],arguments[4],0)}else{if(arguments.length===6){text$6(toP5String(arguments[0]),arguments[1],arguments[2],arguments[3],arguments[4],arguments[5])}}}}}}};p.textMode=function textMode(mode){tMode=mode};p.loadGlyphs=function loadGlyph(url){var x,y,cx,cy,nx,ny,d,a,lastCom,lenC,horiz_adv_x,getXY="[0-9\\-]+",path;var regex=function regex(needle,hay){var i=0,results=[],latest,regexp=new RegExp(needle,"g");latest=results[i]=regexp.exec(hay);while(latest){i++;latest=results[i]=regexp.exec(hay)}return results};var buildPath=function buildPath(d){var c=regex("[A-Za-z][0-9\\- ]+|Z",d);path="var path={draw:function(){saveContext();curContext.beginPath();";x=0;y=0;cx=0;cy=0;nx=0;ny=0;d=0;a=0;lastCom="";lenC=c.length-1;for(var j=0;j<lenC;j++){var com=c[j][0],xy=regex(getXY,com);switch(com[0]){case"M":x=parseFloat(xy[0][0]);y=parseFloat(xy[1][0]);path+="curContext.moveTo("+x+","+(-y)+");";break;case"L":x=parseFloat(xy[0][0]);y=parseFloat(xy[1][0]);path+="curContext.lineTo("+x+","+(-y)+");";break;case"H":x=parseFloat(xy[0][0]);path+="curContext.lineTo("+x+","+(-y)+");";break;case"V":y=parseFloat(xy[0][0]);path+="curContext.lineTo("+x+","+(-y)+");";break;case"T":nx=parseFloat(xy[0][0]);ny=parseFloat(xy[1][0]);if(lastCom==="Q"||lastCom==="T"){d=Math.sqrt(Math.pow(x-cx,2)+Math.pow(cy-y,2));a=Math.PI+Math.atan2(cx-x,cy-y);cx=x+(Math.sin(a)*(d));cy=y+(Math.cos(a)*(d))}else{cx=x;cy=y}path+="curContext.quadraticCurveTo("+cx+","+(-cy)+","+nx+","+(-ny)+");";x=nx;y=ny;break;case"Q":cx=parseFloat(xy[0][0]);cy=parseFloat(xy[1][0]);nx=parseFloat(xy[2][0]);ny=parseFloat(xy[3][0]);path+="curContext.quadraticCurveTo("+cx+","+(-cy)+","+nx+","+(-ny)+");";x=nx;y=ny;break;case"Z":path+="curContext.closePath();";break}lastCom=com[0]}path+="executeContextFill();executeContextStroke();";path+="restoreContext();";path+="curContext.translate("+horiz_adv_x+",0);";path+="}}";return path};var parseSVGFont=function parseSVGFontse(svg){var font=svg.getElementsByTagName("font");p.glyphTable[url].horiz_adv_x=font[0].getAttribute("horiz-adv-x");var font_face=svg.getElementsByTagName("font-face")[0];p.glyphTable[url].units_per_em=parseFloat(font_face.getAttribute("units-per-em"));p.glyphTable[url].ascent=parseFloat(font_face.getAttribute("ascent"));p.glyphTable[url].descent=parseFloat(font_face.getAttribute("descent"));var glyph=svg.getElementsByTagName("glyph"),len=glyph.length;for(var i=0;i<len;i++){var unicode=glyph[i].getAttribute("unicode");var name=glyph[i].getAttribute("glyph-name");horiz_adv_x=glyph[i].getAttribute("horiz-adv-x");if(horiz_adv_x===null){horiz_adv_x=p.glyphTable[url].horiz_adv_x}d=glyph[i].getAttribute("d");if(d!==undef){path=buildPath(d);eval(path);p.glyphTable[url][name]={name:name,unicode:unicode,horiz_adv_x:horiz_adv_x,draw:path.draw}}}};var loadXML=function loadXML(){var xmlDoc;try{xmlDoc=document.implementation.createDocument("","",null)}catch(e_fx_op){Processing.debug(e_fx_op.message);return}try{xmlDoc.async=false;xmlDoc.load(url);parseSVGFont(xmlDoc.getElementsByTagName("svg")[0])}catch(e_sf_ch){Processing.debug(e_sf_ch);try{var xmlhttp=new window.XMLHttpRequest();xmlhttp.open("GET",url,false);xmlhttp.send(null);parseSVGFont(xmlhttp.responseXML.documentElement)}catch(e){Processing.debug(e_sf_ch)}}};p.glyphTable[url]={};loadXML(url);return p.glyphTable[url]};function extendClass(subClass,baseClass){function extendGetterSetter(propertyName){p.defineProperty(subClass,propertyName,{get:function(){return baseClass[propertyName]},set:function(v){baseClass[propertyName]=v},enumerable:true})}var properties=[];for(var propertyName in baseClass){if(!(propertyName in subClass)){if(typeof baseClass[propertyName]==="function"){subClass[propertyName]=baseClass[propertyName]}else{if(propertyName!=="$upcast"){properties.push(propertyName)}}}}while(properties.length>0){extendGetterSetter(properties.shift())}}p.extendClassChain=function(base){var path=[base];for(var self=base.$upcast;self;self=self.$upcast){extendClass(self,base);path.push(self);base=self}while(path.length>0){path.pop().$self=base}};p.addMethod=function addMethod(object,name,fn,superAccessor){if(object[name]){var args=fn.length,oldfn=object[name];object[name]=function(){if(arguments.length===args){return fn.apply(this,arguments)}else{return oldfn.apply(this,arguments)}}}else{object[name]=fn}};p.createJavaArray=function createJavaArray(type,bounds){var result=null;if(typeof bounds[0]==="number"){var itemsCount=0|bounds[0];if(bounds.length<=1){if(type==="int"){result=new Int32Array(itemsCount)}else{if(type==="float"){result=new Float32Array(itemsCount)}else{result=new Array(itemsCount)}}for(var i=0;i<itemsCount;++i){result[i]=0}}else{result=[];var newBounds=bounds.slice(1);for(var j=0;j<itemsCount;++j){result.push(createJavaArray(type,newBounds))}}}return result};function attach(elem,type,fn){if(elem.addEventListener){elem.addEventListener(type,fn,false)}else{elem.attachEvent("on"+type,fn)}eventHandlers.push([elem,type,fn])}attach(curElement,"mousemove",function(e){var element=curElement,offsetX=0,offsetY=0;p.pmouseX=p.mouseX;p.pmouseY=p.mouseY;if(element.offsetParent){do{offsetX+=element.offsetLeft;offsetY+=element.offsetTop}while((element=element.offsetParent))}element=curElement;do{offsetX-=element.scrollLeft||0;offsetY-=element.scrollTop||0}while((element=element.parentNode));offsetX+=stylePaddingLeft;offsetY+=stylePaddingTop;offsetX+=styleBorderLeft;offsetY+=styleBorderTop;p.mouseX=e.clientX-offsetX;p.mouseY=e.clientY-offsetY;if(typeof p.mouseMoved==="function"&&!p.__mousePressed){p.mouseMoved()}if(typeof p.mouseDragged==="function"&&p.__mousePressed){p.mouseDragged();p.mouseDragging=true}});attach(curElement,"mouseout",function(e){});attach(curElement,"mousedown",function(e){p.__mousePressed=true;p.mouseDragging=false;switch(e.which){case 1:p.mouseButton=PConstants.LEFT;break;case 2:p.mouseButton=PConstants.CENTER;break;case 3:p.mouseButton=PConstants.RIGHT;break}if(typeof p.mousePressed==="function"){p.mousePressed()}});attach(curElement,"mouseup",function(e){p.__mousePressed=false;if(typeof p.mouseClicked==="function"&&!p.mouseDragging){p.mouseClicked()}if(typeof p.mouseReleased==="function"){p.mouseReleased()}});var mouseWheelHandler=function(e){var delta=0;if(e.wheelDelta){delta=e.wheelDelta/120;if(window.opera){delta=-delta}}else{if(e.detail){delta=-e.detail/3}}p.mouseScroll=delta;if(delta&&typeof p.mouseScrolled==="function"){p.mouseScrolled()}};attach(document,"DOMMouseScroll",mouseWheelHandler);attach(document,"mousewheel",mouseWheelHandler);function keyCodeMap(code){if(codedKeys.indexOf(code)>=0){p.keyCode=code;if(code===p.INS){p.keyCode=155}return PConstants.CODED}switch(code){case 13:return 10;case 46:return 127}return code}function charCodeMap(code,shift){if(code>=65&&code<=90){if(shift){return code}else{return code+32}}else{if(code>=48&&code<=57){if(shift){switch(code){case 49:return 33;case 50:return 64;case 51:return 35;case 52:return 36;case 53:return 37;case 54:return 94;case 55:return 38;case 56:return 42;case 57:return 40;case 48:return 41}}}else{if(shift){switch(code){case 107:return 43;case 219:return 123;case 221:return 125;case 222:return 34}}else{switch(code){case 188:return 44;case 109:return 45;case 190:return 46;case 191:return 47;case 192:return 96;case 219:return 91;case 220:return 92;case 221:return 93;case 222:return 39}}}}return code}function normalKeyDown(){var tempKeyCode;p.keyPressed();tempKeyCode=p.keyCode;p.keyCode=0;p.keyTyped();p.keyCode=tempKeyCode}function refireKeyDown(){var tempKeyCode;p.keyPressed();tempKeyCode=p.keyCode;p.keyCode=0;p.keyTyped();p.keyCode=tempKeyCode}function keyFunc(e,type){var tempKeyCode;p.key=keyCodeMap(e.keyCode,e.shiftKey);if(type==="keypress"){if(e.keyCode===e.charCode){p.keyCode=-1}}switch(p.keyCode){case 19:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 45:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:case 123:case 145:case 155:case 224:case 225:case 226:case 227:if(type==="keydown"){if(gRefire){p.keyReleased();p.keyPressed()}else{p.keyPressed();gRefire=true}}else{if(type==="keypress"){if(firstCodedDown){firstCodedDown=false}else{p.keyReleased();p.keyPressed()}}else{if(type==="keyup"){p.keyReleased();if(firstCodedDown===false){firstCodedDown=true}if(gRefire){gRefire=false}}}}break;case 16:case 17:case 18:case 20:case 144:if(type==="keydown"){p.keyPressed()}else{if(type==="keyup"){p.keyReleased()}}break;case 46:case 13:if(type==="keydown"){if(firstEDGKeyDown===true){firstEDGKeyDown=false;normalKeyDown()}else{refireKeyDown()}}else{if(type==="keypress"){if(firstEDMKeyDown===true){firstEDMKeyDown=false}else{refireKeyDown()}}else{if(type==="keyup"){p.keyCode=e.keyCode;p.keyReleased();if(firstEDGKeyDown===false){firstEDGKeyDown=true}if(firstEDMKeyDown===false){firstEDMKeyDown=true}}}}break;default:if(p.keyCode===-1){p.keyCode=e.keyCode}if(e.keyCode===0){p.key=charCodeMap(e.charCode,e.shiftKey);if(type==="keypress"){if(firstMKeyDown===true){firstMKeyDown=false}else{refireKeyDown()}}else{if(type==="keyup"){p.keyCode=e.keyCode;p.keyReleased();if(firstMKeyDown===false){firstMKeyDown=true}}}}else{p.key=charCodeMap(e.keyCode,e.shiftKey);if(type==="keydown"){if(firstGKeyDown===true){firstGKeyDown=false;normalKeyDown()}else{refireKeyDown()}}else{if(type==="keyup"){p.keyCode=e.keyCode;p.keyReleased();if(firstMKeyDown===false){firstMKeyDown=true}if(firstGKeyDown===false){firstGKeyDown=true}}}}break}}attach(document,"keydown",function(e){p.keyCode=e.keyCode;p.__keyPressed=true;p.key=keyCodeMap(e.keyCode,e.shiftKey);if(p.key!==PConstants.CODED){p.key=charCodeMap(e.keyCode,e.shiftKey)}keyFunc(e,"keydown")});attach(document,"keypress",function(e){keyFunc(e,"keypress")});attach(document,"keyup",function(e){p.keyCode=e.keyCode;p.__keyPressed=false;p.key=keyCodeMap(e.keyCode,e.shiftKey);if(p.key!==PConstants.CODED){p.key=charCodeMap(e.keyCode,e.shiftKey)}keyFunc(e,"keyup")});Processing.debug=function(e){};if(typeof curElement==="string"){curElement=document.getElementById(curElement)}if(aCode){if(aCode instanceof Processing.Sketch){curSketch=aCode}else{if(typeof aCode==="function"){curSketch=new Processing.Sketch(aCode)}else{curSketch=Processing.compile(aCode)}}p.externals.sketch=curSketch;p.use3DContext=curSketch.use3DContext;if("mozOpaque" in curElement){curElement.mozOpaque=!curSketch.options.isTransparent}if(curSketch.options.pauseOnBlur){p.externals.onfocus=function(){if(doLoop){p.loop()}};p.externals.onblur=function(){if(doLoop&&loopStarted){p.noLoop();doLoop=true}}}if(!curSketch.use3DContext){curContext=curElement.getContext("2d");p.externals.context=curContext;modelView=new PMatrix2D();curContext.translate(0.5,0.5);curContext.lineCap="round";p.stroke(0);p.fill(255);p.noSmooth();p.disableContextMenu()}for(var i in Processing.lib){if(Processing.lib.hasOwnProperty(i)){if(Processing.lib[i].hasOwnProperty("attach")){Processing.lib[i].attach(p)}else{if(Processing.lib[i] instanceof Function){Processing.lib[i].call(this)}}}}var executeSketch=function(processing){if(!curSketch.imageCache.pending&&curSketch.fonts.pending()){curSketch.attach(processing,defaultScope);if(processing.setup){processing.setup();if(!curSketch.use3DContext){curContext.setTransform(1,0,0,1,0,0)}}resetContext();if(processing.draw){if(!doLoop){processing.redraw()}else{processing.loop()}}}else{window.setTimeout(function(){executeSketch(processing)},10)}};executeSketch(p)}else{curSketch=new Processing.Sketch();curSketch.options.isTransparent=true}};Processing.prototype=defaultScope;function getGlobalMembers(){var names=["abs","acos","alpha","ambient","ambientLight","append","applyMatrix","arc","arrayCopy","asin","atan","atan2","background","beginCamera","beginDraw","beginShape","bezier","bezierDetail","bezierPoint","bezierTangent","bezierVertex","binary","blend","blendColor","blit_resize","blue","boolean","box","breakShape","brightness","byte","camera","ceil","char","Character","clear","color","colorMode","concat","console","constrain","copy","cos","createFont","createGraphics","createImage","cursor","curve","curveDetail","curvePoint","curveTangent","curveTightness","curveVertex","day","defaultColor","degrees","directionalLight","disableContextMenu","dist","draw","ellipse","ellipseMode","emissive","enableContextMenu","endCamera","endDraw","endShape","exit","exp","expand","externals","fill","filter","filter_bilinear","filter_new_scanline","float","floor","focused","frameCount","frameRate","frustum","get","glyphLook","glyphTable","green","height","hex","hint","hour","hue","image","imageMode","Import","int","intersect","join","key","keyCode","keyPressed","keyReleased","keyTyped","lerp","lerpColor","lightFalloff","lights","lightSpecular","line","link","loadBytes","loadFont","loadGlyphs","loadImage","loadPixels","loadShape","loadStrings","log","loop","mag","map","match","matchAll","max","millis","min","minute","mix","modelX","modelY","modelZ","modes","month","mouseButton","mouseClicked","mouseDragged","mouseMoved","mousePressed","mouseReleased","mouseScroll","mouseScrolled","mouseX","mouseY","name","nf","nfc","nfp","nfs","noCursor","noFill","noise","noiseDetail","noiseSeed","noLights","noLoop","norm","normal","noSmooth","noStroke","noTint","ortho","peg","perspective","PFont","PImage","pixels","PMatrix2D","PMatrix3D","PMatrixStack","pmouseX","pmouseY","point","pointLight","popMatrix","popStyle","pow","print","printCamera","println","printMatrix","printProjection","PShape","PShapeSVG","pushMatrix","pushStyle","quad","radians","random","Random","randomSeed","rect","rectMode","red","redraw","requestImage","resetMatrix","reverse","rotate","rotateX","rotateY","rotateZ","round","saturation","save","saveFrame","saveStrings","scale","screenX","screenY","screenZ","second","set","setup","shape","shapeMode","shared","shininess","shorten","sin","size","smooth","sort","specular","sphere","sphereDetail","splice","split","splitTokens","spotLight","sq","sqrt","status","str","stroke","strokeCap","strokeJoin","strokeWeight","subset","tan","text","textAlign","textAscent","textDescent","textFont","textLeading","textMode","textSize","texture","textureMode","textWidth","tint","translate","triangle","trim","unbinary","unhex","updatePixels","use3DContext","vertex","width","XMLElement","year","__frameRate","__keyPressed","__mousePressed","__int_cast"];var members={};var i,l;for(i=0,l=names.length;i<l;++i){members[names[i]]=null}for(var lib in Processing.lib){if(Processing.lib.hasOwnProperty(lib)){if(Processing.lib[lib].exports){var exportedNames=Processing.lib[lib].exports;for(i=0,l=exportedNames.length;i<l;++i){members[exportedNames[i]]=null}}}}return members}function parseProcessing(code){var globalMembers=getGlobalMembers();function splitToAtoms(code){var atoms=[];var items=code.split(/([\{\[\(\)\]\}])/);var result=items[0];var stack=[];for(var i=1;i<items.length;i+=2){var item=items[i];if(item==="["||item==="{"||item==="("){stack.push(result);result=item}else{if(item==="]"||item==="}"||item===")"){var kind=item==="}"?"A":item===")"?"B":"C";var index=atoms.length;atoms.push(result+item);result=stack.pop()+'"'+kind+(index+1)+'"'}}result+=items[i+1]}atoms.unshift(result);return atoms}function injectStrings(code,strings){return code.replace(/'(\d+)'/g,function(all,index){var val=strings[index];if(val.charAt(0)==="/"){return val}else{return(/^'((?:[^'\\\n])|(?:\\.[0-9A-Fa-f]*))'$/).test(val)?"(new $p.Character("+val+"))":val}})}function trimSpaces(string){var m1=/^\s*/.exec(string),result;if(m1[0].length===string.length){result={left:m1[0],middle:"",right:""}}else{var m2=/\s*$/.exec(string);result={left:m1[0],middle:string.substring(m1[0].length,m2.index),right:m2[0]}}result.untrim=function(t){return this.left+t+this.right};return result}function trim(string){return string.replace(/^\s+/,"").replace(/\s+$/,"")}function appendToLookupTable(table,array){for(var i=0,l=array.length;i<l;++i){table[array[i]]=null}return table}function isLookupTableEmpty(table){for(var i in table){if(table.hasOwnProperty(i)){return false}}return true}function getAtomIndex(templ){return templ.substring(2,templ.length-1)}var codeWoExtraCr=code.replace(/\r\n?|\n\r/g,"\n");var strings=[];var codeWoStrings=codeWoExtraCr.replace(/("(?:[^"\\\n]|\\.)*")|('(?:[^'\\\n]|\\.)*')|(([\[\(=|&!\^:?]\s*)(\/(?![*\/])(?:[^\/\\\n]|\\.)*\/[gim]*)\b)|(\/\/[^\n]*\n)|(\/\*(?:(?!\*\/)(?:.|\n))*\*\/)/g,function(all,quoted,aposed,regexCtx,prefix,regex,singleComment,comment){var index;if(quoted||aposed){index=strings.length;strings.push(all);return"'"+index+"'"}else{if(regexCtx){index=strings.length;strings.push(regex);return prefix+"'"+index+"'"}else{return comment!==""?" ":"\n"}}});var atoms=splitToAtoms(codeWoStrings);var replaceContext;var declaredClasses={},currentClassId,classIdSeed=0;function addAtom(text,type){var lastIndex=atoms.length;atoms.push(text);return'"'+type+lastIndex+'"'}function generateClassId(){return"class"+(++classIdSeed)}function appendClass(class_,classId,scopeId){class_.classId=classId;class_.scopeId=scopeId;declaredClasses[classId]=class_}var transformClassBody,transformStatementsBlock,transformStatements,transformMain,transformExpression;var classesRegex=/\b((?:(?:public|private|final|protected|static|abstract)\s+)*)(class|interface)\s+([A-Za-z_$][\w$]*\b)(\s+extends\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\b)?(\s+implements\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\b)*)?\s*("A\d+")/g;var methodsRegex=/\b((?:(?:public|private|final|protected|static|abstract|synchronized)\s+)*)((?!(?:else|new|return|throw|function|public|private|protected)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*([A-Za-z_$][\w$]*\b)\s*("B\d+")(\s*throws\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)*)?\s*("A\d+"|;)/g;var fieldTest=/^((?:(?:public|private|final|protected|static)\s+)*)((?!(?:else|new|return|throw)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*([A-Za-z_$][\w$]*\b)\s*(?:"C\d+"\s*)*([=,]|$)/;var cstrsRegex=/\b((?:(?:public|private|final|protected|static|abstract)\s+)*)((?!(?:new|return|throw)\b)[A-Za-z_$][\w$]*\b)\s*("B\d+")(\s*throws\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)*)?\s*("A\d+")/g;var attrAndTypeRegex=/^((?:(?:public|private|final|protected|static)\s+)*)((?!(?:new|return|throw)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*/;var functionsRegex=/\bfunction(?:\s+([A-Za-z_$][\w$]*))?\s*("B\d+")\s*("A\d+")/g;function extractClassesAndMethods(code){var s=code;s=s.replace(classesRegex,function(all){return addAtom(all,"E")});s=s.replace(methodsRegex,function(all){return addAtom(all,"D")});s=s.replace(functionsRegex,function(all){return addAtom(all,"H")});return s}function extractConstructors(code,className){var result=code.replace(cstrsRegex,function(all,attr,name,params,throws_,body){if(name!==className){return all}else{return addAtom(all,"G")}});return result}function AstParam(name){this.name=name}AstParam.prototype.toString=function(){return this.name};function AstParams(params){this.params=params}AstParams.prototype.getNames=function(){var names=[];for(var i=0,l=this.params.length;i<l;++i){names.push(this.params[i].name)}return names};AstParams.prototype.toString=function(){if(this.params.length===0){return"()"}var result="(";for(var i=0,l=this.params.length;i<l;++i){result+=this.params[i]+", "}return result.substring(0,result.length-2)+")"};function transformParams(params){var paramsWoPars=trim(params.substring(1,params.length-1));var result=[];if(paramsWoPars!==""){var paramList=paramsWoPars.split(",");for(var i=0;i<paramList.length;++i){var param=/\b([A-Za-z_$][\w$]*\b)\s*("[ABC][\d]*")?$/.exec(paramList[i]);result.push(new AstParam(param[1]))}}return new AstParams(result)}function preExpressionTransform(expr){var s=expr;s=s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\s*"C\d+")+\s*("A\d+")/g,function(all,type,init){return init});s=s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\s*"B\d+")\s*("A\d+")/g,function(all,type,init){return addAtom(all,"F")});s=s.replace(functionsRegex,function(all){return addAtom(all,"H")});s=s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)\s*("C\d+"(?:\s*"C\d+")*)/g,function(all,type,index){var args=index.replace(/"C(\d+)"/g,function(all,j){return atoms[j]}).replace(/\[\s*\]/g,"[null]").replace(/\s*\]\s*\[\s*/g,", ");var arrayInitializer="{"+args.substring(1,args.length-1)+"}";var createArrayArgs="('"+type+"', "+addAtom(arrayInitializer,"A")+")";return"$p.createJavaArray"+addAtom(createArrayArgs,"B")});s=s.replace(/(\.\s*length)\s*"B\d+"/g,"$1");s=s.replace(/#([0-9A-Fa-f]{6})\b/g,function(all,digits){return"0xFF"+digits});s=s.replace(/"B(\d+)"(\s*(?:[\w$']|"B))/g,function(all,index,next){var atom=atoms[index];if(!/^\(\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\s*(?:"C\d+"\s*)*\)$/.test(atom)){return all}else{if(/^\(\s*int\s*\)$/.test(atom)){return"(int)"+next}else{var indexParts=atom.split(/"C(\d+)"/g);if(indexParts.length>1){if(!/^\[\s*\]$/.test(atoms[indexParts[1]])){return all}}return""+next}}});s=s.replace(/\(int\)([^,\]\)\}\?\:\*\+\-\/\^\|\%\&\~]+)/g,function(all,arg){var trimmed=trimSpaces(arg);return trimmed.untrim("__int_cast("+trimmed.middle+")")});s=s.replace(/\bsuper(\s*"B\d+")/g,"$$superCstr$1").replace(/\bsuper(\s*\.)/g,"$$super$1");s=s.replace(/\b0+((\d*)(?:\.[\d*])?(?:[eE][\-\+]?\d+)?[fF]?)\b/,function(all,numberWo0,intPart){if(numberWo0===intPart){return all}return intPart===""?"0"+numberWo0:numberWo0});s=s.replace(/\b(\.?\d+\.?)[fF]\b/g,"$1");s=s.replace(/([^\s])%([^=\s])/g,"$1 % $2");s=s.replace(/\b(frameRate|keyPressed|mousePressed)\b(?!\s*"B)/g,"__$1");s=s.replace(/\bpixels\s*(("C(\d+)")|\.length)?(\s*=(?!=)([^,\]\)\}\?\:]+))?/g,function(all,indexOrLength,index,atomIndex,equalsPart,rightSide){if(index){var atom=atoms[atomIndex];if(equalsPart){return"pixels.setPixel"+addAtom("("+atom.substring(1,atom.length-1)+","+rightSide+")","B")}else{return"pixels.getPixel"+addAtom("("+atom.substring(1,atom.length-1)+")","B")}}else{if(indexOrLength){return"pixels.getLength"+addAtom("()","B")}else{if(equalsPart){return"pixels.set"+addAtom("("+rightSide+")","B")}else{return"pixels.toArray"+addAtom("()","B")}}}});s=s.replace(/\bthis(\s*"B\d+")/g,"$$constr$1");return s}function AstInlineClass(baseInterfaceName,body){this.baseInterfaceName=baseInterfaceName;this.body=body;body.owner=this}AstInlineClass.prototype.toString=function(){return"new (function() {\n"+this.body+"})"};function transformInlineClass(class_){var m=new RegExp(/\bnew\s*(Runnable)\s*"B\d+"\s*"A(\d+)"/).exec(class_);if(m===null){return"null"}else{var oldClassId=currentClassId,newClassId=generateClassId();currentClassId=newClassId;var inlineClass=new AstInlineClass("Runnable",transformClassBody(atoms[m[2]],m[1]));appendClass(inlineClass,newClassId,oldClassId);currentClassId=oldClassId;return inlineClass}}function AstFunction(name,params,body){this.name=name;this.params=params;this.body=body}AstFunction.prototype.toString=function(){var oldContext=replaceContext;var names=appendToLookupTable({"this":null},this.params.getNames());replaceContext=function(subject){return names.hasOwnProperty(subject.name)?subject.name:oldContext(subject)};var result="function";if(this.name){result+=" "+this.name}result+=this.params+" "+this.body;replaceContext=oldContext;return result};function transformFunction(class_){var m=new RegExp(/\b([A-Za-z_$][\w$]*)\s*"B(\d+)"\s*"A(\d+)"/).exec(class_);return new AstFunction(m[1]!=="function"?m[1]:null,transformParams(atoms[m[2]]),transformStatementsBlock(atoms[m[3]]))}function AstInlineObject(members){this.members=members}AstInlineObject.prototype.toString=function(){var oldContext=replaceContext;replaceContext=function(subject){return subject.name==="this"?"this":oldContext(subject)};var result="";for(var i=0,l=this.members.length;i<l;++i){if(this.members[i].label){result+=this.members[i].label+": "}result+=this.members[i].value.toString()+", "}replaceContext=oldContext;return result.substring(0,result.length-2)};function transformInlineObject(obj){var members=obj.split(",");for(var i=0;i<members.length;++i){var label=members[i].indexOf(":");if(label<0){members[i]={value:transformExpression(members[i])}}else{members[i]={label:trim(members[i].substring(0,label)),value:transformExpression(trim(members[i].substring(label+1)))}}}return new AstInlineObject(members)}function expandExpression(expr){if(expr.charAt(0)==="("||expr.charAt(0)==="["){return expr.charAt(0)+expandExpression(expr.substring(1,expr.length-1))+expr.charAt(expr.length-1)}else{if(expr.charAt(0)==="{"){if(/^\{\s*(?:[A-Za-z_$][\w$]*|'\d+')\s*:/.test(expr)){return"{"+addAtom(expr.substring(1,expr.length-1),"I")+"}"}else{return"["+expandExpression(expr.substring(1,expr.length-1))+"]"}}else{var trimmed=trimSpaces(expr);var result=preExpressionTransform(trimmed.middle);result=result.replace(/"[ABC](\d+)"/g,function(all,index){return expandExpression(atoms[index])});return trimmed.untrim(result)}}}function replaceContextInVars(expr){return expr.replace(/(\.\s*)?(\b[A-Za-z_$][\w$]*\b)(\s*\.\s*(\b[A-Za-z_$][\w$]*\b)(\s*\()?)?/g,function(all,memberAccessSign,identifier,suffix,subMember,callSign){if(memberAccessSign){return all}else{var subject={name:identifier,member:subMember,callSign:!!callSign};return replaceContext(subject)+(suffix===undef?"":suffix)}})}function AstExpression(expr,transforms){this.expr=expr;this.transforms=transforms}AstExpression.prototype.toString=function(){var transforms=this.transforms;var expr=replaceContextInVars(this.expr);return expr.replace(/"!(\d+)"/g,function(all,index){return transforms[index].toString()})};transformExpression=function(expr){var transforms=[];var s=expandExpression(expr);s=s.replace(/"H(\d+)"/g,function(all,index){transforms.push(transformFunction(atoms[index]));return'"!'+(transforms.length-1)+'"'});s=s.replace(/"F(\d+)"/g,function(all,index){transforms.push(transformInlineClass(atoms[index]));return'"!'+(transforms.length-1)+'"'});s=s.replace(/"I(\d+)"/g,function(all,index){transforms.push(transformInlineObject(atoms[index]));return'"!'+(transforms.length-1)+'"'});return new AstExpression(s,transforms)};function AstVarDefinition(name,value,isDefault){this.name=name;this.value=value;this.isDefault=isDefault}AstVarDefinition.prototype.toString=function(){return this.name+" = "+this.value};function transformVarDefinition(def,defaultTypeValue){var eqIndex=def.indexOf("=");var name,value,isDefault;if(eqIndex<0){name=def;value=defaultTypeValue;isDefault=true}else{name=def.substring(0,eqIndex);value=transformExpression(def.substring(eqIndex+1));isDefault=false}return new AstVarDefinition(trim(name.replace(/(\s*"C\d+")+/g,"")),value,isDefault)}function getDefaultValueForType(type){if(type==="int"||type==="float"){return"0"}else{if(type==="boolean"){return"false"}else{if(type==="color"){return"0x00000000"}else{return"null"}}}}function AstVar(definitions,varType){this.definitions=definitions;this.varType=varType}AstVar.prototype.getNames=function(){var names=[];for(var i=0,l=this.definitions.length;i<l;++i){names.push(this.definitions[i].name)}return names};AstVar.prototype.toString=function(){return"var "+this.definitions.join(",")};function AstStatement(expression){this.expression=expression}AstStatement.prototype.toString=function(){return this.expression.toString()};function transformStatement(statement){if(fieldTest.test(statement)){var attrAndType=attrAndTypeRegex.exec(statement);var definitions=statement.substring(attrAndType[0].length).split(",");var defaultTypeValue=getDefaultValueForType(attrAndType[2]);for(var i=0;i<definitions.length;++i){definitions[i]=transformVarDefinition(definitions[i],defaultTypeValue)}return new AstVar(definitions,attrAndType[2])}else{return new AstStatement(transformExpression(statement))}}function AstForExpression(initStatement,condition,step){this.initStatement=initStatement;this.condition=condition;this.step=step}AstForExpression.prototype.toString=function(){return"("+this.initStatement+"; "+this.condition+"; "+this.step+")"};function AstForInExpression(initStatement,container){this.initStatement=initStatement;this.container=container}AstForInExpression.prototype.toString=function(){var init=this.initStatement.toString();if(init.indexOf("=")>=0){init=init.substring(0,init.indexOf("="))}return"("+init+" in "+this.container+")"};function transformForExpression(expr){var content;if(/\bin\b/.test(expr)){content=expr.substring(1,expr.length-1).split(/\bin\b/g);return new AstForInExpression(transformStatement(trim(content[0])),transformExpression(content[1]))}else{content=expr.substring(1,expr.length-1).split(";");return new AstForExpression(transformStatement(trim(content[0])),transformExpression(content[1]),transformExpression(content[2]))}}function AstInnerInterface(name){this.name=name}AstInnerInterface.prototype.toString=function(){return"this."+this.name+" = function "+this.name+"() { throw 'This is an interface'; };"};function AstInnerClass(name,body){this.name=name;this.body=body;body.owner=this}AstInnerClass.prototype.toString=function(){return"this."+this.name+" = function "+this.name+"() {\n"+this.body+"};"};function transformInnerClass(class_){var m=classesRegex.exec(class_);classesRegex.lastIndex=0;var body=atoms[getAtomIndex(m[6])];if(m[2]==="interface"){return new AstInnerInterface(m[3])}else{var oldClassId=currentClassId,newClassId=generateClassId();currentClassId=newClassId;var innerClass=new AstInnerClass(m[3],transformClassBody(body,m[3],m[4],m[5]));appendClass(innerClass,newClassId,oldClassId);currentClassId=oldClassId;return innerClass}}function AstClassMethod(name,params,body){this.name=name;this.params=params;this.body=body}AstClassMethod.prototype.toString=function(){var thisReplacement=replaceContext({name:"this"});var paramNames=appendToLookupTable({},this.params.getNames());var oldContext=replaceContext;replaceContext=function(subject){return paramNames.hasOwnProperty(subject.name)?subject.name:oldContext(subject)};var result="$p.addMethod("+thisReplacement+", '"+this.name+"', function "+this.params+" "+this.body+");";replaceContext=oldContext;return result};function transformClassMethod(method){var m=methodsRegex.exec(method);methodsRegex.lastIndex=0;var body=m[6]!==";"?atoms[getAtomIndex(m[6])]:"{}";return new AstClassMethod(m[3],transformParams(atoms[getAtomIndex(m[4])]),transformStatementsBlock(body))}function AstClassField(definitions,fieldType,isStatic){this.definitions=definitions;this.fieldType=fieldType;this.isStatic=isStatic}AstClassField.prototype.getNames=function(){var names=[];for(var i=0,l=this.definitions.length;i<l;++i){names.push(this.definitions[i].name)}return names};AstClassField.prototype.toString=function(){var thisPrefix=replaceContext({name:"this"});if(this.isStatic){var className=this.owner.name;var staticDeclarations=[];for(var i=0,l=this.definitions.length;i<l;++i){var definition=this.definitions[i];var name=definition.name,staticName=className+"."+name;var declaration="if("+staticName+" === void(0)) {\n "+staticName+" = "+definition.value+"; }\n$p.defineProperty("+thisPrefix+", '"+name+"', { get: function(){return "+staticName+";}, set: function(val){"+staticName+" = val;} });\n";staticDeclarations.push(declaration)}return staticDeclarations.join("")}else{return thisPrefix+"."+this.definitions.join("; "+thisPrefix+".")}};function transformClassField(statement){var attrAndType=attrAndTypeRegex.exec(statement);var isStatic=attrAndType[1].indexOf("static")>=0;var definitions=statement.substring(attrAndType[0].length).split(/,\s*/g);var defaultTypeValue=getDefaultValueForType(attrAndType[2]);for(var i=0;i<definitions.length;++i){definitions[i]=transformVarDefinition(definitions[i],defaultTypeValue)}return new AstClassField(definitions,attrAndType[2],isStatic)}function AstConstructor(params,body){this.params=params;this.body=body}AstConstructor.prototype.toString=function(){var paramNames=appendToLookupTable({},this.params.getNames());var oldContext=replaceContext;replaceContext=function(subject){return paramNames.hasOwnProperty(subject.name)?subject.name:oldContext(subject)};var prefix="function $constr_"+this.params.params.length+this.params.toString();var body=this.body.toString();if(!/\$(superCstr|constr)\b/.test(body)){body="{\n$superCstr();\n"+body.substring(1)}replaceContext=oldContext;return prefix+body+"\n"};function transformConstructor(cstr){var m=new RegExp(/"B(\d+)"\s*"A(\d+)"/).exec(cstr);var params=transformParams(atoms[m[1]]);return new AstConstructor(params,transformStatementsBlock(atoms[m[2]]))}function AstClassBody(name,baseClassName,functions,methods,fields,cstrs,innerClasses,misc){var i,l;this.name=name;this.baseClassName=baseClassName;this.functions=functions;this.methods=methods;this.fields=fields;this.cstrs=cstrs;this.innerClasses=innerClasses;this.misc=misc;for(i=0,l=fields.length;i<l;++i){fields[i].owner=this}}AstClassBody.prototype.getMembers=function(){var members;if(this.owner.base){members=this.owner.base.body.getMembers()}else{members={fields:[],methods:[],innerClasses:[]}}var i,j,l,m;for(i=0,l=this.fields.length;i<l;++i){members.fields=members.fields.concat(this.fields[i].getNames())}for(i=0,l=this.methods.length;i<l;++i){var method=this.methods[i];members.methods.push(method.name)}for(i=0,l=this.innerClasses.length;i<l;++i){var innerClass=this.innerClasses[i];members.innerClasses.push(innerClass.name)}return members};AstClassBody.prototype.toString=function(){function getScopeLevel(p){var i=0;while(p){++i;p=p.scope}return i}var scopeLevel=getScopeLevel(this.owner);var selfId="$this_"+scopeLevel;var result="var "+selfId+" = this;\n";var members=this.getMembers();var thisClassFields=appendToLookupTable({},members.fields),thisClassMethods=appendToLookupTable({},members.methods),thisClassInners=appendToLookupTable({},members.innerClasses);var oldContext=replaceContext;replaceContext=function(subject){var name=subject.name;if(name==="this"){return subject.callSign?selfId+".$self":selfId}else{if(thisClassFields.hasOwnProperty(name)||thisClassInners.hasOwnProperty(name)){return selfId+"."+name}else{if(thisClassMethods.hasOwnProperty(name)){return selfId+".$self."+name}}}return oldContext(subject)};if(this.baseClassName){result+="var $super = { $upcast: "+selfId+" };\n";result+="function $superCstr(){"+this.baseClassName+".apply($super,arguments)}\n"}else{result+="function $superCstr(){$p.extendClassChain("+selfId+")}\n"}result+=this.functions.join("\n")+"\n";result+=this.innerClasses.join("\n");result+=this.fields.join(";\n")+";\n";result+=this.methods.join("\n")+"\n";result+=this.misc.tail;result+=this.cstrs.join("\n")+"\n";result+="function $constr() {\n";var cstrsIfs=[];for(var i=0,l=this.cstrs.length;i<l;++i){var paramsLength=this.cstrs[i].params.params.length;cstrsIfs.push("if(arguments.length === "+paramsLength+") { $constr_"+paramsLength+".apply("+selfId+", arguments); }")}if(cstrsIfs.length>0){result+=cstrsIfs.join(" else ")+" else "}result+="$superCstr(); }\n";result+="$constr.apply(null, arguments);\n";replaceContext=oldContext;return result};transformClassBody=function(body,name,baseName,impls){var declarations=body.substring(1,body.length-1);declarations=extractClassesAndMethods(declarations);declarations=extractConstructors(declarations,name);var methods=[],classes=[],cstrs=[],functions=[];declarations=declarations.replace(/"([DEGH])(\d+)"/g,function(all,type,index){if(type==="D"){methods.push(index)}else{if(type==="E"){classes.push(index)}else{if(type==="H"){functions.push(index)}else{cstrs.push(index)}}}return""});var fields=declarations.split(/;(?:\s*;)*/g);var baseClassName;var i;if(baseName!==undef){baseClassName=baseName.replace(/^\s*extends\s+([A-Za-z_$][\w$]*)\s*$/g,"$1")}for(i=0;i<functions.length;++i){functions[i]=transformFunction(atoms[functions[i]])}for(i=0;i<methods.length;++i){methods[i]=transformClassMethod(atoms[methods[i]])}for(i=0;i<fields.length-1;++i){var field=trimSpaces(fields[i]);fields[i]=transformClassField(field.middle)}var tail=fields.pop();for(i=0;i<cstrs.length;++i){cstrs[i]=transformConstructor(atoms[cstrs[i]])}for(i=0;i<classes.length;++i){classes[i]=transformInnerClass(atoms[classes[i]])}return new AstClassBody(name,baseClassName,functions,methods,fields,cstrs,classes,{tail:tail})};function AstInterface(name){this.name=name}AstInterface.prototype.toString=function(){return"function "+this.name+"() {  throw 'This is an interface'; }\n$p."+this.name+" = "+this.name+";"};function AstClass(name,body){this.name=name;this.body=body;body.owner=this}AstClass.prototype.toString=function(){var staticVars="";for(var i=0,l=this.body.fields.length;i<l;i++){if(this.body.fields[i].isStatic){for(var x=0,xl=this.body.fields[i].definitions.length;x<xl;x++){staticVars+="var "+this.body.fields[i].definitions[x].name+" = "+this.body.name+"."+this.body.fields[i].definitions[x]+";"}}}return"function "+this.name+"() {\n"+this.body+"}\n"+staticVars+"\n$p."+this.name+" = "+this.name+";"};function transformGlobalClass(class_){var m=classesRegex.exec(class_);classesRegex.lastIndex=0;var body=atoms[getAtomIndex(m[6])];if(m[2]==="interface"){return new AstInterface(m[3])}else{var oldClassId=currentClassId,newClassId=generateClassId();currentClassId=newClassId;var globalClass=new AstClass(m[3],transformClassBody(body,m[3],m[4],m[5]));appendClass(globalClass,newClassId,oldClassId);currentClassId=oldClassId;return globalClass}}function AstMethod(name,params,body){this.name=name;this.params=params;this.body=body}AstMethod.prototype.toString=function(){var paramNames=appendToLookupTable({},this.params.getNames());var oldContext=replaceContext;replaceContext=function(subject){return paramNames.hasOwnProperty(subject.name)?subject.name:oldContext(subject)};var result="function "+this.name+this.params+" "+this.body+"\n$p."+this.name+" = "+this.name+";";replaceContext=oldContext;return result};function transformGlobalMethod(method){var m=methodsRegex.exec(method);var result=methodsRegex.lastIndex=0;return new AstMethod(m[3],transformParams(atoms[getAtomIndex(m[4])]),transformStatementsBlock(atoms[getAtomIndex(m[6])]))}function preStatementsTransform(statements){var s=statements;s=s.replace(/\b(catch\s*"B\d+"\s*"A\d+")(\s*catch\s*"B\d+"\s*"A\d+")+/g,"$1");return s}function AstForStatement(argument,misc){this.argument=argument;this.misc=misc}AstForStatement.prototype.toString=function(){return this.misc.prefix+this.argument.toString()};function AstCatchStatement(argument,misc){this.argument=argument;this.misc=misc}AstCatchStatement.prototype.toString=function(){return this.misc.prefix+this.argument.toString()};function AstPrefixStatement(name,argument,misc){this.name=name;this.argument=argument;this.misc=misc}AstPrefixStatement.prototype.toString=function(){var result=this.misc.prefix;if(this.argument!==undef){result+=this.argument.toString()}return result};function AstLabel(label){this.label=label}AstLabel.prototype.toString=function(){return this.label};transformStatements=function(statements,transformMethod,transformClass){var nextStatement=new RegExp(/\b(catch|for|if|switch|while|with)\s*"B(\d+)"|\b(do|else|finally|return|throw|try|break|continue)\b|("[ADEH](\d+)")|\b((?:case\s[^:]+|[A-Za-z_$][\w$]*\s*):)|(;)/g);var res=[];statements=preStatementsTransform(statements);var lastIndex=0,m,space;while((m=nextStatement.exec(statements))!==null){if(m[1]!==undef){var i=statements.lastIndexOf('"B',nextStatement.lastIndex);var statementsPrefix=statements.substring(lastIndex,i);if(m[1]==="for"){res.push(new AstForStatement(transformForExpression(atoms[m[2]]),{prefix:statementsPrefix}))}else{if(m[1]==="catch"){res.push(new AstCatchStatement(transformParams(atoms[m[2]]),{prefix:statementsPrefix}))}else{res.push(new AstPrefixStatement(m[1],transformExpression(atoms[m[2]]),{prefix:statementsPrefix}))}}}else{if(m[3]!==undef){res.push(new AstPrefixStatement(m[3],undef,{prefix:statements.substring(lastIndex,nextStatement.lastIndex)}))}else{if(m[4]!==undef){space=statements.substring(lastIndex,nextStatement.lastIndex-m[4].length);if(trim(space).length!==0){continue}res.push(space);var kind=m[4].charAt(1),atomIndex=m[5];if(kind==="D"){res.push(transformMethod(atoms[atomIndex]))}else{if(kind==="E"){res.push(transformClass(atoms[atomIndex]))}else{if(kind==="H"){res.push(transformFunction(atoms[atomIndex]))}else{res.push(transformStatementsBlock(atoms[atomIndex]))}}}}else{if(m[6]!==undef){space=statements.substring(lastIndex,nextStatement.lastIndex-m[6].length);if(trim(space).length!==0){continue}res.push(new AstLabel(statements.substring(lastIndex,nextStatement.lastIndex)))}else{var statement=trimSpaces(statements.substring(lastIndex,nextStatement.lastIndex-1));res.push(statement.left);res.push(transformStatement(statement.middle));res.push(statement.right+";")}}}}lastIndex=nextStatement.lastIndex}var statementsTail=trimSpaces(statements.substring(lastIndex));res.push(statementsTail.left);if(statementsTail.middle!==""){res.push(transformStatement(statementsTail.middle));res.push(";"+statementsTail.right)}return res};function getLocalNames(statements){var localNames=[];for(var i=0,l=statements.length;i<l;++i){var statement=statements[i];if(statement instanceof AstVar){localNames=localNames.concat(statement.getNames())}else{if(statement instanceof AstForStatement&&statement.argument.initStatement instanceof AstVar){localNames=localNames.concat(statement.argument.initStatement.getNames())}else{if(statement instanceof AstInnerInterface||statement instanceof AstInnerClass||statement instanceof AstInterface||statement instanceof AstClass||statement instanceof AstMethod||statement instanceof AstFunction){localNames.push(statement.name)}}}}return appendToLookupTable({},localNames)}function AstStatementsBlock(statements){this.statements=statements}AstStatementsBlock.prototype.toString=function(){var localNames=getLocalNames(this.statements);var oldContext=replaceContext;if(!isLookupTableEmpty(localNames)){replaceContext=function(subject){return localNames.hasOwnProperty(subject.name)?subject.name:oldContext(subject)}}var result="{\n"+this.statements.join("")+"\n}";replaceContext=oldContext;return result};transformStatementsBlock=function(block){var content=trimSpaces(block.substring(1,block.length-1));return new AstStatementsBlock(transformStatements(content.middle))};function AstRoot(statements){this.statements=statements}AstRoot.prototype.toString=function(){var localNames=getLocalNames(this.statements);replaceContext=function(subject){var name=subject.name;if(localNames.hasOwnProperty(name)){return name}else{if(globalMembers.hasOwnProperty(name)||PConstants.hasOwnProperty(name)||defaultScope.hasOwnProperty(name)){return"$p."+name}}return name};var result="// this code was autogenerated from PJS\n(function($p) {\n"+this.statements.join("")+"\n})";replaceContext=null;return result};transformMain=function(){var statements=extractClassesAndMethods(atoms[0]);statements=statements.replace(/\bimport\s+[^;]+;/g,"");return new AstRoot(transformStatements(statements,transformGlobalMethod,transformGlobalClass))};function generateMetadata(ast){var globalScope={};var id,class_;for(id in declaredClasses){if(declaredClasses.hasOwnProperty(id)){class_=declaredClasses[id];var scopeId=class_.scopeId,name=class_.name;if(scopeId){var scope=declaredClasses[scopeId];class_.scope=scope;if(scope.inScope===undef){scope.inScope={}}scope.inScope[name]=class_}else{globalScope[name]=class_}}}function findInScopes(class_,name){var parts=name.split(".");var currentScope=class_.scope,found;while(currentScope){if(currentScope.hasOwnProperty(parts[0])){found=currentScope[parts[0]];break}currentScope=currentScope.scope}if(found===undef){found=globalScope[parts[0]]}for(var i=1,l=parts.length;i<l&&found;++i){found=found.inScope[parts[i]]}return found}for(id in declaredClasses){if(declaredClasses.hasOwnProperty(id)){class_=declaredClasses[id];var baseClassName=class_.body.baseClassName;if(baseClassName){class_.base=findInScopes(class_,baseClassName)}}}}var transformed=transformMain();generateMetadata(transformed);var redendered=transformed.toString();redendered=redendered.replace(/\s*\n(?:[\t ]*\n)+/g,"\n\n");return injectStrings(redendered,strings)}function preprocessCode(aCode,sketch){var dm=new RegExp(/\/\*\s*@pjs\s+((?:[^\*]|\*+[^\*\/])*)\*\//g).exec(aCode);if(dm&&dm.length===2){var jsonItems=[],directives=dm.splice(1,2)[0].replace(/\{([\s\S]*?)\}/g,(function(){return function(all,item){jsonItems.push(item);return"{"+(jsonItems.length-1)+"}"}}())).replace("\n","").replace("\r","").split(";");var clean=function(s){return s.replace(/^\s*["']?/,"").replace(/["']?\s*$/,"")};for(var i=0,dl=directives.length;i<dl;i++){var pair=directives[i].split("=");if(pair&&pair.length===2){var key=clean(pair[0]),value=clean(pair[1]),list=[];if(key==="preload"){list=value.split(",");for(var j=0,jl=list.length;j<jl;j++){var imageName=clean(list[j]);sketch.imageCache.add(imageName)}}else{if(key==="transparent"){sketch.options.isTransparent=value==="true"}else{if(key==="font"){list=value.split(",");for(var x=0,xl=list.length;x<xl;x++){var fontName=clean(list[x]),index=/^\{(\d*?)\}$/.exec(fontName);sketch.fonts.add(index?JSON.parse("{"+jsonItems[index[1]]+"}"):fontName)}}else{if(key==="crisp"){sketch.options.crispLines=value==="true"}else{if(key==="pauseOnBlur"){sketch.options.pauseOnBlur=value==="true"}else{sketch.options[key]=value}}}}}}}}var codeWoStrings=aCode.replace(/("(?:[^"\\\n]|\\.)*")|('(?:[^'\\\n]|\\.)*')|(([\[\(=|&!\^:?]\s*)(\/(?![*\/])(?:[^\/\\\n]|\\.)*\/[gim]*)\b)|(\/\/[^\n]*\n)|(\/\*(?:(?!\*\/)(?:.|\n))*\*\/)/g,"");if(codeWoStrings.match(/\bsize\((?:.+),(?:.+),\s*(OPENGL|P3D)\s*\);/)){sketch.use3DContext=true}return aCode}Processing.compile=function(pdeCode){var sketch=new Processing.Sketch();var code=preprocessCode(pdeCode,sketch);var compiledPde=parseProcessing(code);sketch.sourceCode=compiledPde;return sketch};Error.prototype.printStackTrace=function(){return this.toString()};var tinylogLite=(function(){var tinylogLite={},undef="undefined",func="function",False=!1,True=!0,logLimit=512,log="log";if(typeof tinylog!==undef&&typeof tinylog[log]===func){tinylogLite[log]=tinylog[log]}else{if(typeof document!==undef&&!document.fake){(function(){var doc=document,$div="div",$style="style",$title="title",containerStyles={zIndex:10000,position:"fixed",bottom:"0px",width:"100%",height:"15%",fontFamily:"sans-serif",color:"#ccc",backgroundColor:"black"},outputStyles={position:"relative",fontFamily:"monospace",overflow:"auto",height:"100%",paddingTop:"5px"},resizerStyles={height:"5px",marginTop:"-5px",cursor:"n-resize",backgroundColor:"darkgrey"},closeButtonStyles={position:"absolute",top:"5px",right:"20px",color:"#111",MozBorderRadius:"4px",webkitBorderRadius:"4px",borderRadius:"4px",cursor:"pointer",fontWeight:"normal",textAlign:"center",padding:"3px 5px",backgroundColor:"#333",fontSize:"12px"},entryStyles={minHeight:"16px"},entryTextStyles={fontSize:"12px",margin:"0 8px 0 8px",maxWidth:"100%",whiteSpace:"pre-wrap",overflow:"auto"},view=doc.defaultView,docElem=doc.documentElement,docElemStyle=docElem[$style],setStyles=function(){var i=arguments.length,elemStyle,styles,style;while(i--){styles=arguments[i--];elemStyle=arguments[i][$style];for(style in styles){if(styles.hasOwnProperty(style)){elemStyle[style]=styles[style]}}}},observer=function(obj,event,handler){if(obj.addEventListener){obj.addEventListener(event,handler,False)}else{if(obj.attachEvent){obj.attachEvent("on"+event,handler)}}return[obj,event,handler]},unobserve=function(obj,event,handler){if(obj.removeEventListener){obj.removeEventListener(event,handler,False)}else{if(obj.detachEvent){obj.detachEvent("on"+event,handler)}}},clearChildren=function(node){var children=node.childNodes,child=children.length;while(child--){node.removeChild(children.item(0))}},append=function(to,elem){return to.appendChild(elem)},createElement=function(localName){return doc.createElement(localName)},createTextNode=function(text){return doc.createTextNode(text)},createLog=tinylogLite[log]=function(message){var uninit,originalPadding=docElemStyle.paddingBottom,container=createElement($div),containerStyle=container[$style],resizer=append(container,createElement($div)),output=append(container,createElement($div)),closeButton=append(container,createElement($div)),resizingLog=False,previousHeight=False,previousScrollTop=False,messages=0,updateSafetyMargin=function(){docElemStyle.paddingBottom=container.clientHeight+"px"},setContainerHeight=function(height){var viewHeight=view.innerHeight,resizerHeight=resizer.clientHeight;if(height<0){height=0}else{if(height+resizerHeight>viewHeight){height=viewHeight-resizerHeight}}containerStyle.height=height/viewHeight*100+"%";updateSafetyMargin()},observers=[observer(doc,"mousemove",function(evt){if(resizingLog){setContainerHeight(view.innerHeight-evt.clientY);output.scrollTop=previousScrollTop}}),observer(doc,"mouseup",function(){if(resizingLog){resizingLog=previousScrollTop=False}}),observer(resizer,"dblclick",function(evt){evt.preventDefault();if(previousHeight){setContainerHeight(previousHeight);previousHeight=False}else{previousHeight=container.clientHeight;containerStyle.height="0px"}}),observer(resizer,"mousedown",function(evt){evt.preventDefault();resizingLog=True;previousScrollTop=output.scrollTop}),observer(resizer,"contextmenu",function(){resizingLog=False}),observer(closeButton,"click",function(){uninit()})];uninit=function(){var i=observers.length;while(i--){unobserve.apply(tinylogLite,observers[i])}docElem.removeChild(container);docElemStyle.paddingBottom=originalPadding;clearChildren(output);clearChildren(container);tinylogLite[log]=createLog};setStyles(container,containerStyles,output,outputStyles,resizer,resizerStyles,closeButton,closeButtonStyles);closeButton[$title]="Close Log";append(closeButton,createTextNode("\u2716"));resizer[$title]="Double-click to toggle log minimization";docElem.insertBefore(container,docElem.firstChild);tinylogLite[log]=function(message){if(messages===logLimit){output.removeChild(output.firstChild)}else{messages++}var entry=append(output,createElement($div)),entryText=append(entry,createElement($div));entry[$title]=(new Date()).toLocaleTimeString();setStyles(entry,entryStyles,entryText,entryTextStyles);append(entryText,createTextNode(message));output.scrollTop=output.scrollHeight};tinylogLite[log](message)}}())}else{if(typeof print===func){tinylogLite[log]=print}}}return tinylogLite}());Processing.logger=tinylogLite;Processing.version="@VERSION@";Processing.lib={};Processing.registerLibrary=function(name,desc){Processing.lib[name]=desc;if(desc.hasOwnProperty("init")){desc.init(defaultScope)}};Processing.instances=[];Processing.instanceIds={};Processing.removeInstance=function(id){Processing.instances.splice(Processing.instanceIds[id],1);delete Processing.instanceIds[id]};Processing.addInstance=function(processing){if(processing.externals.canvas.id===undef||!processing.externals.canvas.id.length){processing.externals.canvas.id="__processing"+Processing.instances.length}Processing.instanceIds[processing.externals.canvas.id]=Processing.instances.length;Processing.instances.push(processing)};Processing.getInstanceById=function(name){return Processing.instances[Processing.instanceIds[name]]};Processing.Sketch=function(attachFunction){this.attachFunction=attachFunction;this.use3DContext=false;this.options={isTransparent:false,crispLines:false,pauseOnBlur:false};this.imageCache={pending:0,images:{},add:function(href){var img=new Image();img.onload=(function(owner){return function(){owner.pending--}}(this));this.pending++;this.images[href]=img;img.src=href}};this.fonts={template:(function(){var element=document.createElement("p");element.style.fontFamily="serif";element.style.fontSize="72px";element.style.visibility="hidden";element.innerHTML="abcmmmmmmmmmmlll";document.getElementsByTagName("body")[0].appendChild(element);return element}()),attempt:0,pending:function(){var r=true;for(var i=0;i<this.fontList.length;i++){if(this.fontList[i].offsetWidth===this.template.offsetWidth&&this.fontList[i].offsetHeight===this.template.offsetHeight){r=false;this.attempt++}else{document.getElementsByTagName("body")[0].removeChild(this.fontList[i]);this.fontList.splice(i--,1);this.attempt=0}}if(this.attempt>=30){r=true;for(var j=0;j<this.fontList.length;j++){document.getElementsByTagName("body")[0].removeChild(this.fontList[j]);this.fontList.splice(j--,1)}}if(r){document.getElementsByTagName("body")[0].removeChild(this.template)}return r},fontList:[],fontFamily:"",style:document.createElement("style"),add:function(fontSrc){var fontName=(typeof fontSrc==="object"?fontSrc.fontFace:fontSrc),fontUrl=(typeof fontSrc==="object"?fontSrc.url:fontSrc);this.fontFamily+="@font-face{\n  font-family: '"+fontName+"';\n  src:  url('"+fontUrl+"');\n}\n";this.style.innerHTML=this.fontFamily;document.getElementsByTagName("head")[0].appendChild(this.style);var preLoader=document.createElement("p");preLoader.style.fontFamily="'"+fontName+"', serif";preLoader.style.fontSize="72px";preLoader.style.visibility="hidden";preLoader.innerHTML="abcmmmmmmmmmmlll";document.getElementsByTagName("body")[0].appendChild(preLoader);this.fontList.push(preLoader)}};this.sourceCode=undefined;this.attach=function(processing){if(typeof this.attachFunction==="function"){this.attachFunction(processing)}else{if(this.sourceCode){var func=eval(this.sourceCode);func(processing);this.attachFunction=func}else{throw"Unable to attach sketch to the processing instance"}}};this.toString=function(){return this.sourceCode||"[attach: "+this.attachFunction+"]"};this.onblur=function(){};this.onfocus=function(){}};var init=function(){var canvas=document.getElementsByTagName("canvas");for(var i=0,l=canvas.length;i<l;i++){var processingSources=canvas[i].getAttribute("data-processing-sources");if(processingSources===null){processingSources=canvas[i].getAttribute("data-src");if(processingSources===null){processingSources=canvas[i].getAttribute("datasrc")}}if(processingSources){var filenames=processingSources.split(" ");var code="";for(var j=0,fl=filenames.length;j<fl;j++){if(filenames[j]){var block=ajax(filenames[j]);if(block!==false){code+=";\n"+block}}}Processing.addInstance(new Processing(canvas[i],code))}}};document.addEventListener("DOMContentLoaded",function(){init()},false);window.addEventListener("blur",function(){for(var i=0;i<Processing.instances.length;i++){Processing.instances[i].externals.onblur()}},false);window.addEventListener("focus",function(){for(var i=0;i<Processing.instances.length;i++){Processing.instances[i].externals.onfocus()}},false)}());;

