/*!
 * Raphael 1.5.2 - JavaScript Vector Library
 * NB: Atlassian patched version - see line 1101 in unminified version
 * minified using uglifyJS at http://marijnhaverbeke.nl/uglifyjs
 *
 * Copyright (c) 2010 Dmitry Baranovskiy (http://raphaeljs.com)
 * Licensed under the MIT (http://raphaeljs.com/license.html) license.
 */
(function(){function cD(a,b,c,d,e,f){function o(a,b){var c,d,e,f,j,k;for(e=a,k=0;k<8;k++){f=m(e)-a;if(B(f)<b)return e;j=(3*i*e+2*h)*e+g;if(B(j)<1e-6)break;e=e-f/j}c=0,d=1,e=a;if(e<c)return c;if(e>d)return d;while(c<d){f=m(e);if(B(f-a)<b)return e;a>f?c=e:d=e,e=(d-c)/2+c}return e}function n(a,b){var c=o(a,b);return((l*c+k)*c+j)*c}function m(a){return((i*a+h)*a+g)*a}var g=3*b,h=3*(d-b)-g,i=1-g-h,j=3*c,k=3*(e-c)-j,l=1-j-k;return n(a,1/(200*f))}function cC(b){return function(c,d,e,f){var g={back:b};a.is(e,"function")?f=e:g.rot=e,c&&c.constructor==bO&&(c=c.attrs.path),c&&(g.along=c);return this.animate(g,d,f)}}function cq(){return this.x+q+this.y}function bn(a,b,c){function d(){var g=Array[e].slice.call(arguments,0),h=g[v]("►"),i=d.cache=d.cache||{},j=d.count=d.count||[];if(i[f](h))return c?c(i[h]):i[h];j[w]>=1e3&&delete i[j.shift()],j[L](h),i[h]=a[m](b,g);return c?c(i[h]):i[h]}return d}function bi(){var a=[],b=0;for(;b<32;b++)a[b]=(~~(y.random()*16))[H](16);a[12]=4,a[16]=(a[16]&3|8)[H](16);return"r-"+a[v]("")}function a(){if(a.is(arguments[0],G)){var b=arguments[0],d=bW[m](a,b.splice(0,3+a.is(b[0],E))),e=d.set();for(var g=0,h=b[w];g<h;g++){var i=b[g]||{};c[f](i.type)&&e[L](d[i.type]().attr(i))}return e}return bW[m](a,arguments)}a.version="1.5.2";var b=/[, ]+/,c={circle:1,rect:1,path:1,ellipse:1,text:1,image:1},d=/\{(\d+)\}/g,e="prototype",f="hasOwnProperty",g=document,h=window,i={was:Object[e][f].call(h,"Raphael"),is:h.Raphael},j=function(){this.customAttributes={}},k,l="appendChild",m="apply",n="concat",o="createTouch"in g,p="",q=" ",r=String,s="split",t="click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend orientationchange touchcancel gesturestart gesturechange gestureend"[s](q),u={mousedown:"touchstart",mousemove:"touchmove",mouseup:"touchend"},v="join",w="length",x=r[e].toLowerCase,y=Math,z=y.max,A=y.min,B=y.abs,C=y.pow,D=y.PI,E="number",F="string",G="array",H="toString",I="fill",J=Object[e][H],K={},L="push",M=/^url\(['"]?([^\)]+?)['"]?\)$/i,N=/^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,O={NaN:1,Infinity:1,"-Infinity":1},P=/^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,Q=y.round,R="setAttribute",S=parseFloat,T=parseInt,U=" progid:DXImageTransform.Microsoft",V="webkitTapHighlightColor",W=r[e].toUpperCase,X={blur:0,"clip-rect":"0 0 1e9 1e9",cursor:"default",cx:0,cy:0,fill:"#fff","fill-opacity":1,font:'10px "Arial"',"font-family":'"Arial"',"font-size":"10","font-style":"normal","font-weight":400,gradient:0,height:0,href:"http://raphaeljs.com/",opacity:1,path:"M0,0",r:0,rotation:0,rx:0,ry:0,scale:"1 1",src:"",stroke:"#000","stroke-dasharray":"","stroke-linecap":"butt","stroke-linejoin":"butt","stroke-miterlimit":0,"stroke-opacity":1,"stroke-width":1,target:"_blank","text-anchor":"middle",title:"Raphael",translation:"0 0",width:0,x:0,y:0},Y={along:"along",blur:E,"clip-rect":"csv",cx:E,cy:E,fill:"colour","fill-opacity":E,"font-size":E,height:E,opacity:E,path:"path",r:E,rotation:"csv",rx:E,ry:E,scale:"csv",stroke:"colour","stroke-opacity":E,"stroke-width":E,translation:"csv",width:E,x:E,y:E},Z="replace",$=/^(from|to|\d+%?)/,_=/\s*,\s*/,ba={hs:1,rg:1},bb=/,?([achlmqrstvxz]),?/gi,bc=/([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[-+]?\d+)?\s*,?\s*)+)/ig,bd=/(-?\d*\.?\d*(?:e[-+]?\d+)?)\s*,?\s*/ig,be=/^r(?:\(([^,]+?)\s*,\s*([^\)]+?)\))?/,bf=function(a,b){return a.key-b.key};a.type=h.SVGAngle||g.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")?"SVG":"VML";if(a.type=="VML"){var bg=g.createElement("div"),bh;bg.innerHTML='<v:shape adj="1"/>',bh=bg.firstChild,bh.style.behavior="url(#default#VML)";if(!bh||typeof bh.adj!="object")return a.type=null;bg=null}a.svg=!(a.vml=a.type=="VML"),j[e]=a[e],k=j[e],a._id=0,a._oid=0,a.fn={},a.is=function(a,b){b=x.call(b);if(b=="finite")return!O[f](+a);return b=="null"&&a===null||b==typeof a||b=="object"&&a===Object(a)||b=="array"&&Array.isArray&&Array.isArray(a)||J.call(a).slice(8,-1).toLowerCase()==b},a.angle=function(b,c,d,e,f,g){if(f==null){var h=b-d,i=c-e;if(!h&&!i)return 0;return((h<0)*180+y.atan(-i/-h)*180/D+360)%360}return a.angle(b,c,f,g)-a.angle(d,e,f,g)},a.rad=function(a){return a%360*D/180},a.deg=function(a){return a*180/D%360},a.snapTo=function(b,c,d){d=a.is(d,"finite")?d:10;if(a.is(b,G)){var e=b.length;while(e--)if(B(b[e]-c)<=d)return b[e]}else{b=+b;var f=c%b;if(f<d)return c-f;if(f>b-d)return c-f+b}return c},a.setWindow=function(a){h=a,g=h.document};var bj=function(b){if(a.vml){var c=/^\s+|\s+$/g,d;try{var e=new ActiveXObject("htmlfile");e.write("<body>"),e.close(),d=e.body}catch(f){d=createPopup().document.body}var h=d.createTextRange();bj=bn(function(a){try{d.style.color=r(a)[Z](c,p);var b=h.queryCommandValue("ForeColor");b=(b&255)<<16|b&65280|(b&16711680)>>>16;return"#"+("000000"+b[H](16)).slice(-6)}catch(e){return"none"}})}else{var i=g.createElement("i");i.title="Raphaël Colour Picker",i.style.display="none",g.body[l](i),bj=bn(function(a){i.style.color=a;return g.defaultView.getComputedStyle(i,p).getPropertyValue("color")})}return bj(b)},bk=function(){return"hsb("+[this.h,this.s,this.b]+")"},bl=function(){return"hsl("+[this.h,this.s,this.l]+")"},bm=function(){return this.hex};a.hsb2rgb=function(b,c,d,e){a.is(b,"object")&&"h"in b&&"s"in b&&"b"in b&&(d=b.b,c=b.s,b=b.h,e=b.o);return a.hsl2rgb(b,c,d/2,e)},a.hsl2rgb=function(b,c,d,e){a.is(b,"object")&&"h"in b&&"s"in b&&"l"in b&&(d=b.l,c=b.s,b=b.h);if(b>1||c>1||d>1)b/=360,c/=100,d/=100;var f={},g=["r","g","b"],h,i,j,k,l,m;if(!c)f={r:d,g:d,b:d};else{d<.5?h=d*(1+c):h=d+c-d*c,i=2*d-h;for(var n=0;n<3;n++)j=b+1/3*-(n-1),j<0&&j++,j>1&&j--,j*6<1?f[g[n]]=i+(h-i)*6*j:j*2<1?f[g[n]]=h:j*3<2?f[g[n]]=i+(h-i)*(2/3-j)*6:f[g[n]]=i}f.r*=255,f.g*=255,f.b*=255,f.hex="#"+(16777216|f.b|f.g<<8|f.r<<16).toString(16).slice(1),a.is(e,"finite")&&(f.opacity=e),f.toString=bm;return f},a.rgb2hsb=function(b,c,d){c==null&&a.is(b,"object")&&"r"in b&&"g"in b&&"b"in b&&(d=b.b,c=b.g,b=b.r);if(c==null&&a.is(b,F)){var e=a.getRGB(b);b=e.r,c=e.g,d=e.b}if(b>1||c>1||d>1)b/=255,c/=255,d/=255;var f=z(b,c,d),g=A(b,c,d),h,i,j=f;if(g==f)return{h:0,s:0,b:f,toString:bk};var k=f-g;i=k/f,b==f?h=(c-d)/k:c==f?h=2+(d-b)/k:h=4+(b-c)/k,h/=6,h<0&&h++,h>1&&h--;return{h:h,s:i,b:j,toString:bk}},a.rgb2hsl=function(b,c,d){c==null&&a.is(b,"object")&&"r"in b&&"g"in b&&"b"in b&&(d=b.b,c=b.g,b=b.r);if(c==null&&a.is(b,F)){var e=a.getRGB(b);b=e.r,c=e.g,d=e.b}if(b>1||c>1||d>1)b/=255,c/=255,d/=255;var f=z(b,c,d),g=A(b,c,d),h,i,j=(f+g)/2,k;if(g==f)k={h:0,s:0,l:j};else{var l=f-g;i=j<.5?l/(f+g):l/(2-f-g),b==f?h=(c-d)/l:c==f?h=2+(d-b)/l:h=4+(b-c)/l,h/=6,h<0&&h++,h>1&&h--,k={h:h,s:i,l:j}}k.toString=bl;return k},a._path2string=function(){return this.join(",")[Z](bb,"$1")},a.getRGB=bn(function(b){if(!b||!!((b=r(b)).indexOf("-")+1))return{r:-1,g:-1,b:-1,hex:"none",error:1};if(b=="none")return{r:-1,g:-1,b:-1,hex:"none"};!ba[f](b.toLowerCase().substring(0,2))&&b.charAt()!="#"&&(b=bj(b));var c,d,e,g,h,i,j,k=b.match(N);if(k){k[2]&&(g=T(k[2].substring(5),16),e=T(k[2].substring(3,5),16),d=T(k[2].substring(1,3),16)),k[3]&&(g=T((i=k[3].charAt(3))+i,16),e=T((i=k[3].charAt(2))+i,16),d=T((i=k[3].charAt(1))+i,16)),k[4]&&(j=k[4][s](_),d=S(j[0]),j[0].slice(-1)=="%"&&(d*=2.55),e=S(j[1]),j[1].slice(-1)=="%"&&(e*=2.55),g=S(j[2]),j[2].slice(-1)=="%"&&(g*=2.55),k[1].toLowerCase().slice(0,4)=="rgba"&&(h=S(j[3])),j[3]&&j[3].slice(-1)=="%"&&(h/=100));if(k[5]){j=k[5][s](_),d=S(j[0]),j[0].slice(-1)=="%"&&(d*=2.55),e=S(j[1]),j[1].slice(-1)=="%"&&(e*=2.55),g=S(j[2]),j[2].slice(-1)=="%"&&(g*=2.55),(j[0].slice(-3)=="deg"||j[0].slice(-1)=="°")&&(d/=360),k[1].toLowerCase().slice(0,4)=="hsba"&&(h=S(j[3])),j[3]&&j[3].slice(-1)=="%"&&(h/=100);return a.hsb2rgb(d,e,g,h)}if(k[6]){j=k[6][s](_),d=S(j[0]),j[0].slice(-1)=="%"&&(d*=2.55),e=S(j[1]),j[1].slice(-1)=="%"&&(e*=2.55),g=S(j[2]),j[2].slice(-1)=="%"&&(g*=2.55),(j[0].slice(-3)=="deg"||j[0].slice(-1)=="°")&&(d/=360),k[1].toLowerCase().slice(0,4)=="hsla"&&(h=S(j[3])),j[3]&&j[3].slice(-1)=="%"&&(h/=100);return a.hsl2rgb(d,e,g,h)}k={r:d,g:e,b:g},k.hex="#"+(16777216|g|e<<8|d<<16).toString(16).slice(1),a.is(h,"finite")&&(k.opacity=h);return k}return{r:-1,g:-1,b:-1,hex:"none",error:1}},a),a.getColor=function(a){var b=this.getColor.start=this.getColor.start||{h:0,s:1,b:a||.75},c=this.hsb2rgb(b.h,b.s,b.b);b.h+=.075,b.h>1&&(b.h=0,b.s-=.2,b.s<=0&&(this.getColor.start={h:0,s:1,b:b.b}));return c.hex},a.getColor.reset=function(){delete this.start},a.parsePathString=bn(function(b){if(!b)return null;var c={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},d=[];a.is(b,G)&&a.is(b[0],G)&&(d=bp(b)),d[w]||r(b)[Z](bc,function(a,b,e){var f=[],g=x.call(b);e[Z](bd,function(a,b){b&&f[L](+b)}),g=="m"&&f[w]>2&&(d[L]([b][n](f.splice(0,2))),g="l",b=b=="m"?"l":"L");while(f[w]>=c[g]){d[L]([b][n](f.splice(0,c[g])));if(!c[g])break}}),d[H]=a._path2string;return d}),a.findDotsAtSegment=function(a,b,c,d,e,f,g,h,i){var j=1-i,k=C(j,3)*a+C(j,2)*3*i*c+j*3*i*i*e+C(i,3)*g,l=C(j,3)*b+C(j,2)*3*i*d+j*3*i*i*f+C(i,3)*h,m=a+2*i*(c-a)+i*i*(e-2*c+a),n=b+2*i*(d-b)+i*i*(f-2*d+b),o=c+2*i*(e-c)+i*i*(g-2*e+c),p=d+2*i*(f-d)+i*i*(h-2*f+d),q=(1-i)*a+i*c,r=(1-i)*b+i*d,s=(1-i)*e+i*g,t=(1-i)*f+i*h,u=90-y.atan((m-o)/(n-p))*180/D;(m>o||n<p)&&(u+=180);return{x:k,y:l,m:{x:m,y:n},n:{x:o,y:p},start:{x:q,y:r},end:{x:s,y:t},alpha:u}};var bo=bn(function(a){if(!a)return{x:0,y:0,width:0,height:0};a=bx(a);var b=0,c=0,d=[],e=[],f;for(var g=0,h=a[w];g<h;g++){f=a[g];if(f[0]=="M")b=f[1],c=f[2],d[L](b),e[L](c);else{var i=bw(b,c,f[1],f[2],f[3],f[4],f[5],f[6]);d=d[n](i.min.x,i.max.x),e=e[n](i.min.y,i.max.y),b=f[5],c=f[6]}}var j=A[m](0,d),k=A[m](0,e);return{x:j,y:k,width:z[m](0,d)-j,height:z[m](0,e)-k}}),bp=function(b){var c=[];if(!a.is(b,G)||!a.is(b&&b[0],G))b=a.parsePathString(b);for(var d=0,e=b[w];d<e;d++){c[d]=[];for(var f=0,g=b[d][w];f<g;f++)c[d][f]=b[d][f]}c[H]=a._path2string;return c},bq=bn(function(b){if(!a.is(b,G)||!a.is(b&&b[0],G))b=a.parsePathString(b);var c=[],d=0,e=0,f=0,g=0,h=0;b[0][0]=="M"&&(d=b[0][1],e=b[0][2],f=d,g=e,h++,c[L](["M",d,e]));for(var i=h,j=b[w];i<j;i++){var k=c[i]=[],l=b[i];if(l[0]!=x.call(l[0])){k[0]=x.call(l[0]);switch(k[0]){case"a":k[1]=l[1],k[2]=l[2],k[3]=l[3],k[4]=l[4],k[5]=l[5],k[6]=+(l[6]-d).toFixed(3),k[7]=+(l[7]-e).toFixed(3);break;case"v":k[1]=+(l[1]-e).toFixed(3);break;case"m":f=l[1],g=l[2];default:for(var m=1,n=l[w];m<n;m++)k[m]=+(l[m]-(m%2?d:e)).toFixed(3)}}else{k=c[i]=[],l[0]=="m"&&(f=l[1]+d,g=l[2]+e);for(var o=0,p=l[w];o<p;o++)c[i][o]=l[o]}var q=c[i][w];switch(c[i][0]){case"z":d=f,e=g;break;case"h":d+=+c[i][q-1];break;case"v":e+=+c[i][q-1];break;default:d+=+c[i][q-2],e+=+c[i][q-1]}}c[H]=a._path2string;return c},0,bp),br=bn(function(b){if(!a.is(b,G)||!a.is(b&&b[0],G))b=a.parsePathString(b);var c=[],d=0,e=0,f=0,g=0,h=0;b[0][0]=="M"&&(d=+b[0][1],e=+b[0][2],f=d,g=e,h++,c[0]=["M",d,e]);for(var i=h,j=b[w];i<j;i++){var k=c[i]=[],l=b[i];if(l[0]!=W.call(l[0])){k[0]=W.call(l[0]);switch(k[0]){case"A":k[1]=l[1],k[2]=l[2],k[3]=l[3],k[4]=l[4],k[5]=l[5],k[6]=+(l[6]+d),k[7]=+(l[7]+e);break;case"V":k[1]=+l[1]+e;break;case"H":k[1]=+l[1]+d;break;case"M":f=+l[1]+d,g=+l[2]+e;default:for(var m=1,n=l[w];m<n;m++)k[m]=+l[m]+(m%2?d:e)}}else for(var o=0,p=l[w];o<p;o++)c[i][o]=l[o];switch(k[0]){case"Z":d=f,e=g;break;case"H":d=k[1];break;case"V":e=k[1];break;case"M":f=c[i][c[i][w]-2],g=c[i][c[i][w]-1];default:d=c[i][c[i][w]-2],e=c[i][c[i][w]-1]}}c[H]=a._path2string;return c},null,bp),bs=function(a,b,c,d){return[a,b,c,d,c,d]},bt=function(a,b,c,d,e,f){var g=1/3,h=2/3;return[g*a+h*c,g*b+h*d,g*e+h*c,g*f+h*d,e,f]},bu=function(a,b,c,d,e,f,g,h,i,j){var k=D*120/180,l=D/180*(+e||0),m=[],o,p=bn(function(a,b,c){var d=a*y.cos(c)-b*y.sin(c),e=a*y.sin(c)+b*y.cos(c);return{x:d,y:e}});if(!j){o=p(a,b,-l),a=o.x,b=o.y,o=p(h,i,-l),h=o.x,i=o.y;var q=y.cos(D/180*e),r=y.sin(D/180*e),t=(a-h)/2,u=(b-i)/2,x=t*t/(c*c)+u*u/(d*d);x>1&&(x=y.sqrt(x),c=x*c,d=x*d);var z=c*c,A=d*d,C=(f==g?-1:1)*y.sqrt(B((z*A-z*u*u-A*t*t)/(z*u*u+A*t*t))),E=C*c*u/d+(a+h)/2,F=C*-d*t/c+(b+i)/2,G=y.asin(((b-F)/d).toFixed(9)),H=y.asin(((i-F)/d).toFixed(9));G=a<E?D-G:G,H=h<E?D-H:H,G<0&&(G=D*2+G),H<0&&(H=D*2+H),g&&G>H&&(G=G-D*2),!g&&H>G&&(H=H-D*2)}else G=j[0],H=j[1],E=j[2],F=j[3];var I=H-G;if(B(I)>k){var J=H,K=h,L=i;H=G+k*(g&&H>G?1:-1),h=E+c*y.cos(H),i=F+d*y.sin(H),m=bu(h,i,c,d,e,0,g,K,L,[H,J,E,F])}I=H-G;var M=y.cos(G),N=y.sin(G),O=y.cos(H),P=y.sin(H),Q=y.tan(I/4),R=4/3*c*Q,S=4/3*d*Q,T=[a,b],U=[a+R*N,b-S*M],V=[h+R*P,i-S*O],W=[h,i];U[0]=2*T[0]-U[0],U[1]=2*T[1]-U[1];if(j)return[U,V,W][n](m);m=[U,V,W][n](m)[v]()[s](",");var X=[];for(var Y=0,Z=m[w];Y<Z;Y++)X[Y]=Y%2?p(m[Y-1],m[Y],l).y:p(m[Y],m[Y+1],l).x;return X},bv=function(a,b,c,d,e,f,g,h,i){var j=1-i;return{x:C(j,3)*a+C(j,2)*3*i*c+j*3*i*i*e+C(i,3)*g,y:C(j,3)*b+C(j,2)*3*i*d+j*3*i*i*f+C(i,3)*h}},bw=bn(function(a,b,c,d,e,f,g,h){var i=e-2*c+a-(g-2*e+c),j=2*(c-a)-2*(e-c),k=a-c,l=(-j+y.sqrt(j*j-4*i*k))/2/i,n=(-j-y.sqrt(j*j-4*i*k))/2/i,o=[b,h],p=[a,g],q;B(l)>"1e12"&&(l=.5),B(n)>"1e12"&&(n=.5),l>0&&l<1&&(q=bv(a,b,c,d,e,f,g,h,l),p[L](q.x),o[L](q.y)),n>0&&n<1&&(q=bv(a,b,c,d,e,f,g,h,n),p[L](q.x),o[L](q.y)),i=f-2*d+b-(h-2*f+d),j=2*(d-b)-2*(f-d),k=b-d,l=(-j+y.sqrt(j*j-4*i*k))/2/i,n=(-j-y.sqrt(j*j-4*i*k))/2/i,B(l)>"1e12"&&(l=.5),B(n)>"1e12"&&(n=.5),l>0&&l<1&&(q=bv(a,b,c,d,e,f,g,h,l),p[L](q.x),o[L](q.y)),n>0&&n<1&&(q=bv(a,b,c,d,e,f,g,h,n),p[L](q.x),o[L](q.y));return{min:{x:A[m](0,p),y:A[m](0,o)},max:{x:z[m](0,p),y:z[m](0,o)}}}),bx=bn(function(a,b){var c=br(a),d=b&&br(b),e={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},f={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},g=function(a,b){var c,d;if(!a)return["C",b.x,b.y,b.x,b.y,b.x,b.y];!(a[0]in{T:1,Q:1})&&(b.qx=b.qy=null);switch(a[0]){case"M":b.X=a[1],b.Y=a[2];break;case"A":a=["C"][n](bu[m](0,[b.x,b.y][n](a.slice(1))));break;case"S":c=b.x+(b.x-(b.bx||b.x)),d=b.y+(b.y-(b.by||b.y)),a=["C",c,d][n](a.slice(1));break;case"T":b.qx=b.x+(b.x-(b.qx||b.x)),b.qy=b.y+(b.y-(b.qy||b.y)),a=["C"][n](bt(b.x,b.y,b.qx,b.qy,a[1],a[2]));break;case"Q":b.qx=a[1],b.qy=a[2],a=["C"][n](bt(b.x,b.y,a[1],a[2],a[3],a[4]));break;case"L":a=["C"][n](bs(b.x,b.y,a[1],a[2]));break;case"H":a=["C"][n](bs(b.x,b.y,a[1],b.y));break;case"V":a=["C"][n](bs(b.x,b.y,b.x,a[1]));break;case"Z":a=["C"][n](bs(b.x,b.y,b.X,b.Y))}return a},h=function(a,b){if(a[b][w]>7){a[b].shift();var e=a[b];while(e[w])a.splice(b++,0,["C"][n](e.splice(0,6)));a.splice(b,1),k=z(c[w],d&&d[w]||0)}},i=function(a,b,e,f,g){a&&b&&a[g][0]=="M"&&b[g][0]!="M"&&(b.splice(g,0,["M",f.x,f.y]),e.bx=0,e.by=0,e.x=a[g][1],e.y=a[g][2],k=z(c[w],d&&d[w]||0))};for(var j=0,k=z(c[w],d&&d[w]||0);j<k;j++){c[j]=g(c[j],e),h(c,j),d&&(d[j]=g(d[j],f)),d&&h(d,j),i(c,d,e,f,j),i(d,c,f,e,j);var l=c[j],o=d&&d[j],p=l[w],q=d&&o[w];e.x=l[p-2],e.y=l[p-1],e.bx=S(l[p-4])||e.x,e.by=S(l[p-3])||e.y,f.bx=d&&(S(o[q-4])||f.x),f.by=d&&(S(o[q-3])||f.y),f.x=d&&o[q-2],f.y=d&&o[q-1]}return d?[c,d]:c},null,bp),by=bn(function(b){var c=[];for(var d=0,e=b[w];d<e;d++){var f={},g=b[d].match(/^([^:]*):?([\d\.]*)/);f.color=a.getRGB(g[1]);if(f.color.error)return null;f.color=f.color.hex,g[2]&&(f.offset=g[2]+"%"),c[L](f)}for(d=1,e=c[w]-1;d<e;d++)if(!c[d].offset){var h=S(c[d-1].offset||0),i=0;for(var j=d+1;j<e;j++)if(c[j].offset){i=c[j].offset;break}i||(i=100,j=e),i=S(i);var k=(i-h)/(j-d+1);for(;d<j;d++)h+=k,c[d].offset=h+"%"}return c}),bz=function(b,c,d,e){var f;if(!a.is(b,F)&&!a.is(b,"object"))return{container:1,x:b,y:c,width:d,height:e};f=a.is(b,F)?g.getElementById(b):b;if(f.tagName)return c==null?{container:f,width:f.style.pixelWidth||f.offsetWidth,height:f.style.pixelHeight||f.offsetHeight}:{container:f,width:c,height:d}},bA=function(a,b){var c=this;for(var d in b)if(b[f](d)&&!(d in a))switch(typeof b[d]){case"function":(function(b){a[d]=a===c?b:function(){return b[m](c,arguments)}})(b[d]);break;case"object":a[d]=a[d]||{},bA.call(this,a[d],b[d]);break;default:a[d]=b[d]}},bB=function(a,b){a==b.top&&(b.top=a.prev),a==b.bottom&&(b.bottom=a.next),a.next&&(a.next.prev=a.prev),a.prev&&(a.prev.next=a.next)},bC=function(a,b){b.top!==a&&(bB(a,b),a.next=null,a.prev=b.top,b.top.next=a,b.top=a)},bD=function(a,b){b.bottom!==a&&(bB(a,b),a.next=b.bottom,a.prev=null,b.bottom.prev=a,b.bottom=a)},bE=function(a,b,c){bB(a,c),b==c.top&&(c.top=a),b.next&&(b.next.prev=a),a.next=b.next,a.prev=b,b.next=a},bF=function(a,b,c){bB(a,c),b==c.bottom&&(c.bottom=a),b.prev&&(b.prev.next=a),a.prev=b.prev,b.prev=a,a.next=b},bG=function(a){return function(){throw new Error("Raphaël: you are calling to method “"+a+"” of removed object")}};a.pathToRelative=bq;if(a.svg){k.svgns="http://www.w3.org/2000/svg",k.xlink="http://www.w3.org/1999/xlink",Q=function(a){return+a+(~~a===a)*.5};var bH=function(a,b){if(!b){a=g.createElementNS(k.svgns,a),a.style&&(a.style.webkitTapHighlightColor="rgba(0,0,0,0)");return a}for(var c in b)b[f](c)&&a[R](c,r(b[c]))};a[H]=function(){return"Your browser supports SVG.\nYou are running Raphaël "+this.version};var bI=function(a,b){var c=bH("path");b.canvas&&b.canvas[l](c);var d=new bO(c,b);d.type="path",bL(d,{fill:"none",stroke:"#000",path:a});return d},bJ=function(a,b,c){var d="linear",e=.5,f=.5,h=a.style;b=r(b)[Z](be,function(a,b,c){d="radial";if(b&&c){e=S(b),f=S(c);var g=(f>.5)*2-1;C(e-.5,2)+C(f-.5,2)>.25&&(f=y.sqrt(.25-C(e-.5,2))*g+.5)&&f!=.5&&(f=f.toFixed(5)-1e-5*g)}return p}),b=b[s](/\s*\-\s*/);if(d=="linear"){var i=b.shift();i=-S(i);if(isNaN(i))return null;var j=[0,0,y.cos(i*D/180),y.sin(i*D/180)],k=1/(z(B(j[2]),B(j[3]))||1);j[2]*=k,j[3]*=k,j[2]<0&&(j[0]=-j[2],j[2]=0),j[3]<0&&(j[1]=-j[3],j[3]=0)}var m=by(b);if(!m)return null;var n=a.getAttribute(I);n=n.match(/^url\(#(.*)\)$/),n&&c.defs.removeChild(g.getElementById(n[1]));var o=bH(d+"Gradient");o.id=bi(),bH(o,d=="radial"?{fx:e,fy:f}:{x1:j[0],y1:j[1],x2:j[2],y2:j[3]}),c.defs[l](o);for(var q=0,t=m[w];q<t;q++){var u=bH("stop");bH(u,{offset:m[q].offset?m[q].offset:q?"100%":"0%","stop-color":m[q].color||"#fff"}),o[l](u)}bH(a,{fill:"url(#"+o.id+")",opacity:1,"fill-opacity":1}),h.fill=p,h.opacity=1,h.fillOpacity=1;return 1},bK=function(b){var c=b.getBBox();bH(b.pattern,{patternTransform:a.format("translate({0},{1})",c.x,c.y)})},bL=function(c,d){var e={"":[0],none:[0],"-":[3,1],".":[1,1],"-.":[3,1,1,1],"-..":[3,1,1,1,1,1],". ":[1,3],"- ":[4,3],"--":[8,3],"- .":[4,3,1,3],"--.":[8,3,1,3],"--..":[8,3,1,3,1,3]},h=c.node,i=c.attrs,j=c.rotate(),k=function(a,b){b=e[x.call(b)];if(b){var c=a.attrs["stroke-width"]||"1",f=({round:c,square:c,butt:0})[a.attrs["stroke-linecap"]||d["stroke-linecap"]]||0,g=[],i=b[w];while(i--)g[i]=b[i]*c+(i%2?1:-1)*f;bH(h,{"stroke-dasharray":g[v](",")})}};d[f]("rotation")&&(j=d.rotation);var m=r(j)[s](b);m.length-1?(m[1]=+m[1],m[2]=+m[2]):m=null,S(j)&&c.rotate(0,!0);for(var n in d)if(d[f](n)){if(!X[f](n))continue;var o=d[n];i[n]=o;switch(n){case"blur":c.blur(o);break;case"rotation":c.rotate(o,!0);break;case"href":case"title":case"target":var t=h.parentNode;if(x.call(t.tagName)!="a"){var u=bH("a");t.insertBefore(u,h),u[l](h),t=u}n=="target"&&o=="blank"?t.setAttributeNS(c.paper.xlink,"show","new"):t.setAttributeNS(c.paper.xlink,n,o);break;case"cursor":h.style.cursor=o;break;case"clip-rect":var y=r(o)[s](b);if(y[w]==4){c.clip&&c.clip.parentNode.parentNode.removeChild(c.clip.parentNode);var z=bH("clipPath"),A=bH("rect");z.id=bi(),bH(A,{x:y[0],y:y[1],width:y[2],height:y[3]}),z[l](A),c.paper.defs[l](z),bH(h,{"clip-path":"url(#"+z.id+")"}),c.clip=A}if(!o){var B=g.getElementById(h.getAttribute("clip-path")[Z](/(^url\(#|\)$)/g,p));B&&B.parentNode.removeChild(B),bH(h,{"clip-path":p}),delete c.clip}break;case"path":c.type=="path"&&bH(h,{d:o?i.path=br(o):"M0,0"});break;case"width":h[R](n,o);if(i.fx)n="x",o=i.x;else break;case"x":i.fx&&(o=-i.x-(i.width||0));case"rx":if(n=="rx"&&c.type=="rect")break;case"cx":m&&(n=="x"||n=="cx")&&(m[1]+=o-i[n]),h[R](n,o),c.pattern&&bK(c);break;case"height":h[R](n,o);if(i.fy)n="y",o=i.y;else break;case"y":i.fy&&(o=-i.y-(i.height||0));case"ry":if(n=="ry"&&c.type=="rect")break;case"cy":m&&(n=="y"||n=="cy")&&(m[2]+=o-i[n]),h[R](n,o),c.pattern&&bK(c);break;case"r":c.type=="rect"?bH(h,{rx:o,ry:o}):h[R](n,o);break;case"src":c.type=="image"&&h.setAttributeNS(c.paper.xlink,"href",o);break;case"stroke-width":h.style.strokeWidth=o,h[R](n,o),i["stroke-dasharray"]&&k(c,i["stroke-dasharray"]);break;case"stroke-dasharray":k(c,o);break;case"translation":var C=r(o)[s](b);C[0]=+C[0]||0,C[1]=+C[1]||0,m&&(m[1]+=C[0],m[2]+=C[1]),cB.call(c,C[0],C[1]);break;case"scale":C=r(o)[s](b),c.scale(+C[0]||1,+C[1]||+C[0]||1,isNaN(S(C[2]))?null:+C[2],isNaN(S(C[3]))?null:+C[3]);break;case I:var D=r(o).match(M);if(D){z=bH("pattern");var E=bH("image");z.id=bi(),bH(z,{x:0,y:0,patternUnits:"userSpaceOnUse",height:1,width:1}),bH(E,{x:0,y:0}),E.setAttributeNS(c.paper.xlink,"href",D[1]),z[l](E);var F=g.createElement("img");F.style.cssText="position:absolute;left:-9999em;top-9999em",F.onload=function(){bH(z,{width:this.offsetWidth,height:this.offsetHeight}),bH(E,{width:this.offsetWidth,height:this.offsetHeight}),g.body.removeChild(this),c.paper.safari()},g.body[l](F),F.src=D[1],c.paper.defs[l](z),h.style.fill="url(#"+z.id+")",bH(h,{fill:"url(#"+z.id+")"}),c.pattern=z,c.pattern&&bK(c);break}var G=a.getRGB(o);if(!G.error)delete d.gradient,delete i.gradient,!a.is(i.opacity,"undefined")&&a.is(d.opacity,"undefined")&&bH(h,{opacity:i.opacity}),!a.is(i["fill-opacity"],"undefined")&&a.is(d["fill-opacity"],"undefined")&&bH(h,{"fill-opacity":i["fill-opacity"]});else if((({circle:1,ellipse:1})[f](c.type)||r(o).charAt()!="r")&&bJ(h,o,c.paper)){i.gradient=o,i.fill="none";break}G[f]("opacity")&&bH(h,{"fill-opacity":G.opacity>1?G.opacity/100:G.opacity});case"stroke":G=a.getRGB(o),h[R](n,G.hex),n=="stroke"&&G[f]("opacity")&&bH(h,{"stroke-opacity":G.opacity>1?G.opacity/100:G.opacity});break;case"gradient":(({circle:1,ellipse:1})[f](c.type)||r(o).charAt()!="r")&&bJ(h,o,c.paper);break;case"opacity":i.gradient&&!i[f]("stroke-opacity")&&bH(h,{"stroke-opacity":o>1?o/100:o});case"fill-opacity":if(i.gradient){var H=g.getElementById(h.getAttribute(I)[Z](/^url\(#|\)$/g,p));if(H){var J=H.getElementsByTagName("stop");J[J[w]-1][R]("stop-opacity",o)}break};default:n=="font-size"&&(o=T(o,10)+"px");var K=n[Z](/(\-.)/g,function(a){return W.call(a.substring(1))});h.style[K]=o,h[R](n,o)}}bN(c,d),m?c.rotate(m.join(q)):S(j)&&c.rotate(j,!0)},bM=1.2,bN=function(b,c){if(b.type=="text"&&!!(c[f]("text")||c[f]("font")||c[f]("font-size")||c[f]("x")||c[f]("y"))){var d=b.attrs,e=b.node,h=e.firstChild?T(g.defaultView.getComputedStyle(e.firstChild,p).getPropertyValue("font-size"),10):10;if(c[f]("text")){d.text=c.text;while(e.firstChild)e.removeChild(e.firstChild);var i=r(c.text)[s]("\n");for(var j=0,k=i[w];j<k;j++)if(i[j]){var m=bH("tspan");j&&bH(m,{dy:h*bM,x:d.x}),m[l](g.createTextNode(i[j])),e[l](m)}}else{i=e.getElementsByTagName("tspan");for(j=0,k=i[w];j<k;j++)j&&bH(i[j],{dy:h*bM,x:d.x})}bH(e,{y:d.y});var n=b.getBBox(),o=d.y-(n.y+n.height/2);o&&a.is(o,"finite")&&bH(e,{y:d.y+o})}},bO=function(b,c){var d=0,e=0;this[0]=b,this.id=a._oid++,this.node=b,b.raphael=this,this.paper=c,this.attrs=this.attrs||{},this.transformations=[],this._={tx:0,ty:0,rt:{deg:0,cx:0,cy:0},sx:1,sy:1},!c.bottom&&(c.bottom=this),this.prev=c.top,c.top&&(c.top.next=this),c.top=this,this.next=null},bP=bO[e];bO[e].rotate=function(c,d,e){if(this.removed)return this;if(c==null){if(this._.rt.cx)return[this._.rt.deg,this._.rt.cx,this._.rt.cy][v](q);return this._.rt.deg}var f=this.getBBox();c=r(c)[s](b),c[w]-1&&(d=S(c[1]),e=S(c[2])),c=S(c[0]),d!=null&&d!==!1?this._.rt.deg=c:this._.rt.deg+=c,e==null&&(d=null),this._.rt.cx=d,this._.rt.cy=e,d=d==null?f.x+f.width/2:d,e=e==null?f.y+f.height/2:e,this._.rt.deg?(this.transformations[0]=a.format("rotate({0} {1} {2})",this._.rt.deg,d,e),this.clip&&bH(this.clip,{transform:a.format("rotate({0} {1} {2})",-this._.rt.deg,d,e)})):(this.transformations[0]=p,this.clip&&bH(this.clip,{transform:p})),bH(this.node,{transform:this.transformations[v](q)});return this},bO[e].hide=function(){!this.removed&&(this.node.style.display="none");return this},bO[e].show=function(){!this.removed&&(this.node.style.display="");return this},bO[e].remove=function(){if(!this.removed){bB(this,this.paper),this.node.parentNode.removeChild(this.node);for(var a in this)delete this[a];this.removed=!0}},bO[e].getBBox=function(){if(this.removed)return this;if(this.type=="path")return bo(this.attrs.path);if(this.node.style.display=="none"){this.show();var a=!0}var b={};try{b=this.node.getBBox()}catch(c){}finally{b=b||{}}if(this.type=="text"){b={x:b.x,y:Infinity,width:0,height:0};for(var d=0,e=this.node.getNumberOfChars();d<e;d++){var f=this.node.getExtentOfChar(d);f.y<b.y&&(b.y=f.y),f.y+f.height-b.y>b.height&&(b.height=f.y+f.height-b.y),f.x+f.width-b.x>b.width&&(b.width=f.x+f.width-b.x)}}a&&this.hide();return b},bO[e].attr=function(b,c){if(this.removed)return this;if(b==null){var d={};for(var e in this.attrs)this.attrs[f](e)&&(d[e]=this.attrs[e]);this._.rt.deg&&(d.rotation=this.rotate()),(this._.sx!=1||this._.sy!=1)&&(d.scale=this.scale()),d.gradient&&d.fill=="none"&&(d.fill=d.gradient)&&delete d.gradient;return d}if(c==null&&a.is(b,F)){if(b=="translation")return cB.call(this);if(b=="rotation")return this.rotate();if(b=="scale")return this.scale();if(b==I&&this.attrs.fill=="none"&&this.attrs.gradient)return this.attrs.gradient;return this.attrs[b]}if(c==null&&a.is(b,G)){var g={};for(var h=0,i=b.length;h<i;h++)g[b[h]]=this.attr(b[h]);return g}if(c!=null){var j={};j[b]=c}else b!=null&&a.is(b,"object")&&(j=b);for(var k in this.paper.customAttributes)if(this.paper.customAttributes[f](k)&&j[f](k)&&a.is(this.paper.customAttributes[k],"function")){var l=this.paper.customAttributes[k].apply(this,[][n](j[k]));this.attrs[k]=j[k];for(var m in l)l[f](m)&&(j[m]=l[m])}bL(this,j);return this},bO[e].toFront=function(){if(this.removed)return this;this.node.parentNode[l](this.node);var a=this.paper;a.top!=this&&bC(this,a);return this},bO[e].toBack=function(){if(this.removed)return this;if(this.node.parentNode.firstChild!=this.node){this.node.parentNode.insertBefore(this.node,this.node.parentNode.firstChild),bD(this,this.paper);var a=this.paper}return this},bO[e].insertAfter=function(a){if(this.removed)return this;var b=a.node||a[a.length-1].node;b.nextSibling?b.parentNode.insertBefore(this.node,b.nextSibling):b.parentNode[l](this.node),bE(this,a,this.paper);return this},bO[e].insertBefore=function(a){if(this.removed)return this;var b=a.node||a[0].node;b.parentNode.insertBefore(this.node,b),bF(this,a,this.paper);return this},bO[e].blur=function(a){var b=this;if(+a!==0){var c=bH("filter"),d=bH("feGaussianBlur");b.attrs.blur=a,c.id=bi(),bH(d,{stdDeviation:+a||1.5}),c.appendChild(d),b.paper.defs.appendChild(c),b._blur=c,bH(b.node,{filter:"url(#"+c.id+")"})}else b._blur&&(b._blur.parentNode.removeChild(b._blur),delete b._blur,delete b.attrs.blur),b.node.removeAttribute("filter")};var bQ=function(a,b,c,d){var e=bH("circle");a.canvas&&a.canvas[l](e);var f=new bO(e,a);f.attrs={cx:b,cy:c,r:d,fill:"none",stroke:"#000"},f.type="circle",bH(e,f.attrs);return f},bR=function(a,b,c,d,e,f){var g=bH("rect");a.canvas&&a.canvas[l](g);var h=new bO(g,a);h.attrs={x:b,y:c,width:d,height:e,r:f||0,rx:f||0,ry:f||0,fill:"none",stroke:"#000"},h.type="rect",bH(g,h.attrs);return h},bS=function(a,b,c,d,e){var f=bH("ellipse");a.canvas&&a.canvas[l](f);var g=new bO(f,a);g.attrs={cx:b,cy:c,rx:d,ry:e,fill:"none",stroke:"#000"},g.type="ellipse",bH(f,g.attrs);return g},bT=function(a,b,c,d,e,f){var g=bH("image");bH(g,{x:c,y:d,width:e,height:f,preserveAspectRatio:"none"}),g.setAttributeNS(a.xlink,"href",b),a.canvas&&a.canvas[l](g);var h=new bO(g,a);h.attrs={x:c,y:d,width:e,height:f,src:b},h.type="image";return h},bU=function(a,b,c,d){var e=bH("text");bH(e,{x:b,y:c,"text-anchor":"middle"}),a.canvas&&a.canvas[l](e);var f=new bO(e,a);f.attrs={x:b,y:c,"text-anchor":"middle",text:d,font:X.font,stroke:"none",fill:"#000"},f.type="text",bL(f,f.attrs);return f},bV=function(a,b){this.width=a||this.width,this.height=b||this.height,this.canvas[R]("width",this.width),this.canvas[R]("height",this.height);return this},bW=function(){var b=bz[m](0,arguments),c=b&&b.container,d=b.x,e=b.y,f=b.width,h=b.height;if(!c)throw new Error("SVG container not found.");var i=bH("svg");d=d||0,e=e||0,f=f||512,h=h||342,bH(i,{xmlns:"http://www.w3.org/2000/svg",version:1.1,width:f,height:h}),c==1?(i.style.cssText="position:absolute;left:"+d+"px;top:"+e+"px",g.body[l](i)):c.firstChild?c.insertBefore(i,c.firstChild):c[l](i),c=new j,c.width=f,c.height=h,c.canvas=i,bA.call(c,c,a.fn),c.clear();return c};k.clear=function(){var a=this.canvas;while(a.firstChild)a.removeChild(a.firstChild);this.bottom=this.top=null,(this.desc=bH("desc"))[l](g.createTextNode("Created with Raphaël")),a[l](this.desc),a[l](this.defs=bH("defs"))},k.remove=function(){this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas);for(var a in this)this[a]=bG(a)}}if(a.vml){var bX={M:"m",L:"l",C:"c",Z:"x",m:"t",l:"r",c:"v",z:"x"},bY=/([clmz]),?([^clmz]*)/gi,bZ=/ progid:\S+Blur\([^\)]+\)/g,b$=/-?[^,\s-]+/g,b_=1e3+q+1e3,ca=10,cb={path:1,rect:1},cc=function(a){var b=/[ahqstv]/ig,c=br;r(a).match(b)&&(c=bx),b=/[clmz]/g;if(c==br&&!r(a).match(b)){var d=r(a)[Z](bY,function(a,b,c){var d=[],e=x.call(b)=="m",f=bX[b];c[Z](b$,function(a){e&&d[w]==2&&(f+=d+bX[b=="m"?"l":"L"],d=[]),d[L](Q(a*ca))});return f+d});return d}var e=c(a),f,g;d=[];for(var h=0,i=e[w];h<i;h++){f=e[h],g=x.call(e[h][0]),g=="z"&&(g="x");for(var j=1,k=f[w];j<k;j++)g+=Q(f[j]*ca)+(j!=k-1?",":p);d[L](g)}return d[v](q)};a[H]=function(){return"Your browser doesn’t support SVG. Falling down to VML.\nYou are running Raphaël "+this.version},bI=function(a,b){var c=ce("group");c.style.cssText="position:absolute;left:0;top:0;width:"+b.width+"px;height:"+b.height+"px",c.coordsize=b.coordsize,c.coordorigin=b.coordorigin;var d=ce("shape"),e=d.style;e.width=b.width+"px",e.height=b.height+"px",d.coordsize=b_,d.coordorigin=b.coordorigin,c[l](d);var f=new bO(d,c,b),g={fill:"none",stroke:"#000"};a&&(g.path=a),f.type="path",f.path=[],f.Path=p,bL(f,g),b.canvas[l](c);return f},bL=function(c,d){c.attrs=c.attrs||{};var e=c.node,h=c.attrs,i=e.style,j,k=(d.x!=h.x||d.y!=h.y||d.width!=h.width||d.height!=h.height||d.r!=h.r)&&c.type=="rect",m=c;for(var n in d)d[f](n)&&(h[n]=d[n]);k&&(h.path=cd(h.x,h.y,h.width,h.height,h.r),c.X=h.x,c.Y=h.y,c.W=h.width,c.H=h.height),d.href&&(e.href=d.href),d.title&&(e.title=d.title),d.target&&(e.target=d.target),d.cursor&&(i.cursor=d.cursor),"blur"in d&&c.blur(d.blur);if(d.path&&c.type=="path"||k)e.path=cc(h.path);d.rotation!=null&&c.rotate(d.rotation,!0),d.translation&&(j=r(d.translation)[s](b),cB.call(c,j[0],j[1]),c._.rt.cx!=null&&(c._.rt.cx+=+j[0],c._.rt.cy+=+j[1],c.setBox(c.attrs,j[0],j[1]))),d.scale&&(j=r(d.scale)[s](b),c.scale(+j[0]||1,+j[1]||+j[0]||1,+j[2]||null,+j[3]||null));if("clip-rect"in d){var o=r(d["clip-rect"])[s](b);if(o[w]==4){o[2]=+o[2]+ +o[0],o[3]=+o[3]+ +o[1];var q=e.clipRect||g.createElement("div"),t=q.style,u=e.parentNode;t.clip=a.format("rect({1}px {2}px {3}px {0}px)",o),e.clipRect||(t.position="absolute",t.top=0,t.left=0,t.width=c.paper.width+"px",t.height=c.paper.height+"px",u.parentNode.insertBefore(q,u),q[l](u),e.clipRect=q)}d["clip-rect"]||e.clipRect&&(e.clipRect.style.clip=p)}c.type=="image"&&d.src&&(e.src=d.src),c.type=="image"&&d.opacity&&(e.filterOpacity=U+".Alpha(opacity="+d.opacity*100+")",i.filter=(e.filterMatrix||p)+(e.filterOpacity||p)),d.font&&(i.font=d.font),d["font-family"]&&(i.fontFamily='"'+d["font-family"][s](",")[0][Z](/^['"]+|['"]+$/g,p)+'"'),d["font-size"]&&(i.fontSize=d["font-size"]),d["font-weight"]&&(i.fontWeight=d["font-weight"]),d["font-style"]&&(i.fontStyle=d["font-style"]);if(d.opacity!=null||d["stroke-width"]!=null||d.fill!=null||d.stroke!=null||d["stroke-width"]!=null||d["stroke-opacity"]!=null||d["fill-opacity"]!=null||d["stroke-dasharray"]!=null||d["stroke-miterlimit"]!=null||d["stroke-linejoin"]!=null||d["stroke-linecap"]!=null){e=c.shape||e;var v=e.getElementsByTagName(I)&&e.getElementsByTagName(I)[0],x=!1;!v&&(x=v=ce(I));if("fill-opacity"in d||"opacity"in d){var y=((+h["fill-opacity"]+1||2)-1)*((+h.opacity+1||2)-1)*((+a.getRGB(d.fill).o+1||2)-1);y=A(z(y,0),1),v.opacity=y}d.fill&&(v.on=!0);if(v.on==null||d.fill=="none")v.on=!1;if(v.on&&d.fill){var B=d.fill.match(M);B?(v.src=B[1],v.type="tile"):(v.color=a.getRGB(d.fill).hex,v.src=p,v.type="solid",a.getRGB(d.fill).error&&(m.type in{circle:1,ellipse:1}||r(d.fill).charAt()!="r")&&bJ(m,d.fill)&&(h.fill="none",h.gradient=d.fill))}x&&e[l](v);var C=e.getElementsByTagName("stroke")&&e.getElementsByTagName("stroke")[0],D=!1;!C&&(D=C=ce("stroke"));if(d.stroke&&d.stroke!="none"||d["stroke-width"]||d["stroke-opacity"]!=null||d["stroke-dasharray"]||d["stroke-miterlimit"]||d["stroke-linejoin"]||d["stroke-linecap"])C.on=!0;(d.stroke=="none"||C.on==null||d.stroke==0||d["stroke-width"]==0)&&(C.on=!1);var E=a.getRGB(d.stroke);C.on&&d.stroke&&(C.color=E.hex),y=((+h["stroke-opacity"]+1||2)-1)*((+h.opacity+1||2)-1)*((+E.o+1||2)-1);var F=(S(d["stroke-width"])||1)*.75;y=A(z(y,0),1),d["stroke-width"]==null&&(F=h["stroke-width"]),d["stroke-width"]&&(C.weight=F),F&&F<1&&(y*=F)&&(C.weight=1),C.opacity=y,d["stroke-linejoin"]&&(C.joinstyle=d["stroke-linejoin"]||"miter"),C.miterlimit=d["stroke-miterlimit"]||8,d["stroke-linecap"]&&(C.endcap=d["stroke-linecap"]=="butt"?"flat":d["stroke-linecap"]=="square"?"square":"round");if(d["stroke-dasharray"]){var G={"-":"shortdash",".":"shortdot","-.":"shortdashdot","-..":"shortdashdotdot",". ":"dot","- ":"dash","--":"longdash","- .":"dashdot","--.":"longdashdot","--..":"longdashdotdot"};C.dashstyle=G[f](d["stroke-dasharray"])?G[d["stroke-dasharray"]]:p}D&&e[l](C)}if(m.type=="text"){i=m.paper.span.style,h.font&&(i.font=h.font),h["font-family"]&&(i.fontFamily=h["font-family"]),h["font-size"]&&(i.fontSize=h["font-size"]),h["font-weight"]&&(i.fontWeight=h["font-weight"]),h["font-style"]&&(i.fontStyle=h["font-style"]),m.node.string&&(m.paper.span.innerHTML=r(m.node.string)[Z](/</g,"&#60;")[Z](/&/g,"&#38;")[Z](/\n/g,"<br>")),m.W=h.w=m.paper.span.offsetWidth,m.H=h.h=m.paper.span.offsetHeight,m.X=h.x,m.Y=h.y+Q(m.H/2);switch(h["text-anchor"]){case"start":m.node.style["v-text-align"]="left",m.bbx=Q(m.W/2);break;case"end":m.node.style["v-text-align"]="right",m.bbx=-Q(m.W/2);break;default:m.node.style["v-text-align"]="center"}}},bJ=function(a,b){a.attrs=a.attrs||{};var c=a.attrs,d,e="linear",f=".5 .5";a.attrs.gradient=b,b=r(b)[Z](be,function(a,b,c){e="radial",b&&c&&(b=S(b),c=S(c),C(b-.5,2)+C(c-.5,2)>.25&&(c=y.sqrt(.25-C(b-.5,2))*((c>.5)*2-1)+.5),f=b+q+c);return p}),b=b[s](/\s*\-\s*/);if(e=="linear"){var g=b.shift();g=-S(g);if(isNaN(g))return null}var h=by(b);if(!h)return null;a=a.shape||a.node,d=a.getElementsByTagName(I)[0]||ce(I),!d.parentNode&&a.appendChild(d);if(h[w]){d.on=!0,d.method="none",d.color=h[0].color,d.color2=h[h[w]-1].color;var i=[];for(var j=0,k=h[w];j<k;j++)h[j].offset&&i[L](h[j].offset+q+h[j].color);d.colors&&(d.colors.value=i[w]?i[v]():"0% "+d.color),e=="radial"?(d.type="gradientradial",d.focus="100%",d.focussize=f,d.focusposition=f):(d.type="gradient",d.angle=(270-g)%360)}return 1},bO=function(b,c,d){var e=0,f=0,g=0,h=1;this[0]=b,this.id=a._oid++,this.node=b,b.raphael=this,this.X=0,this.Y=0,this.attrs={},this.Group=c,this.paper=d,this._={tx:0,ty:0,rt:{deg:0},sx:1,sy:1},!d.bottom&&(d.bottom=this),this.prev=d.top,d.top&&(d.top.next=this),d.top=this,this.next=null},bP=bO[e],bP.rotate=function(a,c,d){if(this.removed)return this;if(a==null){if(this._.rt.cx)return[this._.rt.deg,this._.rt.cx,this._.rt.cy][v](q);return this._.rt.deg}a=r(a)[s](b),a[w]-1&&(c=S(a[1]),d=S(a[2])),a=S(a[0]),c!=null?this._.rt.deg=a:this._.rt.deg+=a,d==null&&(c=null),this._.rt.cx=c,this._.rt.cy=d,this.setBox(this.attrs,c,d),this.Group.style.rotation=this._.rt.deg;return this},bP.setBox=function(a,b,c){if(this.removed)return this;var d=this.Group.style,e=this.shape&&this.shape.style||this.node.style;a=a||{};for(var g in a)a[f](g)&&(this.attrs[g]=a[g]);b=b||this._.rt.cx,c=c||this._.rt.cy;var h=this.attrs,i,j,k,l;switch(this.type){case"circle":i=h.cx-h.r,j=h.cy-h.r,k=l=h.r*2;break;case"ellipse":i=h.cx-h.rx,j=h.cy-h.ry,k=h.rx*2,l=h.ry*2;break;case"image":i=+h.x,j=+h.y,k=h.width||0,l=h.height||0;break;case"text":this.textpath.v=["m",Q(h.x),", ",Q(h.y-2),"l",Q(h.x)+1,", ",Q(h.y-2)][v](p),i=h.x-Q(this.W/2),j=h.y-this.H/2,k=this.W,l=this.H;break;case"rect":case"path":if(!this.attrs.path)i=0,j=0,k=this.paper.width,l=this.paper.height;else{var m=bo(this.attrs.path);i=m.x,j=m.y,k=m.width,l=m.height}break;default:i=0,j=0,k=this.paper.width,l=this.paper.height}b=b==null?i+k/2:b,c=c==null?j+l/2:c;var n=b-this.paper.width/2,o=c-this.paper.height/2,q;d.left!=(q=n+"px")&&(d.left=q),d.top!=(q=o+"px")&&(d.top=q),this.X=cb[f](this.type)?-n:i,this.Y=cb[f](this.type)?-o:j,this.W=k,this.H=l,cb[f](this.type)?(e.left!=(q=-n*ca+"px")&&(e.left=q),e.top!=(q=-o*ca+"px")&&(e.top=q)):this.type=="text"?(e.left!=(q=-n+"px")&&(e.left=q),e.top!=(q=-o+"px")&&(e.top=q)):(d.width!=(q=this.paper.width+"px")&&(d.width=q),d.height!=(q=this.paper.height+"px")&&(d.height=q),e.left!=(q=i-n+"px")&&(e.left=q),e.top!=(q=j-o+"px")&&(e.top=q),e.width!=(q=k+"px")&&(e.width=q),e.height!=(q=l+"px")&&(e.height=q))},bP.hide=function(){!this.removed&&(this.Group.style.display="none");return this},bP.show=function(){!this.removed&&(this.Group.style.display="block");return this},bP.getBBox=function(){if(this.removed)return this;if(cb[f](this.type))return bo(this.attrs.path);return{x:this.X+(this.bbx||0),y:this.Y,width:this.W,height:this.H}},bP.remove=function(){if(!this.removed){bB(this,this.paper),this.node.parentNode.removeChild(this.node),this.Group.parentNode.removeChild(this.Group),this.shape&&this.shape.parentNode.removeChild(this.shape);for(var a in this)delete this[a];this.removed=!0}},bP.attr=function(b,c){if(this.removed)return this;if(b==null){var d={};for(var e in this.attrs)this.attrs[f](e)&&(d[e]=this.attrs[e]);this._.rt.deg&&(d.rotation=this.rotate()),(this._.sx!=1||this._.sy!=1)&&(d.scale=this.scale()),d.gradient&&d.fill=="none"&&(d.fill=d.gradient)&&delete d.gradient;return d}if(c==null&&a.is(b,"string")){if(b=="translation")return cB.call(this);if(b=="rotation")return this.rotate();if(b=="scale")return this.scale();if(b==I&&this.attrs.fill=="none"&&this.attrs.gradient)return this.attrs.gradient;return this.attrs[b]}if(this.attrs&&c==null&&a.is(b,G)){var g,h={};for(e=0,g=b[w];e<g;e++)h[b[e]]=this.attr(b[e]);return h}var i;c!=null&&(i={},i[b]=c),c==null&&a.is(b,"object")&&(i=b);if(i){for(var j in this.paper.customAttributes)if(this.paper.customAttributes[f](j)&&i[f](j)&&a.is(this.paper.customAttributes[j],"function")){var k=this.paper.customAttributes[j].apply(this,[][n](i[j]));this.attrs[j]=i[j];for(var l in k)k[f](l)&&(i[l]=k[l])}i.text&&this.type=="text"&&(this.node.string=i.text),bL(this,i),i.gradient&&(({circle:1,ellipse:1})[f](this.type)||r(i.gradient).charAt()!="r")&&bJ(this,i.gradient),(!cb[f](this.type)||this._.rt.deg)&&this.setBox(this.attrs)}return this},bP.toFront=function(){!this.removed&&this.Group.parentNode[l](this.Group),this.paper.top!=this&&bC(this,this.paper);return this},bP.toBack=function(){if(this.removed)return this;this.Group.parentNode.firstChild!=this.Group&&(this.Group.parentNode.insertBefore(this.Group,this.Group.parentNode.firstChild),bD(this,this.paper));return this},bP.insertAfter=function(a){if(this.removed)return this;a.constructor==cE&&(a=a[a.length-1]),a.Group.nextSibling?a.Group.parentNode.insertBefore(this.Group,a.Group.nextSibling):a.Group.parentNode[l](this.Group),bE(this,a,this.paper);return this},bP.insertBefore=function(a){if(this.removed)return this;a.constructor==cE&&(a=a[0]),a.Group.parentNode.insertBefore(this.Group,a.Group),bF(this,a,this.paper);return this},bP.blur=function(b){var c=this.node.runtimeStyle,d=c.filter;d=d.replace(bZ,p),+b!==0?(this.attrs.blur=b,c.filter=d+q+U+".Blur(pixelradius="+(+b||1.5)+")",c.margin=a.format("-{0}px 0 0 -{0}px",Q(+b||1.5))):(c.filter=d,c.margin=0,delete this.attrs.blur)},bQ=function(a,b,c,d){var e=ce("group"),f=ce("oval"),g=f.style;e.style.cssText="position:absolute;left:0;top:0;width:"+a.width+"px;height:"+a.height+"px",e.coordsize=b_,e.coordorigin=a.coordorigin,e[l](f);var h=new bO(f,e,a);h.type="circle",bL(h,{stroke:"#000",fill:"none"}),h.attrs.cx=b,h.attrs.cy=c,h.attrs.r=d,h.setBox({x:b-d,y:c-d,width:d*2,height:d*2}),a.canvas[l](e);return h};function cd(b,c,d,e,f){return f?a.format("M{0},{1}l{2},0a{3},{3},0,0,1,{3},{3}l0,{5}a{3},{3},0,0,1,{4},{3}l{6},0a{3},{3},0,0,1,{4},{4}l0,{7}a{3},{3},0,0,1,{3},{4}z",b+f,c,d-f*2,f,-f,e-f*2,f*2-d,f*2-e):a.format("M{0},{1}l{2},0,0,{3},{4},0z",b,c,d,e,-d)}bR=function(a,b,c,d,e,f){var g=cd(b,c,d,e,f),h=a.path(g),i=h.attrs;h.X=i.x=b,h.Y=i.y=c,h.W=i.width=d,h.H=i.height=e,i.r=f,i.path=g,h.type="rect";return h},bS=function(a,b,c,d,e){var f=ce("group"),g=ce("oval"),h=g.style;f.style.cssText="position:absolute;left:0;top:0;width:"+a.width+"px;height:"+a.height+"px",f.coordsize=b_,f.coordorigin=a.coordorigin,f[l](g);var i=new bO(g,f,a);i.type="ellipse",bL(i,{stroke:"#000"}),i.attrs.cx=b,i.attrs.cy=c,i.attrs.rx=d,i.attrs.ry=e,i.setBox({x:b-d,y:c-e,width:d*2,height:e*2}),a.canvas[l](f);return i},bT=function(a,b,c,d,e,f){var g=ce("group"),h=ce("image");g.style.cssText="position:absolute;left:0;top:0;width:"+a.width+"px;height:"+a.height+"px",g.coordsize=b_,g.coordorigin=a.coordorigin,h.src=b,g[l](h);var i=new bO(h,g,a);i.type="image",i.attrs.src=b,i.attrs.x=c,i.attrs.y=d,i.attrs.w=e,i.attrs.h=f,i.setBox({x:c,y:d,width:e,height:f}),a.canvas[l](g);return i},bU=function(b,c,d,e){var f=ce("group"),g=ce("shape"),h=g.style,i=ce("path"),j=i.style,k=ce("textpath");f.style.cssText="position:absolute;left:0;top:0;width:"+b.width+"px;height:"+b.height+"px",f.coordsize=b_,f.coordorigin=b.coordorigin,i.v=a.format("m{0},{1}l{2},{1}",Q(c*10),Q(d*10),Q(c*10)+1),i.textpathok=!0,h.width=b.width,h.height=b.height,k.string=r(e),k.on=!0,g[l](k),g[l](i),f[l](g);var m=new bO(k,f,b);m.shape=g,m.textpath=i,m.type="text",m.attrs.text=e,m.attrs.x=c,m.attrs.y=d,m.attrs.w=1,m.attrs.h=1,bL(m,{font:X.font,stroke:"none",fill:"#000"}),m.setBox(),b.canvas[l](f);return m},bV=function(a,b){var c=this.canvas.style;a==+a&&(a+="px"),b==+b&&(b+="px"),c.width=a,c.height=b,c.clip="rect(0 "+a+" "+b+" 0)";return this};var ce;g.createStyleSheet().addRule(".rvml","behavior:url(#default#VML)");try{!g.namespaces.rvml&&g.namespaces.add("rvml","urn:schemas-microsoft-com:vml"),ce=function(a){return g.createElement("<rvml:"+a+' class="rvml">')}}catch(cf){ce=function(a){return g.createElement("<"+a+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}bW=function(){var b=bz[m](0,arguments),c=b.container,d=b.height,e,f=b.width,h=b.x,i=b.y;if(!c)throw new Error("VML container not found.");var k=new j,n=k.canvas=g.createElement("div"),o=n.style;h=h||0,i=i||0,f=f||512,d=d||342,f==+f&&(f+="px"),d==+d&&(d+="px"),k.width=1e3,k.height=1e3,k.coordsize=ca*1e3+q+ca*1e3,k.coordorigin="0 0",k.span=g.createElement("span"),k.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;",n[l](k.span),o.cssText=a.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden",f,d),c==1?(g.body[l](n),o.left=h+"px",o.top=i+"px",o.position="absolute"):c.firstChild?c.insertBefore(n,c.firstChild):c[l](n),bA.call(k,k,a.fn);return k},k.clear=function(){this.canvas.innerHTML=p,this.span=g.createElement("span"),this.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;",this.canvas[l](this.span),this.bottom=this.top=null},k.remove=function(){this.canvas.parentNode.removeChild(this.canvas);for(var a in this)this[a]=bG(a);return!0}}var cg=navigator.userAgent.match(/Version\/(.*?)\s/);navigator.vendor=="Apple Computer, Inc."&&(cg&&cg[1]<4||navigator.platform.slice(0,2)=="iP")?k.safari=function(){var a=this.rect(-99,-99,this.width+99,this.height+99).attr({stroke:"none"});h.setTimeout(function(){a.remove()})}:k.safari=function(){};var ch=function(){this.returnValue=!1},ci=function(){return this.originalEvent.preventDefault()},cj=function(){this.cancelBubble=!0},ck=function(){return this.originalEvent.stopPropagation()},cl=function(){if(g.addEventListener)return function(a,b,c,d){var e=o&&u[b]?u[b]:b,g=function(e){if(o&&u[f](b))for(var g=0,h=e.targetTouches&&e.targetTouches.length;g<h;g++)if(e.targetTouches[g].target==a){var i=e;e=e.targetTouches[g],e.originalEvent=i,e.preventDefault=ci,e.stopPropagation=ck;break}return c.call(d,e)};a.addEventListener(e,g,!1);return function(){a.removeEventListener(e,g,!1);return!0}};if(g.attachEvent)return function(a,b,c,d){var e=function(a){a=a||h.event,a.preventDefault=a.preventDefault||ch,a.stopPropagation=a.stopPropagation||cj;return c.call(d,a)};a.attachEvent("on"+b,e);var f=function(){a.detachEvent("on"+b,e);return!0};return f}}(),cm=[],cn=function(a){var b=a.clientX,c=a.clientY,d=g.documentElement.scrollTop||g.body.scrollTop,e=g.documentElement.scrollLeft||g.body.scrollLeft,f,h=cm.length;while(h--){f=cm[h];if(o){var i=a.touches.length,j;while(i--){j=a.touches[i];if(j.identifier==f.el._drag.id){b=j.clientX,c=j.clientY,(a.originalEvent?a.originalEvent:a).preventDefault();break}}}else a.preventDefault();b+=e,c+=d,f.move&&f.move.call(f.move_scope||f.el,b-f.el._drag.x,c-f.el._drag.y,b,c,a)}},co=function(b){a.unmousemove(cn).unmouseup(co);var c=cm.length,d;while(c--)d=cm[c],d.el._drag={},d.end&&d.end.call(d.end_scope||d.start_scope||d.move_scope||d.el,b);cm=[]};for(var cp=t[w];cp--;)(function(b){a[b]=bO[e][b]=function(c,d){a.is(c,"function")&&(this.events=this.events||[],this.events.push({name:b,f:c,unbind:cl(this.shape||this.node||g,b,c,d||this)}));return this},a["un"+b]=bO[e]["un"+b]=function(a){var c=this.events,d=c[w];while(d--)if(c[d].name==b&&c[d].f==a){c[d].unbind(),c.splice(d,1),!c.length&&delete this.events;return this}return this}})(t[cp]);bP.hover=function(a,b,c,d){return this.mouseover(a,c).mouseout(b,d||c)},bP.unhover=function(a,b){return this.unmouseover(a).unmouseout(b)},bP.drag=function(b,c,d,e,f,h){this._drag={},this.mousedown(function(i){(i.originalEvent||i).preventDefault();var j=g.documentElement.scrollTop||g.body.scrollTop,k=g.documentElement.scrollLeft||g.body.scrollLeft;this._drag.x=i.clientX+k,this._drag.y=i.clientY+j,this._drag.id=i.identifier,c&&c.call(f||e||this,i.clientX+k,i.clientY+j,i),!cm.length&&a.mousemove(cn).mouseup(co),cm.push({el:this,move:b,end:d,move_scope:e,start_scope:f,end_scope:h})});return this},bP.undrag=function(b,c,d){var e=cm.length;while(e--)cm[e].el==this&&cm[e].move==b&&cm[e].end==d&&cm.splice(e++,1);!cm.length&&a.unmousemove(cn).unmouseup(co)},k.circle=function(a,b,c){return bQ(this,a||0,b||0,c||0)},k.rect=function(a,b,c,d,e){return bR(this,a||0,b||0,c||0,d||0,e||0)},k.ellipse=function(a,b,c,d){return bS(this,a||0,b||0,c||0,d||0)},k.path=function(b){b&&!a.is(b,F)&&!a.is(b[0],G)&&(b+=p);return bI(a.format[m](a,arguments),this)},k.image=function(a,b,c,d,e){return bT(this,a||"about:blank",b||0,c||0,d||0,e||0)},k.text=function(a,b,c){return bU(this,a||0,b||0,r(c))},k.set=function(a){arguments[w]>1&&(a=Array[e].splice.call(arguments,0,arguments[w]));return new cE(a)},k.setSize=bV,k.top=k.bottom=null,k.raphael=a,bP.resetScale=function(){if(this.removed)return this;this._.sx=1,this._.sy=1,this.attrs.scale="1 1"},bP.scale=function(a,b,c,d){if(this.removed)return this;if(a==null&&b==null)return{x:this._.sx,y:this._.sy,toString:cq};b=b||a,!+b&&(b=a);var e,f,g,h,i=this.attrs;if(a!=0){var j=this.getBBox(),k=j.x+j.width/2,l=j.y+j.height/2,m=B(a/this._.sx),o=B(b/this._.sy);c=+c||c==0?c:k,d=+d||d==0?d:l;var r=this._.sx>0,s=this._.sy>0,t=~~(a/B(a)),u=~~(b/B(b)),x=m*t,y=o*u,z=this.node.style,A=c+B(k-c)*x*(k>c==r?1:-1),C=d+B(l-d)*y*(l>d==s?1:-1),D=a*t>b*u?o:m;switch(this.type){case"rect":case"image":var E=i.width*m,F=i.height*o;this.attr({height:F,r:i.r*D,width:E,x:A-E/2,y:C-F/2});break;case"circle":case"ellipse":this.attr({rx:i.rx*m,ry:i.ry*o,r:i.r*D,cx:A,cy:C});break;case"text":this.attr({x:A,y:C});break;case"path":var G=bq(i.path),H=!0,I=r?x:m,J=s?y:o;for(var K=0,L=G[w];K<L;K++){var M=G[K],N=W.call(M[0]);if(N=="M"&&H)continue;H=!1;if(N=="A")M[G[K][w]-2]*=I,M[G[K][w]-1]*=J,M[1]*=m,M[2]*=o,M[5]=+(t+u?!!+M[5]:!+M[5]);else if(N=="H")for(var O=1,P=M[w];O<P;O++)M[O]*=I;else if(N=="V")for(O=1,P=M[w];O<P;O++)M[O]*=J;else for(O=1,P=M[w];O<P;O++)M[O]*=O%2?I:J}var Q=bo(G);e=A-Q.x-Q.width/2,f=C-Q.y-Q.height/2,G[0][1]+=e,G[0][2]+=f,this.attr({path:G})}this.type in{text:1,image:1}&&(t!=1||u!=1)?this.transformations?(this.transformations[2]="scale("[n](t,",",u,")"),this.node[R]("transform",this.transformations[v](q)),e=t==-1?-i.x-(E||0):i.x,f=u==-1?-i.y-(F||0):i.y,this.attr({x:e,y:f}),i.fx=t-1,i.fy=u-1):(this.node.filterMatrix=U+".Matrix(M11="[n](t,", M12=0, M21=0, M22=",u,", Dx=0, Dy=0, sizingmethod='auto expand', filtertype='bilinear')"),z.filter=(this.node.filterMatrix||p)+(this.node.filterOpacity||p)):this.transformations?(this.transformations[2]=p,this.node[R]("transform",this.transformations[v](q)),i.fx=0,i.fy=0):(this.node.filterMatrix=p,z.filter=(this.node.filterMatrix||p)+(this.node.filterOpacity||p)),i.scale=[a,b,c,d][v](q),this._.sx=a,this._.sy=b}return this},bP.clone=function(){if(this.removed)return null;var a=this.attr();delete a.scale,delete a.translation;return this.paper[this.type]().attr(a)};var cr={},cs=function(b,c,d,e,f,g,h,i,j){var k=0,l=100,m=[b,c,d,e,f,g,h,i].join(),n=cr[m],o,p;!n&&(cr[m]=n={data:[]}),n.timer&&clearTimeout(n.timer),n.timer=setTimeout(function(){delete cr[m]},2e3);if(j!=null){var q=cs(b,c,d,e,f,g,h,i);l=~~q*10}for(var r=0;r<l+1;r++){n.data[j]>r?p=n.data[r*l]:(p=a.findDotsAtSegment(b,c,d,e,f,g,h,i,r/l),n.data[r]=p),r&&(k+=C(C(o.x-p.x,2)+C(o.y-p.y,2),.5));if(j!=null&&k>=j)return p;o=p}if(j==null)return k},ct=function(b,c){return function(d,e,f){d=bx(d);var g,h,i,j,k="",l={},m,n=0;for(var o=0,p=d.length;o<p;o++){i=d[o];if(i[0]=="M")g=+i[1],h=+i[2];else{j=cs(g,h,i[1],i[2],i[3],i[4],i[5],i[6]);if(n+j>e){if(c&&!l.start){m=cs(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n),k+=["C",m.start.x,m.start.y,m.m.x,m.m.y,m.x,m.y];if(f)return k;l.start=k,k=["M",m.x,m.y+"C",m.n.x,m.n.y,m.end.x,m.end.y,i[5],i[6]][v](),n+=j,g=+i[5],h=+i[6];continue}if(!b&&!c){m=cs(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n);return{x:m.x,y:m.y,alpha:m.alpha}}}n+=j,g=+i[5],h=+i[6]}k+=i}l.end=k,m=b?n:c?l:a.findDotsAtSegment(g,h,i[1],i[2],i[3],i[4],i[5],i[6],1),m.alpha&&(m={x:m.x,y:m.y,alpha:m.alpha});return m}},cu=ct(1),cv=ct(),cw=ct(0,1);bP.getTotalLength=function(){if(this.type=="path"){if(this.node.getTotalLength)return this.node.getTotalLength();return cu(this.attrs.path)}},bP.getPointAtLength=function(a){if(this.type=="path")return cv(this.attrs.path,a)},bP.getSubpath=function(a,b){if(this.type=="path"){if(B(this.getTotalLength()-b)<"1e-6")return cw(this.attrs.path,a).end;var c=cw(this.attrs.path,b,1);return a?cw(c,a).end:c}},a.easing_formulas={linear:function(a){return a},"<":function(a){return C(a,3)},">":function(a){return C(a-1,3)+1},"<>":function(a){a=a*2;if(a<1)return C(a,3)/2;a-=2;return(C(a,3)+2)/2},backIn:function(a){var b=1.70158;return a*a*((b+1)*a-b)},backOut:function(a){a=a-1;var b=1.70158;return a*a*((b+1)*a+b)+1},elastic:function(a){if(a==0||a==1)return a;var b=.3,c=b/4;return C(2,-10*a)*y.sin((a-c)*2*D/b)+1},bounce:function(a){var b=7.5625,c=2.75,d;a<1/c?d=b*a*a:a<2/c?(a-=1.5/c,d=b*a*a+.75):a<2.5/c?(a-=2.25/c,d=b*a*a+.9375):(a-=2.625/c,d=b*a*a+.984375);return d}};var cx=[],cy=function(){var b=+(new Date);for(var c=0;c<cx[w];c++){var d=cx[c];if(d.stop||d.el.removed)continue;var e=b-d.start,g=d.ms,h=d.easing,i=d.from,j=d.diff,k=d.to,l=d.t,m=d.el,n={},o;if(e<g){var r=h(e/g);for(var s in i)if(i[f](s)){switch(Y[s]){case"along":o=r*g*j[s],k.back&&(o=k.len-o);var t=cv(k[s],o);m.translate(j.sx-j.x||0,j.sy-j.y||0),j.x=t.x,j.y=t.y,m.translate(t.x-j.sx,t.y-j.sy),k.rot&&m.rotate(j.r+t.alpha,t.x,t.y);break;case E:o=+i[s]+r*g*j[s];break;case"colour":o="rgb("+[cA(Q(i[s].r+r*g*j[s].r)),cA(Q(i[s].g+r*g*j[s].g)),cA(Q(i[s].b+r*g*j[s].b))][v](",")+")";break;case"path":o=[];for(var u=0,x=i[s][w];u<x;u++){o[u]=[i[s][u][0]];for(var y=1,z=i[s][u][w];y<z;y++)o[u][y]=+i[s][u][y]+r*g*j[s][u][y];o[u]=o[u][v](q)}o=o[v](q);break;case"csv":switch(s){case"translation":var A=r*g*j[s][0]-l.x,B=r*g*j[s][1]-l.y;l.x+=A,l.y+=B,o=A+q+B;break;case"rotation":o=+i[s][0]+r*g*j[s][0],i[s][1]&&(o+=","+i[s][1]+","+i[s][2]);break;case"scale":o=[+i[s][0]+r*g*j[s][0],+i[s][1]+r*g*j[s][1],2 in k[s]?k[s][2]:p,3 in k[s]?k[s][3]:p][v](q);break;case"clip-rect":o=[],u=4;while(u--)o[u]=+i[s][u]+r*g*j[s][u]}break;default:var C=[].concat(i[s]);o=[],u=m.paper.customAttributes[s].length;while(u--)o[u]=+C[u]+r*g*j[s][u]}n[s]=o}m.attr(n),m._run&&m._run.call(m)}else k.along&&(t=cv(k.along,k.len*!k.back),m.translate(j.sx-(j.x||0)+t.x-j.sx,j.sy-(j.y||0)+t.y-j.sy),k.rot&&m.rotate(j.r+t.alpha,t.x,t.y)),(l.x||l.y)&&m.translate(-l.x,-l.y),k.scale&&(k.scale+=p),m.attr(k),cx.splice(c--,1)}a.svg&&m&&m.paper&&m.paper.safari(),cx[w]&&setTimeout(cy)},cz=function(b,c,d,e,f){var g=d-e;c.timeouts.push(setTimeout(function(){a.is(f,"function")&&f.call(c),c.animate(b,g,b.easing)},e))},cA=function(a){return z(A(a,255),0)},cB=function(a,b){if(a==null)return{x:this._.tx,y:this._.ty,toString:cq};this._.tx+=+a,this._.ty+=+b;switch(this.type){case"circle":case"ellipse":this.attr({cx:+a+this.attrs.cx,cy:+b+this.attrs.cy});break;case"rect":case"image":case"text":this.attr({x:+a+this.attrs.x,y:+b+this.attrs.y});break;case"path":var c=bq(this.attrs.path);c[0][1]+=+a,c[0][2]+=+b,this.attr({path:c})}return this};bP.animateWith=function(a,b,c,d,e){for(var f=0,g=cx.length;f<g;f++)cx[f].el.id==a.id&&(b.start=cx[f].start);return this.animate(b,c,d,e)},bP.animateAlong=cC(),bP.animateAlongBack=cC(1),bP.onAnimation=function(a){this._run=a||0;return this},bP.animate=function(c,d,e,g){var h=this;h.timeouts=h.timeouts||[];if(a.is(e,"function")||!e)g=e||null;if(h.removed){g&&g.call(h);return h}var i={},j={},k=!1,l={};for(var m in c)if(c[f](m))if(Y[f](m)||h.paper.customAttributes[f](m)){k=!0,i[m]=h.attr(m),i[m]==null&&(i[m]=X[m]),j[m]=c[m];switch(Y[m]){case"along":var n=cu(c[m]),o=cv(c[m],n*!!c.back),p=h.getBBox();l[m]=n/d,l.tx=p.x,l.ty=p.y,l.sx=o.x,l.sy=o.y,j.rot=c.rot,j.back=c.back,j.len=n,c.rot&&(l.r=S(h.rotate())||0);break;case E:l[m]=(j[m]-i[m])/d;break;case"colour":i[m]=a.getRGB(i[m]);var q=a.getRGB(j[m]);l[m]={r:(q.r-i[m].r)/d,g:(q.g-i[m].g)/d,b:(q.b-i[m].b)/d};break;case"path":var t=bx(i[m],j[m]);i[m]=t[0];var u=t[1];l[m]=[];for(var v=0,x=i[m][w];v<x;v++){l[m][v]=[0];for(var y=1,z=i[m][v][w];y<z;y++)l[m][v][y]=(u[v][y]-i[m][v][y])/d}break;case"csv":var A=r(c[m])[s](b),B=r(i[m])[s](b);switch(m){case"translation":i[m]=[0,0],l[m]=[A[0]/d,A[1]/d];break;case"rotation":i[m]=B[1]==A[1]&&B[2]==A[2]?B:[0,A[1],A[2]],l[m]=[(A[0]-i[m][0])/d,0,0];break;case"scale":c[m]=A,i[m]=r(i[m])[s](b),l[m]=[(A[0]-i[m][0])/d,(A[1]-i[m][1])/d,0,0];break;case"clip-rect":i[m]=r(i[m])[s](b),l[m]=[],v=4;while(v--)l[m][v]=(A[v]-i[m][v])/d}j[m]=A;break;default:A=[].concat(c[m]),B=[].concat(i[m]),l[m]=[],v=h.paper.customAttributes[m][w];while(v--)l[m][v]=((A[v]||0)-(B[v]||0))/d}}if(!k){var C=[],D;for(var F in c)c[f](F)&&$.test(F)&&(m={value:c[F]},F=="from"&&(F=0),F=="to"&&(F=100),m.key=T(F,10),C.push(m));C.sort(bf),C[0].key&&C.unshift({key:0,value:h.attrs});for(v=0,x=C[w];v<x;v++)cz(C[v].value,h,d/100*C[v].key,d/100*(C[v-1]&&C[v-1].key||0),C[v-1]&&C[v-1].value.callback);D=C[C[w]-1].value.callback,D&&h.timeouts.push(setTimeout(function(){D.call(h)},d))}else{var G=a.easing_formulas[e];if(!G){G=r(e).match(P);if(G&&G[w]==5){var H=G;G=function(a){return cD(a,+H[1],+H[2],+H[3],+H[4],d)}}else G=function(a){return a}}cx.push({start:c.start||+(new Date),ms:d,easing:G,from:i,diff:l,to:j,el:h,t:{x:0,y:0}}),a.is(g,"function")&&(h._ac=setTimeout(function(){g.call(h)},d)),cx[w]==1&&setTimeout(cy)}return this},bP.stop=function(){for(var a=0;a<cx.length;a++)cx[a].el.id==this.id&&cx.splice(a--,1);for(a=0,ii=this.timeouts&&this.timeouts.length;a<ii;a++)clearTimeout(this.timeouts[a]);this.timeouts=[],clearTimeout(this._ac),delete this._ac;return this},bP.translate=function(a,b){return this.attr({translation:a+" "+b})},bP[H]=function(){return"Raphaël’s object"},a.ae=cx;var cE=function(a){this.items=[],this[w]=0,this.type="set";if(a)for(var b=0,c=a[w];b<c;b++)a[b]&&(a[b].constructor==bO||a[b].constructor==cE)&&(this[this.items[w]]=this.items[this.items[w]]=a[b],this[w]++)};cE[e][L]=function(){var a,b;for(var c=0,d=arguments[w];c<d;c++)a=arguments[c],a&&(a.constructor==bO||a.constructor==cE)&&(b=this.items[w],this[b]=this.items[b]=a,this[w]++);return this},cE[e].pop=function(){delete this[this[w]--];return this.items.pop()};for(var cF in bP)bP[f](cF)&&(cE[e][cF]=function(a){return function(){for(var b=0,c=this.items[w];b<c;b++)this.items[b][a][m](this.items[b],arguments);return this}}(cF));cE[e].attr=function(b,c){if(b&&a.is(b,G)&&a.is(b[0],"object"))for(var d=0,e=b[w];d<e;d++)this.items[d].attr(b[d]);else for(var f=0,g=this.items[w];f<g;f++)this.items[f].attr(b,c);return this},cE[e].animate=function(b,c,d,e){(a.is(d,"function")||!d)&&(e=d||null);var f=this.items[w],g=f,h,i=this,j;e&&(j=function(){!--f&&e.call(i)}),d=a.is(d,F)?d:j,h=this.items[--g].animate(b,c,d,j);while(g--)this.items[g]&&!this.items[g].removed&&this.items[g].animateWith(h,b,c,d,j);return this},cE[e].insertAfter=function(a){var b=this.items[w];while(b--)this.items[b].insertAfter(a);return this},cE[e].getBBox=function(){var a=[],b=[],c=[],d=[];for(var e=this.items[w];e--;){var f=this.items[e].getBBox();a[L](f.x),b[L](f.y),c[L](f.x+f.width),d[L](f.y+f.height)}a=A[m](0,a),b=A[m](0,b);return{x:a,y:b,width:z[m](0,c)-a,height:z[m](0,d)-b}},cE[e].clone=function(a){a=new cE;for(var b=0,c=this.items[w];b<c;b++)a[L](this.items[b].clone());return a},a.registerFont=function(a){if(!a.face)return a;this.fonts=this.fonts||{};var b={w:a.w,face:{},glyphs:{}},c=a.face["font-family"];for(var d in a.face)a.face[f](d)&&(b.face[d]=a.face[d]);this.fonts[c]?this.fonts[c][L](b):this.fonts[c]=[b];if(!a.svg){b.face["units-per-em"]=T(a.face["units-per-em"],10);for(var e in a.glyphs)if(a.glyphs[f](e)){var g=a.glyphs[e];b.glyphs[e]={w:g.w,k:{},d:g.d&&"M"+g.d[Z](/[mlcxtrv]/g,function(a){return({l:"L",c:"C",x:"z",t:"m",r:"l",v:"c"})[a]||"M"})+"z"};if(g.k)for(var h in g.k)g[f](h)&&(b.glyphs[e].k[h]=g.k[h])}}return a},k.getFont=function(b,c,d,e){e=e||"normal",d=d||"normal",c=+c||({normal:400,bold:700,lighter:300,bolder:800})[c]||400;if(!!a.fonts){var g=a.fonts[b];if(!g){var h=new RegExp("(^|\\s)"+b[Z](/[^\w\d\s+!~.:_-]/g,p)+"(\\s|$)","i");for(var i in a.fonts)if(a.fonts[f](i)&&h.test(i)){g=a.fonts[i];break}}var j;if(g)for(var k=0,l=g[w];k<l;k++){j=g[k];if(j.face["font-weight"]==c&&(j.face["font-style"]==d||!j.face["font-style"])&&j.face["font-stretch"]==e)break}return j}},k.print=function(c,d,e,f,g,h,i){h=h||"middle",i=z(A(i||0,1),-1);var j=this.set(),k=r(e)[s](p),l=0,m=p,n;a.is(f,e)&&(f=this.getFont(f));if(f){n=(g||16)/f.face["units-per-em"];var o=f.face.bbox.split(b),q=+o[0],t=+o[1]+(h=="baseline"?o[3]-o[1]+ +f.face.descent:(o[3]-o[1])/2);for(var u=0,v=k[w];u<v;u++){var x=u&&f.glyphs[k[u-1]]||{},y=f.glyphs[k[u]];l+=u?(x.w||f.w)+(x.k&&x.k[k[u]]||0)+f.w*i:0,y&&y.d&&j[L](this.path(y.d).attr({fill:"#000",stroke:"none",translation:[l,0]}))}j.scale(n,n,q,t).translate(c-q,d-t)}return j},a.format=function(b,c){var e=a.is(c,G)?[0][n](c):arguments;b&&a.is(b,F)&&e[w]-1&&(b=b[Z](d,function(a,b){return e[++b]==null?p:e[b]}));return b||p},a.ninja=function(){i.was?h.Raphael=i.is:delete Raphael;return a},a.el=bP,a.st=cE[e],i.was?h.Raphael=a:Raphael=a})()
if(window.Raphael){Raphael.shadow=function(K,J,L,F,Q){Q=Q||{};var B=jQuery(Q.target),N=jQuery("<div/>",{"class":"aui-shadow"}),A=Q.shadow||Q.color||"#000",P=Q.size*10||0,O=Q.offsetSize||3,M=Q.zindex||0,H=Q.radius||0,G="0.4",D=Q.blur||3,C,I,E;L+=P+2*D;F+=P+2*D;if(Raphael.shadow.BOX_SHADOW_SUPPORT){B.addClass("aui-box-shadow");return N.addClass("hidden")}if(K===0&&J===0&&B.length>0){E=B.offset();K=O-D+E.left;J=O-D+E.top}if(jQuery.browser.msie&&jQuery.browser.version<"9"){A="#f0f0f0";G="0.2"}N.css({position:"absolute",left:K,top:J,width:L,height:F,zIndex:M});if(B.length>0){N.appendTo(document.body);C=Raphael(N[0],L,F,H)}else{C=Raphael(K,J,L,F,H)}C.canvas.style.position="absolute";I=C.rect(D,D,L-2*D,F-2*D).attr({fill:A,stroke:A,blur:""+D,opacity:G});return N};Raphael.shadow.BOX_SHADOW_SUPPORT=(function(){var C=document.documentElement.style;var A=["boxShadow","MozBoxShadow","WebkitBoxShadow","msBoxShadow"];for(var B=0;B<A.length;B++){if(A[B] in C){return true}}return false})()};
(function(a,b){function ci(a){return d.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cf(a){if(!b_[a]){var b=d("<"+a+">").appendTo("body"),c=b.css("display");b.remove();if(c==="none"||c==="")c="block";b_[a]=c}return b_[a]}function ce(a,b){var c={};d.each(cd.concat.apply([],cd.slice(0,b)),function(){c[this]=a});return c}function b$(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function bZ(){try{return new a.XMLHttpRequest}catch(b){}}function bY(){d(a).unload(function(){for(var a in bW)bW[a](0,1)})}function bS(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var e=a.dataTypes,f={},g,h,i=e.length,j,k=e[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(f[h.toLowerCase()]=a.converters[h]);l=k,k=e[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=f[m]||f["* "+k];if(!n){p=b;for(o in f){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=f[j[1]+" "+k];if(p){o=f[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&d.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bR(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function bQ(a,b,c,e){if(d.isArray(b)&&b.length)d.each(b,function(b,f){c||bs.test(a)?e(a,f):bQ(a+"["+(typeof f=="object"||d.isArray(f)?b:"")+"]",f,c,e)});else if(!c&&b!=null&&typeof b=="object")if(d.isArray(b)||d.isEmptyObject(b))e(a,"");else for(var f in b)bQ(a+"["+f+"]",b[f],c,e);else e(a,b)}function bP(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bJ,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bP(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bP(a,c,d,e,"*",g));return l}function bO(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(d.isFunction(c)){var e=b.toLowerCase().split(bD),f=0,g=e.length,h,i,j;for(;f<g;f++)h=e[f],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bq(a,b,c){var e=b==="width"?bk:bl,f=b==="width"?a.offsetWidth:a.offsetHeight;if(c==="border")return f;d.each(e,function(){c||(f-=parseFloat(d.css(a,"padding"+this))||0),c==="margin"?f+=parseFloat(d.css(a,"margin"+this))||0:f-=parseFloat(d.css(a,"border"+this+"Width"))||0});return f}function bc(a,b){b.src?d.ajax({url:b.src,async:!1,dataType:"script"}):d.globalEval(b.text||b.textContent||b.innerHTML||""),b.parentNode&&b.parentNode.removeChild(b)}function bb(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function ba(a,b){if(b.nodeType===1){var c=b.nodeName.toLowerCase();b.clearAttributes(),b.mergeAttributes(a);if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(d.expando)}}function _(a,b){if(b.nodeType===1&&!!d.hasData(a)){var c=d.expando,e=d.data(a),f=d.data(b,e);if(e=e[c]){var g=e.events;f=f[c]=d.extend({},e);if(g){delete f.handle,f.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)d.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function $(a,b){return d.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Q(a,b,c){if(d.isFunction(b))return d.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return d.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var e=d.grep(a,function(a){return a.nodeType===1});if(L.test(b))return d.filter(b,e,!c);b=d.filter(b,e)}return d.grep(a,function(a,e){return d.inArray(a,b)>=0===c})}function P(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function H(a,b){return(a&&a!=="*"?a+".":"")+b.replace(t,"`").replace(u,"&")}function G(a){var b,c,e,f,g,h,i,j,k,l,m,n,o,p=[],q=[],s=d._data(this,"events");if(!(a.liveFired===this||!s||!s.live||a.target.disabled||a.button&&a.type==="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var t=s.live.slice(0);for(i=0;i<t.length;i++)g=t[i],g.origType.replace(r,"")===a.type?q.push(g.selector):t.splice(i--,1);f=d(a.target).closest(q,a.currentTarget);for(j=0,k=f.length;j<k;j++){m=f[j];for(i=0;i<t.length;i++){g=t[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,e=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,e=d(a.relatedTarget).closest(g.selector)[0];(!e||e!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){f=p[j];if(c&&f.level>c)break;a.currentTarget=f.elem,a.data=f.handleObj.data,a.handleObj=f.handleObj,o=f.handleObj.origHandler.apply(f.elem,arguments);if(o===!1||a.isPropagationStopped()){c=f.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function E(a,c,e){var f=d.extend({},e[0]);f.type=a,f.originalEvent={},f.liveFired=b,d.event.handle.call(c,f),f.isDefaultPrevented()&&e[0].preventDefault()}function y(){return!0}function x(){return!1}function i(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function h(a,c,e){if(e===b&&a.nodeType===1){e=a.getAttribute("data-"+c);if(typeof e=="string"){try{e=e==="true"?!0:e==="false"?!1:e==="null"?null:d.isNaN(e)?g.test(e)?d.parseJSON(e):e:parseFloat(e)}catch(f){}d.data(a,c,e)}else e=b}return e}var c=a.document,d=function(){function G(){if(!d.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(G,1);return}d.ready()}}var d=function(a,b){return new d.fn.init(a,b,g)},e=a.jQuery,f=a.$,g,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,i=/\S/,j=/^\s+/,k=/\s+$/,l=/\d/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=navigator.userAgent,w,x,y,z=Object.prototype.toString,A=Object.prototype.hasOwnProperty,B=Array.prototype.push,C=Array.prototype.slice,D=String.prototype.trim,E=Array.prototype.indexOf,F={};d.fn=d.prototype={constructor:d,init:function(a,e,f){var g,i,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!e&&c.body){this.context=c,this[0]=c.body,this.selector="body",this.length=1;return this}if(typeof a=="string"){g=h.exec(a);if(g&&(g[1]||!e)){if(g[1]){e=e instanceof d?e[0]:e,k=e?e.ownerDocument||e:c,j=m.exec(a),j?d.isPlainObject(e)?(a=[c.createElement(j[1])],d.fn.attr.call(a,e,!0)):a=[k.createElement(j[1])]:(j=d.buildFragment([g[1]],[k]),a=(j.cacheable?d.clone(j.fragment):j.fragment).childNodes);return d.merge(this,a)}i=c.getElementById(g[2]);if(i&&i.parentNode){if(i.id!==g[2])return f.find(a);this.length=1,this[0]=i}this.context=c,this.selector=a;return this}return!e||e.jquery?(e||f).find(a):this.constructor(e).find(a)}if(d.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return d.makeArray(a,this)},selector:"",jquery:"1.5.2",length:0,size:function(){return this.length},toArray:function(){return C.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var e=this.constructor();d.isArray(a)?B.apply(e,a):d.merge(e,a),e.prevObject=this,e.context=this.context,b==="find"?e.selector=this.selector+(this.selector?" ":"")+c:b&&(e.selector=this.selector+"."+b+"("+c+")");return e},each:function(a,b){return d.each(this,a,b)},ready:function(a){d.bindReady(),x.done(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(C.apply(this,arguments),"slice",C.call(arguments).join(","))},map:function(a){return this.pushStack(d.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:B,sort:[].sort,splice:[].splice},d.fn.init.prototype=d.fn,d.extend=d.fn.extend=function(){var a,c,e,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!d.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){e=i[c],f=a[c];if(i===f)continue;l&&f&&(d.isPlainObject(f)||(g=d.isArray(f)))?(g?(g=!1,h=e&&d.isArray(e)?e:[]):h=e&&d.isPlainObject(e)?e:{},i[c]=d.extend(l,h,f)):f!==b&&(i[c]=f)}return i},d.extend({noConflict:function(b){a.$=f,b&&(a.jQuery=e);return d},isReady:!1,readyWait:1,ready:function(a){a===!0&&d.readyWait--;if(!d.readyWait||a!==!0&&!d.isReady){if(!c.body)return setTimeout(d.ready,1);d.isReady=!0;if(a!==!0&&--d.readyWait>0)return;x.resolveWith(c,[d]),d.fn.trigger&&d(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!x){x=d._Deferred();if(c.readyState==="complete")return setTimeout(d.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",y,!1),a.addEventListener("load",d.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",y),a.attachEvent("onload",d.ready);var b=!1;try{b=a.frameElement==null}catch(e){}c.documentElement.doScroll&&b&&G()}}},isFunction:function(a){return d.type(a)==="function"},isArray:Array.isArray||function(a){return d.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNaN:function(a){return a==null||!l.test(a)||isNaN(a)},type:function(a){return a==null?String(a):F[z.call(a)]||"object"},isPlainObject:function(a){if(!a||d.type(a)!=="object"||a.nodeType||d.isWindow(a))return!1;if(a.constructor&&!A.call(a,"constructor")&&!A.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a);return c===b||A.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=d.trim(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return a.JSON&&a.JSON.parse?a.JSON.parse(b):(new Function("return "+b))();d.error("Invalid JSON: "+b)},parseXML:function(b,c,e){a.DOMParser?(e=new DOMParser,c=e.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),e=c.documentElement,(!e||!e.nodeName||e.nodeName==="parsererror")&&d.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(a){if(a&&i.test(a)){var b=c.head||c.getElementsByTagName("head")[0]||c.documentElement,e=c.createElement("script");d.support.scriptEval()?e.appendChild(c.createTextNode(a)):e.text=a,b.insertBefore(e,b.firstChild),b.removeChild(e)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,e){var f,g=0,h=a.length,i=h===b||d.isFunction(a);if(e){if(i){for(f in a)if(c.apply(a[f],e)===!1)break}else for(;g<h;)if(c.apply(a[g++],e)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(var j=a[0];g<h&&c.call(j,g,j)!==!1;j=a[++g]);return a},trim:D?function(a){return a==null?"":D.call(a)}:function(a){return a==null?"":a.toString().replace(j,"").replace(k,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var e=d.type(a);a.length==null||e==="string"||e==="function"||e==="regexp"||d.isWindow(a)?B.call(c,a):d.merge(c,a)}return c},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,b,c){var d=[],e;for(var f=0,g=a.length;f<g;f++)e=b(a[f],f,c),e!=null&&(d[d.length]=e);return d.concat.apply([],d)},guid:1,proxy:function(a,c,e){arguments.length===2&&(typeof c=="string"?(e=a,a=e[c],c=b):c&&!d.isFunction(c)&&(e=c,c=b)),!c&&a&&(c=function(){return a.apply(e||this,arguments)}),a&&(c.guid=a.guid=a.guid||c.guid||d.guid++);return c},access:function(a,c,e,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)d.access(a,j,c[j],f,g,e);return a}if(e!==b){f=!h&&f&&d.isFunction(e);for(var k=0;k<i;k++)g(a[k],c,f?e.call(a[k],k,g(a[k],c)):e,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}d.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.subclass=this.subclass,a.fn.init=function(b,c){c&&c instanceof d&&!(c instanceof a)&&(c=a(c));return d.fn.init.call(this,b,c,e)},a.fn.init.prototype=a.fn;var e=a(c);return a},browser:{}}),d.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){F["[object "+b+"]"]=b.toLowerCase()}),w=d.uaMatch(v),w.browser&&(d.browser[w.browser]=!0,d.browser.version=w.version),d.browser.webkit&&(d.browser.safari=!0),E&&(d.inArray=function(a,b){return E.call(b,a)}),i.test("\u00a0")&&(j=/^[\s\xA0]+/,k=/[\s\xA0]+$/),g=d(c),c.addEventListener?y=function(){c.removeEventListener("DOMContentLoaded",y,!1),d.ready()}:c.attachEvent&&(y=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",y),d.ready())});return d}(),e="then done fail isResolved isRejected promise".split(" "),f=[].slice;d.extend({_Deferred:function(){var a=[],b,c,e,f={done:function(){if(!e){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=d.type(i),j==="array"?f.done.apply(f,i):j==="function"&&a.push(i);k&&f.resolveWith(k[0],k[1])}return this},resolveWith:function(d,f){if(!e&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(d,f)}finally{b=[d,f],c=0}}return this},resolve:function(){f.resolveWith(this,arguments);return this},isResolved:function(){return!!c||!!b},cancel:function(){e=1,a=[];return this}};return f},Deferred:function(a){var b=d._Deferred(),c=d._Deferred(),f;d.extend(b,{then:function(a,c){b.done(a).fail(c);return this},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,promise:function(a){if(a==null){if(f)return f;f=a={}}var c=e.length;while(c--)a[e[c]]=b[e[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){function i(a){return function(c){b[a]=arguments.length>1?f.call(arguments,0):c,--g||h.resolveWith(h,f.call(b,0))}}var b=arguments,c=0,e=b.length,g=e,h=e<=1&&a&&d.isFunction(a.promise)?a:d.Deferred();if(e>1){for(;c<e;c++)b[c]&&d.isFunction(b[c].promise)?b[c].promise().then(i(c),h.reject):--g;g||h.resolveWith(h,b)}else h!==a&&h.resolveWith(h,e?[a]:[]);return h.promise()}}),function(){d.support={};var b=c.createElement("div");b.style.display="none",b.innerHTML="   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=b.getElementsByTagName("*"),f=b.getElementsByTagName("a")[0],g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=b.getElementsByTagName("input")[0];if(!(!e||!e.length||!f)){d.support={leadingWhitespace:b.firstChild.nodeType===3,tbody:!b.getElementsByTagName("tbody").length,htmlSerialize:!!b.getElementsByTagName("link").length,style:/red/.test(f.getAttribute("style")),hrefNormalized:f.getAttribute("href")==="/a",opacity:/^0.55$/.test(f.style.opacity),cssFloat:!!f.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,deleteExpando:!0,optDisabled:!1,checkClone:!1,noCloneEvent:!0,noCloneChecked:!0,boxModel:null,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableHiddenOffsets:!0,reliableMarginRight:!0},i.checked=!0,d.support.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,d.support.optDisabled=!h.disabled;var j=null;d.support.scriptEval=function(){if(j===null){var b=c.documentElement,e=c.createElement("script"),f="script"+d.now();try{e.appendChild(c.createTextNode("window."+f+"=1;"))}catch(g){}b.insertBefore(e,b.firstChild),a[f]?(j=!0,delete a[f]):j=!1,b.removeChild(e)}return j};try{delete b.test}catch(k){d.support.deleteExpando=!1}!b.addEventListener&&b.attachEvent&&b.fireEvent&&(b.attachEvent("onclick",function l(){d.support.noCloneEvent=!1,b.detachEvent("onclick",l)}),b.cloneNode(!0).fireEvent("onclick")),b=c.createElement("div"),b.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";var m=c.createDocumentFragment();m.appendChild(b.firstChild),d.support.checkClone=m.cloneNode(!0).cloneNode(!0).lastChild.checked,d(function(){var a=c.createElement("div"),b=c.getElementsByTagName("body")[0];if(!!b){a.style.width=a.style.paddingLeft="1px",b.appendChild(a),d.boxModel=d.support.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,d.support.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",d.support.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";var e=a.getElementsByTagName("td");d.support.reliableHiddenOffsets=e[0].offsetHeight===0,e[0].style.display="",e[1].style.display="none",d.support.reliableHiddenOffsets=d.support.reliableHiddenOffsets&&e[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(a.style.width="1px",a.style.marginRight="0",d.support.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(a,null)||{marginRight:0}).marginRight,10)||0)===0),b.removeChild(a).style.display="none",a=e=null}});var n=function(a){var b=c.createElement("div");a="on"+a;if(!b.attachEvent)return!0;var d=a in b;d||(b.setAttribute(a,"return;"),d=typeof b[a]=="function");return d};d.support.submitBubbles=n("submit"),d.support.changeBubbles=n("change"),b=e=f=null}}();var g=/^(?:\{.*\}|\[.*\])$/;d.extend({cache:{},uuid:0,expando:"jQuery"+(d.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?d.cache[a[d.expando]]:a[d.expando];return!!a&&!i(a)},data:function(a,c,e,f){if(!!d.acceptData(a)){var g=d.expando,h=typeof c=="string",i,j=a.nodeType,k=j?d.cache:a,l=j?a[d.expando]:a[d.expando]&&d.expando;if((!l||f&&l&&!k[l][g])&&h&&e===b)return;l||(j?a[d.expando]=l=++d.uuid:l=d.expando),k[l]||(k[l]={},j||(k[l].toJSON=d.noop));if(typeof c=="object"||typeof c=="function")f?k[l][g]=d.extend(k[l][g],c):k[l]=d.extend(k[l],c);i=k[l],f&&(i[g]||(i[g]={}),i=i[g]),e!==b&&(i[c]=e);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[c]:i}},removeData:function(a,b,c){if(!!d.acceptData(a)){var e=d.expando,f=a.nodeType,g=f?d.cache:a,h=f?a[d.expando]:d.expando;if(!g[h])return;if(b){var j=c?g[h][e]:g[h];if(j){delete j[b];if(!i(j))return}}if(c){delete g[h][e];if(!i(g[h]))return}var k=g[h][e];d.support.deleteExpando||!d.isWindow(g)?delete g[h]:g[h]=null,k?(g[h]={},f||(g[h].toJSON=d.noop),g[h][e]=k):f&&(d.support.deleteExpando?delete a[d.expando]:a.removeAttribute?a.removeAttribute(d.expando):a[d.expando]=null)}},_data:function(a,b,c){return d.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=d.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),d.fn.extend({data:function(a,c){var e=null;if(typeof a=="undefined"){if(this.length){e=d.data(this[0]);if(this[0].nodeType===1){var f=this[0].attributes,g;for(var i=0,j=f.length;i<j;i++)g=f[i].name,g.indexOf("data-")===0&&(g=g.substr(5),h(this[0],g,e[g]))}}return e}if(typeof a=="object")return this.each(function(){d.data(this,a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(c===b){e=this.triggerHandler("getData"+k[1]+"!",[k[0]]),e===b&&this.length&&(e=d.data(this[0],a),e=h(this[0],a,e));return e===b&&k[1]?this.data(k[0]):e}return this.each(function(){var b=d(this),e=[k[0],c];b.triggerHandler("setData"+k[1]+"!",e),d.data(this,a,c),b.triggerHandler("changeData"+k[1]+"!",e)})},removeData:function(a){return this.each(function(){d.removeData(this,a)})}}),d.extend({queue:function(a,b,c){if(!!a){b=(b||"fx")+"queue";var e=d._data(a,b);if(!c)return e||[];!e||d.isArray(c)?e=d._data(a,b,d.makeArray(c)):e.push(c);return e}},dequeue:function(a,b){b=b||"fx";var c=d.queue(a,b),e=c.shift();e==="inprogress"&&(e=c.shift()),e&&(b==="fx"&&c.unshift("inprogress"),e.call(a,function(){d.dequeue(a,b)})),c.length||d.removeData(a,b+"queue",!0)}}),d.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return d.queue(this[0],a);return this.each(function(b){var e=d.queue(this,a,c);a==="fx"&&e[0]!=="inprogress"&&d.dequeue(this,a)})},dequeue:function(a){return this.each(function(){d.dequeue(this,a)})},delay:function(a,b){a=d.fx?d.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){d.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var j=/[\n\t\r]/g,k=/\s+/,l=/\r/g,m=/^(?:href|src|style)$/,n=/^(?:button|input)$/i,o=/^(?:button|input|object|select|textarea)$/i,p=/^a(?:rea)?$/i,q=/^(?:radio|checkbox)$/i;d.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"},d.fn.extend({attr:function(a,b){return d.access(this,a,b,!0,d.attr)},removeAttr:function(a,b){return this.each(function(){d.attr(this,a,""),this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.addClass(a.call(this,b,c.attr("class")))});if(a&&typeof a=="string"){var b=(a||"").split(k);for(var c=0,e=this.length;c<e;c++){var f=this[c];if(f.nodeType===1)if(!f.className)f.className=a;else{var g=" "+f.className+" ",h=f.className;for(var i=0,j=b.length;i<j;i++)g.indexOf(" "+b[i]+" ")<0&&(h+=" "+b[i]);f.className=d.trim(h)}}}return this},removeClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.removeClass(a.call(this,b,c.attr("class")))});if(a&&typeof a=="string"||a===b){var c=(a||"").split(k);for(var e=0,f=this.length;e<f;e++){var g=this[e];if(g.nodeType===1&&g.className)if(a){var h=(" "+g.className+" ").replace(j," ");for(var i=0,l=c.length;i<l;i++)h=h.replace(" "+c[i]+" "," ");g.className=d.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,e=typeof b=="boolean";if(d.isFunction(a))return this.each(function(c){var e=d(this);e.toggleClass(a.call(this,c,e.attr("class"),b),b)});return this.each(function(){if(c==="string"){var f,g=0,h=d(this),i=b,j=a.split(k);while(f=j[g++])i=e?i:!h.hasClass(f),h[i?"addClass":"removeClass"](f)}else if(c==="undefined"||c==="boolean")this.className&&d._data(this,"__className__",this.className),this.className=this.className||a===!1?"":d._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(j," ").indexOf(b)>-1)return!0;return!1},val:function(a){if(!arguments.length){var c=this[0];if(c){if(d.nodeName(c,"option")){var e=c.attributes.value;return!e||e.specified?c.value:c.text}if(d.nodeName(c,"select")){var f=c.selectedIndex,g=[],h=c.options,i=c.type==="select-one";if(f<0)return null;for(var j=i?f:0,k=i?f+1:h.length;j<k;j++){var m=h[j];if(m.selected&&(d.support.optDisabled?!m.disabled:m.getAttribute("disabled")===null)&&(!m.parentNode.disabled||!d.nodeName(m.parentNode,"optgroup"))){a=d(m).val();if(i)return a;g.push(a)}}if(i&&!g.length&&h.length)return d(h[f]).val();return g}if(q.test(c.type)&&!d.support.checkOn)return c.getAttribute("value")===null?"on":c.value;return(c.value||"").replace(l,"")}return b}var n=d.isFunction(a);return this.each(function(b){var c=d(this),e=a;if(this.nodeType===1){n&&(e=a.call(this,b,c.val())),e==null?e="":typeof e=="number"?e+="":d.isArray(e)&&(e=d.map(e,function(a){return a==null?"":a+""}));if(d.isArray(e)&&q.test(this.type))this.checked=d.inArray(c.val(),e)>=0;else if(d.nodeName(this,"select")){var f=d.makeArray(e);d("option",this).each(function(){this.selected=d.inArray(d(this).val(),f)>=0}),f.length||(this.selectedIndex=-1)}else this.value=e}})}}),d.extend({attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,e,f){if(!a||a.nodeType===3||a.nodeType===8||a.nodeType===2)return b;if(f&&c in d.attrFn)return d(a)[c](e);var g=a.nodeType!==1||!d.isXMLDoc(a),h=e!==b;c=g&&d.props[c]||c;if(a.nodeType===1){var i=m.test(c);if(c==="selected"&&!d.support.optSelected){var j=a.parentNode;j&&(j.selectedIndex,j.parentNode&&j.parentNode.selectedIndex)}if((c in a||a[c]!==b)&&g&&!i){h&&(c==="type"&&n.test(a.nodeName)&&a.parentNode&&d.error("type property can't be changed"),e===null?a.nodeType===1&&a.removeAttribute(c):a[c]=e);if(d.nodeName(a,"form")&&a.getAttributeNode(c))return a.getAttributeNode(c).nodeValue;if(c==="tabIndex"){var k=a.getAttributeNode("tabIndex");return k&&k.specified?k.value:o.test(a.nodeName)||p.test(a.nodeName)&&a.href?0:b}return a[c]}if(!d.support.style&&g&&c==="style"){h&&(a.style.cssText=""+e);return a.style.cssText}h&&a.setAttribute(c,""+e);if(!a.attributes[c]&&a.hasAttribute&&!a.hasAttribute(c))return b;var l=!d.support.hrefNormalized&&g&&i?a.getAttribute(c,2):a.getAttribute(c);return l===null?b:l}h&&(a[c]=e);return a[c]}});var r=/\.(.*)$/,s=/^(?:textarea|input|select)$/i,t=/\./g,u=/ /g,v=/[^\w\s.|`]/g,w=function(a){return a.replace(v,"\\$&")};d.event={add:function(c,e,f,g){if(c.nodeType!==3&&c.nodeType!==8){try{d.isWindow(c)&&c!==a&&!c.frameElement&&(c=a)}catch(h){}if(f===!1)f=x;else if(!f)return;var i,j;f.handler&&(i=f,f=i.handler),f.guid||(f.guid=d.guid++);var k=d._data(c);if(!k)return;var l=k.events,m=k.handle;l||(k.events=l={}),m||(k.handle=m=function(a){return typeof d!="undefined"&&d.event.triggered!==a.type?d.event.handle.apply(m.elem,arguments):b}),m.elem=c,e=e.split(" ");var n,o=0,p;while(n=e[o++]){j=i?d.extend({},i):{handler:f,data:g},n.indexOf(".")>-1?(p=n.split("."),n=p.shift(),j.namespace=p.slice(0).sort().join(".")):(p=[],j.namespace=""),j.type=n,j.guid||(j.guid=f.guid);var q=l[n],r=d.event.special[n]||{};if(!q){q=l[n]=[];if(!r.setup||r.setup.call(c,g,p,m)===!1)c.addEventListener?c.addEventListener(n,m,!1):c.attachEvent&&c.attachEvent("on"+n,m)}r.add&&(r.add.call(c,j),j.handler.guid||(j.handler.guid=f.guid)),q.push(j),d.event.global[n]=!0}c=null}},global:{},remove:function(a,c,e,f){if(a.nodeType!==3&&a.nodeType!==8){e===!1&&(e=x);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=d.hasData(a)&&d._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(e=c.handler,c=c.type);if(!c||typeof c=="string"&&c.charAt(0)==="."){c=c||"";for(h in t)d.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+d.map(m.slice(0).sort(),w).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!e){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))d.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=d.event.special[h]||{};for(j=f||0;j<p.length;j++){q=p[j];if(e.guid===q.guid){if(l||n.test(q.namespace))f==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(f!=null)break}}if(p.length===0||f!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&d.removeEvent(a,h,s.handle),g=null,delete t[h]}if(d.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,d.isEmptyObject(s)&&d.removeData(a,b,!0)}}},trigger:function(a,c,e){var f=a.type||a,g=arguments[3];if(!g){a=typeof a=="object"?a[d.expando]?a:d.extend(d.Event(f),a):d.Event(f),f.indexOf("!")>=0&&(a.type=f=f.slice(0,-1),a.exclusive=!0),e||(a.stopPropagation(),d.event.global[f]&&d.each(d.cache,function(){var b=d.expando,e=this[b];e&&e.events&&e.events[f]&&d.event.trigger(a,c,e.handle.elem)}));if(!e||e.nodeType===3||e.nodeType===8)return b;a.result=b,a.target=e,c=d.makeArray(c),c.unshift(a)}a.currentTarget=e;var h=d._data(e,"handle");h&&h.apply(e,c);var i=e.parentNode||e.ownerDocument;try{e&&e.nodeName&&d.noData[e.nodeName.toLowerCase()]||e["on"+f]&&e["on"+f].apply(e,c)===!1&&(a.result=!1,a.preventDefault())}catch(j){}if(!a.isPropagationStopped()&&i)d.event.trigger(a,c,i,!0);else if(!a.isDefaultPrevented()){var k,l=a.target,m=f.replace(r,""),n=d.nodeName(l,"a")&&m==="click",o=d.event.special[m]||{};if((!o._default||o._default.call(e,a)===!1)&&!n&&!(l&&l.nodeName&&d.noData[l.nodeName.toLowerCase()])){try{l[m]&&(k=l["on"+m],k&&(l["on"+m]=null),d.event.triggered=a.type,l[m]())}catch(p){}k&&(l["on"+m]=k),d.event.triggered=b}}},handle:function(c){var e,f,g,h,i,j=[],k=d.makeArray(arguments);c=k[0]=d.event.fix(c||a.event),c.currentTarget=this,e=c.type.indexOf(".")<0&&!c.exclusive,e||(g=c.type.split("."),c.type=g.shift(),j=g.slice(0).sort(),h=new RegExp("(^|\\.)"+j.join("\\.(?:.*\\.)?")+"(\\.|$)")),c.namespace=c.namespace||j.join("."),i=d._data(this,"events"),f=(i||{})[c.type];if(i&&f){f=f.slice(0);for(var l=0,m=f.length;l<m;l++){var n=f[l];if(e||h.test(n.namespace)){c.handler=n.handler,c.data=n.data,c.handleObj=n;var o=n.handler.apply(this,k);o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[d.expando])return a;var e=a;a=d.Event(e);for(var f=this.props.length,g;f;)g=this.props[--f],a[g]=e[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=c.documentElement,i=c.body;a.pageX=a.clientX+(h&&h.scrollLeft||i&&i.scrollLeft||0)-(h&&h.clientLeft||i&&i.clientLeft||0),a.pageY=a.clientY+(h&&h.scrollTop||i&&i.scrollTop||0)-(h&&h.clientTop||i&&i.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:d.proxy,special:{ready:{setup:d.bindReady,teardown:d.noop},live:{add:function(a){d.event.add(this,H(a.origType,a.selector),d.extend({},a,{handler:G,guid:a.handler.guid}))},remove:function(a){d.event.remove(this,H(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){d.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},d.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},d.Event=function(a){if(!this.preventDefault)return new d.Event(a);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?y:x):this.type=a,this.timeStamp=d.now(),this[d.expando]=!0},d.Event.prototype={preventDefault:function(){this.isDefaultPrevented=y;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=y;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=y,this.stopPropagation()},isDefaultPrevented:x,isPropagationStopped:x,isImmediatePropagationStopped:x};var z=function(a){var b=a.relatedTarget;try{if(b&&b!==c&&!b.parentNode)return;while(b&&b!==this)b=b.parentNode;b!==this&&(a.type=a.data,d.event.handle.apply(this,arguments))}catch(e){}},A=function(a){a.type=a.data,d.event.handle.apply(this,arguments)};d.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){d.event.special[a]={setup:function(c){d.event.add(this,b,c&&c.selector?A:z,a)},teardown:function(a){d.event.remove(this,b,a&&a.selector?A:z)}}}),d.support.submitBubbles||(d.event.special.submit={setup:function(a,b){if(this.nodeName&&this.nodeName.toLowerCase()!=="form")d.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&d(b).closest("form").length&&E("submit",this,arguments)}),d.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&d(b).closest("form").length&&a.keyCode===13&&E("submit",this,arguments)});else return!1},teardown:function(a){d.event.remove(this,".specialSubmit")}});if(!d.support.changeBubbles){var B,C=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?d.map(a.options,function(a){return a.selected}).join("-"):"":a.nodeName.toLowerCase()==="select"&&(c=a.selectedIndex);return c},D=function D(a){var c=a.target,e,f;if(!!s.test(c.nodeName)&&!c.readOnly){e=d._data(c,"_change_data"),f=C(c),(a.type!=="focusout"||c.type!=="radio")&&d._data(c,"_change_data",f);if(e===b||f===e)return;if(e!=null||f)a.type="change",a.liveFired=b,d.event.trigger(a,arguments[1],c)}};d.event.special.change={filters:{focusout:D,beforedeactivate:D,click:function(a){var b=a.target,c=b.type;(c==="radio"||c==="checkbox"||b.nodeName.toLowerCase()==="select")&&D.call(this,a)},keydown:function(a){var b=a.target,c=b.type;(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&D.call(this,a)},beforeactivate:function(a){var b=a.target;d._data(b,"_change_data",C(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in B)d.event.add(this,c+".specialChange",B[c]);return s.test(this.nodeName)},teardown:function(a){d.event.remove(this,".specialChange");return s.test(this.nodeName)}},B=d.event.special.change.filters,B.focus=B.beforeactivate}c.addEventListener&&d.each({focus:"focusin",blur:"focusout"},function(a,b){function f(a){var c=d.event.fix(a);c.type=b,c.originalEvent={},d.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var e=0;d.event.special[b]={setup:function(){e++===0&&c.addEventListener(a,f,!0)},teardown:function(){--e===0&&c.removeEventListener(a,f,!0)}}}),d.each(["bind","one"],function(a,c){d.fn[c]=function(a,e,f){if(typeof a=="object"){for(var g in a)this[c](g,e,a[g],f);return this}if(d.isFunction(e)||e===!1)f=e,e=b;var h=c==="one"?d.proxy(f,function(a){d(this).unbind(a,h);return f.apply(this,arguments)}):f;if(a==="unload"&&c!=="one")this.one(a,e,f);else for(var i=0,j=this.length;i<j;i++)d.event.add(this[i],a,h,e);return this}}),d.fn.extend({unbind:function(a,b){if(typeof a=="object"&&!a.preventDefault)for(var c in a)this.unbind(c,a[c]);else for(var e=0,f=this.length;e<f;e++)d.event.remove(this[e],a,b);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){d.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var c=d.Event(a);c.preventDefault(),c.stopPropagation(),d.event.trigger(c,b,this[0]);return c.result}},toggle:function(a){var b=arguments,c=1;while(c<b.length)d.proxy(a,b[c++]);return this.click(d.proxy(a,function(e){var f=(d._data(this,"lastToggle"+a.guid)||0)%c;d._data(this,"lastToggle"+a.guid,f+1),e.preventDefault();return b[f].apply(this,arguments)||!1}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var F={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};d.each(["live","die"],function(a,c){d.fn[c]=function(a,e,f,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:d(this.context);if(typeof a=="object"&&!a.preventDefault){for(var o in a)n[c](o,e,a[o],m);return this}d.isFunction(e)&&(f=e,e=b),a=(a||"").split(" ");while((h=a[i++])!=null){j=r.exec(h),k="",j&&(k=j[0],h=h.replace(r,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,h==="focus"||h==="blur"?(a.push(F[h]+k),h=h+k):h=(F[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)d.event.add(n[p],"live."+H(h,m),{data:e,selector:m,handler:f,origType:h,origHandler:f,preType:l});else n.unbind("live."+H(h,m),f)}return this}}),d.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){d.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},d.attrFn&&(d.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,e,g){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(f.call(n)==="[object Array]")if(!u)e.push.apply(e,n);else if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&e.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&e.push(j[t]);else p(n,e);o&&(k(o,h,e,g),k.uniqueSort(e));return e};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(!f)g=o=!0;else if(f===!0)continue}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return"text"===c&&(b===c||b===null)},radio:function(a){return"radio"===a.type},checkbox:function(a){return"checkbox"===a.type},file:function(a){return"file"===a.type},password:function(a){return"password"===a.type},submit:function(a){return"submit"===a.type},image:function(a){return"image"===a.type},reset:function(a){return"reset"===a.type},button:function(a){return"button"===a.type||a.nodeName.toLowerCase()==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(f.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(a===b){g=!0;return 0}if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(e||!l.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return k(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};d.find=k,d.expr=k.selectors,d.expr[":"]=d.expr.filters,d.unique=k.uniqueSort,d.text=k.getText,d.isXMLDoc=k.isXML,d.contains=k.contains}();var I=/Until$/,J=/^(?:parents|prevUntil|prevAll)/,K=/,/,L=/^.[^:#\[\.,]*$/,M=Array.prototype.slice,N=d.expr.match.POS,O={children:!0,contents:!0,next:!0,prev:!0};d.fn.extend({find:function(a){var b=this.pushStack("","find",a),c=0;for(var e=0,f=this.length;e<f;e++){c=b.length,d.find(a,this[e],b);if(e>0)for(var g=c;g<b.length;g++)for(var h=0;h<c;h++)if(b[h]===b[g]){b.splice(g--,1);break}}return b},has:function(a){var b=d(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(d.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(Q(this,a,!1),"not",a)},filter:function(a){return this.pushStack(Q(this,a,!0),"filter",a)},is:function(a){return!!a&&d.filter(a,this).length>0},closest:function(a,b){var c=[],e,f,g=this[0];if(d.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(e=0,f=a.length;e<f;e++)i=a[e],j[i]||(j[i]=d.expr.match.POS.test(i)?d(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:d(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=N.test(a)?d(a,b||this.context):null;for(e=0,f=this.length;e<f;e++){g=this[e];while(g){if(l?l.index(g)>-1:d.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b)break}}c=c.length>1?d.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a||typeof a=="string")return d.inArray(this[0],a?d(a):this.parent().children());return d.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?d(a,b):d.makeArray(a),e=d.merge(this.get(),c);return this.pushStack(P(c[0])||P(e[0])?e:d.unique(e))},andSelf:function(){return this.add(this.prevObject)}}),d.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return d.dir(a,"parentNode")},parentsUntil:function(a,b,c){return d.dir(a,"parentNode",c)},next:function(a){return d.nth(a,2,"nextSibling")},prev:function(a){return d.nth(a,2,"previousSibling")},nextAll:function(a){return d.dir(a,"nextSibling")},prevAll:function(a){return d.dir(a,"previousSibling")},nextUntil:function(a,b,c){return d.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return d.dir(a,"previousSibling",c)},siblings:function(a){return d.sibling(a.parentNode.firstChild,a)},children:function(a){return d.sibling(a.firstChild)},contents:function(a){return d.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:d.makeArray(a.childNodes)}},function(a,b){d.fn[a]=function(c,e){var f=d.map(this,b,c),g=M.call(arguments);I.test(a)||(e=c),e&&typeof e=="string"&&(f=d.filter(e,f)),f=this.length>1&&!O[a]?d.unique(f):f,(this.length>1||K.test(e))&&J.test(a)&&(f=f.reverse());return this.pushStack(f,a,g.join(","))}}),d.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?d.find.matchesSelector(b[0],a)?[b[0]]:[]:d.find.matches(a,b)},dir:function(a,c,e){var f=[],g=a[c];while(g&&g.nodeType!==9&&(e===b||g.nodeType!==1||!d(g).is(e)))g.nodeType===1&&f.push(g),g=g[c];return f},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var R=/ jQuery\d+="(?:\d+|null)"/g,S=/^\s+/,T=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,U=/<([\w:]+)/,V=/<tbody/i,W=/<|&#?\w+;/,X=/<(?:script|object|embed|option|style)/i,Y=/checked\s*(?:[^=]|=\s*.checked.)/i,Z={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};Z.optgroup=Z.option,Z.tbody=Z.tfoot=Z.colgroup=Z.caption=Z.thead,Z.th=Z.td,d.support.htmlSerialize||(Z._default=[1,"div<div>","</div>"]),d.fn.extend({text:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return d.text(this)},wrapAll:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapAll(a.call(this,b))});if(this[0]){var b=d(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapInner(a.call(this,b))});return this.each(function(){var b=d(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){d(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){d.nodeName(this,"body")||d(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=d(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,d(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,e;(e=this[c])!=null;c++)if(!a||d.filter(a,[e]).length)!b&&e.nodeType===1&&(d.cleanData(e.getElementsByTagName("*")),d.cleanData([e])),e.parentNode&&e.parentNode.removeChild(e);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&d.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return d.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(R,""):null;if(typeof a=="string"&&!X.test(a)&&(d.support.leadingWhitespace||!S.test(a))&&!Z[(U.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(T,"<$1></$2>");try{for(var c=0,e=this.length;c<e;c++)this[c].nodeType===1&&(d.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(f){this.empty().append(a)}}else d.isFunction(a)?this.each(function(b){var c=d(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(d.isFunction(a))return this.each(function(b){var c=d(this),e=c.html();c.replaceWith(a.call(this,b,e))});typeof a!="string"&&(a=d(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;d(this).remove(),b?d(b).before(a):d(c).append(a)})}return this.length?this.pushStack(d(d.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,e){var f,g,h,i,j=a[0],k=[];if(!d.support.checkClone&&arguments.length===3&&typeof j=="string"&&Y.test(j))return this.each(function(){d(this).domManip(a,c,e,!0)});if(d.isFunction(j))return this.each(function(f){var g=d(this);a[0]=j.call(this,f,c?g.html():b),g.domManip(a,c,e)});if(this[0]){i=j&&j.parentNode,d.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?f={fragment:i}:f=d.buildFragment(a,this,k),h=f.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&d.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)e.call(c?$(this[l],g):this[l],f.cacheable||m>1&&l<n?d.clone(h,!0,!0):h)}k.length&&d.each(k,bc)}return this}}),d.buildFragment=function(a,b,e){var f,g,h,i=b&&b[0]?b[0].ownerDocument||b[0]:c;a.length===1&&typeof a[0]=="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!X.test(a[0])&&(d.support.checkClone||!Y.test(a[0]))&&(g=!0,h=d.fragments[a[0]],h&&h!==1&&(f=h)),f||(f=i.createDocumentFragment(),d.clean(a,i,f,e)),g&&(d.fragments[a[0]]=h?f:1);return{fragment:f,cacheable:g}},d.fragments={},d.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){d.fn[a]=function(c){var e=[],f=d(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&f.length===1){f[b](this[0]);return this}for(var h=0,i=f.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();d(f[h])[b](j),e=e.concat(j)}return this.pushStack(e,a,f.selector)}}),d.extend({clone:function(a,b,c){var e=a.cloneNode(!0),f,g,h;if((!d.support.noCloneEvent||!d.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!d.isXMLDoc(a)){ba(a,e),f=bb(a),g=bb(e);for(h=0;f[h];++h)ba(f[h],g[h])}if(b){_(a,e);if(c){f=bb(a),g=bb(e);for(h=0;f[h];++h)_(f[h],g[h])}}f=g=null;return e},clean:function(a,b,e,f){b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var g=[];for(var h=0,i;(i=a[h])!=null;h++){typeof i=="number"&&(i+="");if(!i)continue;if(typeof i=="string"&&!W.test(i))i=b.createTextNode(i);else if(typeof i=="string"){i=i.replace(T,"<$1></$2>");var j=(U.exec(i)||["",""])[1].toLowerCase(),k=Z[j]||Z._default,l=k[0],m=b.createElement("div");m.innerHTML=k[1]+i+k[2];while(l--)m=m.lastChild;if(!d.support.tbody){var n=V.test(i),o=j==="table"&&!n?m.firstChild&&m.firstChild.childNodes:k[1]==="<table>"&&!n?m.childNodes:[];for(var p=o.length-1;p>=0;--p)d.nodeName(o[p],"tbody")&&!o[p].childNodes.length&&o[p].parentNode.removeChild(o[p])}!d.support.leadingWhitespace&&S.test(i)&&m.insertBefore(b.createTextNode(S.exec(i)[0]),m.firstChild),i=m.childNodes}i.nodeType?g.push(i):g=d.merge(g,i)}if(e)for(h=0;g[h];h++)f&&d.nodeName(g[h],"script")&&(!g[h].type||g[h].type.toLowerCase()==="text/javascript")?f.push(g[h].parentNode?g[h].parentNode.removeChild(g[h]):g[h]):(g[h].nodeType===1&&g.splice.apply(g,[h+1,0].concat(d.makeArray(g[h].getElementsByTagName("script")))),e.appendChild(g[h]));return g},cleanData:function(a){var b,c,e=d.cache,f=d.expando,g=d.event.special,h=d.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&d.noData[j.nodeName.toLowerCase()])continue;c=j[d.expando];if(c){b=e[c]&&e[c][f];if(b&&b.events){for(var k in b.events)g[k]?d.event.remove(j,k):d.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[d.expando]:j.removeAttribute&&j.removeAttribute(d.expando),delete e[c]}}}});var bd=/alpha\([^)]*\)/i,be=/opacity=([^)]*)/,bf=/-([a-z])/ig,bg=/([A-Z]|^ms)/g,bh=/^-?\d+(?:px)?$/i,bi=/^-?\d/,bj={position:"absolute",visibility:"hidden",display:"block"},bk=["Left","Right"],bl=["Top","Bottom"],bm,bn,bo,bp=function(a,b){return b.toUpperCase()};d.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return d.access(this,a,c,!0,function(a,c,e){return e!==b?d.style(a,c,e):d.css(a,c)})},d.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bm(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{zIndex:!0,fontWeight:!0,opacity:!0,zoom:!0,lineHeight:!0},cssProps:{"float":d.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,e,f){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h=d.camelCase(c),i=a.style,j=d.cssHooks[h];c=d.cssProps[h]||h;if(e===b){if(j&&"get"in j&&(g=j.get(a,!1,f))!==b)return g;return i[c]}if(typeof e=="number"&&isNaN(e)||e==null)return;typeof e=="number"&&!d.cssNumber[h]&&(e+="px");if(!j||!("set"in j)||(e=j.set(a,e))!==b)try{i[c]=e}catch(k){}}},css:function(a,c,e){var f,g=d.camelCase(c),h=d.cssHooks[g];c=d.cssProps[g]||g;if(h&&"get"in h&&(f=h.get(a,!0,e))!==b)return f;if(bm)return bm(a,c,g)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]},camelCase:function(a){return a.replace(bf,bp)}}),d.curCSS=d.css,d.each(["height","width"],function(a,b){d.cssHooks[b]={get:function(a,c,e){var f;if(c){a.offsetWidth!==0?f=bq(a,b,e):d.swap(a,bj,function(){f=bq(a,b,e)});if(f<=0){f=bm(a,b,b),f==="0px"&&bo&&(f=bo(a,b,b));if(f!=null)return f===""||f==="auto"?"0px":f}if(f<0||f==null){f=a.style[b];return f===""||f==="auto"?"0px":f}return typeof f=="string"?f:f+"px"}},set:function(a,b){if(!bh.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),d.support.opacity||(d.cssHooks.opacity={get:function(a,b){return be.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style;c.zoom=1;var e=d.isNaN(b)?"":"alpha(opacity="+b*100+")",f=c.filter||"";c.filter=bd.test(f)?f.replace(bd,e):c.filter+" "+e}}),d(function(){d.support.reliableMarginRight||(d.cssHooks.marginRight={get:function(a,b){var c;d.swap(a,{display:"inline-block"},function(){b?c=bm(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bn=function(a,c,e){var f,g,h;e=e.replace(bg,"-$1").toLowerCase();if(!(g=a.ownerDocument.defaultView))return b;if(h=g.getComputedStyle(a,null))f=h.getPropertyValue(e),f===""&&!d.contains(a.ownerDocument.documentElement,a)&&(f=d.style(a,e));return f}),c.documentElement.currentStyle&&(bo=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bh.test(d)&&bi.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bm=bn||bo,d.expr&&d.expr.filters&&(d.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!d.support.reliableHiddenOffsets&&(a.style.display||d.css(a,"display"))==="none"},d.expr.filters.visible=function(a){return!d.expr.filters.hidden(a)});var br=/%20/g,bs=/\[\]$/,bt=/\r?\n/g,bu=/#.*$/,bv=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bw=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bx=/^(?:about|app|app\-storage|.+\-extension|file|widget):$/,by=/^(?:GET|HEAD)$/,bz=/^\/\//,bA=/\?/,bB=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bC=/^(?:select|textarea)/i,bD=/\s+/,bE=/([?&])_=[^&]*/,bF=/(^|\-)([a-z])/g,bG=function(a,b,c){return b+c.toUpperCase()},bH=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bI=d.fn.load,bJ={},bK={},bL,bM;try{bL=c.location.href}catch(bN){bL=c.createElement("a"),bL.href="",bL=bL.href}bM=bH.exec(bL.toLowerCase())||[],d.fn.extend({load:function(a,c,e){if(typeof a!="string"&&bI)return bI.apply(this,arguments);if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var g=a.slice(f,a.length);a=a.slice(0,f)}var h="GET";c&&(d.isFunction(c)?(e=c,c=b):typeof c=="object"&&(c=d.param(c,d.ajaxSettings.traditional),h="POST"));var i=this;d.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?d("<div>").append(c.replace(bB,"")).find(g):c)),e&&i.each(e,[c,b,a])}});return this},serialize:function(){return d.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?d.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bC.test(this.nodeName)||bw.test(this.type))}).map(function(a,b){var c=d(this).val();return c==null?null:d.isArray(c)?d.map(c,function(a,c){return{name:b.name,value:a.replace(bt,"\r\n")}}):{name:b.name,value:c.replace(bt,"\r\n")}}).get()}}),d.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){d.fn[b]=function(a){return this.bind(b,a)}}),d.each(["get","post"],function(a,c){d[c]=function(a,e,f,g){d.isFunction(e)&&(g=g||f,f=e,e=b);return d.ajax({type:c,url:a,data:e,success:f,dataType:g})}}),d.extend({getScript:function(a,c){return d.get(a,b,c,"script")},getJSON:function(a,b,c){return d.get(a,b,c,"json")},ajaxSetup:function(a,b){b?d.extend(!0,a,d.ajaxSettings,b):(b=a,a=d.extend(!0,d.ajaxSettings,b));for(var c in{context:1,url:1})c in b?a[c]=b[c]:c in d.ajaxSettings&&(a[c]=d.ajaxSettings[c]);return a},ajaxSettings:{url:bL,isLocal:bx.test(bM[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":d.parseJSON,"text xml":d.parseXML}},ajaxPrefilter:bO(bJ),ajaxTransport:bO(bK),ajax:function(a,c){function v(a,c,l,n){if(r!==2){r=2,p&&clearTimeout(p),o=b,m=n||"",u.readyState=a?4:0;var q,t,v,w=l?bR(e,u,l):b,x,y;if(a>=200&&a<300||a===304){if(e.ifModified){if(x=u.getResponseHeader("Last-Modified"))d.lastModified[k]=x;if(y=u.getResponseHeader("Etag"))d.etag[k]=y}if(a===304)c="notmodified",q=!0;else try{t=bS(e,w),c="success",q=!0}catch(z){c="parsererror",v=z}}else{v=c;if(!c||a)c="error",a<0&&(a=0)}u.status=a,u.statusText=c,q?h.resolveWith(f,[t,c,u]):h.rejectWith(f,[u,c,v]),u.statusCode(j),j=b,s&&g.trigger("ajax"+(q?"Success":"Error"),[u,e,q?t:v]),i.resolveWith(f,[u,c]),s&&(g.trigger("ajaxComplete",[u,e]),--d.active||d.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var e=d.ajaxSetup({},c),f=e.context||e,g=f!==e&&(f.nodeType||f instanceof d)?d(f):d.event,h=d.Deferred(),i=d._Deferred(),j=e.statusCode||{},k,l={},m,n,o,p,q,r=0,s,t,u={readyState:0,setRequestHeader:function(a,b){r||(l[a.toLowerCase().replace(bF,bG)]=b);return this},getAllResponseHeaders:function(){return r===2?m:null},getResponseHeader:function(a){var c;if(r===2){if(!n){n={};while(c=bv.exec(m))n[c[1].toLowerCase()]=c[2]}c=n[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){r||(e.mimeType=a);return this},abort:function(a){a=a||"abort",o&&o.abort(a),v(0,a);return this}};h.promise(u),u.success=u.done,u.error=u.fail,u.complete=i.done,u.statusCode=function(a){if(a){var b;if(r<2)for(b in a)j[b]=[j[b],a[b]];else b=a[u.status],u.then(b,b)}return this},e.url=((a||e.url)+"").replace(bu,"").replace(bz,bM[1]+"//"),e.dataTypes=d.trim(e.dataType||"*").toLowerCase().split(bD),e.crossDomain==null&&(q=bH.exec(e.url.toLowerCase()),e.crossDomain=!(!q||q[1]==bM[1]&&q[2]==bM[2]&&(q[3]||(q[1]==="http:"?80:443))==(bM[3]||(bM[1]==="http:"?80:443)))),e.data&&e.processData&&typeof e.data!="string"&&(e.data=d.param(e.data,e.traditional)),bP(bJ,e,c,u);if(r===2)return!1;s=e.global,e.type=e.type.toUpperCase(),e.hasContent=!by.test(e.type),s&&d.active++===0&&d.event.trigger("ajaxStart");if(!e.hasContent){e.data&&(e.url+=(bA.test(e.url)?"&":"?")+e.data),k=e.url;if(e.cache===!1){var w=d.now(),x=e.url.replace(bE,"$1_="+w);e.url=x+(x===e.url?(bA.test(e.url)?"&":"?")+"_="+w:"")}}if(e.data&&e.hasContent&&e.contentType!==!1||c.contentType)l["Content-Type"]=e.contentType;e.ifModified&&(k=k||e.url,d.lastModified[k]&&(l["If-Modified-Since"]=d.lastModified[k]),d.etag[k]&&(l["If-None-Match"]=d.etag[k])),l.Accept=e.dataTypes[0]&&e.accepts[e.dataTypes[0]]?e.accepts[e.dataTypes[0]]+(e.dataTypes[0]!=="*"?", */*; q=0.01":""):e.accepts["*"];for(t in e.headers)u.setRequestHeader(t,e.headers[t]);if(e.beforeSend&&(e.beforeSend.call(f,u,e)===!1||r===2)){u.abort();return!1}for(t in{success:1,error:1,complete:1})u[t](e[t]);o=bP(bK,e,c,u);if(!o)v(-1,"No Transport");else{u.readyState=1,s&&g.trigger("ajaxSend",[u,e]),e.async&&e.timeout>0&&(p=setTimeout(function(){u.abort("timeout")},e.timeout));try{r=1,o.send(l,v)}catch(y){status<2?v(-1,y):d.error(y)}}return u},param:function(a,c){var e=[],f=function(a,b){b=d.isFunction(b)?b():b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=d.ajaxSettings.traditional);if(d.isArray(a)||a.jquery&&!d.isPlainObject(a))d.each(a,function(){f(this.name,this.value)});else for(var g in a)bQ(g,a[g],c,f);return e.join("&").replace(br,"+")}}),d.extend({active:0,lastModified:{},etag:{}});var bT=d.now(),bU=/(\=)\?(&|$)|\?\?/i;d.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return d.expando+"_"+bT++}}),d.ajaxPrefilter("json jsonp",function(b,c,e){var f=typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||c.jsonpCallback||c.jsonp!=null||b.jsonp!==!1&&(bU.test(b.url)||f&&bU.test(b.data))){var g,h=b.jsonpCallback=d.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2",m=function(){a[h]=i,g&&d.isFunction(i)&&a[h](g[0])};b.jsonp!==!1&&(j=j.replace(bU,l),b.url===j&&(f&&(k=k.replace(bU,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},e.then(m,m),b.converters["script json"]=function(){g||d.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),d.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){d.globalEval(a);return a}}}),d.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),d.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var bV=d.now(),bW,bX;d.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&bZ()||b$()}:bZ,bX=d.ajaxSettings.xhr(),d.support.ajax=!!bX,d.support.cors=bX&&"withCredentials"in bX,bX=b,d.support.ajax&&d.ajaxTransport(function(a){if(!a.crossDomain||d.support.cors){var c;return{send:function(e,f){var g=a.xhr(),h,i;a.username?g.open(a.type,a.url,a.async,a.username,a.password):g.open(a.type,a.url,a.async);if(a.xhrFields)for(i in a.xhrFields)g[i]=a.xhrFields[i];a.mimeType&&g.overrideMimeType&&g.overrideMimeType(a.mimeType),!a.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(i in e)g.setRequestHeader(i,e[i])}catch(j){}g.send(a.hasContent&&a.data||null),c=function(e,i){var j,k,l,m,n;try{if(c&&(i||g.readyState===4)){c=b,h&&(g.onreadystatechange=d.noop,delete bW[h]);if(i)g.readyState!==4&&g.abort();else{j=g.status,l=g.getAllResponseHeaders(),m={},n=g.responseXML,n&&n.documentElement&&(m.xml=n),m.text=g.responseText;try{k=g.statusText}catch(o){k=""}!j&&a.isLocal&&!a.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){i||f(-1,p)}m&&f(j,k,m,l)},!a.async||g.readyState===4?c():(bW||(bW={},bY()),h=bV++,g.onreadystatechange=bW[h]=c)},abort:function(){c&&c(0,1)}}}});var b_={},ca=/^(?:toggle|show|hide)$/,cb=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cc,cd=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];d.fn.extend({show:function(a,b,c){var e,f;if(a||a===0)return this.animate(ce("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)e=this[g],f=e.style.display,!d._data(e,"olddisplay")&&f==="none"&&(f=e.style.display=""),f===""&&d.css(e,"display")==="none"&&d._data(e,"olddisplay",cf(e.nodeName));for(g=0;g<h;g++){e=this[g],f=e.style.display;if(f===""||f==="none")e.style.display=d._data(e,"olddisplay")||""}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ce("hide",3),a,b,c);for(var e=0,f=this.length;e<f;e++){var g=d.css(this[e],"display");g!=="none"&&!d._data(this[e],"olddisplay")&&d._data(this[e],"olddisplay",g)}for(e=0;e<f;e++)this[e].style.display="none";return this},_toggle:d.fn.toggle,toggle:function(a,b,c){var e=typeof a=="boolean";d.isFunction(a)&&d.isFunction(b)?this._toggle.apply(this,arguments):a==null||e?this.each(function(){var b=e?a:d(this).is(":hidden");d(this)[b?"show":"hide"]()}):this.animate(ce("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,e){var f=d.speed(b,c,e);if(d.isEmptyObject(a))return this.each(f.complete);return this[f.queue===!1?"each":"queue"](function(){var b=d.extend({},f),c,e=this.nodeType===1,g=e&&d(this).is(":hidden"),h=this;for(c in a){var i=d.camelCase(c);c!==i&&(a[i]=a[c],delete a[c],c=i);if(a[c]==="hide"&&g||a[c]==="show"&&!g)return b.complete.call(this);if(e&&(c==="height"||c==="width")){b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(d.css(this,"display")==="inline"&&d.css(this,"float")==="none")if(!d.support.inlineBlockNeedsLayout)this.style.display="inline-block";else{var j=cf(this.nodeName);j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)}}d.isArray(a[c])&&((b.specialEasing=b.specialEasing||{})[c]=a[c][1],a[c]=a[c][0])}b.overflow!=null&&(this.style.overflow="hidden"),b.curAnim=d.extend({},a),d.each(a,function(c,e){var f=new d.fx(h,b,c);if(ca.test(e))f[e==="toggle"?g?"show":"hide":e](a);else{var i=cb.exec(e),j=f.cur();if(i){var k=parseFloat(i[2]),l=i[3]||(d.cssNumber[c]?"":"px");l!=="px"&&(d.style(h,c,(k||1)+l),j=(k||1)/f.cur()*j,d.style(h,c,j+l)),i[1]&&(k=(i[1]==="-="?-1:1)*k+j),f.custom(j,k,l)}else f.custom(j,e,"")}});return!0})},stop:function(a,b){var c=d.timers;a&&this.queue([]),this.each(function(){for(var a=c.length-1;a>=0;a--)c[a].elem===this&&(b&&c[a](!0),c.splice(a,1))}),b||this.dequeue();return this}}),d.each({slideDown:ce("show",1),slideUp:ce("hide",1),slideToggle:ce("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){d.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),d.extend({speed:function(a,b,c){var e=a&&typeof a=="object"?d.extend({},a):{complete:c||!c&&b||d.isFunction(a)&&a,duration:a,easing:c&&b||b&&!d.isFunction(b)&&b};e.duration=d.fx.off?0:typeof e.duration=="number"?e.duration:e.duration in d.fx.speeds?d.fx.speeds[e.duration]:d.fx.speeds._default,e.old=e.complete,e.complete=function(){e.queue!==!1&&d(this).dequeue(),d.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig||(b.orig={})}}),d.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(d.fx.step[this.prop]||d.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=d.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,b,c){function g(a){return e.step(a)}var e=this,f=d.fx;this.startTime=d.now(),this.start=a,this.end=b,this.unit=c||this.unit||(d.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,g.elem=this.elem,g()&&d.timers.push(g)&&!cc&&(cc=setInterval(f.tick,f.interval))},show:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),d(this.elem).show()},hide:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=d.now(),c=!0;if(a||b>=this.options.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),this.options.curAnim[this.prop]=!0;for(var e in this.options.curAnim)this.options.curAnim[e]!==!0&&(c=!1);if(c){if(this.options.overflow!=null&&!d.support.shrinkWrapBlocks){var f=this.elem,g=this.options;d.each(["","X","Y"],function(a,b){f.style["overflow"+b]=g.overflow[a]})}this.options.hide&&d(this.elem).hide();if(this.options.hide||this.options.show)for(var h in this.options.curAnim)d.style(this.elem,h,this.options.orig[h]);this.options.complete.call(this.elem)}return!1}var i=b-this.startTime;this.state=i/this.options.duration;var j=this.options.specialEasing&&this.options.specialEasing[this.prop],k=this.options.easing||(d.easing.swing?"swing":"linear");this.pos=d.easing[j||k](this.state,i,0,1,this.options.duration),this.now=this.start+(this.end-this.start)*this.pos,this.update();return!0}},d.extend(d.fx,{tick:function(){var a=d.timers;for(var b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||d.fx.stop()},interval:13,stop:function(){clearInterval(cc),cc=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){d.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=a.now}}}),d.expr&&d.expr.filters&&(d.expr.filters.animated=function(a){return d.grep(d.timers,function(b){return a===b.elem}).length});var cg=/^t(?:able|d|h)$/i,ch=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?d.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,g=f.documentElement;if(!c||!d.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=f.body,i=ci(f),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||d.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||d.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:d.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);d.offset.initialize();var c,e=b.offsetParent,f=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(d.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===e&&(l+=b.offsetTop,m+=b.offsetLeft,d.offset.doesNotAddBorder&&(!d.offset.doesAddBorderForTableAndCells||!cg.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),f=e,e=b.offsetParent),d.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;d.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},d.offset={initialize:function(){var a=c.body,b=c.createElement("div"),e,f,g,h,i=parseFloat(d.css(a,"marginTop"))||0,j="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";d.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),e=b.firstChild,f=e.firstChild,h=e.nextSibling.firstChild.firstChild,this.doesNotAddBorder=f.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,f.style.position="fixed",f.style.top="20px",this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15,f.style.position=f.style.top="",e.style.overflow="hidden",e.style.position="relative",this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),d.offset.initialize=d.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;d.offset.initialize(),d.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(d.css(a,"marginTop"))||0,c+=parseFloat(d.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var e=d.css(a,"position");e==="static"&&(a.style.position="relative");var f=d(a),g=f.offset(),h=d.css(a,"top"),i=d.css(a,"left"),j=(e==="absolute"||e==="fixed")&&d.inArray("auto",[h,i])>-1,k={},l={},m,n;j&&(l=f.position()),m=j?l.top:parseInt(h,10)||0,n=j?l.left:parseInt(i,10)||0,d.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):f.css(k)}},d.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),e=ch.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(d.css(a,"marginTop"))||0,c.left-=parseFloat(d.css(a,"marginLeft"))||0,e.top+=parseFloat(d.css(b[0],"borderTopWidth"))||0,e.left+=parseFloat(d.css(b[0],"borderLeftWidth"))||0;return{top:c.top-e.top,left:c.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!ch.test(a.nodeName)&&d.css(a,"position")==="static")a=a.offsetParent;return a})}}),d.each(["Left","Top"],function(a,c){var e="scroll"+c;d.fn[e]=function(c){var f=this[0],g;if(!f)return null;if(c!==b)return this.each(function(){g=ci(this),g?g.scrollTo(a?d(g).scrollLeft():c,a?c:d(g).scrollTop()):this[e]=c});g=ci(f);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:d.support.boxModel&&g.document.documentElement[e]||g.document.body[e]:f[e]}}),d.each(["Height","Width"],function(a,c){var e=c.toLowerCase();d.fn["inner"+c]=function(){return this[0]?parseFloat(d.css(this[0],e,"padding")):null},d.fn["outer"+c]=function(a){return this[0]?parseFloat(d.css(this[0],e,a?"margin":"border")):null},d.fn[e]=function(a){var f=this[0];if(!f)return a==null?null:this;if(d.isFunction(a))return this.each(function(b){var c=d(this);c[e](a.call(this,b,c[e]()))});if(d.isWindow(f)){var g=f.document.documentElement["client"+c];return f.document.compatMode==="CSS1Compat"&&g||f.document.body["client"+c]||g}if(f.nodeType===9)return Math.max(f.documentElement["client"+c],f.body["scroll"+c],f.documentElement["scroll"+c],f.body["offset"+c],f.documentElement["offset"+c]);if(a===b){var h=d.css(f,e),i=parseFloat(h);return d.isNaN(i)?h:i}return this.css(e,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=d})(window)
jQuery.noConflict();
jQuery.os={};var jQueryOSplatform=navigator.platform.toLowerCase();jQuery.os.windows=(jQueryOSplatform.indexOf("win")!=-1);jQuery.os.mac=(jQueryOSplatform.indexOf("mac")!=-1);jQuery.os.linux=(jQueryOSplatform.indexOf("linux")!=-1);
/**
 * Atlassian custom download containing:
 * CORE - Core, Widget, Mouse
 * INTERACTIONS - Draggable, Sortable
 * Load jquery-ui-other for droppable and other resources.
 * This load profile will be updated to something more logical in a future version.
 */
/*!
 * jQuery UI 1.8.11
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
(function(c,j){function k(a){return!c(a).parents().andSelf().filter(function(){return c.curCSS(this,"visibility")==="hidden"||c.expr.filters.hidden(this)}).length}c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.11",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,
NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,
"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==j)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");
if(b==="absolute"||b==="relative"||b==="fixed"){b=parseInt(a.css("zIndex"),10);if(!isNaN(b)&&b!==0)return b}a=a.parent()}}return 0},disableSelection:function(){return this.bind((c.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});c.each(["Width","Height"],function(a,b){function d(f,g,l,m){c.each(e,function(){g-=parseFloat(c.curCSS(f,"padding"+this,true))||0;if(l)g-=parseFloat(c.curCSS(f,
"border"+this+"Width",true))||0;if(m)g-=parseFloat(c.curCSS(f,"margin"+this,true))||0});return g}var e=b==="Width"?["Left","Right"]:["Top","Bottom"],h=b.toLowerCase(),i={innerWidth:c.fn.innerWidth,innerHeight:c.fn.innerHeight,outerWidth:c.fn.outerWidth,outerHeight:c.fn.outerHeight};c.fn["inner"+b]=function(f){if(f===j)return i["inner"+b].call(this);return this.each(function(){c(this).css(h,d(this,f)+"px")})};c.fn["outer"+b]=function(f,g){if(typeof f!=="number")return i["outer"+b].call(this,f);return this.each(function(){c(this).css(h,
d(this,f,true,g)+"px")})}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");if("area"===b){b=a.parentNode;d=b.name;if(!a.href||!d||b.nodeName.toLowerCase()!=="map")return false;a=c("img[usemap=#"+d+"]")[0];return!!a&&k(a)}return(/input|select|textarea|button|object/.test(b)?!a.disabled:"a"==b?a.href||!isNaN(d):!isNaN(d))&&k(a)},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}});
c(function(){var a=document.body,b=a.appendChild(b=document.createElement("div"));c.extend(b.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});c.support.minHeight=b.offsetHeight===100;c.support.selectstart="onselectstart"in b;a.removeChild(b).style.display="none"});c.extend(c.ui,{plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&
b[e][1].apply(a.element,d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")==="hidden")return false;b=b&&b==="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,h,i){return c.ui.isOverAxis(a,d,h)&&c.ui.isOverAxis(b,e,i)}})}})(jQuery);
;/*!
 * jQuery UI Widget 1.8.11
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */
(function(b,j){if(b.cleanData){var k=b.cleanData;b.cleanData=function(a){for(var c=0,d;(d=a[c])!=null;c++)b(d).triggerHandler("remove");k(a)}}else{var l=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add([this]).each(function(){b(this).triggerHandler("remove")});return l.call(b(this),a,c)})}}b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h,
a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend(true,{},c.options);b[e][a].prototype=b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.charAt(0)==="_")return h;
e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==j){h=i;return false}}):this.each(function(){var g=b.data(this,a);g?g.option(d||{})._init():b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){b.data(c,this.widgetName,this);this.element=b(c);this.options=b.extend(true,{},this.options,
this._getCreateOptions(),a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return b.metadata&&b.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},
widget:function(){return this.element},option:function(a,c){var d=a;if(arguments.length===0)return b.extend({},this.options);if(typeof a==="string"){if(c===j)return this.options[a];d={};d[a]=c}this._setOptions(d);return this},_setOptions:function(a){var c=this;b.each(a,function(d,e){c._setOption(d,e)});return this},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},
enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery);
;/*!
 * jQuery UI Mouse 1.8.11
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Mouse
 *
 * Depends:
 *	jquery.ui.widget.js
 */
(function(b){b.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(c){return a._mouseDown(c)}).bind("click."+this.widgetName,function(c){if(true===b.data(c.target,a.widgetName+".preventClickEvent")){b.removeData(c.target,a.widgetName+".preventClickEvent");c.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent=
a.originalEvent||{};if(!a.originalEvent.mouseHandled){this._mouseStarted&&this._mouseUp(a);this._mouseDownEvent=a;var c=this,e=a.which==1,f=typeof this.options.cancel=="string"?b(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){c.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted=
this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault();return true}}true===b.data(a.target,this.widgetName+".preventClickEvent")&&b.removeData(a.target,this.widgetName+".preventClickEvent");this._mouseMoveDelegate=function(d){return c._mouseMove(d)};this._mouseUpDelegate=function(d){return c._mouseUp(d)};b(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);a.preventDefault();return a.originalEvent.mouseHandled=
true}},_mouseMove:function(a){if(b.browser.msie&&!(document.documentMode>=9)&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);return a.preventDefault()}if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);
if(this._mouseStarted){this._mouseStarted=false;a.target==this._mouseDownEvent.target&&b.data(a.target,this.widgetName+".preventClickEvent",true);this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery);
;/*
 * jQuery UI Draggable 1.8.11
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function(d){d.widget("ui.draggable",d.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function(){if(this.options.helper==
"original"&&!/^(?:r|a|f)/.test(this.element.css("position")))this.element[0].style.position="relative";this.options.addClasses&&this.element.addClass("ui-draggable");this.options.disabled&&this.element.addClass("ui-draggable-disabled");this._mouseInit()},destroy:function(){if(this.element.data("draggable")){this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();return this}},_mouseCapture:function(a){var b=
this.options;if(this.helper||b.disabled||d(a.target).is(".ui-resizable-handle"))return false;this.handle=this._getHandle(a);if(!this.handle)return false;return true},_mouseStart:function(a){var b=this.options;this.helper=this._createHelper(a);this._cacheHelperProportions();if(d.ui.ddmanager)d.ui.ddmanager.current=this;this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-
this.margins.top,left:this.offset.left-this.margins.left};d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);b.containment&&this._setContainment();if(this._trigger("start",a)===false){this._clear();return false}this._cacheHelperProportions();
d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(a,true);return true},_mouseDrag:function(a,b){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");if(!b){b=this._uiHash();if(this._trigger("drag",a,b)===false){this._mouseUp({});return false}this.position=b.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||
this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);return false},_mouseStop:function(a){var b=false;if(d.ui.ddmanager&&!this.options.dropBehaviour)b=d.ui.ddmanager.drop(this,a);if(this.dropped){b=this.dropped;this.dropped=false}if((!this.element[0]||!this.element[0].parentNode)&&this.options.helper=="original")return false;if(this.options.revert=="invalid"&&!b||this.options.revert=="valid"&&b||this.options.revert===true||d.isFunction(this.options.revert)&&
this.options.revert.call(this.element,b)){var c=this;d(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){c._trigger("stop",a)!==false&&c._clear()})}else this._trigger("stop",a)!==false&&this._clear();return false},cancel:function(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this},_getHandle:function(a){var b=!this.options.handle||!d(this.options.handle,this.element).length?true:false;d(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==
a.target)b=true});return b},_createHelper:function(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a])):b.helper=="clone"?this.element.clone():this.element;a.parents("body").length||a.appendTo(b.appendTo=="parent"?this.element[0].parentNode:b.appendTo);a[0]!=this.element[0]&&!/(fixed|absolute)/.test(a.css("position"))&&a.css("position","absolute");return a},_adjustOffsetFromHelper:function(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0],top:+a[1]||
0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],
this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top-
(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),
height:this.helper.outerHeight()}},_setContainment:function(){var a=this.options;if(a.containment=="parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[(a.containment=="document"?0:d(window).scrollLeft())-this.offset.relative.left-this.offset.parent.left,(a.containment=="document"?0:d(window).scrollTop())-this.offset.relative.top-this.offset.parent.top,(a.containment=="document"?0:d(window).scrollLeft())+d(a.containment=="document"?
document:window).width()-this.helperProportions.width-this.margins.left,(a.containment=="document"?0:d(window).scrollTop())+(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)&&a.containment.constructor!=Array){var b=d(a.containment)[0];if(b){a=d(a.containment).offset();var c=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),
10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0),a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0),a.left+(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,a.top+(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),
10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom]}}else if(a.containment.constructor==Array)this.containment=a.containment},_convertPositionTo:function(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName);return{top:b.top+this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&
d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():f?0:c.scrollLeft())*a)}},_generatePosition:function(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],
this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName),e=a.pageX,g=a.pageY;if(this.originalPosition){if(this.containment){if(a.pageX-this.offset.click.left<this.containment[0])e=this.containment[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<this.containment[1])g=this.containment[1]+this.offset.click.top;if(a.pageX-this.offset.click.left>this.containment[2])e=this.containment[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>this.containment[3])g=
this.containment[3]+this.offset.click.top}if(b.grid){g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1];g=this.containment?!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g;e=this.originalPageX+Math.round((e-this.originalPageX)/b.grid[0])*b.grid[0];e=this.containment?!(e-this.offset.click.left<this.containment[0]||e-this.offset.click.left>this.containment[2])?
e:!(e-this.offset.click.left<this.containment[0])?e-b.grid[0]:e+b.grid[0]:e}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop()),left:e-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():
f?0:c.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove();this.helper=null;this.cancelHelperRemoval=false},_trigger:function(a,b,c){c=c||this._uiHash();d.ui.plugin.call(this,a,[b,c]);if(a=="drag")this.positionAbs=this._convertPositionTo("absolute");return d.Widget.prototype._trigger.call(this,a,b,c)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,
offset:this.positionAbs}}});d.extend(d.ui.draggable,{version:"1.8.11"});d.ui.plugin.add("draggable","connectToSortable",{start:function(a,b){var c=d(this).data("draggable"),f=c.options,e=d.extend({},b,{item:c.element});c.sortables=[];d(f.connectToSortable).each(function(){var g=d.data(this,"sortable");if(g&&!g.options.disabled){c.sortables.push({instance:g,shouldRevert:g.options.revert});g.refreshPositions();g._trigger("activate",a,e)}})},stop:function(a,b){var c=d(this).data("draggable"),f=d.extend({},
b,{item:c.element});d.each(c.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;c.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert)this.instance.options.revert=true;this.instance._mouseStop(a);this.instance.options.helper=this.instance.options._helper;c.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",a,f)}})},drag:function(a,b){var c=
d(this).data("draggable"),f=this;d.each(c.sortables,function(){this.instance.positionAbs=c.positionAbs;this.instance.helperProportions=c.helperProportions;this.instance.offset.click=c.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=d(f).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return b.helper[0]};
a.target=this.instance.currentItem[0];this.instance._mouseCapture(a,true);this.instance._mouseStart(a,true,true);this.instance.offset.click.top=c.offset.click.top;this.instance.offset.click.left=c.offset.click.left;this.instance.offset.parent.left-=c.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=c.offset.parent.top-this.instance.offset.parent.top;c._trigger("toSortable",a);c.dropped=this.instance.element;c.currentItem=c.element;this.instance.fromOutside=c}this.instance.currentItem&&
this.instance._mouseDrag(a)}else if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",a,this.instance._uiHash(this.instance));this.instance._mouseStop(a,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();this.instance.placeholder&&this.instance.placeholder.remove();c._trigger("fromSortable",a);c.dropped=false}})}});d.ui.plugin.add("draggable","cursor",
{start:function(){var a=d("body"),b=d(this).data("draggable").options;if(a.css("cursor"))b._cursor=a.css("cursor");a.css("cursor",b.cursor)},stop:function(){var a=d(this).data("draggable").options;a._cursor&&d("body").css("cursor",a._cursor)}});d.ui.plugin.add("draggable","iframeFix",{start:function(){var a=d(this).data("draggable").options;d(a.iframeFix===true?"iframe":a.iframeFix).each(function(){d('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+
"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1E3}).css(d(this).offset()).appendTo("body")})},stop:function(){d("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)})}});d.ui.plugin.add("draggable","opacity",{start:function(a,b){a=d(b.helper);b=d(this).data("draggable").options;if(a.css("opacity"))b._opacity=a.css("opacity");a.css("opacity",b.opacity)},stop:function(a,b){a=d(this).data("draggable").options;a._opacity&&d(b.helper).css("opacity",
a._opacity)}});d.ui.plugin.add("draggable","scroll",{start:function(){var a=d(this).data("draggable");if(a.scrollParent[0]!=document&&a.scrollParent[0].tagName!="HTML")a.overflowOffset=a.scrollParent.offset()},drag:function(a){var b=d(this).data("draggable"),c=b.options,f=false;if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!="HTML"){if(!c.axis||c.axis!="x")if(b.overflowOffset.top+b.scrollParent[0].offsetHeight-a.pageY<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop+
c.scrollSpeed;else if(a.pageY-b.overflowOffset.top<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop-c.scrollSpeed;if(!c.axis||c.axis!="y")if(b.overflowOffset.left+b.scrollParent[0].offsetWidth-a.pageX<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft+c.scrollSpeed;else if(a.pageX-b.overflowOffset.left<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft-c.scrollSpeed}else{if(!c.axis||c.axis!="x")if(a.pageY-d(document).scrollTop()<
c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()-c.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()+c.scrollSpeed);if(!c.axis||c.axis!="y")if(a.pageX-d(document).scrollLeft()<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()-c.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()+
c.scrollSpeed)}f!==false&&d.ui.ddmanager&&!c.dropBehaviour&&d.ui.ddmanager.prepareOffsets(b,a)}});d.ui.plugin.add("draggable","snap",{start:function(){var a=d(this).data("draggable"),b=a.options;a.snapElements=[];d(b.snap.constructor!=String?b.snap.items||":data(draggable)":b.snap).each(function(){var c=d(this),f=c.offset();this!=a.element[0]&&a.snapElements.push({item:this,width:c.outerWidth(),height:c.outerHeight(),top:f.top,left:f.left})})},drag:function(a,b){for(var c=d(this).data("draggable"),
f=c.options,e=f.snapTolerance,g=b.offset.left,n=g+c.helperProportions.width,m=b.offset.top,o=m+c.helperProportions.height,h=c.snapElements.length-1;h>=0;h--){var i=c.snapElements[h].left,k=i+c.snapElements[h].width,j=c.snapElements[h].top,l=j+c.snapElements[h].height;if(i-e<g&&g<k+e&&j-e<m&&m<l+e||i-e<g&&g<k+e&&j-e<o&&o<l+e||i-e<n&&n<k+e&&j-e<m&&m<l+e||i-e<n&&n<k+e&&j-e<o&&o<l+e){if(f.snapMode!="inner"){var p=Math.abs(j-o)<=e,q=Math.abs(l-m)<=e,r=Math.abs(i-n)<=e,s=Math.abs(k-g)<=e;if(p)b.position.top=
c._convertPositionTo("relative",{top:j-c.helperProportions.height,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i-c.helperProportions.width}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k}).left-c.margins.left}var t=p||q||r||s;if(f.snapMode!="outer"){p=Math.abs(j-m)<=e;q=Math.abs(l-o)<=e;r=Math.abs(i-g)<=e;s=Math.abs(k-n)<=e;if(p)b.position.top=
c._convertPositionTo("relative",{top:j,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l-c.helperProportions.height,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k-c.helperProportions.width}).left-c.margins.left}if(!c.snapElements[h].snapping&&(p||q||r||s||t))c.options.snap.snap&&c.options.snap.snap.call(c.element,a,d.extend(c._uiHash(),
{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=p||q||r||s||t}else{c.snapElements[h].snapping&&c.options.snap.release&&c.options.snap.release.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=false}}}});d.ui.plugin.add("draggable","stack",{start:function(){var a=d(this).data("draggable").options;a=d.makeArray(d(a.stack)).sort(function(c,f){return(parseInt(d(c).css("zIndex"),10)||0)-(parseInt(d(f).css("zIndex"),10)||0)});if(a.length){var b=
parseInt(a[0].style.zIndex)||0;d(a).each(function(c){this.style.zIndex=b+c});this[0].style.zIndex=b+a.length}}});d.ui.plugin.add("draggable","zIndex",{start:function(a,b){a=d(b.helper);b=d(this).data("draggable").options;if(a.css("zIndex"))b._zIndex=a.css("zIndex");a.css("zIndex",b.zIndex)},stop:function(a,b){a=d(this).data("draggable").options;a._zIndex&&d(b.helper).css("zIndex",a._zIndex)}})})(jQuery);
;/*
 * jQuery UI Sortable 1.8.11
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Sortables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function(d){d.widget("ui.sortable",d.ui.mouse,{widgetEventPrefix:"sort",options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:"auto",cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1E3},_create:function(){this.containerCache={};this.element.addClass("ui-sortable");
this.refresh();this.floating=this.items.length?/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):false;this.offset=this.element.offset();this._mouseInit()},destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable");this._mouseDestroy();for(var a=this.items.length-1;a>=0;a--)this.items[a].item.removeData("sortable-item");return this},_setOption:function(a,b){if(a==="disabled"){this.options[a]=
b;this.widget()[b?"addClass":"removeClass"]("ui-sortable-disabled")}else d.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(a,b){if(this.reverting)return false;if(this.options.disabled||this.options.type=="static")return false;this._refreshItems(a);var c=null,e=this;d(a.target).parents().each(function(){if(d.data(this,"sortable-item")==e){c=d(this);return false}});if(d.data(a.target,"sortable-item")==e)c=d(a.target);if(!c)return false;if(this.options.handle&&!b){var f=false;
d(this.options.handle,c).find("*").andSelf().each(function(){if(this==a.target)f=true});if(!f)return false}this.currentItem=c;this._removeCurrentsFromItems();return true},_mouseStart:function(a,b,c){b=this.options;var e=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(a);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-
this.margins.left};this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};
this.helper[0]!=this.currentItem[0]&&this.currentItem.hide();this._createPlaceholder();b.containment&&this._setContainment();if(b.cursor){if(d("body").css("cursor"))this._storedCursor=d("body").css("cursor");d("body").css("cursor",b.cursor)}if(b.opacity){if(this.helper.css("opacity"))this._storedOpacity=this.helper.css("opacity");this.helper.css("opacity",b.opacity)}if(b.zIndex){if(this.helper.css("zIndex"))this._storedZIndex=this.helper.css("zIndex");this.helper.css("zIndex",b.zIndex)}if(this.scrollParent[0]!=
document&&this.scrollParent[0].tagName!="HTML")this.overflowOffset=this.scrollParent.offset();this._trigger("start",a,this._uiHash());this._preserveHelperProportions||this._cacheHelperProportions();if(!c)for(c=this.containers.length-1;c>=0;c--)this.containers[c]._trigger("activate",a,e._uiHash(this));if(d.ui.ddmanager)d.ui.ddmanager.current=this;d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(a);
return true},_mouseDrag:function(a){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs)this.lastPositionAbs=this.positionAbs;if(this.options.scroll){var b=this.options,c=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if(this.overflowOffset.top+this.scrollParent[0].offsetHeight-a.pageY<b.scrollSensitivity)this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop+b.scrollSpeed;else if(a.pageY-this.overflowOffset.top<
b.scrollSensitivity)this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop-b.scrollSpeed;if(this.overflowOffset.left+this.scrollParent[0].offsetWidth-a.pageX<b.scrollSensitivity)this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft+b.scrollSpeed;else if(a.pageX-this.overflowOffset.left<b.scrollSensitivity)this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft-b.scrollSpeed}else{if(a.pageY-d(document).scrollTop()<b.scrollSensitivity)c=d(document).scrollTop(d(document).scrollTop()-
b.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<b.scrollSensitivity)c=d(document).scrollTop(d(document).scrollTop()+b.scrollSpeed);if(a.pageX-d(document).scrollLeft()<b.scrollSensitivity)c=d(document).scrollLeft(d(document).scrollLeft()-b.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<b.scrollSensitivity)c=d(document).scrollLeft(d(document).scrollLeft()+b.scrollSpeed)}c!==false&&d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,
a)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(b=this.items.length-1;b>=0;b--){c=this.items[b];var e=c.item[0],f=this._intersectsWithPointer(c);if(f)if(e!=this.currentItem[0]&&this.placeholder[f==1?"next":"prev"]()[0]!=e&&!d.ui.contains(this.placeholder[0],e)&&(this.options.type=="semi-dynamic"?!d.ui.contains(this.element[0],
e):true)){this.direction=f==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(c))this._rearrange(a,c);else break;this._trigger("change",a,this._uiHash());break}}this._contactContainers(a);d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);this._trigger("sort",a,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(a,b){if(a){d.ui.ddmanager&&!this.options.dropBehaviour&&d.ui.ddmanager.drop(this,a);if(this.options.revert){var c=this;b=c.placeholder.offset();
c.reverting=true;d(this.helper).animate({left:b.left-this.offset.parent.left-c.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:b.top-this.offset.parent.top-c.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){c._clear(a)})}else this._clear(a,b);return false}},cancel:function(){var a=this;if(this.dragging){this._mouseUp({target:null});this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):
this.currentItem.show();for(var b=this.containers.length-1;b>=0;b--){this.containers[b]._trigger("deactivate",null,a._uiHash(this));if(this.containers[b].containerCache.over){this.containers[b]._trigger("out",null,a._uiHash(this));this.containers[b].containerCache.over=0}}}if(this.placeholder){this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove();d.extend(this,{helper:null,
dragging:false,reverting:false,_noFinalSort:null});this.domPosition.prev?d(this.domPosition.prev).after(this.currentItem):d(this.domPosition.parent).prepend(this.currentItem)}return this},serialize:function(a){var b=this._getItemsAsjQuery(a&&a.connected),c=[];a=a||{};d(b).each(function(){var e=(d(a.item||this).attr(a.attribute||"id")||"").match(a.expression||/(.+)[-=_](.+)/);if(e)c.push((a.key||e[1]+"[]")+"="+(a.key&&a.expression?e[1]:e[2]))});!c.length&&a.key&&c.push(a.key+"=");return c.join("&")},
toArray:function(a){var b=this._getItemsAsjQuery(a&&a.connected),c=[];a=a||{};b.each(function(){c.push(d(a.item||this).attr(a.attribute||"id")||"")});return c},_intersectsWith:function(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,e=this.positionAbs.top,f=e+this.helperProportions.height,g=a.left,h=g+a.width,i=a.top,k=i+a.height,j=this.offset.click.top,l=this.offset.click.left;j=e+j>i&&e+j<k&&b+l>g&&b+l<h;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||
this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?j:g<b+this.helperProportions.width/2&&c-this.helperProportions.width/2<h&&i<e+this.helperProportions.height/2&&f-this.helperProportions.height/2<k},_intersectsWithPointer:function(a){var b=d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top,a.height);a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left,a.width);b=b&&a;a=this._getDragVerticalDirection();
var c=this._getDragHorizontalDirection();if(!b)return false;return this.floating?c&&c=="right"||a=="down"?2:1:a&&(a=="down"?2:1)},_intersectsWithSides:function(a){var b=d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top+a.height/2,a.height);a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left+a.width/2,a.width);var c=this._getDragVerticalDirection(),e=this._getDragHorizontalDirection();return this.floating&&e?e=="right"&&a||e=="left"&&!a:c&&(c=="down"&&b||c=="up"&&!b)},
_getDragVerticalDirection:function(){var a=this.positionAbs.top-this.lastPositionAbs.top;return a!=0&&(a>0?"down":"up")},_getDragHorizontalDirection:function(){var a=this.positionAbs.left-this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left")},refresh:function(a){this._refreshItems(a);this.refreshPositions();return this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(a){var b=[],c=[],e=this._connectWith();
if(e&&a)for(a=e.length-1;a>=0;a--)for(var f=d(e[a]),g=f.length-1;g>=0;g--){var h=d.data(f[g],"sortable");if(h&&h!=this&&!h.options.disabled)c.push([d.isFunction(h.options.items)?h.options.items.call(h.element):d(h.options.items,h.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),h])}c.push([d.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):d(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),
this]);for(a=c.length-1;a>=0;a--)c[a][0].each(function(){b.push(this)});return d(b)},_removeCurrentsFromItems:function(){for(var a=this.currentItem.find(":data(sortable-item)"),b=0;b<this.items.length;b++)for(var c=0;c<a.length;c++)a[c]==this.items[b].item[0]&&this.items.splice(b,1)},_refreshItems:function(a){this.items=[];this.containers=[this];var b=this.items,c=[[d.isFunction(this.options.items)?this.options.items.call(this.element[0],a,{item:this.currentItem}):d(this.options.items,this.element),
this]],e=this._connectWith();if(e)for(var f=e.length-1;f>=0;f--)for(var g=d(e[f]),h=g.length-1;h>=0;h--){var i=d.data(g[h],"sortable");if(i&&i!=this&&!i.options.disabled){c.push([d.isFunction(i.options.items)?i.options.items.call(i.element[0],a,{item:this.currentItem}):d(i.options.items,i.element),i]);this.containers.push(i)}}for(f=c.length-1;f>=0;f--){a=c[f][1];e=c[f][0];h=0;for(g=e.length;h<g;h++){i=d(e[h]);i.data("sortable-item",a);b.push({item:i,instance:a,width:0,height:0,left:0,top:0})}}},refreshPositions:function(a){if(this.offsetParent&&
this.helper)this.offset.parent=this._getParentOffset();for(var b=this.items.length-1;b>=0;b--){var c=this.items[b],e=this.options.toleranceElement?d(this.options.toleranceElement,c.item):c.item;if(!a){c.width=e.outerWidth();c.height=e.outerHeight()}e=e.offset();c.left=e.left;c.top=e.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(b=this.containers.length-1;b>=0;b--){e=this.containers[b].element.offset();this.containers[b].containerCache.left=
e.left;this.containers[b].containerCache.top=e.top;this.containers[b].containerCache.width=this.containers[b].element.outerWidth();this.containers[b].containerCache.height=this.containers[b].element.outerHeight()}return this},_createPlaceholder:function(a){var b=a||this,c=b.options;if(!c.placeholder||c.placeholder.constructor==String){var e=c.placeholder;c.placeholder={element:function(){var f=d(document.createElement(b.currentItem[0].nodeName)).addClass(e||b.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];
if(!e)f.style.visibility="hidden";return f},update:function(f,g){if(!(e&&!c.forcePlaceholderSize)){g.height()||g.height(b.currentItem.innerHeight()-parseInt(b.currentItem.css("paddingTop")||0,10)-parseInt(b.currentItem.css("paddingBottom")||0,10));g.width()||g.width(b.currentItem.innerWidth()-parseInt(b.currentItem.css("paddingLeft")||0,10)-parseInt(b.currentItem.css("paddingRight")||0,10))}}}}b.placeholder=d(c.placeholder.element.call(b.element,b.currentItem));b.currentItem.after(b.placeholder);
c.placeholder.update(b,b.placeholder)},_contactContainers:function(a){for(var b=null,c=null,e=this.containers.length-1;e>=0;e--)if(!d.ui.contains(this.currentItem[0],this.containers[e].element[0]))if(this._intersectsWith(this.containers[e].containerCache)){if(!(b&&d.ui.contains(this.containers[e].element[0],b.element[0]))){b=this.containers[e];c=e}}else if(this.containers[e].containerCache.over){this.containers[e]._trigger("out",a,this._uiHash(this));this.containers[e].containerCache.over=0}if(b)if(this.containers.length===
1){this.containers[c]._trigger("over",a,this._uiHash(this));this.containers[c].containerCache.over=1}else if(this.currentContainer!=this.containers[c]){b=1E4;e=null;for(var f=this.positionAbs[this.containers[c].floating?"left":"top"],g=this.items.length-1;g>=0;g--)if(d.ui.contains(this.containers[c].element[0],this.items[g].item[0])){var h=this.items[g][this.containers[c].floating?"left":"top"];if(Math.abs(h-f)<b){b=Math.abs(h-f);e=this.items[g]}}if(e||this.options.dropOnEmpty){this.currentContainer=
this.containers[c];e?this._rearrange(a,e,null,true):this._rearrange(a,null,this.containers[c].element,true);this._trigger("change",a,this._uiHash());this.containers[c]._trigger("change",a,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[c]._trigger("over",a,this._uiHash(this));this.containers[c].containerCache.over=1}}},_createHelper:function(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a,this.currentItem])):
b.helper=="clone"?this.currentItem.clone():this.currentItem;a.parents("body").length||d(b.appendTo!="parent"?b.appendTo:this.currentItem[0].parentNode)[0].appendChild(a[0]);if(a[0]==this.currentItem[0])this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")};if(a[0].style.width==""||b.forceHelperSize)a.width(this.currentItem.width());if(a[0].style.height==
""||b.forceHelperSize)a.height(this.currentItem.height());return a},_adjustOffsetFromHelper:function(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0],top:+a[1]||0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=
this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),
10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.currentItem.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions=
{width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var a=this.options;if(a.containment=="parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(d(a.containment=="document"?document:window).height()||
document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)){var b=d(a.containment)[0];a=d(a.containment).offset();var c=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0)-this.margins.left,a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0)-this.margins.top,a.left+(c?Math.max(b.scrollWidth,
b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,a.top+(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=
document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(c[0].tagName);return{top:b.top+this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():
e?0:c.scrollLeft())*a)}},_generatePosition:function(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(c[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0]))this.offset.relative=this._getRelativeOffset();var f=a.pageX,g=a.pageY;if(this.originalPosition){if(this.containment){if(a.pageX-
this.offset.click.left<this.containment[0])f=this.containment[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<this.containment[1])g=this.containment[1]+this.offset.click.top;if(a.pageX-this.offset.click.left>this.containment[2])f=this.containment[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>this.containment[3])g=this.containment[3]+this.offset.click.top}if(b.grid){g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1];g=this.containment?!(g-this.offset.click.top<
this.containment[1]||g-this.offset.click.top>this.containment[3])?g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g;f=this.originalPageX+Math.round((f-this.originalPageX)/b.grid[0])*b.grid[0];f=this.containment?!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:!(f-this.offset.click.left<this.containment[0])?f-b.grid[0]:f+b.grid[0]:f}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&
this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:c.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(d.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:c.scrollLeft())}},_rearrange:function(a,b,c,e){c?c[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?b.item[0]:b.item[0].nextSibling);this.counter=
this.counter?++this.counter:1;var f=this,g=this.counter;window.setTimeout(function(){g==f.counter&&f.refreshPositions(!e)},0)},_clear:function(a,b){this.reverting=false;var c=[];!this._noFinalSort&&this.currentItem[0].parentNode&&this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var e in this._storedCSS)if(this._storedCSS[e]=="auto"||this._storedCSS[e]=="static")this._storedCSS[e]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();
this.fromOutside&&!b&&c.push(function(f){this._trigger("receive",f,this._uiHash(this.fromOutside))});if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!b)c.push(function(f){this._trigger("update",f,this._uiHash())});if(!d.ui.contains(this.element[0],this.currentItem[0])){b||c.push(function(f){this._trigger("remove",f,this._uiHash())});for(e=this.containers.length-1;e>=0;e--)if(d.ui.contains(this.containers[e].element[0],
this.currentItem[0])&&!b){c.push(function(f){return function(g){f._trigger("receive",g,this._uiHash(this))}}.call(this,this.containers[e]));c.push(function(f){return function(g){f._trigger("update",g,this._uiHash(this))}}.call(this,this.containers[e]))}}for(e=this.containers.length-1;e>=0;e--){b||c.push(function(f){return function(g){f._trigger("deactivate",g,this._uiHash(this))}}.call(this,this.containers[e]));if(this.containers[e].containerCache.over){c.push(function(f){return function(g){f._trigger("out",
g,this._uiHash(this))}}.call(this,this.containers[e]));this.containers[e].containerCache.over=0}}this._storedCursor&&d("body").css("cursor",this._storedCursor);this._storedOpacity&&this.helper.css("opacity",this._storedOpacity);if(this._storedZIndex)this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex);this.dragging=false;if(this.cancelHelperRemoval){if(!b){this._trigger("beforeStop",a,this._uiHash());for(e=0;e<c.length;e++)c[e].call(this,a);this._trigger("stop",a,this._uiHash())}return false}b||
this._trigger("beforeStop",a,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.helper[0]!=this.currentItem[0]&&this.helper.remove();this.helper=null;if(!b){for(e=0;e<c.length;e++)c[e].call(this,a);this._trigger("stop",a,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){d.Widget.prototype._trigger.apply(this,arguments)===false&&this.cancel()},_uiHash:function(a){var b=a||this;return{helper:b.helper,placeholder:b.placeholder||d([]),position:b.position,
originalPosition:b.originalPosition,offset:b.positionAbs,item:b.currentItem,sender:a?a.element:null}}});d.extend(d.ui.sortable,{version:"1.8.11"})})(jQuery);
;
jQuery.ui.draggable.prototype._mouseCapture=(function(A){return function(C){var B=A.call(this,C);if(B&&jQuery.browser.msie){C.stopPropagation()}return B}})(jQuery.ui.draggable.prototype._mouseCapture);
(function(){var _after=1;var _afterThrow=2;var _afterFinally=3;var _before=4;var _around=5;var _intro=6;var _regexEnabled=true;var _arguments="arguments";var _undef="undefined";var getType=(function(){var toString=Object.prototype.toString,toStrings={},nodeTypes={1:"element",3:"textnode",9:"document",11:"fragment"},types="Arguments Array Boolean Date Document Element Error Fragment Function NodeList Null Number Object RegExp String TextNode Undefined Window".split(" ");for(var i=types.length;i--;){var type=types[i],constructor=window[type];if(constructor){try{toStrings[toString.call(new constructor)]=type.toLowerCase()}catch(e){}}}return function(item){return item==null&&(item===undefined?_undef:"null")||item.nodeType&&nodeTypes[item.nodeType]||typeof item.length=="number"&&(item.callee&&_arguments||item.alert&&"window"||item.item&&"nodelist")||toStrings[toString.call(item)]}})();var isFunc=function(obj){return getType(obj)=="function"};var weaveOne=function(source,method,advice){var old=source[method];if(advice.type!=_intro&&!isFunc(old)){var oldObject=old;old=function(){var code=arguments.length>0?_arguments+"[0]":"";for(var i=1;i<arguments.length;i++){code+=","+_arguments+"["+i+"]"}return eval("oldObject("+code+");")}}var aspect;if(advice.type==_after||advice.type==_afterThrow||advice.type==_afterFinally){aspect=function(){var returnValue,exceptionThrown=null;try{returnValue=old.apply(this,arguments)}catch(e){exceptionThrown=e}if(advice.type==_after){if(exceptionThrown==null){returnValue=advice.value.apply(this,[returnValue,method])}else{throw exceptionThrown}}else{if(advice.type==_afterThrow&&exceptionThrown!=null){returnValue=advice.value.apply(this,[exceptionThrown,method])}else{if(advice.type==_afterFinally){returnValue=advice.value.apply(this,[returnValue,exceptionThrown,method])}}}return returnValue}}else{if(advice.type==_before){aspect=function(){advice.value.apply(this,[arguments,method]);return old.apply(this,arguments)}}else{if(advice.type==_intro){aspect=function(){return advice.value.apply(this,arguments)}}else{if(advice.type==_around){aspect=function(){var invocation={object:this,args:Array.prototype.slice.call(arguments)};return advice.value.apply(invocation.object,[{arguments:invocation.args,method:method,proceed:function(){return old.apply(invocation.object,invocation.args)}}])}}}}}aspect.unweave=function(){source[method]=old;pointcut=source=aspect=old=null};source[method]=aspect;return aspect};var search=function(source,pointcut,advice){var methods=[];for(var method in source){var item=null;try{item=source[method]}catch(e){}if(item!=null&&method.match(pointcut.method)&&isFunc(item)){methods[methods.length]={source:source,method:method,advice:advice}}}return methods};var weave=function(pointcut,advice){var source=typeof (pointcut.target.prototype)!=_undef?pointcut.target.prototype:pointcut.target;var advices=[];if(advice.type!=_intro&&typeof (source[pointcut.method])==_undef){var methods=search(pointcut.target,pointcut,advice);if(methods.length==0){methods=search(source,pointcut,advice)}for(var i in methods){advices[advices.length]=weaveOne(methods[i].source,methods[i].method,methods[i].advice)}}else{advices[0]=weaveOne(source,pointcut.method,advice)}return _regexEnabled?advices:advices[0]};jQuery.aop={after:function(pointcut,advice){return weave(pointcut,{type:_after,value:advice})},afterThrow:function(pointcut,advice){return weave(pointcut,{type:_afterThrow,value:advice})},afterFinally:function(pointcut,advice){return weave(pointcut,{type:_afterFinally,value:advice})},before:function(pointcut,advice){return weave(pointcut,{type:_before,value:advice})},around:function(pointcut,advice){return weave(pointcut,{type:_around,value:advice})},introduction:function(pointcut,advice){return weave(pointcut,{type:_intro,value:advice})},setup:function(settings){_regexEnabled=settings.regexMatch}}})();
/*
 * jQuery Form Plugin
 * version: 2.67 (12-MAR-2011)
 * @requires jQuery v1.3.2 or later
 *
 * Examples and documentation 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
 */
(function(B){B.fn.ajaxSubmit=function(Q){if(!this.length){A("ajaxSubmit: skipping submit process - no element selected");return this}if(typeof Q=="function"){Q={success:Q}}var H=this.attr("action");var D=(typeof H==="string")?B.trim(H):"";if(D){D=(D.match(/^([^#]+)/)||[])[1]}D=D||window.location.href||"";Q=B.extend(true,{url:D,type:this[0].getAttribute("method")||"GET",iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"},Q);var R={};this.trigger("form-pre-serialize",[this,Q,R]);if(R.veto){A("ajaxSubmit: submit vetoed via form-pre-serialize trigger");return this}if(Q.beforeSerialize&&Q.beforeSerialize(this,Q)===false){A("ajaxSubmit: submit aborted via beforeSerialize callback");return this}var F,N,L=this.formToArray(Q.semantic);if(Q.data){Q.extraData=Q.data;for(F in Q.data){if(Q.data[F] instanceof Array){for(var I in Q.data[F]){L.push({name:F,value:Q.data[F][I]})}}else{N=Q.data[F];N=B.isFunction(N)?N():N;L.push({name:F,value:N})}}}if(Q.beforeSubmit&&Q.beforeSubmit(L,this,Q)===false){A("ajaxSubmit: submit aborted via beforeSubmit callback");return this}this.trigger("form-submit-validate",[L,this,Q,R]);if(R.veto){A("ajaxSubmit: submit vetoed via form-submit-validate trigger");return this}var C=B.param(L);if(Q.type.toUpperCase()=="GET"){Q.url+=(Q.url.indexOf("?")>=0?"&":"?")+C;Q.data=null}else{Q.data=C}var P=this,K=[];if(Q.resetForm){K.push(function(){P.resetForm()})}if(Q.clearForm){K.push(function(){P.clearForm()})}if(!Q.dataType&&Q.target){var O=Q.success||function(){};K.push(function(T){var S=Q.replaceTarget?"replaceWith":"html";B(Q.target)[S](T).each(O,arguments)})}else{if(Q.success){K.push(Q.success)}}Q.success=function(W,T,X){var V=Q.context||Q;for(var U=0,S=K.length;U<S;U++){K[U].apply(V,[W,T,X||P,P])}};var G=B("input:file",this).length>0;var E="multipart/form-data";var J=(P.attr("enctype")==E||P.attr("encoding")==E);if(Q.iframe!==false&&(G||Q.iframe||J)){if(Q.closeKeepAlive){B.get(Q.closeKeepAlive,M)}else{M()}}else{B.ajax(Q)}this.trigger("form-submit-notify",[this,Q]);return this;function M(){var U=P[0];if(B(":input[name=submit],:input[id=submit]",U).length){alert('Error: Form elements must not have name or id of "submit".');return }var a=B.extend(true,{},B.ajaxSettings,Q);a.context=a.context||a;var d="jqFormIO"+(new Date().getTime()),Y="_"+d;var V=B('<iframe id="'+d+'" name="'+d+'" src="'+a.iframeSrc+'" />');var Z=V[0];V.css({position:"absolute",top:"-1000px",left:"-1000px"});var W={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(){A("aborting upload...");var g="aborted";this.aborted=1;V.attr("src",a.iframeSrc);W.error=g;a.error&&a.error.call(a.context,W,"error",g);i&&B.event.trigger("ajaxError",[W,a,g]);a.complete&&a.complete.call(a.context,W,"error")}};var i=a.global;if(i&&!B.active++){B.event.trigger("ajaxStart")}if(i){B.event.trigger("ajaxSend",[W,a])}if(a.beforeSend&&a.beforeSend.call(a.context,W,a)===false){if(a.global){B.active--}return }if(W.aborted){return }var h=0;var X=U.clk;if(X){var e=X.name;if(e&&!X.disabled){a.extraData=a.extraData||{};a.extraData[e]=X.value;if(X.type=="image"){a.extraData[e+".x"]=U.clk_x;a.extraData[e+".y"]=U.clk_y}}}function f(){var o=P.attr("target"),g=P.attr("action");U.setAttribute("target",d);if(U.getAttribute("method")!="POST"){U.setAttribute("method","POST")}if(U.getAttribute("action")!=a.url){U.setAttribute("action",a.url)}if(!a.skipEncodingOverride){P.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"})}if(a.timeout){setTimeout(function(){h=true;c()},a.timeout)}var m=[];try{if(a.extraData){for(var p in a.extraData){m.push(B('<input type="hidden" name="'+p+'" value="'+a.extraData[p]+'" />').appendTo(U)[0])}}V.appendTo("body");Z.attachEvent?Z.attachEvent("onload",c):Z.addEventListener("load",c,false);U.submit()}finally{U.setAttribute("action",g);if(o){U.setAttribute("target",o)}else{P.removeAttr("target")}B(m).remove()}}if(a.forceSync){f()}else{setTimeout(f,10)}var k,l,j=50;function c(){if(W.aborted){return }var r=Z.contentWindow?Z.contentWindow.document:Z.contentDocument?Z.contentDocument:Z.document;if(!r||r.location.href==a.iframeSrc){return }Z.detachEvent?Z.detachEvent("onload",c):Z.removeEventListener("load",c,false);var n=true;try{if(h){throw"timeout"}var s=a.dataType=="xml"||r.XMLDocument||B.isXMLDoc(r);A("isXml="+s);if(!s&&window.opera&&(r.body==null||r.body.innerHTML=="")){if(--j){A("requeing onLoad callback, DOM not available");setTimeout(c,250);return }}W.responseText=r.body?r.body.innerHTML:r.documentElement?r.documentElement.innerHTML:null;W.responseXML=r.XMLDocument?r.XMLDocument:r;W.getResponseHeader=function(u){var t={"content-type":a.dataType};return t[u]};var q=/(json|script)/.test(a.dataType);if(q||a.textarea){var m=r.getElementsByTagName("textarea")[0];if(m){W.responseText=m.value}else{if(q){var p=r.getElementsByTagName("pre")[0];var g=r.getElementsByTagName("body")[0];if(p){W.responseText=p.textContent}else{if(g){W.responseText=g.innerHTML}}}}}else{if(a.dataType=="xml"&&!W.responseXML&&W.responseText!=null){W.responseXML=b(W.responseText)}}k=S(W,a.dataType,a)}catch(o){A("error caught:",o);n=false;W.error=o;a.error&&a.error.call(a.context,W,"error",o);i&&B.event.trigger("ajaxError",[W,a,o])}if(W.aborted){A("upload aborted");n=false}if(n){a.success&&a.success.call(a.context,k,"success",W);i&&B.event.trigger("ajaxSuccess",[W,a])}i&&B.event.trigger("ajaxComplete",[W,a]);if(i&&!--B.active){B.event.trigger("ajaxStop")}a.complete&&a.complete.call(a.context,W,n?"success":"error");setTimeout(function(){V.removeData("form-plugin-onload");V.remove();W.responseXML=null},100)}var b=B.parseXML||function(g,m){if(window.ActiveXObject){m=new ActiveXObject("Microsoft.XMLDOM");m.async="false";m.loadXML(g)}else{m=(new DOMParser()).parseFromString(g,"text/xml")}return(m&&m.documentElement&&m.documentElement.nodeName!="parsererror")?m:null};var T=B.parseJSON||function(g){return window["eval"]("("+g+")")};var S=function(q,o,n){var m=q.getResponseHeader("content-type")||"",g=o==="xml"||!o&&m.indexOf("xml")>=0,p=g?q.responseXML:q.responseText;if(g&&p.documentElement.nodeName==="parsererror"){B.error&&B.error("parsererror")}if(n&&n.dataFilter){p=n.dataFilter(p,o)}if(typeof p==="string"){if(o==="json"||!o&&m.indexOf("json")>=0){p=T(p)}else{if(o==="script"||!o&&m.indexOf("javascript")>=0){B.globalEval(p)}}}return p}}};B.fn.ajaxForm=function(C){if(this.length===0){var D={s:this.selector,c:this.context};if(!B.isReady&&D.s){A("DOM not ready, queuing ajaxForm");B(function(){B(D.s,D.c).ajaxForm(C)});return this}A("terminating; zero elements found by selector"+(B.isReady?"":" (DOM not ready)"));return this}return this.ajaxFormUnbind().bind("submit.form-plugin",function(E){if(!E.isDefaultPrevented()){E.preventDefault();B(this).ajaxSubmit(C)}}).bind("click.form-plugin",function(I){var H=I.target;var F=B(H);if(!(F.is(":submit,input:image"))){var E=F.closest(":submit");if(E.length==0){return }H=E[0]}var G=this;G.clk=H;if(H.type=="image"){if(I.offsetX!=undefined){G.clk_x=I.offsetX;G.clk_y=I.offsetY}else{if(typeof B.fn.offset=="function"){var J=F.offset();G.clk_x=I.pageX-J.left;G.clk_y=I.pageY-J.top}else{G.clk_x=I.pageX-H.offsetLeft;G.clk_y=I.pageY-H.offsetTop}}}setTimeout(function(){G.clk=G.clk_x=G.clk_y=null},100)})};B.fn.ajaxFormUnbind=function(){return this.unbind("submit.form-plugin click.form-plugin")};B.fn.formToArray=function(N){var M=[];if(this.length===0){return M}var D=this[0];var G=N?D.getElementsByTagName("*"):D.elements;if(!G){return M}var I,H,F,O,E,K,C;for(I=0,K=G.length;I<K;I++){E=G[I];F=E.name;if(!F){continue}if(N&&D.clk&&E.type=="image"){if(!E.disabled&&D.clk==E){M.push({name:F,value:B(E).val()});M.push({name:F+".x",value:D.clk_x},{name:F+".y",value:D.clk_y})}continue}O=B.fieldValue(E,true);if(O&&O.constructor==Array){for(H=0,C=O.length;H<C;H++){M.push({name:F,value:O[H]})}}else{if(O!==null&&typeof O!="undefined"){M.push({name:F,value:O})}}}if(!N&&D.clk){var J=B(D.clk),L=J[0];F=L.name;if(F&&!L.disabled&&L.type=="image"){M.push({name:F,value:J.val()});M.push({name:F+".x",value:D.clk_x},{name:F+".y",value:D.clk_y})}}return M};B.fn.formSerialize=function(C){return B.param(this.formToArray(C))};B.fn.fieldSerialize=function(D){var C=[];this.each(function(){var H=this.name;if(!H){return }var F=B.fieldValue(this,D);if(F&&F.constructor==Array){for(var G=0,E=F.length;G<E;G++){C.push({name:H,value:F[G]})}}else{if(F!==null&&typeof F!="undefined"){C.push({name:this.name,value:F})}}});return B.param(C)};B.fn.fieldValue=function(H){for(var G=[],E=0,C=this.length;E<C;E++){var F=this[E];var D=B.fieldValue(F,H);if(D===null||typeof D=="undefined"||(D.constructor==Array&&!D.length)){continue}D.constructor==Array?B.merge(G,D):G.push(D)}return G};B.fieldValue=function(C,I){var E=C.name,N=C.type,O=C.tagName.toLowerCase();if(I===undefined){I=true}if(I&&(!E||C.disabled||N=="reset"||N=="button"||(N=="checkbox"||N=="radio")&&!C.checked||(N=="submit"||N=="image")&&C.form&&C.form.clk!=C||O=="select"&&C.selectedIndex==-1)){return null}if(O=="select"){var J=C.selectedIndex;if(J<0){return null}var L=[],D=C.options;var G=(N=="select-one");var K=(G?J+1:D.length);for(var F=(G?J:0);F<K;F++){var H=D[F];if(H.selected){var M=H.value;if(!M){M=(H.attributes&&H.attributes.value&&!(H.attributes.value.specified))?H.text:H.value}if(G){return M}L.push(M)}}return L}return B(C).val()};B.fn.clearForm=function(){return this.each(function(){B("input,select,textarea",this).clearFields()})};B.fn.clearFields=B.fn.clearInputs=function(){return this.each(function(){var D=this.type,C=this.tagName.toLowerCase();if(D=="text"||D=="password"||C=="textarea"){this.value=""}else{if(D=="checkbox"||D=="radio"){this.checked=false}else{if(C=="select"){this.selectedIndex=-1}}}})};B.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=="function"||(typeof this.reset=="object"&&!this.reset.nodeType)){this.reset()}})};B.fn.enable=function(C){if(C===undefined){C=true}return this.each(function(){this.disabled=!C})};B.fn.selected=function(C){if(C===undefined){C=true}return this.each(function(){var D=this.type;if(D=="checkbox"||D=="radio"){this.checked=C}else{if(this.tagName.toLowerCase()=="option"){var E=B(this).parent("select");if(C&&E[0]&&E[0].type=="select-one"){E.find("option").selected(false)}this.selected=C}}})};function A(){if(B.fn.ajaxSubmit.debug){var C="[jquery.form] "+Array.prototype.join.call(arguments,"");if(window.console&&window.console.log){window.console.log(C)}else{if(window.opera&&window.opera.postError){window.opera.postError(C)}}}}})(jQuery);
(function(D){function C(G,E){function F(){E.tm=window.setTimeout(function(){E.loadedChars=""},700)}E.loadedChars=E.loadedChars+G;if(!E.tm){F()}else{clearTimeout(E.tm);F()}}function A(E){return !(this!==E.target&&(/textarea|select/i.test(E.target.nodeName)||E.target.type==="text"||E.target.type==="password"))}D.hotKeys={version:"0.8",specialKeys:{8:"backspace",9:"tab",13:"return",16:"shift",17:"ctrl",18:"alt",19:"pause",20:"capslock",27:"esc",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",45:"insert",46:"del",96:"0",97:"1",98:"2",91:"meta",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9",106:"*",107:"+",109:"-",110:".",111:"/",112:"f1",113:"f2",114:"f3",115:"f4",116:"f5",117:"f6",118:"f7",119:"f8",120:"f9",121:"f10",122:"f11",123:"f12",144:"numlock",145:"scroll",188:",",190:".",191:"/",224:"meta",219:"[",221:"]"},keypressKeys:["<",">","?"],shiftNums:{"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":'"',",":"<",".":">","/":"?","\\":"|"}};D.each(D.hotKeys.keypressKeys,function(E,F){D.hotKeys.shiftNums[F]=F});function B(F){var E,G;if(typeof F.data!=="string"){return }E=F.handler;G=F.data.toLowerCase().split(" ");F.loadedChars="";D(this).bind("keydown",function(I){var H;if(!A(I)){return }H=D.hotKeys.specialKeys[I.which];if((H==="alt"||I.altKey)){C("alt+",F)}if((H==="ctrl"||I.ctrlKey)&&!/ctrl\+/.test(F.loadedChars)){C("ctrl+",F)}if(((H!=="ctrl"&&!I.ctrlKey)&&(H==="meta"||I.metaKey))&&!/meta\+/.test(F.loadedChars)){C("meta+",F)}});F.handler=function(K){var J,I,L,H;if(!A(K)){return }I=D.hotKeys.specialKeys[K.which];L=String.fromCharCode(K.which).toLowerCase();H={};if(I){H[I]=true}if(K.shiftKey){H[F.loadedChars+D.hotKeys.shiftNums[L]||I]=true}else{H[F.loadedChars+L]=true}for(J=0,l=G.length;J<l;J++){if(H[G[J]]){F.loadedChars="";return E.apply(this,arguments)}else{if(G[J].charAt(F.loadedChars.length)===L){C(L,F)}}}}}D.each(["keydown","keyup","keypress"],function(){D.event.special[this]={add:B}})})(jQuery);
if(typeof jQuery!="undefined"){var AJS=(function(){var E=[];function F(G){switch(G){case"<":return"&lt;";case">":return"&gt;";case"&":return"&amp;";case"'":return"&#39;";default:return"&quot;"}}var B=/[&"'<>]/g;var D={version:"3.5.1",params:{},$:jQuery,log:function(G){if(typeof console!="undefined"&&console.log){console.log(G)}},I18n:{getText:function(G){return G}},stopEvent:function(G){G.stopPropagation();return false},include:function(G){if(!this.contains(E,G)){E.push(G);var H=document.createElement("script");H.src=G;this.$("body").append(H)}},toggleClassName:function(G,H){if(!(G=this.$(G))){return }G.toggleClass(H)},setVisible:function(H,G){if(!(H=this.$(H))){return }var I=this.$;I(H).each(function(){var J=I(this).hasClass("hidden");if(J&&G){I(this).removeClass("hidden")}else{if(!J&&!G){I(this).addClass("hidden")}}})},setCurrent:function(G,H){if(!(G=this.$(G))){return }if(H){G.addClass("current")}else{G.removeClass("current")}},isVisible:function(G){return !this.$(G).hasClass("hidden")},populateParameters:function(){var G=this;this.$(".parameters input").each(function(){var H=this.value,I=this.title||this.id;if(G.$(this).hasClass("list")){if(G.params[I]){G.params[I].push(H)}else{G.params[I]=[H]}}else{G.params[I]=(H.match(/^(tru|fals)e$/i)?H.toLowerCase()=="true":H)}})},toInit:function(H){var G=this;this.$(function(){try{H.apply(this,arguments)}catch(I){G.log("Failed to run init function: "+I)}});return this},indexOf:function(K,J,H){var I=K.length;if(H==null){H=0}else{if(H<0){H=Math.max(0,I+H)}}for(var G=H;G<I;G++){if(K[G]===J){return G}}return -1},contains:function(H,G){return this.indexOf(H,G)>-1},format:function(I){var G=/^((?:(?:[^']*'){2})*?[^']*?)\{(\d+)\}/,H=/'(?!')/g;AJS.format=function(M){var K=arguments,L="",J=M.match(G);while(J){M=M.substring(J[0].length);L+=J[1].replace(H,"")+(K.length>++J[2]?K[J[2]]:"");J=M.match(G)}return L+=M.replace(H,"")};return AJS.format.apply(AJS,arguments)},firebug:function(){var G=this.$(document.createElement("script"));G.attr("src","http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js");this.$("head").append(G);(function(){if(window.firebug){firebug.init()}else{setTimeout(arguments.callee,0)}})()},clone:function(G){return AJS.$(G).clone().removeAttr("id")},alphanum:function(N,M){N=(N+"").toLowerCase();M=(M+"").toLowerCase();var I=/(\d+|\D+)/g,J=N.match(I),G=M.match(I),L=Math.max(J.length,G.length);for(var H=0;H<L;H++){if(H==J.length){return -1}if(H==G.length){return 1}var O=parseInt(J[H],10),K=parseInt(G[H],10);if(O==J[H]&&K==G[H]&&O!=K){return(O-K)/Math.abs(O-K)}if((O!=J[H]||K!=G[H])&&J[H]!=G[H]){return J[H]<G[H]?-1:1}}return 0},dim:function(){if(AJS.dim.dim){AJS.dim.dim.remove();AJS.dim.dim=null}else{AJS.dim.dim=AJS("div").css({width:"100%",height:AJS.$(document).height(),background:"#000",opacity:0.5,position:"absolute",top:0,left:0});AJS.$("body").append(AJS.dim.dim)}},onTextResize:function(H){if(typeof H=="function"){if(AJS.onTextResize["on-text-resize"]){AJS.onTextResize["on-text-resize"].push(function(I){H(I)})}else{var G=AJS("div");G.css({width:"1em",height:"1em",position:"absolute",top:"-9999em",left:"-9999em"});this.$("body").append(G);G.size=G.width();setInterval(function(){if(G.size!=G.width()){G.size=G.width();for(var I=0,J=AJS.onTextResize["on-text-resize"].length;I<J;I++){AJS.onTextResize["on-text-resize"][I](G.size)}}},0);AJS.onTextResize.em=G;AJS.onTextResize["on-text-resize"]=[function(I){H(I)}]}}},unbindTextResize:function(I){for(var G=0,H=AJS.onTextResize["on-text-resize"].length;G<H;G++){if(AJS.onTextResize["on-text-resize"][G]==I){return AJS.onTextResize["on-text-resize"].splice(G,1)}}},escape:function(G){return escape(G).replace(/%u\w{4}/gi,function(H){return unescape(H)})},escapeHtml:function(G){return G.replace(B,F)},filterBySearch:function(K,P,Q){if(P==""){return[]}var I=this.$;var N=(Q&&Q.keywordsField)||"keywords";var M=(Q&&Q.ignoreForCamelCase)?"i":"";var J=(Q&&Q.matchBoundary)?"\\b":"";var H=(Q&&Q.splitRegex)||(/\s+/);var L=P.split(H);var G=[];I.each(L,function(){var S=[new RegExp(J+this,"i")];if(/^([A-Z][a-z]*){2,}$/.test(this)){var R=this.replace(/([A-Z][a-z]*)/g,"\\b$1[^,]*");S.push(new RegExp(R,M))}G.push(S)});var O=[];I.each(K,function(){for(var T=0;T<G.length;T++){var R=false;for(var S=0;S<G[T].length;S++){if(G[T][S].test(this[N])){R=true;break}}if(!R){return }}O.push(this)});return O},drawLogo:function(J){options={};options=AJS.$.extend(J,options);var N=options.scaleFactor||1,M=options.fill||"#fff",L=options.stroke||"#000",I=400*N,G=40*N;strokeWidth=options.strokeWidth||1;if(AJS.$(".aui-logo").size()==0){AJS.$("body").append("<div id='aui-logo' class='aui-logo'><div>")}strokeWidth=options.strokeWidth||1,containerID=options.containerID||".aui-logo";var H=Raphael(containerID,I+50*N,G+100*N);var K=H.path("M 0,0 c 3.5433333,-4.7243333 7.0866667,-9.4486667 10.63,-14.173 -14.173,0 -28.346,0 -42.519,0 C -35.432667,-9.4486667 -38.976333,-4.7243333 -42.52,0 -28.346667,0 -14.173333,0 0,0 z m 277.031,28.346 c -14.17367,0 -28.34733,0 -42.521,0 C 245.14,14.173 255.77,0 266.4,-14.173 c -14.17267,0 -28.34533,0 -42.518,0 C 213.25167,0 202.62133,14.173 191.991,28.346 c -14.17333,0 -28.34667,0 -42.52,0 14.17333,-18.8976667 28.34667,-37.7953333 42.52,-56.693 -7.08667,-9.448667 -14.17333,-18.897333 -21.26,-28.346 -14.173,0 -28.346,0 -42.519,0 7.08667,9.448667 14.17333,18.897333 21.26,28.346 -14.17333,18.8976667 -28.34667,37.7953333 -42.52,56.693 -14.173333,0 -28.346667,0 -42.52,0 10.63,-14.173 21.26,-28.346 31.89,-42.519 -14.390333,0 -28.780667,0 -43.171,0 C 42.520733,1.330715e-4 31.889933,14.174867 21.26,28.347 c -42.520624,6.24e-4 -85.039187,-8.13e-4 -127.559,-0.001 11.220667,-14.961 22.441333,-29.922 33.662,-44.883 -6.496,-8.661 -12.992,-17.322 -19.488,-25.983 5.905333,0 11.810667,0 17.716,0 -10.63,-14.173333 -21.26,-28.346667 -31.89,-42.52 14.173333,0 28.346667,0 42.52,0 10.63,14.173333 21.26,28.346667 31.89,42.52 14.173333,0 28.3466667,0 42.52,0 -10.63,-14.173333 -21.26,-28.346667 -31.89,-42.52 14.1733333,0 28.3466667,0 42.52,0 10.63,14.173333 21.26,28.346667 31.89,42.52 14.390333,0 28.780667,0 43.171,0 -10.63,-14.173333 -21.26,-28.346667 -31.89,-42.52 42.51967,0 85.03933,0 127.559,0 10.63033,14.173333 21.26067,28.346667 31.891,42.52 14.17267,0 28.34533,0 42.518,0 -10.63,-14.173333 -21.26,-28.346667 -31.89,-42.52 14.17367,0 28.34733,0 42.521,0 14.17333,18.897667 28.34667,37.795333 42.52,56.693 -14.17333,18.8976667 -28.34667,37.7953333 -42.52,56.693 z");console.log(G);K.scale(N,-N,0,0);K.translate(120*N,G);K.attr("fill",M);K.attr("stroke",L);K.attr("stroke-width",strokeWidth)}};if(typeof AJS!="undefined"){for(var C in AJS){D[C]=AJS[C]}}var A=function(){var G=null;if(arguments.length&&typeof arguments[0]=="string"){G=arguments.callee.$(document.createElement(arguments[0]));if(arguments.length==2){G.html(arguments[1])}}return G};for(var C in D){A[C]=D[C]}return A})();AJS.$(function(){AJS.populateParameters()})}if(typeof console=="undefined"){console={messages:[],log:function(A){this.messages.push(A)},show:function(){alert(this.messages.join("\n"));this.messages=[]}}}else{console.show=function(){}}AJS.$.ajaxSettings.traditional=true;
AJS=AJS||{};(function(){var A=false;AJS.contextPath=function(){var B=null;var D=[A,window.contextPath,window.Confluence&&Confluence.getContextPath(),window.BAMBOO&&BAMBOO.contextPath,window.FECRU&&FECRU.pageContext];for(var C=0;C<D.length;C++){if(typeof D[C]==="string"){B=D[C];break}}return B}})();
AJS.bind=function(A,C,B){try{return jQuery(window).bind(A,C,B)}catch(D){AJS.log("error while binding: "+D.message)}};AJS.unbind=function(A,B){try{return jQuery(window).unbind(A,B)}catch(C){AJS.log("error while unbinding: "+C.message)}};AJS.trigger=function(A,C){try{return jQuery(window).trigger(A,C)}catch(B){AJS.log("error while triggering: "+B.message)}};
(function(){var E="AJS.conglomerate.cookie";function B(F,I){I=I||"";var H=new RegExp(F+"=([^|]+)"),G=I.match(H);return G&&G[1]}function A(F,H,J){var G=new RegExp("\\s*"+F+"=[^|]+(\\||$)");J=J||"";J=J.replace(G,"")+(J?"|":"");if(H){var I=F+"="+H;if(J.length+I.length<4020){J+=I}}return J}function D(F){var H=new RegExp(F+"=([^;]+)"),G=document.cookie.match(H);return G&&G[1]}function C(F,H,J){var G="";if(J){var I=new Date();I.setTime(+I+J*24*60*60*1000);G="; expires="+I.toGMTString()}document.cookie=F+"="+H+G+";path=/"}AJS.Cookie={save:function(G,H,F){var I=D(E);I=A(G,H,I);C(E,I,F||365)},read:function(G,F){var I=D(E);var H=B(G,I);if(H!=null){return H}return F},erase:function(F){this.save(F,"")}}})();
AJS.dim=function(A){if(!AJS.dim.dim){AJS.dim.dim=AJS("div").addClass("aui-blanket");if(AJS.$.browser.msie){AJS.dim.dim.css({width:"200%",height:Math.max(AJS.$(document).height(),AJS.$(window).height())+"px"})}AJS.$("body").append(AJS.dim.dim);if(AJS.$.browser.msie&&typeof AJS.hasFlash==="undefined"&&A===false){AJS.hasFlash=false;AJS.$("object, embed, iframe").each(function(){if(this.nodeName.toLowerCase()==="iframe"){if(AJS.$(this).contents().find("object, embed").length){AJS.hasFlash=true;return false}}else{AJS.hasFlash=true;return false}})}if(AJS.$.browser.msie&&(A!==false||AJS.hasFlash)){AJS.dim.shim=AJS.$('<iframe frameBorder="0" class="aui-blanket-shim" src="javascript:false;"/>');AJS.dim.shim.css({height:Math.max(AJS.$(document).height(),AJS.$(window).height())+"px"});AJS.$("body").append(AJS.dim.shim)}if(AJS.$.browser.msie&&parseInt(AJS.$.browser.version,10)<8){AJS.dim.cachedOverflow=AJS.$("html").css("overflow");AJS.$("html").css("overflow","hidden")}else{AJS.dim.cachedOverflow=AJS.$("body").css("overflow");AJS.$("body").css("overflow","hidden")}}};AJS.undim=function(){if(AJS.dim.dim){AJS.dim.dim.remove();AJS.dim.dim=null;if(AJS.dim.shim){AJS.dim.shim.remove()}if(AJS.$.browser.msie&&parseInt(AJS.$.browser.version,10)<8){AJS.$("html").css("overflow",AJS.dim.cachedOverflow)}else{AJS.$("body").css("overflow",AJS.dim.cachedOverflow)}if(AJS.$.browser.safari){var A=AJS.$(window).scrollTop();AJS.$(window).scrollTop(10+5*(A==10)).scrollTop(A)}}};AJS.popup=function(I){var D={width:800,height:600,closeOnOutsideClick:false,keypressListener:function(J){if(J.keyCode===27&&B.is(":visible")){F.hide()}}};if(typeof I!="object"){I={width:arguments[0],height:arguments[1],id:arguments[2]};I=AJS.$.extend({},I,arguments[3])}I=AJS.$.extend({},D,I);var B=AJS("div").addClass("aui-popup");if(I.id){B.attr("id",I.id)}var E=3000;AJS.$(".aui-dialog").each(function(){var J=AJS.$(this);E=(J.css("z-index")>E)?J.css("z-index"):E});var G=(function(K,J){I.width=(K=(K||I.width));I.height=(J=(J||I.height));B.css({marginTop:-Math.round(J/2)+"px",marginLeft:-Math.round(K/2)+"px",width:K,height:J,background:"#fff","z-index":parseInt(E,10)+2});return arguments.callee})(I.width,I.height);AJS.$("body").append(B);B.hide();B.enable();var C=AJS.$(".aui-blanket"),A=function(N){var O=false,K=AJS.$(":input:visible:enabled:first",N),J=N.children(":visible");if(K.length&&K[0].tabIndex>=0){K.focus();return O=true}if(N.length&&N[0].tabIndex>=0){N.focus();return O=true}for(var L=0,M=J.length;L<M;L++){O=A(jQuery(J[L]));if(O){break}}return O},H=function(J){if(A(AJS.$(".dialog-page-body",J))){return }if(A(AJS.$(".dialog-button-panel",J))){return }A(AJS.$(".dialog-page-menu",J))};var F={changeSize:function(J,K){if((J&&J!=I.width)||(K&&K!=I.height)){G(J,K);if(this.shadow){this.shadow.remove();this.shadow=null}}this.show()},show:function(){var J=function(){var K=5;if(AJS.$.browser.msie&&~~(AJS.$.browser.version)<9){K=3}AJS.$(document).keydown(I.keypressListener);AJS.dim();C=AJS.$(".aui-blanket");if(C.size()!=0&&I.closeOnOutsideClick){C.click(function(){if(B.is(":visible")){F.hide()}})}B.show();if(!this.shadow){var L=B.offset();this.shadow=Raphael.shadow(L.top,L.left,I.width,I.height,{target:B[0],zindex:(B.css("z-index")-1)});this.shadow.css({position:"fixed",top:"50%",left:"50%",marginLeft:-(I.width/2-K)+"px",marginTop:-(I.height/2-K)+"px"})}AJS.popup.current=this;H(B);AJS.$(document).trigger("showLayer",["popup",this])};J.call(this);this.show=J},hide:function(){AJS.$(document).unbind("keydown",I.keypressListener);C.unbind();this.element.hide();if(this.shadow){this.shadow.remove();this.shadow=null}if(AJS.$(".aui-dialog:visible").size()==0){AJS.undim()}AJS.$(document).trigger("hideLayer",["popup",this]);AJS.popup.current=null;this.enable()},element:B,remove:function(){if(this.shadow){this.shadow.remove();this.shadow=null;this.shadowParent.remove();this.shadowParent=null}B.remove();this.element=null},disable:function(){if(!this.disabled){this.popupBlanket=AJS.$("<div class='dialog-blanket'> </div>").css({height:B.height(),width:B.width()});B.append(this.popupBlanket);this.disabled=true}},enable:function(){if(this.disabled){this.disabled=false;this.popupBlanket.remove();this.popupBlanket=null}}};return F};(function(){function A(J,H,G,I){if(!J.buttonpanel){J.addButtonPanel()}this.page=J;this.onclick=G;this._onclick=function(){return G.call(this,J.dialog,J)===true};this.item=AJS("button",H).addClass("button-panel-button");if(I){this.item.addClass(I)}if(typeof G=="function"){this.item.click(this._onclick)}J.buttonpanel.append(this.item);this.id=J.button.length;J.button[this.id]=this}function B(K,I,H,J,G){if(!K.buttonpanel){K.addButtonPanel()}if(!G){G="#"}this.page=K;this.onclick=H;this._onclick=function(){return H.call(this,K.dialog,K)===true};this.item=AJS("a",I).attr("href",G).addClass("button-panel-link");if(J){this.item.addClass(J)}if(typeof H=="function"){this.item.click(this._onclick)}K.buttonpanel.append(this.item);this.id=K.button.length;K.button[this.id]=this}function D(I,H){var G=I=="left"?-1:1;return function(M){var K=this.page[H];if(this.id!=((G==1)?K.length-1:0)){G*=(M||1);K[this.id+G].item[(G<0?"before":"after")](this.item);K.splice(this.id,1);K.splice(this.id+G,0,this);for(var J=0,L=K.length;J<L;J++){if(H=="panel"&&this.page.curtab==K[J].id){this.page.curtab=J}K[J].id=J}}return this}}function F(G){return function(){this.page[G].splice(this.id,1);for(var H=0,I=this.page[G].length;H<I;H++){this.page[G][H].id=H}this.item.remove()}}A.prototype.moveUp=A.prototype.moveLeft=D("left","button");A.prototype.moveDown=A.prototype.moveRight=D("right","button");A.prototype.remove=F("button");A.prototype.html=function(G){return this.item.html(G)};A.prototype.onclick=function(G){if(typeof G=="undefined"){return this.onclick}else{this.item.unbind("click",this._onclick);this._onclick=function(){return G.call(this,page.dialog,page)===true};if(typeof G=="function"){this.item.click(this._onclick)}}};var E=function(M,N,G,L,J){if(!(G instanceof AJS.$)){G=AJS.$(G)}this.dialog=M.dialog;this.page=M;this.id=M.panel.length;this.button=AJS("button").html(N).addClass("item-button");if(J){this.button[0].id=J}this.item=AJS("li").append(this.button).addClass("page-menu-item");this.body=AJS("div").append(G).addClass("dialog-panel-body").css("height",M.dialog.height+"px");this.padding=10;if(L){this.body.addClass(L)}var I=M.panel.length,K=this;M.menu.append(this.item);M.body.append(this.body);M.panel[I]=this;var H=function(){var O;if(M.curtab+1){O=M.panel[M.curtab];O.body.hide();O.item.removeClass("selected");(typeof O.onblur=="function")&&O.onblur()}M.curtab=K.id;K.body.show();K.item.addClass("selected");(typeof K.onselect=="function")&&K.onselect();(typeof M.ontabchange=="function")&&M.ontabchange(K,O)};if(!this.button.click){AJS.log("atlassian-dialog:Panel:constructor - this.button.click false");this.button.onclick=H}else{this.button.click(H)}H();if(I==0){M.menu.css("display","none")}else{M.menu.show()}};E.prototype.select=function(){this.button.click()};E.prototype.moveUp=E.prototype.moveLeft=D("left","panel");E.prototype.moveDown=E.prototype.moveRight=D("right","panel");E.prototype.remove=F("panel");E.prototype.html=function(G){if(G){this.body.html(G);return this}else{return this.body.html()}};E.prototype.setPadding=function(G){if(!isNaN(+G)){this.body.css("padding",+G);this.padding=+G;this.page.recalcSize()}return this};var C=function(G,H){this.dialog=G;this.id=G.page.length;this.element=AJS("div").addClass("dialog-components");this.body=AJS("div").addClass("dialog-page-body");this.menu=AJS("ul").addClass("dialog-page-menu").css("height",G.height+"px");this.body.append(this.menu);this.curtab;this.panel=[];this.button=[];if(H){this.body.addClass(H)}G.popup.element.append(this.element.append(this.menu).append(this.body));G.page[G.page.length]=this};C.prototype.recalcSize=function(){var G=this.header?43:0;var J=this.buttonpanel?43:0;for(var I=this.panel.length;I--;){var H=this.dialog.height-G-J;this.panel[I].body.css("height",H-this.panel[I].padding*2);this.menu.css("height",H-parseFloat(this.menu.css("padding-top")))}};C.prototype.addButtonPanel=function(){this.buttonpanel=AJS("div").addClass("dialog-button-panel");this.element.append(this.buttonpanel)};C.prototype.addPanel=function(J,G,I,H){new E(this,J,G,I,H);this.recalcSize();return this};C.prototype.addHeader=function(H,G){if(this.header){this.header.remove()}this.header=AJS("h2").html(H||"").addClass("dialog-title");G&&this.header.addClass(G);this.element.prepend(this.header);this.recalcSize();return this};C.prototype.addButton=function(H,G,I){new A(this,H,G,I);this.recalcSize();return this};C.prototype.addLink=function(I,H,J,G){new B(this,I,H,J,G);this.recalcSize();return this};C.prototype.gotoPanel=function(G){this.panel[G.id||G].select()};C.prototype.getCurrentPanel=function(){return this.panel[this.curtab]};C.prototype.hide=function(){this.element.hide()};C.prototype.show=function(){this.element.show()};C.prototype.remove=function(){this.element.remove()};AJS.Dialog=function(I,G,J){var H={};if(!+I){H=Object(I);I=H.width;G=H.height;J=H.id}this.height=G||480;this.width=I||640;this.id=J;H=AJS.$.extend({},H,{width:this.width,height:this.height,id:this.id});this.popup=AJS.popup(H);this.popup.element.addClass("aui-dialog");this.page=[];this.curpage=0;new C(this)};AJS.Dialog.prototype.addHeader=function(H,G){this.page[this.curpage].addHeader(H,G);return this};AJS.Dialog.prototype.addButton=function(H,G,I){this.page[this.curpage].addButton(H,G,I);return this};AJS.Dialog.prototype.addLink=function(I,H,J,G){this.page[this.curpage].addLink(I,H,J,G);return this};AJS.Dialog.prototype.addSubmit=function(H,G){this.page[this.curpage].addButton(H,G,"button-panel-submit-button");return this};AJS.Dialog.prototype.addCancel=function(H,G){this.page[this.curpage].addLink(H,G,"button-panel-cancel-link");return this};AJS.Dialog.prototype.addButtonPanel=function(){this.page[this.curpage].addButtonPanel();return this};AJS.Dialog.prototype.addPanel=function(J,G,I,H){this.page[this.curpage].addPanel(J,G,I,H);return this};AJS.Dialog.prototype.addPage=function(G){new C(this,G);this.page[this.curpage].hide();this.curpage=this.page.length-1;return this};AJS.Dialog.prototype.nextPage=function(){this.page[this.curpage++].hide();if(this.curpage>=this.page.length){this.curpage=0}this.page[this.curpage].show();return this};AJS.Dialog.prototype.prevPage=function(){this.page[this.curpage--].hide();if(this.curpage<0){this.curpage=this.page.length-1}this.page[this.curpage].show();return this};AJS.Dialog.prototype.gotoPage=function(G){this.page[this.curpage].hide();this.curpage=G;if(this.curpage<0){this.curpage=this.page.length-1}else{if(this.curpage>=this.page.length){this.curpage=0}}this.page[this.curpage].show();return this};AJS.Dialog.prototype.getPanel=function(H,I){var G=(I==null)?this.curpage:H;if(I==null){I=H}return this.page[G].panel[I]};AJS.Dialog.prototype.getPage=function(G){return this.page[G]};AJS.Dialog.prototype.getCurrentPanel=function(){return this.page[this.curpage].getCurrentPanel()};AJS.Dialog.prototype.gotoPanel=function(I,H){if(H!=null){var G=I.id||I;this.gotoPage(G)}this.page[this.curpage].gotoPanel(typeof H=="undefined"?I:H)};AJS.Dialog.prototype.show=function(){this.popup.show();AJS.trigger("show.dialog",{dialog:this});return this};AJS.Dialog.prototype.hide=function(){this.popup.hide();AJS.trigger("hide.dialog",{dialog:this});return this};AJS.Dialog.prototype.remove=function(){this.popup.hide();this.popup.remove();AJS.trigger("remove.dialog",{dialog:this})};AJS.Dialog.prototype.disable=function(){this.popup.disable();return this};AJS.Dialog.prototype.enable=function(){this.popup.enable();return this};AJS.Dialog.prototype.get=function(O){var H=[],N=this;var P='#([^"][^ ]*|"[^"]*")';var Q=":(\\d+)";var I="page|panel|button|header";var J="(?:("+I+")(?:"+P+"|"+Q+")?|"+P+")";var L=new RegExp("(?:^|,)\\s*"+J+"(?:\\s+"+J+")?\\s*(?=,|$)","ig");(O+"").replace(L,function(b,R,a,S,Y,X,U,c,Z){R=R&&R.toLowerCase();var T=[];if(R=="page"&&N.page[S]){T.push(N.page[S]);R=X;R=R&&R.toLowerCase();a=U;S=c;Y=Z}else{T=N.page}a=a&&(a+"").replace(/"/g,"");U=U&&(U+"").replace(/"/g,"");Y=Y&&(Y+"").replace(/"/g,"");Z=Z&&(Z+"").replace(/"/g,"");if(R||Y){for(var W=T.length;W--;){if(Y||(R=="panel"&&(a||(!a&&S==null)))){for(var V=T[W].panel.length;V--;){if(T[W].panel[V].button.html()==Y||T[W].panel[V].button.html()==a||(R=="panel"&&!a&&S==null)){H.push(T[W].panel[V])}}}if(Y||(R=="button"&&(a||(!a&&S==null)))){for(var V=T[W].button.length;V--;){if(T[W].button[V].item.html()==Y||T[W].button[V].item.html()==a||(R=="button"&&!a&&S==null)){H.push(T[W].button[V])}}}if(T[W][R]&&T[W][R][S]){H.push(T[W][R][S])}if(R=="header"&&T[W].header){H.push(T[W].header)}}}else{H=H.concat(T)}});var M={length:H.length};for(var K=H.length;K--;){M[K]=H[K];for(var G in H[K]){if(!(G in M)){(function(R){M[R]=function(){for(var S=this.length;S--;){if(typeof this[S][R]=="function"){this[S][R].apply(this[S],arguments)}}}})(G)}}}return M};AJS.Dialog.prototype.updateHeight=function(){var G=0;for(var H=0;this.getPanel(H);H++){if(this.getPanel(H).body.css({height:"auto",display:"block"}).outerHeight()>G){G=this.getPanel(H).body.outerHeight()}if(H!==this.page[this.curpage].curtab){this.getPanel(H).body.css({display:"none"})}}for(H=0;this.getPanel(H);H++){this.getPanel(H).body.css({height:G||this.height})}this.page[0].menu.height(G);this.height=G+87;this.popup.changeSize(undefined,G+87)};AJS.Dialog.prototype.getCurPanel=function(){return this.getPanel(this.page[this.curpage].curtab)};AJS.Dialog.prototype.getCurPanelButton=function(){return this.getCurPanel().button}})();
AJS.dropDown=function(L,E){var U=null,I=[],Q=false,H=AJS.$(document),C={item:"li:has(a)",activeClass:"active",alignment:"right",displayHandler:function(W){return W.name},escapeHandler:function(){this.hide("escape");return false},hideHandler:function(){},moveHandler:function(X,W){},useDisabled:false};AJS.$.extend(C,E);C.alignment={left:"left",right:"right"}[C.alignment.toLowerCase()]||"left";if(L&&L.jquery){U=L}else{if(typeof L=="string"){U=AJS.$(L)}else{if(L&&L.constructor==Array){U=AJS("div").addClass("aui-dropdown").toggleClass("hidden",!!C.isHiddenByDefault);for(var P=0,K=L.length;P<K;P++){var J=AJS("ol");for(var O=0,S=L[P].length;O<S;O++){var M=AJS("li");var G=L[P][O];if(G.href){M.append(AJS("a").html("<span>"+C.displayHandler(G)+"</span>").attr({href:G.href}).addClass(G.className));AJS.$.data(AJS.$("a > span",M)[0],"properties",G)}else{M.html(G.html).addClass(G.className)}if(G.icon){M.prepend(AJS("img").attr("src",G.icon))}if(G.insideSpanIcon){M.children("a").prepend(AJS("span").attr("class","icon"))}AJS.$.data(M[0],"properties",G);J.append(M)}if(P==K-1){J.addClass("last")}U.append(J)}AJS.$("body").append(U)}else{throw new Error("AJS.dropDown function was called with illegal parameter. Should be AJS.$ object, AJS.$ selector or array.")}}}var F=function(){N(+1)};var T=function(){N(-1)};var N=function(Z){var Y=!Q,W=AJS.dropDown.current.$[0],X=AJS.dropDown.current.links,a=W.focused;Q=true;W.focused=(typeof W.focused=="number"?W.focused:-1);if(!AJS.dropDown.current){AJS.log("move - not current, aborting");return true}W.focused=W.focused+Z;if(W.focused<0){W.focused=X.length-1}if(W.focused>X.length-1){W.focused=0}C.moveHandler(AJS.$(X[W.focused]),Z<0?"up":"down");if(Y&&X.length){AJS.$(X[W.focused]).addClass(C.activeClass);Q=false}else{if(!X.length){Q=false}}};var V=function(Y){if(!AJS.dropDown.current){return true}var Z=Y.which,W=AJS.dropDown.current.$[0],X=AJS.dropDown.current.links;AJS.dropDown.current.cleanActive();switch(Z){case 40:F();break;case 38:T();break;case 27:return C.escapeHandler.call(AJS.dropDown.current,Y);case 13:if(W.focused>=0){if(!C.selectionHandler){if(AJS.$(X[W.focused]).attr("nodeName")!="a"){return AJS.$("a",X[W.focused]).trigger("focus")}else{return AJS.$(X[W.focused]).trigger("focus")}}else{return C.selectionHandler.call(AJS.dropDown.current,Y,AJS.$(X[W.focused]))}}return true;default:if(X.length){AJS.$(X[W.focused]).addClass(C.activeClass)}return true}Y.stopPropagation();Y.preventDefault();return false};var A=function(W){if(!((W&&W.which&&(W.which==3))||(W&&W.button&&(W.button==2))||false)){if(AJS.dropDown.current){AJS.dropDown.current.hide("click")}}};var D=function(W){return function(){if(!AJS.dropDown.current){return }AJS.dropDown.current.cleanFocus();this.originalClass=this.className;AJS.$(this).addClass(C.activeClass);AJS.dropDown.current.$[0].focused=W}};var R=function(W){if(W.button||W.metaKey||W.ctrlKey||W.shiftKey){return true}if(AJS.dropDown.current&&C.selectionHandler){C.selectionHandler.call(AJS.dropDown.current,W,AJS.$(this))}};var B=function(X){var W=false;if(X.data("events")){AJS.$.each(X.data("events"),function(Y,Z){AJS.$.each(Z,function(b,a){if(R===a){W=true;return false}})})}return W};U.each(function(){var W=this,Y=AJS.$(this),Z;var X={reset:function(){Z=AJS.$.extend(Z||{},{$:Y,links:AJS.$(C.item||"li:has(a)",W),cleanActive:function(){if(W.focused+1&&Z.links.length){AJS.$(Z.links[W.focused]).removeClass(C.activeClass)}},cleanFocus:function(){Z.cleanActive();W.focused=-1},moveDown:F,moveUp:T,moveFocus:V,getFocusIndex:function(){return(typeof W.focused=="number")?W.focused:-1}});Z.links.each(function(a){var b=AJS.$(this);if(!B(b)){b.hover(D(a),Z.cleanFocus);b.click(R)}});return arguments.callee}(),appear:function(a){if(a){Y.removeClass("hidden");Y.addClass("aui-dropdown-"+C.alignment)}else{Y.addClass("hidden")}},fade:function(a){if(a){Y.fadeIn("fast")}else{Y.fadeOut("fast")}},scroll:function(a){if(a){Y.slideDown("fast")}else{Y.slideUp("fast")}}};Z.addControlProcess=function(b,a){AJS.$.aop.around({target:this,method:b},a)};Z.addCallback=function(b,a){return AJS.$.aop.after({target:this,method:b},a)};Z.reset=X.reset();Z.show=function(a){if(C.useDisabled&&this.$.closest(".aui-dd-parent").hasClass("disabled")){return }this.alignment=C.alignment;A();AJS.dropDown.current=this;this.method=a||this.method||"appear";this.timer=setTimeout(function(){H.click(A)},0);H.keydown(V);if(C.firstSelected&&this.links[0]){D(0).call(this.links[0])}AJS.$(W.offsetParent).css({zIndex:2000});X[this.method](true);AJS.$(document).trigger("showLayer",["dropdown",AJS.dropDown.current])};Z.hide=function(a){this.method=this.method||"appear";AJS.$(Y.get(0).offsetParent).css({zIndex:""});this.cleanFocus();X[this.method](false);H.unbind("click",A).unbind("keydown",V);AJS.$(document).trigger("hideLayer",["dropdown",AJS.dropDown.current]);AJS.dropDown.current=null;return a};Z.addCallback("reset",function(){if(C.firstSelected&&this.links[0]){D(0).call(this.links[0])}});if(!AJS.dropDown.iframes){AJS.dropDown.iframes=[]}AJS.dropDown.createShims=function(){AJS.$("iframe").each(function(a){var b=this;if(!b.shim){b.shim=AJS.$("<div />").addClass("shim hidden").appendTo("body");AJS.dropDown.iframes.push(b)}});return arguments.callee}();Z.addCallback("show",function(){AJS.$(AJS.dropDown.iframes).each(function(){var a=AJS.$(this);if(a.is(":visible")){var b=a.offset();b.height=a.height();b.width=a.width();this.shim.css({left:b.left+"px",top:b.top+"px",height:b.height+"px",width:b.width+"px"}).removeClass("hidden")}})});Z.addCallback("hide",function(){AJS.$(AJS.dropDown.iframes).each(function(){this.shim.addClass("hidden")});C.hideHandler()});(function(){var a=function(){var b=this.$.offset();if(this.shadow){this.shadow.remove()}if(this.$.is(":visible")){this.shadow=Raphael.shadow(0,0,this.$.outerWidth(true),this.$.outerHeight(true),{target:this.$[0]})}};Z.addCallback("reset",a);Z.addCallback("show",a);Z.addCallback("hide",function(){if(this.shadow){this.shadow.remove()}})})();if(AJS.$.browser.msie){(function(){var a=function(){if(this.$.is(":visible")){if(!this.iframeShim){this.iframeShim=AJS.$('<iframe class="dropdown-shim" src="javascript:false;" frameBorder="0" />').insertBefore(this.$)}this.iframeShim.css({display:"block",top:this.$.css("top"),width:this.$.outerWidth()+"px",height:this.$.outerHeight()+"px"});if(C.alignment=="left"){this.iframeShim.css({left:"0px"})}else{this.iframeShim.css({right:"0px"})}}};Z.addCallback("reset",a);Z.addCallback("show",a);Z.addCallback("hide",function(){if(this.iframeShim){this.iframeShim.css({display:"none"})}})})()}I.push(Z)});return I};AJS.dropDown.getAdditionalPropertyValue=function(D,A){var C=D[0];if(!C||(typeof C.tagName!="string")||C.tagName.toLowerCase()!="li"){AJS.log("AJS.dropDown.getAdditionalPropertyValue : item passed in should be an LI element wrapped by jQuery")}var B=AJS.$.data(C,"properties");return B?B[A]:null};AJS.dropDown.removeAllAdditionalProperties=function(A){};AJS.dropDown.Standard=function(H){var C=[],G,B={selector:".aui-dd-parent",dropDown:".aui-dropdown",trigger:".aui-dd-trigger"};AJS.$.extend(B,H);var F=function(I,L,K,J){AJS.$.extend(J,{trigger:I});L.addClass("dd-allocated");K.addClass("hidden");if(B.isHiddenByDefault==false){J.show()}J.addCallback("show",function(){L.addClass("active")});J.addCallback("hide",function(){L.removeClass("active")})};var A=function(K,I,L,J){if(J!=AJS.dropDown.current){L.css({top:I.outerHeight()});J.show();K.stopImmediatePropagation()}K.preventDefault()};if(B.useLiveEvents){var D=[];var E=[];AJS.$(B.trigger).live("click",function(L){var I=AJS.$(this);var N,M,J;var K;if((K=AJS.$.inArray(this,D))>=0){var O=E[K];N=O.parent;M=O.dropdown;J=O.ddcontrol}else{N=I.closest(B.selector);M=N.find(B.dropDown);if(M.length===0){return }J=AJS.dropDown(M,B)[0];if(!J){return }D.push(this);O={parent:N,dropdown:M,ddcontrol:J};F(I,N,M,J);E.push(O)}A(L,I,M,J)})}else{if(this instanceof AJS.$){G=this}else{G=AJS.$(B.selector)}G=G.not(".dd-allocated").filter(":has("+B.dropDown+")").filter(":has("+B.trigger+")");G.each(function(){var L=AJS.$(this),K=AJS.$(B.dropDown,this),I=AJS.$(B.trigger,this),J=AJS.dropDown(K,B)[0];AJS.$.extend(J,{trigger:I});F(I,L,K,J);I.click(function(M){A(M,I,K,J)});C.push(J)})}return C};AJS.dropDown.Ajax=function(C){var B,A={cache:true};AJS.$.extend(A,C||{});B=AJS.dropDown.Standard.call(this,A);AJS.$(B).each(function(){var D=this;AJS.$.extend(D,{getAjaxOptions:function(E){var F=function(G){if(A.formatResults){G=A.formatResults(G)}if(A.cache){D.cache.set(D.getAjaxOptions(),G)}D.refreshSuccess(G)};if(A.ajaxOptions){if(AJS.$.isFunction(A.ajaxOptions)){return AJS.$.extend(A.ajaxOptions.call(D),{success:F})}else{return AJS.$.extend(A.ajaxOptions,{success:F})}}return AJS.$.extend(E,{success:F})},refreshSuccess:function(E){this.$.html(E)},cache:function(){var E={};return{get:function(F){var G=F.data||"";return E[(F.url+G).replace(/[\?\&]/gi,"")]},set:function(F,G){var H=F.data||"";E[(F.url+H).replace(/[\?\&]/gi,"")]=G},reset:function(){E={}}}}(),show:function(E){return function(F){if(A.cache&&!!D.cache.get(D.getAjaxOptions())){D.refreshSuccess(D.cache.get(D.getAjaxOptions()));E.call(D)}else{AJS.$(AJS.$.ajax(D.getAjaxOptions())).throbber({target:D.$,end:function(){D.reset()}});E.call(D);D.shadow.hide();if(D.iframeShim){D.iframeShim.hide()}}}}(D.show),resetCache:function(){D.cache.reset()}});D.addCallback("refreshSuccess",function(){D.reset()})});return B};AJS.$.fn.dropDown=function(B,A){B=(B||"Standard").replace(/^([a-z])/,function(C){return C.toUpperCase()});return AJS.dropDown[B].call(this,A)};
(function(){AJS.icons=AJS.icons||{};AJS.icons.addIcon=function(B,C){AJS.icons[B]=function(E,D){return A(C,E,D)}};AJS.icons.addIcon.init=function(){var D=this.className.split(" "),B=D.length,C=this.className.match(/(^|\s)size-(\d+)(\s|$)/);C=C&&+C[2];while(B--){if(D[B]!="addIcon"&&D[B] in AJS.icons){AJS.icons[D[B]](this,C)}}};function A(E,C,B){B=B||24;var D=Raphael([C,B+1,B+1].concat(E));D.scale(B/24,B/24,0,0)}})();AJS.$(function(){AJS.$(".svg-icon").each(AJS.icons.addIcon.init)});AJS.icons.addIcon("generic",[{stroke:"none",fill:"#999",type:"path",path:"M22.465,8.464c1.944,1.944,1.944,5.126,0,7.07l-6.93,6.93c-1.944,1.945-5.126,1.945-7.07,0l-6.929-6.93c-1.945-1.943-1.945-5.125,0-7.07l6.929-6.93c1.944-1.944,5.126-1.944,7.07,0L22.465,8.464z"},{type:"path",stroke:"none",fill:"90-#999996-#a1a19f:20-#b8b8b7:70-#ccc",path:"M9.172,2.242L9.172,2.242l-6.929,6.93C1.491,9.923,1.077,10.927,1.077,12c0,1.072,0.414,2.076,1.166,2.828l6.929,6.93c0.751,0.752,1.756,1.166,2.828,1.166s2.076-0.414,2.828-1.166l6.93-6.93c0.751-0.752,1.165-1.756,1.165-2.828c0-1.072-0.414-2.076-1.165-2.828l-6.93-6.93C13.269,0.682,10.731,0.682,9.172,2.242z"},{type:"path",stroke:"none",fill:"270-#999996-#a1a19f:20-#b8b8b7:70-#ccc",path:"M7.181,5.869 7.181,17.95 16.974,17.95 16.974,9.205 13.638,5.869"},{type:"path",stroke:"none",fill:"#fff",path:"M12.724,9.619v-2.75H8.181V16.95h7.793v-6.832h-2.75C12.946,10.119,12.724,9.894,12.724,9.619zM13.724,7.369c0,0.521,0,1.32,0,1.75c0.428,0,1.229,0,1.75,0L13.724,7.369z"}]);AJS.icons.addIcon("error",[{type:"path",stroke:"none",fill:"#c00",path:"M7.857,22L2,16.143 2,7.857 7.857,1.999 16.143,1.999 22,7.857 22,16.143 16.143,22z"},{type:"path",stroke:"none",fill:"90-#c00-#d50909-#ed2121-#f33",path:"M8.271,2.999C7.771,3.5,3.501,7.77,3,8.271c0,0.708,0,6.748,0,7.457c0.501,0.5,4.771,4.77,5.271,5.271c0.708,0,6.749,0,7.457,0c0.501-0.502,4.771-4.771,5.271-5.271c0-0.709,0-6.749,0-7.457c-0.501-0.501-4.771-4.771-5.271-5.272C15.021,2.999,8.979,2.999,8.271,2.999z"},{type:"rect",x:5.318,y:9.321,fill:"270-#c00-#d50909-#ed2121-#f33",stroke:"none",width:13.363,height:5.356},{type:"rect",x:6.318,y:10.321,fill:"#fff",stroke:"none",width:11.363,height:3.356}]);AJS.icons.addIcon("success",[{type:"path",stroke:"none",path:"M22,18.801C22,20.559,20.561,22,18.799,22H5.201C3.439,22,2,20.559,2,18.801V5.199C2,3.44,3.439,2,5.201,2h13.598C20.561,2,22,3.44,22,5.199V18.801z",fill:"#393"},{type:"path",path:"M5.201,3C3.987,3,3,3.986,3,5.199v13.602C3,20.014,3.987,21,5.201,21h13.598C20.013,21,21,20.014,21,18.801V5.199C21,3.986,20.013,3,18.799,3H5.201z",stroke:"none",fill:"90-#393-#33a23c-#3c6"},{type:"path",path:"M10.675,12.158c-0.503-0.57-1.644-1.862-1.644-1.862l-3.494,2.833l3.663,5.313l4.503,1.205L17.73,4.624l-4.361-0.056C13.369,4.568,11.424,10.047,10.675,12.158z",stroke:"none",fill:"270-#393-#33a23c-#3c6"},{type:"path",path:"M14.072,5.577 11.05,14.092 8.917,11.677 6.886,13.324 9.815,17.57 12.997,18.422 16.432,5.607",stroke:"none",fill:"#fff"}]);AJS.icons.addIcon("hint",[{type:"path",path:"M22.465,8.464c1.944,1.944,1.944,5.126,0,7.07l-6.93,6.93c-1.944,1.945-5.126,1.945-7.07,0l-6.929-6.93c-1.945-1.943-1.945-5.125,0-7.07l6.929-6.93c1.944-1.944,5.126-1.944,7.07,0L22.465,8.464z",stroke:"none",fill:"#009898"},{type:"path",path:"M9.172,2.242L9.172,2.242l-6.929,6.93C1.491,9.923,1.077,10.927,1.077,12c0,1.072,0.414,2.076,1.166,2.828l6.929,6.93c0.751,0.752,1.756,1.166,2.828,1.166s2.076-0.414,2.828-1.166l6.93-6.93c0.751-0.752,1.165-1.756,1.165-2.828c0-1.072-0.414-2.076-1.165-2.828l-6.93-6.93C13.269,0.682,10.731,0.682,9.172,2.242z",stroke:"none",fill:"270-#099-#00a2a2-#00baba-#0cc"},{type:"path",path:"M12,5.077c-2.679,0-4.857,2.179-4.857,4.857c0,1.897,0.741,2.864,1.337,3.639c0.385,0.502,0.662,0.863,0.761,1.443l0.045,0.264v2.25c0,0.854,0.693,1.547,1.546,1.547h2.338c0.852,0,1.545-0.693,1.545-1.547v-2.254l0.044-0.258c0.1-0.582,0.377-0.943,0.762-1.443c0.596-0.777,1.338-1.743,1.338-3.641C16.857,7.255,14.679,5.077,12,5.077z",stroke:"none",fill:"270-#099-#00a2a2-#00baba-#0cc"},{type:"path",path:"M10.227,14.849c-0.331-1.936-2.084-2.197-2.084-4.915c0-2.131,1.727-3.857,3.857-3.857c2.13,0,3.857,1.727,3.857,3.857c0,2.717-1.754,2.979-2.085,4.915H10.227z M10.285,15.849v1.682c0,0.301,0.246,0.547,0.546,0.547h2.338c0.3,0,0.545-0.246,0.545-0.547v-1.682H10.285z",stroke:"none",fill:"#fff"}]);AJS.icons.addIcon("info",[{type:"circle",cx:12,cy:12,r:10,stroke:"none",fill:"#06c"},{type:"path",path:"M3,12c0,4.962,4.037,9,9,9s9-4.038,9-9s-4.037-9-9-9S3,7.037,3,12z",stroke:"none",fill:"90-#06c-#006FD5-#0087ED-#0099FF"},{type:"path",path:"M9.409,7.472c0,0.694,0.282,1.319,0.729,1.785c-0.288,0-0.729,0-0.729,0v9.425h5.182V9.257c0,0-0.44,0-0.729,0c0.446-0.466,0.729-1.09,0.729-1.785c0-1.429-1.162-2.591-2.591-2.591S9.409,6.043,9.409,7.472z",stroke:"none",fill:"270-#06c-#006FD5-#0087ED-#0099FF"},{type:"path",path:"M13.591,10.257v7.425h-3.182v-7.425H13.591z M12,9.063c0.879,0,1.591-0.712,1.591-1.591S12.879,5.881,12,5.881s-1.591,0.712-1.591,1.591S11.121,9.063,12,9.063z",stroke:"none",fill:"#fff"}]);AJS.icons.addIcon("warning",[{type:"path",path:"M8.595,4.368c1.873-3.245,4.938-3.245,6.811,0c1.873,3.245,4.938,8.554,6.812,11.798c1.874,3.244,0.342,5.898-3.405,5.898c-3.746,0-9.876,0-13.624,0c-3.746,0-5.278-2.654-3.405-5.898C3.656,12.922,6.721,7.613,8.595,4.368z",stroke:"none",fill:"#f90"},{type:"path",path:"M9.461,4.868L2.649,16.666c-0.72,1.246-0.863,2.371-0.404,3.166s1.504,1.232,2.943,1.232h13.624c1.439,0,2.485-0.438,2.944-1.232s0.315-1.92-0.405-3.166L14.539,4.868C13.82,3.622,12.918,2.935,12,2.935S10.181,3.621,9.461,4.868z",stroke:"none",fill:"90-#f90-#ffa209-#ffba21-#fc3"},{type:"path",path:"M9.274,6.187c0,0,0.968,9.68,0.986,9.862c-0.532,0.476-0.881,1.148-0.881,1.916c0,1.433,1.165,2.598,2.597,2.598c1.433,0,2.598-1.165,2.598-2.598c0-0.77-0.351-1.441-0.883-1.918c0.018-0.184,0.988-9.86,0.988-9.86H9.274z",stroke:"none",fill:"270-#f90-#ffa209-#ffba21-#fc3"},{type:"path",path:"M11.177,15.171l-0.798-7.984h3.194l-0.8,7.984H11.177z M11.976,16.368c-0.882,0-1.597,0.716-1.597,1.597c0,0.883,0.715,1.598,1.597,1.598c0.881,0,1.598-0.715,1.598-1.598C13.573,17.084,12.856,16.368,11.976,16.368z",stroke:"none",fill:"#fff"}]);AJS.icons.addIcon("close",[{type:"path",path:"M15.535,12l4.95-4.95c0.977-0.977,0.977-2.559,0-3.536s-2.56-0.977-3.536,0L12,8.464l-4.95-4.95c-0.977-0.977-2.559-0.977-3.536,0s-0.977,2.559,0,3.536L8.464,12l-4.95,4.95c-0.977,0.977-0.977,2.559,0,3.535s2.559,0.977,3.536,0L12,15.535l4.949,4.949c0.977,0.977,2.56,0.977,3.536,0s0.977-2.559,0-3.535L15.535,12z",stroke:"none",fill:"#999"},{type:"path",path:"M18.718,20.217c-0.401,0-0.777-0.156-1.062-0.439L12,14.121l-5.657,5.656c-0.284,0.283-0.66,0.439-1.061,0.439c-0.4,0-0.777-0.156-1.061-0.439c-0.283-0.283-0.439-0.66-0.439-1.061s0.156-0.777,0.439-1.061L9.878,12L4.222,6.343c-0.283-0.284-0.439-0.66-0.439-1.061c0-0.4,0.156-0.777,0.439-1.061c0.284-0.283,0.66-0.439,1.061-0.439c0.401,0,0.777,0.156,1.061,0.439L12,9.878l5.656-5.657c0.284-0.283,0.66-0.439,1.062-0.439c0.4,0,0.776,0.156,1.061,0.439c0.283,0.284,0.439,0.66,0.439,1.061c0,0.401-0.156,0.777-0.439,1.061L14.121,12l5.657,5.657c0.283,0.283,0.439,0.66,0.439,1.061s-0.156,0.777-0.439,1.061C19.494,20.061,19.118,20.217,18.718,20.217L18.718,20.217z",stroke:"none",fill:"90-#999996-#a1a19f-#b8b8b7-#ccc"}]);
(function(A){AJS.InlineDialog=function(T,H,K,I){var R=A.extend(false,AJS.InlineDialog.opts,I);var E;var J;var b;var N=false;var S=false;var Z=false;var a;var P;var B=A('<div id="inline-dialog-'+H+'" class="aui-inline-dialog"><div class="contents"></div><div id="arrow-'+H+'" class="arrow"></div></div>');var G=A("#arrow-"+H,B);var Y=B.find(".contents");Y.css("width",R.width+"px");Y.mouseover(function(c){clearTimeout(J);B.unbind("mouseover")}).mouseout(function(){W()});var V=function(){if(!E){E={popup:B,hide:function(){W(0)},id:H,show:function(){Q()},reset:function(){function d(f,e){f.css(e.popupCss);if(window.Raphael){if(!f.arrowCanvas){f.arrowCanvas=Raphael("arrow-"+H,16,16)}var g=R.getArrowPath,h=A.isFunction(g)?g(e):g;f.arrowCanvas.path(h).attr(R.getArrowAttributes())}G.css(e.arrowCss)}var c=R.calculatePositions(B,P,a,R);d(B,c);B.fadeIn(R.fadeTime,function(){});if(R.displayShadow){if(B.shadow){B.shadow.remove()}B.shadow=Raphael.shadow(0,0,Y.width(),Y.height(),{target:Y}).hide().fadeIn(R.fadeTime)}if(AJS.$.browser.msie){if(A("#inline-dialog-shim-"+H).length==0){A(B).prepend(A('<iframe class = "inline-dialog-shim" id="inline-dialog-shim-'+H+'" frameBorder="0" src="javascript:false;"></iframe>'))}A("#inline-dialog-shim-"+H).css({width:Y.outerWidth(),height:Y.outerHeight()})}}}}return E};var Q=function(){if(B.is(":visible")){return }b=setTimeout(function(){if(!Z||!S){return }R.addActiveClass&&A(T).addClass("active");N=true;F();AJS.InlineDialog.current=V();AJS.$(document).trigger("showLayer",["inlineDialog",V()]);V().reset()},R.showDelay)};var W=function(c){S=false;if(N){c=(c==null)?R.hideDelay:c;clearTimeout(J);clearTimeout(b);if(c!=null){J=setTimeout(function(){U();R.addActiveClass&&A(T).removeClass("active");B.fadeOut(R.fadeTime,function(){R.hideCallback.call(B[0].popup)});if(R.displayShadow){B.shadow.remove();B.shadow=null}B.arrowCanvas.remove();B.arrowCanvas=null;N=false;S=false;AJS.$(document).trigger("hideLayer",["inlineDialog",V()]);AJS.InlineDialog.current=null;if(!R.cacheContent){Z=false;O=false}},c)}}};var X=function(f,c){R.upfrontCallback.call({popup:B,hide:function(){W(0)},id:H,show:function(){Q()}});B.each(function(){if(typeof this.popup!="undefined"){this.popup.hide()}});if(R.closeOthers){AJS.$(".aui-inline-dialog").each(function(){this.popup.hide()})}if(!f){a={x:T.offset().left,y:T.offset().top};P={target:T}}else{a={x:f.pageX,y:f.pageY};P={target:A(f.target)}}if(!N){clearTimeout(b)}S=true;var d=function(){O=false;Z=true;R.initCallback.call({popup:B,hide:function(){W(0)},id:H,show:function(){Q()}});Q()};if(!O){O=true;if(A.isFunction(K)){K(Y,c,d)}else{AJS.$.get(K,function(g,e,h){Y.html(R.responseHandler(g,e,h));Z=true;R.initCallback.call({popup:B,hide:function(){W(0)},id:H,show:function(){Q()}});Q()})}}clearTimeout(J);if(!N){Q()}return false};B[0].popup=V();var O=false;var M=false;var L=function(){if(!M){A(R.container).append(B);M=true}};if(R.onHover){if(R.useLiveEvents){A(T).live("mousemove",function(c){L();X(c,this)}).live("mouseout",function(){W()})}else{A(T).mousemove(function(c){L();X(c,this)}).mouseout(function(){W()})}}else{if(!R.noBind){if(R.useLiveEvents){A(T).live("click",function(c){L();X(c,this);return false}).live("mouseout",function(){W()})}else{A(T).click(function(c){L();X(c,this);return false}).mouseout(function(){W()})}}}var D=false;var C=H+".inline-dialog-check";var F=function(){if(!D){A("body").bind("click."+C,function(d){var c=A(d.target);if(c.closest("#inline-dialog-"+H+" .contents").length===0){W(0)}});D=true}};var U=function(){if(D){A("body").unbind("click."+C)}D=false};B.show=function(c){if(c){c.stopPropagation()}L();X(null,this)};B.hide=function(){W(0)};B.refresh=function(){if(N){V().reset()}};B.getOptions=function(){return R};return B};AJS.InlineDialog.opts={onTop:false,responseHandler:function(C,B,D){return C},closeOthers:true,isRelativeToMouse:false,addActiveClass:true,onHover:false,useLiveEvents:false,noBind:false,fadeTime:100,hideDelay:10000,showDelay:0,width:300,offsetX:0,offsetY:10,container:"body",cacheContent:true,displayShadow:true,hideCallback:function(){},initCallback:function(){},upfrontCallback:function(){},calculatePositions:function(C,J,S,N){var K;var U;var Q;var G=-7;var H;var L;var T=J.target.offset();var O=parseInt(J.target.css("padding-left"))+parseInt(J.target.css("padding-right"));var B=J.target.width()+O;var E=T.left+B/2;var P=(window.pageYOffset||document.documentElement.scrollTop)+A(window).height();var F=10;Q=T.top+J.target.height()+N.offsetY;K=T.left+N.offsetX;var I=T.top>C.height();var D=(Q+C.height())<P;L=(!D&&I)||(N.onTop&&I);var M=A(window).width()-(K+N.width+F);if(L){Q=T.top-C.height()-8;var R=N.displayShadow?(AJS.$.browser.msie?10:9):0;G=C.height()-R}H=E-K;if(N.isRelativeToMouse){if(M<0){U=F;K="auto";H=S.x-(A(window).width()-N.width)}else{K=S.x-20;U="auto";H=S.x-K}}else{if(M<0){U=F;K="auto";H=E-(A(window).width()-N.width)}else{if(N.width<=B/2){H=N.width/2;K=E-N.width/2}}}return{displayAbove:L,popupCss:{left:K,right:U,top:Q},arrowCss:{position:"absolute",left:H,right:"auto",top:G}}},getArrowPath:function(B){return B.displayAbove?"M0,8L8,16,16,8":"M0,8L8,0,16,8"},getArrowAttributes:function(){return{fill:"#fff",stroke:"#bbb"}}}})(jQuery);
AJS.warnAboutFirebug=function(B){if(!AJS.Cookie.read("COOKIE_FB_WARNING")&&window.console&&window.console.firebug){if(!B){B="Firebug is known to cause performance problems with Atlassian products. Try disabling it, if you notice any issues."}var A=AJS.$("<div id='firebug-warning'><p>"+B+"</p><a class='close'>Close</a></div>");AJS.$(".close",A).click(function(){A.slideUp("fast");AJS.Cookie.save("COOKIE_FB_WARNING","true")});A.prependTo(AJS.$("body"))}};
AJS.inlineHelp=function(){AJS.$(".icon-inline-help").click(function(){var A=AJS.$(this).siblings(".field-help");if(A.hasClass("hidden")){A.removeClass("hidden")}else{A.addClass("hidden")}})};
(function(){AJS.messages={setup:function(){AJS.messages.createMessage("generic");AJS.messages.createMessage("error");AJS.messages.createMessage("warning");AJS.messages.createMessage("info");AJS.messages.createMessage("success");AJS.messages.createMessage("hint");AJS.messages.makeCloseable()},makeCloseable:function(A){AJS.$(A||"div.aui-message.closeable").each(function(){var C=AJS.$(this),B=AJS.$('<span class="aui-icon icon-close"></span>').click(function(){C.closeMessage()});C.append(B);B.each(AJS.icons.addIcon.init)})},template:'<div class="aui-message {type} {closeable} {shadowed}"><p class="title"><span class="aui-icon icon-{type}"></span><strong>{title}</strong></p>{body}</div><!-- .aui-message -->',createMessage:function(A){AJS.messages[A]=function(C,E){var D=this.template,B;if(!E){E=C;C="#aui-message-bar"}E.closeable=(E.closeable==false)?false:true;E.shadowed=(E.shadowed==false)?false:true;B=AJS.$(AJS.template(D).fill({type:A,closeable:E.closeable?"closeable":"",shadowed:E.shadowed?"shadowed":"",title:E.title||"","body:html":E.body||""}).toString());if(E.id){if(/[#\'\"\.\s]/g.test(E.id)){AJS.log("AJS.Messages error: ID rejected, must not include spaces, hashes, dots or quotes.")}else{B.attr("id",E.id)}}B.appendTo(C);E.closeable&&AJS.messages.makeCloseable(B)}}};AJS.$.fn.closeMessage=function(){var A=AJS.$(this);if(A.hasClass("aui-message","closeable")){A.trigger("messageClose",[this]).remove()}};AJS.$(function(){AJS.messages.setup()})})();
(function(){var B,E,C=/#.*/,D="active-tab",A="active-pane";AJS.tabs={setup:function(){B=AJS.$("div.aui-tabs:not(.aui-tabs-disabled)");for(var F=0,G=B.length;F<G;F++){E=AJS.$("ul.tabs-menu",B[F]);AJS.$("a",E).click(function(H){AJS.tabs.change(AJS.$(this),H);H&&H.preventDefault()})}},change:function(G,H){var F=AJS.$(G.attr("href").match(C)[0]);F.addClass(A).siblings().removeClass(A);G.parent("li.menu-item").addClass(D).siblings().removeClass(D);G.trigger("tabSelect",{tab:G,pane:F})}};AJS.$(AJS.tabs.setup)})();
AJS.template=(function(G){var J=/\{([^\}]+)\}/g,D=/(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g,H=/([^\\])'/g,F=function(O,N,P,L){var M=P;N.replace(D,function(S,R,Q,U,T){R=R||U;if(M){if(R+":html" in M){M=M[R+":html"];L=true}else{if(R in M){M=M[R]}}if(T&&typeof M=="function"){M=M()}}});if(M==null||M==P){M=O}M=String(M);if(!L){M=E.escape(M)}return M},B=function(L){this.template=this.template.replace(J,function(N,M){return F(N,M,L,true)});return this},K=function(L){this.template=this.template.replace(J,function(N,M){return F(N,M,L)});return this},C=function(){return this.template};var E=function(M){function L(){return L.template}L.template=String(M);L.toString=L.valueOf=C;L.fill=K;L.fillHtml=B;return L},A={},I=[];E.load=function(L){L=String(L);if(!A.hasOwnProperty(L)){I.length>=1000&&delete A[I.shift()];I.push(L);A[L]=G("script[title='"+L.replace(H,"$1\\'")+"']")[0].text}return this(A[L])};E.escape=AJS.escapeHtml;return E})(window.jQuery);
AJS.whenIType=function(D){var A,E=function(F){F=F.toString();jQuery(document).bind("keypress",F,function(){if(!AJS.popup.current&&A){A()}});jQuery(document).bind("keypress keyup",F,function(G){G.preventDefault()})},B=function(F){var H=jQuery(F),I=H.attr("title")||"",G=D.split("");if(H.data("kbShortcutAppended")){C(H,G,I);return }I+=" ( "+AJS.params.keyType+" '"+G.shift()+"'";jQuery.each(G,function(){I+=" "+AJS.params.keyThen+" '"+this+"'"});I+=" )";H.attr("title",I);H.data("kbShortcutAppended",true)},C=function(G,F,H){H=H.replace(/\)$/," OR ");H+="'"+F.shift()+"'";jQuery.each(F,function(){H+=" "+AJS.params.keyThen+" '"+this+"'"});H+=" )";G.attr("title",H)};E(D);return{moveToNextItem:function(F){A=function(){var H,G=jQuery(F),I=jQuery(F+".focused");if(!A.blurHandler){jQuery(document).one("keypress",function(J){if(J.keyCode===jQuery.ui.keyCode.ESCAPE&&I){I.removeClass("focused")}})}if(I.length===0){I=jQuery(F).eq(0)}else{I.removeClass("focused");H=jQuery.inArray(I.get(0),G);if(H<G.length-1){H=H+1;I=G.eq(H)}else{I.removeClass("focused");I=jQuery(F).eq(0)}}if(I&&I.length>0){I.addClass("focused");I.moveTo();I.find("a:first").focus()}}},moveToPrevItem:function(F){A=function(){var H,G=jQuery(F),I=jQuery(F+".focused");if(!A.blurHandler){jQuery(document).one("keypress",function(J){if(J.keyCode===jQuery.ui.keyCode.ESCAPE&&I){I.removeClass("focused")}})}if(I.length===0){I=jQuery(F+":last")}else{I.removeClass("focused");H=jQuery.inArray(I.get(0),G);if(H>0){H=H-1;I=G.eq(H)}else{I.removeClass("focused");I=jQuery(F+":last")}}if(I&&I.length>0){I.addClass("focused");I.moveTo();I.find("a:first").focus()}}},click:function(F){B(F);A=function(){var G=jQuery(F);if(G.length>0){G.click()}}},goTo:function(F){A=function(){window.location.href=F}},followLink:function(F){B(F);A=function(){var G=jQuery(F);if(G.length>0&&G.attr("nodeName").toLowerCase()==="a"){window.location.href=G.attr("href")}}},execute:function(F){A=function(){F()}},moveToAndClick:function(F){B(F);A=function(){var G=jQuery(F);if(G.length>0){G.click();G.moveTo()}}},moveToAndFocus:function(F){B(F);A=function(){var G=jQuery(F);if(G.length>0){G.focus();G.moveTo()}}},or:function(F){E(F);return this}}};jQuery(document).bind("iframeAppended",function(B,A){jQuery(A).load(function(){var C=jQuery(A).contents();C.bind("keyup keydown keypress",function(D){if(jQuery.browser.safari&&D.type==="keypress"){return }if(!jQuery(D.target).is(":input")){jQuery(document).trigger(D)}})})});AJS.whenIType.fromJSON=function(A){if(A){jQuery.each(A,function(C,D){var B=D.op,E=D.param;jQuery.each(D.keys,function(){if(B==="execute"){E=new Function(E)}AJS.whenIType(this)[B](E)})})}};
AJS.toInit(function(D){if(D.browser.msie){var F=D(".aui-toolbar .toolbar-group");F.each(function(G,H){D(H).children(":first").addClass("first");D(H).children(":last").addClass("last")});if(parseInt(D.browser.version,10)==7){function B(){D(".aui-toolbar button").closest(".toolbar-item").addClass("contains-button")}function C(){D(".aui-toolbar .toolbar-split-right").each(function(J,M){var K=D(M),N=K.closest(".aui-toolbar"),G=N.find(".toolbar-split-left"),I=N.data("leftWidth"),L=N.data("rightWidth");if(!I){I=G.outerWidth();N.data("leftWidth",I)}if(!L){L=0;D(".toolbar-item",M).each(function(P,Q){L+=D(Q).outerWidth()});N.data("rightWidth",L)}var O=N.width(),H=O-I;if(O>L&&L>H){G.addClass("force-split")}else{G.removeClass("force-split")}})}function E(){F.each(function(G,H){var I=0;D(H).children(".toolbar-item").each(function(K,J){I+=D(this).outerWidth()});D(this).width(I)})}E();B();var A=false;D(window).resize(function(){if(A!==false){clearTimeout(A)}A=setTimeout(C,200)})}}});
(function(A){A.fn.autocomplete=function(B,C,K){K=typeof C=="function"?C:(typeof K=="function"?K:function(){});C=!isNaN(Number(C))?C:3;var J=this;J[0].lastSelectedValue=J.val();var H=A(document.createElement("ol"));var D=J.offset();var G=parseInt(A("body").css("border-left-width"));H.css({position:"absolute",width:J.outerWidth()-2+"px"});H.addClass("autocompleter");this.after(H);H.css({margin:(Math.abs(this.offset().left-H.offset().left)>=Math.abs(this.offset().top-H.offset().top))?J.outerHeight()+"px 0 0 -"+J.outerWidth()+"px":"-1px 0 0 0"});H.hide();function F(){H.hide();A(document).unbind("click",F)}function E(){var L=J.val();if(L.length>=C&&L!=J[0].lastQuery&&L!=J[0].lastSelectedValue){A.getJSON(B+encodeURI(L),function(P){var R="";L=L.toLowerCase();var U=L.split(" ");for(var Q=0,W=P.length;Q<W;Q++){var S=false;if(P[Q].fullName&&P[Q].username){var V=P[Q].fullName+" ("+P[Q].username+")";var M=P[Q].fullName.split(" ");for(var O=0,T=M.length;O<T;O++){for(var N=0;N<U.length;N++){if(M[O].toLowerCase().indexOf(U[N])==0){M[O]="<strong>"+M[O].substring(0,U[N].length)+"</strong>"+M[O].substring(U[N].length);S=true}}}if(!S){for(var N=0;N<U.length;N++){if(P[Q].username&&P[Q].username.toLowerCase().indexOf(U[N])==0){P[Q].username="<strong>"+P[Q].username.substring(0,U[N].length)+"</strong>"+P[Q].username.substring(U[N].length)}}}P[Q].fullName=M.join(" ");R+="<li><span>"+P[Q].fullName+"</span> <span class='username-in-autocomplete-list'>("+P[Q].username+")</span><i class='fullDetails'>"+V+"</i><i class='username'>"+P[Q].username+"</i><i class='fullName'>"+P[Q].fullName+"</i></li>"}if(P[Q].status){R+="<li>"+P[Q].status+"</li>"}}H.html(R);A("li",H).click(function(Y){Y.stopPropagation();var X=A("i.fullDetails",this).html();I(X)}).hover(function(){A(".focused").removeClass("focused");A(this).addClass("focused")},function(){});A(document).click(F);H.show()});J[0].lastQuery=L}else{if(L.length<C){F()}}}J.keydown(function(M){var L=this;if(this.timer){clearTimeout(this.timer)}var N={"40":function(){var O=A(".focused").removeClass("focused").next();if(O.length){O.addClass("focused")}else{A(".autocompleter li:first").addClass("focused")}},"38":function(){var O=A(".focused").removeClass("focused").prev();if(O.length){O.addClass("focused")}else{A("li:last",H).addClass("focused")}},"27":function(){F()},"13":function(){var O=A(".focused i.fullDetails").html();I(O)},"9":function(){this[13]();setTimeout(function(){L.focus()},0)}};if(H.css("display")!="none"&&M.keyCode in N){M.preventDefault();N[M.keyCode]()}this.timer=setTimeout(E,300)});function I(N){var M=J.val();if(N){J[0].lastSelectedValue=N;J.val(N);var L={input:J,originalValue:M,value:N,fullName:A(".focused i.fullName").text(),username:A(".focused i.username").text()};K(L);F()}}}})(jQuery);
jQuery.fn.isDirty=function(){var B,A=[];window.onbeforeunload=function(){var C=window.onbeforeunload;if(B!==false){jQuery.each(A,function(){if(this.initVal!==AJS.$(this).val()){B=true;return false}})}if(B){window.onbeforeunload=null;window.setTimeout(function(){jQuery(document).bind("mousemove",function(){window.onbeforeunload=C;jQuery(document).unbind("mousemove",arguments.callee)})},1000);B=void (0);return AJS.params.dirtyMessage||""}};return function(D){if(this.length===0){return }function C(F){var E=jQuery(this);jQuery.fn.isDirty.fieldInFocus=E;if(jQuery.inArray(this,A)===-1){this.initVal=E.val();A.push(this);E.die(F.type,C)}}jQuery(":not(:input)").live("click",function(){delete jQuery.fn.isDirty.fieldInFocus});jQuery(":input[type != hidden]",this.selector).bind("keydown",C).bind("keypress",C).bind("click",C);jQuery(D.ignoreUnloadFromElems).live("mousedown",function(){B=false});this.each(function(){this.onsubmit=function(E){return function(){B=false;if(E){return E.apply(this,arguments)}}}(this.onsubmit);AJS.$(this).submit(function(){B=false})});return this}}();
(function(A){A.fn.progressBar=function(I,L){var C=this;var F={height:"1em",showPercentage:true};var B=A.extend(F,L);var J=C.attr("id")+"-incomplete-bar";var D=C.attr("id")+"-complete-bar";var K=C.attr("id")+"-percent-complete-text";if(A("#"+J).length==0){var E=A(document.createElement("div"));E.attr("id",J);E.css({width:"90%",border:"solid 1px #ccc","float":"left","margin-right":"0.5em"});E.addClass("progress-background-color");var G=A(document.createElement("div"));G.attr("id",D);G.addClass("progress-fill-color");G.css({height:B.height,width:I+"%"});var H=A(document.createElement("span"));H.attr("id",K);H.addClass("percent-complete-text");H.html(I+"%");E.append(G);C.append(E);if(B.showPercentage){C.append(H)}}else{A("#"+D).css("width",I+"%");A("#"+K).html(I+"%")}}})(jQuery);
(function(A){if(document.selection){var B=function(C){return C.replace(/\u000D/g,"")};A.fn.selection=function(F){var E=this[0];this.focus();if(!E){return false}if(F==null){return document.selection.createRange().text}else{var D=E.scrollTop;var C=document.selection.createRange();C.text=F;C.select();E.focus();E.scrollTop=D}};A.fn.selectionRange=function(C,F){var G=this[0];this.focus();var I=document.selection.createRange();if(C==null){var K=this.val(),J=K.length,E=I.duplicate();E.moveToElementText(G);E.setEndPoint("StartToEnd",I);var D=J-B(E.text).length;E.setEndPoint("StartToStart",I);var H=J-B(E.text).length;if(D!=H&&K.charAt(D+1)=="\n"){D+=1}return{end:D,start:H,text:K.substring(H,D),textBefore:K.substring(0,H),textAfter:K.substring(D)}}else{I.moveToElementText(G);I.collapse(true);I.moveStart("character",C);I.moveEnd("character",F-C);I.select()}}}else{A.fn.selection=function(E){var D=this[0];if(!D){return false}if(E==null){if(D.setSelectionRange){return D.value.substring(D.selectionStart,D.selectionEnd)}else{return false}}else{var C=D.scrollTop;if(!!D.setSelectionRange){var F=D.selectionStart;D.value=D.value.substring(0,F)+E+D.value.substring(D.selectionEnd);D.selectionStart=F;D.selectionEnd=F+E.length}D.focus();D.scrollTop=C}};A.fn.selectionRange=function(F,C){if(F==null){var D={start:this[0].selectionStart,end:this[0].selectionEnd};var E=this.val();D.text=E.substring(D.start,D.end);D.textBefore=E.substring(0,D.start);D.textAfter=E.substring(D.end);return D}else{this[0].selectionStart=F;this[0].selectionEnd=C}}}A.fn.wrapSelection=function(C,D){this.selection(C+this.selection()+(D||""))}})(jQuery);
jQuery.fn.throbber=function(A){return function(){var C=[],B={isLatentThreshold:100,minThrobberDisplay:200,loadingClass:"loading"};A(document).ajaxComplete(function(E,D){A(C).each(function(F){if(D===this.get(0)){this.hideThrobber();C.splice(F,1)}})});return function(F){var E,G,D=function(I,H){D.t=setTimeout(function(){clearTimeout(D.t);D.t=undefined;I()},H)};F=A.extend(B,F||{});if(!F.target){return this}G=jQuery(F.target);C.push(A.extend(this,{showThrobber:function(){D(function(){if(!E){G.addClass(F.loadingClass);D(function(){if(E){E()}},F.minThrobberDisplay)}},F.isLatentThreshold)},hideThrobber:function(){E=function(){G.removeClass(F.loadingClass);if(F.end){F.end()}};if(!D.t){E()}}}));this.showThrobber();return this}}()}(jQuery);
(function(D){function C(G,E){function F(){E.tm=window.setTimeout(function(){E.loadedChars=""},700)}E.loadedChars=E.loadedChars+G;if(!E.tm){F()}else{clearTimeout(E.tm);F()}}function A(E){return !(this!==E.target&&(/textarea|select/i.test(E.target.nodeName)||E.target.type==="text"||E.target.type==="password"))}D.hotKeys={version:"0.8",specialKeys:{8:"backspace",9:"tab",13:"return",16:"shift",17:"ctrl",18:"alt",19:"pause",20:"capslock",27:"esc",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",45:"insert",46:"del",96:"0",97:"1",98:"2",91:"meta",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9",106:"*",107:"+",109:"-",110:".",111:"/",112:"f1",113:"f2",114:"f3",115:"f4",116:"f5",117:"f6",118:"f7",119:"f8",120:"f9",121:"f10",122:"f11",123:"f12",144:"numlock",145:"scroll",188:",",190:".",191:"/",224:"meta",219:"[",221:"]"},keypressKeys:["<",">","?"],shiftNums:{"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":'"',",":"<",".":">","/":"?","\\":"|"}};D.each(D.hotKeys.keypressKeys,function(E,F){D.hotKeys.shiftNums[F]=F});function B(F){var E,G;if(typeof F.data!=="string"){return }E=F.handler;G=F.data.toLowerCase().split(" ");F.loadedChars="";D(this).bind("keydown",function(I){var H;if(!A(I)){return }H=D.hotKeys.specialKeys[I.which];if((H==="alt"||I.altKey)){C("alt+",F)}if((H==="ctrl"||I.ctrlKey)&&!/ctrl\+/.test(F.loadedChars)){C("ctrl+",F)}if(((H!=="ctrl"&&!I.ctrlKey)&&(H==="meta"||I.metaKey))&&!/meta\+/.test(F.loadedChars)){C("meta+",F)}});F.handler=function(K){var J,I,L,H;if(!A(K)){return }I=D.hotKeys.specialKeys[K.which];L=String.fromCharCode(K.which).toLowerCase();H={};if(I){H[I]=true}if(K.shiftKey){H[F.loadedChars+D.hotKeys.shiftNums[L]||I]=true}else{H[F.loadedChars+L]=true}for(J=0,l=G.length;J<l;J++){if(H[G[J]]){F.loadedChars="";return E.apply(this,arguments)}else{if(G[J].charAt(F.loadedChars.length)===L){C(L,F)}}}}}D.each(["keydown","keyup","keypress"],function(){D.event.special[this]={add:B}})})(jQuery);
jQuery.fn.moveTo=function(D){var H={transition:false,scrollOffset:35};var G=jQuery.extend(H,D),A=this,E=A.offset().top,F=jQuery("#stalker"),B=F.outerHeight()+G.scrollOffset,C;if(!F.hasClass("detached")&&(E<=F.offset().top)){B=0}if((jQuery(window).scrollTop()+jQuery(window).height()-this.outerHeight()<E||jQuery(window).scrollTop()+B>E)&&jQuery(window).height()>B){if(jQuery(window).scrollTop()+B>E){C=E-(jQuery(window).height()-this.outerHeight())+G.scrollOffset}else{C=E-B}if(!jQuery.fn.moveTo.animating&&G.transition){jQuery(document).trigger("moveToStarted",this);jQuery.fn.moveTo.animating=true;jQuery("html,body").animate({scrollTop:C},1000,function(){F.trigger("positionChanged");jQuery(document).trigger("moveToFinished",A);delete jQuery.fn.moveTo.animating});return this}else{if(jQuery("html, body").is(":animated")){jQuery("html, body").stop();delete jQuery.fn.moveTo.animating}jQuery(document).trigger("moveToStarted");jQuery(window).scrollTop(C);F.trigger("positionChanged");setTimeout(function(){jQuery(document).trigger("moveToFinished",A)},100);return this}}jQuery(document).trigger("moveToFinished",this);return this};
AJS.whenIType=function(D){var A,E=function(F){F=F.toString();jQuery(document).bind("keypress",F,function(){if(!AJS.popup.current&&A){A()}});jQuery(document).bind("keypress keyup",F,function(G){G.preventDefault()})},B=function(F){var H=jQuery(F),I=H.attr("title")||"",G=D.split("");if(H.data("kbShortcutAppended")){C(H,G,I);return }I+=" ( "+AJS.params.keyType+" '"+G.shift()+"'";jQuery.each(G,function(){I+=" "+AJS.params.keyThen+" '"+this+"'"});I+=" )";H.attr("title",I);H.data("kbShortcutAppended",true)},C=function(G,F,H){H=H.replace(/\)$/," OR ");H+="'"+F.shift()+"'";jQuery.each(F,function(){H+=" "+AJS.params.keyThen+" '"+this+"'"});H+=" )";G.attr("title",H)};E(D);return{moveToNextItem:function(F){A=function(){var H,G=jQuery(F),I=jQuery(F+".focused");if(!A.blurHandler){jQuery(document).one("keypress",function(J){if(J.keyCode===jQuery.ui.keyCode.ESCAPE&&I){I.removeClass("focused")}})}if(I.length===0){I=jQuery(F).eq(0)}else{I.removeClass("focused");H=jQuery.inArray(I.get(0),G);if(H<G.length-1){H=H+1;I=G.eq(H)}else{I.removeClass("focused");I=jQuery(F).eq(0)}}if(I&&I.length>0){I.addClass("focused");I.moveTo();I.find("a:first").focus()}}},moveToPrevItem:function(F){A=function(){var H,G=jQuery(F),I=jQuery(F+".focused");if(!A.blurHandler){jQuery(document).one("keypress",function(J){if(J.keyCode===jQuery.ui.keyCode.ESCAPE&&I){I.removeClass("focused")}})}if(I.length===0){I=jQuery(F+":last")}else{I.removeClass("focused");H=jQuery.inArray(I.get(0),G);if(H>0){H=H-1;I=G.eq(H)}else{I.removeClass("focused");I=jQuery(F+":last")}}if(I&&I.length>0){I.addClass("focused");I.moveTo();I.find("a:first").focus()}}},click:function(F){B(F);A=function(){var G=jQuery(F);if(G.length>0){G.click()}}},goTo:function(F){A=function(){window.location.href=F}},followLink:function(F){B(F);A=function(){var G=jQuery(F);if(G.length>0&&G.attr("nodeName").toLowerCase()==="a"){window.location.href=G.attr("href")}}},execute:function(F){A=function(){F()}},moveToAndClick:function(F){B(F);A=function(){var G=jQuery(F);if(G.length>0){G.click();G.moveTo()}}},moveToAndFocus:function(F){B(F);A=function(){var G=jQuery(F);if(G.length>0){G.focus();G.moveTo()}}},or:function(F){E(F);return this}}};jQuery(document).bind("iframeAppended",function(B,A){jQuery(A).load(function(){var C=jQuery(A).contents();C.bind("keyup keydown keypress",function(D){if(jQuery.browser.safari&&D.type==="keypress"){return }if(!jQuery(D.target).is(":input")){jQuery(document).trigger(D)}})})});AJS.whenIType.fromJSON=function(A){if(A){jQuery.each(A,function(C,D){var B=D.op,E=D.param;jQuery.each(D.keys,function(){if(B==="execute"){E=new Function(E)}AJS.whenIType(this)[B](E)})})}};
//=============================================================================================
//=============================================================================================
//=============================================================================================
//fixed Cookie.js: AJS-655 & AJS-515
(function () {

    // Cookie handling functions

    var COOKIE_NAME = "AJS.conglomerate.cookie",
            UNESCAPE_COOKIE_REGEX = /(\\|^"|"$)/g,
            CONSECUTIVE_PIPE_CHARS_REGEX = /\|\|+/g,
            ANY_QUOTE_REGEX = /"/g;

    function getValueFromConglomerate(name, cookieValue) {
        // a null cookieValue is just the first time through so create it
        cookieValue = cookieValue || "";
        var reg = new RegExp(name + "=([^|]+)"),
            res = cookieValue.match(reg);
        return res && res[1];
    }

    //either append or replace the value in the cookie string
    function addOrAppendToValue(name, value, cookieValue) {
        //A cookie name follows after any amount of white space mixed with any amount of '|' characters
        //A cookie value is preceded by '=', then anything except for '|'
        var reg = new RegExp("(\\s|\\|)*\\b" + name + "=[^|]*[|]*");

        cookieValue = cookieValue || "";
        cookieValue = cookieValue.replace(reg, "|");
        if (value !== "") {
            var pair = name + "=" + value;
            if (cookieValue.length + pair.length < 4020) {
                cookieValue += "|" + pair;
            }
        }
        return cookieValue.replace(CONSECUTIVE_PIPE_CHARS_REGEX, "|");
    }

    function unescapeCookieValue(name) {
        return name.replace(UNESCAPE_COOKIE_REGEX, "");
    }

    function getCookieValue(name) {
        var reg = new RegExp("\\b" + name + "=(.+?[^\\\\])(;|$)"),
            res = document.cookie.match(reg);
        return res && unescapeCookieValue(res[1]);
    }

    function saveCookie(name, value, days) {
        var ex = "",
            d,
            quotedValue = '"' + value.replace(ANY_QUOTE_REGEX, '\\"') + '"';

        if (days) {
            d = new Date();
            d.setTime(+d + days * 24 * 60 * 60 * 1000);
            ex = "; expires=" + d.toGMTString();
        }
        document.cookie = name + "=" + quotedValue + ex + ";path=/";
    }

    /**
     * The Atlassian Conglomerate Cookie - to let us use cookies without running out.
     * @class Cookie
     * @namespace AJS
     */
    AJS.Cookie = {
        /**
         * Save a cookie.
         * @param name {String} name of cookie
         * @param value {String} value of cookie
         * @param expires {Number} number of days before cookie expires
         */
        save : function (name, value, expires) {
            var cookieValue = getCookieValue(COOKIE_NAME);
            cookieValue = addOrAppendToValue(name, value, cookieValue);
            saveCookie(COOKIE_NAME, cookieValue, expires || 365);
        },
        /**
         * Get the value of a cookie.
         * @param name {String} name of cookie to read
         * @param defaultValue {String} the default value of the cookie to return if not found
         */
        read : function(name, defaultValue) {
            var cookieValue = getCookieValue(COOKIE_NAME);
            var value = getValueFromConglomerate(name, cookieValue);
            if (value != null) {
                return value;
            }
            return defaultValue;
        },
        /**
         * Remove the given cookie.
         * @param name {String} the name of the cookie to remove
         */
        erase: function (name) {
            this.save(name, "");
        }
    };
    
})();

//=============================================================================================
//=============================================================================================
//=============================================================================================

/*!
 * Amplify Store - Persistent Client-Side Storage @VERSION
 *
 * Copyright 2011 appendTo LLC. (http://appendto.com/team)
 * Dual licensed under the MIT or GPL licenses.
 * http://appendto.com/open-source-licenses
 *
 * http://amplifyjs.com
 */
(function( amplify, undefined ) {

// MooTools Compatibility
JSON.stringify = JSON.stringify||JSON.encode;
JSON.parse = JSON.parse||JSON.decode;

var store = amplify.store = function( key, value, options, type ) {
	var type = store.type;
	if ( options && options.type && options.type in store.types ) {
		type = options.type;
	}
	return store.types[ type ]( key, value, options || {} );
};

store.types = {};
store.type = null;
store.addType = function( type, storage ) {
	if ( !store.type ) {
		store.type = type;
	}

	store.types[ type ] = storage;
	store[ type ] = function( key, value, options ) {
		options = options || {};
		options.type = type;
		return store( key, value, options );
	};
}
store.error = function() {
	return "amplify.store quota exceeded";
};

function createSimpleStorage( storageType, storage ) {
	var values = storage.__amplify__ ? JSON.parse( storage.__amplify__ ) : {};
	store.addType( storageType, function( key, value, options ) {
		var ret = value,
			now = (new Date()).getTime(),
			storedValue,
			parsed;

		if ( !key ) {
			ret = {};
			for ( key in values ) {
				storedValue = storage[ key ];
				parsed = storedValue ? JSON.parse( storedValue ) : { expires: -1 };
				if ( parsed.expires && parsed.expires <= now ) {
					delete storage[ key ];
					delete values[ key ];
				} else {
					ret[ key.replace( /^__amplify__/, "" ) ] = parsed.data;
				}
			}
			storage.__amplify__ = JSON.stringify( values );
			return ret;
		}

		// protect against overwriting built-in properties
		key = "__amplify__" + key;

		if ( value === undefined ) {
			if ( values[ key ] ) {
				storedValue = storage[ key ];
				parsed = storedValue ? JSON.parse( storedValue ) : { expires: -1 };
				if ( parsed.expires && parsed.expires <= now ) {
					delete storage[ key ];
					delete values[ key ];
				} else {
					return parsed.data;
				}
			}
		} else {
			if ( value === null ) {
				delete storage[ key ];
				delete values[ key ];
			} else {
				parsed = JSON.stringify({
					data: value,
					expires: options.expires ? now + options.expires : null
				});
				try {
					storage[ key ] = parsed;
					values[ key ] = true;
				// quota exceeded
				} catch( error ) {
					// expire old data and try again
					store[ storageType ]();
					try {
						storage[ key ] = parsed;
						values[ key ] = true;
					} catch( error ) {
						throw store.error();
					}
				}
			}
		}

		storage.__amplify__ = JSON.stringify( values );
		return ret;
	});
}

// localStorage + sessionStorage
// IE 8+, Firefox 3.5+, Safari 4+, Chrome 4+, Opera 10.5+, iPhone 2+, Android 2+
for ( var webStorageType in { localStorage: 1, sessionStorage: 1 } ) {
	// try/catch for file protocol in Firefox
	try {
		if ( window[ webStorageType ].getItem ) {
			createSimpleStorage( webStorageType, window[ webStorageType ] );
		}
	} catch( e ) {}
}

// globalStorage
// non-standard: Firefox 2+
// https://developer.mozilla.org/en/dom/storage#globalStorage
if ( window.globalStorage ) {
	createSimpleStorage( "globalStorage",
		window.globalStorage[ window.location.hostname ] );
	// Firefox 2.0 and 3.0 have sessionStorage and globalStorage
	// make sure we defualt to globalStorage
	// but don't default to globalStorage in 3.5+ which also has localStorage
	if ( store.type === "sessionStorage" ) {
		store.type = "globalStorage";
	}
}

// userData
// non-standard: IE 5+
// http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx
(function() {
	// append to html instead of body so we can do this from the head
	var div = document.createElement( "div" ),
		attrKey = "amplify",
		attrs;
	div.style.display = "none";
	document.getElementsByTagName( "head" )[ 0 ].appendChild( div );
	if ( div.addBehavior ) {
		div.addBehavior( "#default#userdata" );
		div.load( attrKey );
		attrs = div.getAttribute( attrKey ) ? JSON.parse( div.getAttribute( attrKey ) ) : {};

		store.addType( "userData", function( key, value, options ) {
			var ret = value,
				now = (new Date()).getTime(),
				attr,
				parsed,
				prevValue;

			if ( !key ) {
				ret = {};
				for ( key in attrs ) {
					attr = div.getAttribute( key );
					parsed = attr ? JSON.parse( attr ) : { expires: -1 };
					if ( parsed.expires && parsed.expires <= now ) {
						div.removeAttribute( key );
						delete attrs[ key ];
					} else {
						ret[ key ] = parsed.data;
					}
				}
				div.setAttribute( attrKey, JSON.stringify( attrs ) );
				div.save( attrKey );
				return ret;
			}

			// convert invalid characters to dashes
			// http://www.w3.org/TR/REC-xml/#NT-Name
			// simplified to assume the starting character is valid
			// also removed colon as it is invalid in HTML attribute names
			key = key.replace( /[^-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u37f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/g, "-" );

			if ( value === undefined ) {
				if ( key in attrs ) {
					attr = div.getAttribute( key );
					parsed = attr ? JSON.parse( attr ) : { expires: -1 };
					if ( parsed.expires && parsed.expires <= now ) {
						div.removeAttribute( key );
						delete attrs[ key ];
					} else {
						return parsed.data;
					}
				}
			} else {
				if ( value === null ) {
					div.removeAttribute( key );
					delete attrs[ key ];
				} else {
					// we need to get the previous value in case we need to rollback
					prevValue = div.getAttribute( key );
					parsed = JSON.stringify({
						data: value,
						expires: (options.expires ? (now + options.expires) : null)
					});
					div.setAttribute( key, parsed );
					attrs[ key ] = true;
				}
			}

			div.setAttribute( attrKey, JSON.stringify( attrs ) );
			try {
				div.save( attrKey );
			// quota exceeded
			} catch ( error ) {
				// roll the value back to the previous value
				if ( prevValue === null ) {
					div.removeAttribute( key );
					delete attrs[ key ];
				} else {
					div.setAttribute( key, prevValue );
				}

				// expire old data and try again
				store.userData();
				try {
					div.setAttribute( key, parsed );
					attrs[ key ] = true;
					div.save( attrKey );
				} catch ( error ) {
					// roll the value back to the previous value
					if ( prevValue === null ) {
						div.removeAttribute( key );
						delete attrs[ key ];
					} else {
						div.setAttribute( key, prevValue );
					}
					throw store.error();
				}
			}
			return ret;
		});
	}
}() );

// in-memory storage
// fallback for all browsers to enable the API even if we can't persist data
createSimpleStorage( "memory", {} );

}( this.amplify = this.amplify || {} ) );

/**
 * History.js jQuery Adapter
 * @author Benjamin Arthur Lupton <contact@balupton.com>
 * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */

// Closure
(function(window,undefined){
	// Localise Globals
	var
		History = window.History = window.History||{},
		jQuery = window.jQuery;

	// Check Existence
	if ( typeof History.Adapter !== 'undefined' ) {
		throw new Error('History.js Adapter has already been loaded...');
	}

	// Add the Adapter
	History.Adapter = {
		/**
		 * History.Adapter.bind(el,event,callback)
		 * @param {Element|Selector} el
		 * @param {String} event - custom and standard events
		 * @param {Function} callback
		 * @return
		 */
		bind: function(el,event,callback){
			jQuery(el).bind(event,callback);
		},

		/**
		 * History.Adapter.trigger(el,event)
		 * @param {Element|Selector} el
		 * @param {String} event - custom and standard events
		 * @return
		 */
		trigger: function(el,event){
			jQuery(el).trigger(event);
		},

		/**
		 * History.Adapter.trigger(el,event,data)
		 * @param {Function} callback
		 * @return
		 */
		onDomLoad: function(callback) {
			jQuery(callback);
		}
	};

	// Try and Initialise History
	if ( typeof History.init !== 'undefined' ) {
		History.init();
	}

})(window);

/**
 * History.js Core
 * @author Benjamin Arthur Lupton <contact@balupton.com>
 * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */

(function(window,undefined){
	"use strict";

	// --------------------------------------------------------------------------
	// Initialise

	// Localise Globals
	var
		console = window.console||undefined, // Prevent a JSLint complain
		document = window.document, // Make sure we are using the correct document
		navigator = window.navigator, // Make sure we are using the correct navigator
		amplify = window.amplify||false, // Amplify.js
		setTimeout = window.setTimeout,
		clearTimeout = window.clearTimeout,
		setInterval = window.setInterval,
		clearInterval = window.clearInterval,
		JSON = window.JSON,
		History = window.History = window.History||{}, // Public History Object
		history = window.history; // Old History Object

	// MooTools Compatibility
	JSON.stringify = JSON.stringify||JSON.encode;
	JSON.parse = JSON.parse||JSON.decode;

	// Check Existence
	if ( typeof History.init !== 'undefined' ) {
		throw new Error('History.js Core has already been loaded...');
	}

	// Initialise History
	History.init = function(){
		// Check Load Status of Adapter
		if ( typeof History.Adapter === 'undefined' ) {
			return false;
		}

		// Check Load Status of Core
		if ( typeof History.initCore !== 'undefined' ) {
			History.initCore();
		}

		// Check Load Status of HTML4 Support
		if ( typeof History.initHtml4 !== 'undefined' ) {
			History.initHtml4();
		}

		// Return true
		return true;
	};

	// --------------------------------------------------------------------------
	// Initialise Core

	// Initialise Core
	History.initCore = function(){
		// Initialise
		if ( typeof History.initCore.initialized !== 'undefined' ) {
			// Already Loaded
			return false;
		}
		else {
			History.initCore.initialized = true;
		}

		// ----------------------------------------------------------------------
		// Options

		/**
		 * History.options
		 * Configurable options
		 */
		History.options = History.options||{};

		/**
		 * History.options.hashChangeInterval
		 * How long should the interval be before hashchange checks
		 */
		History.options.hashChangeInterval = History.options.hashChangeInterval || 100;

		/**
		 * History.options.safariPollInterval
		 * How long should the interval be before safari poll checks
		 */
		History.options.safariPollInterval = History.options.safariPollInterval || 500;

		/**
		 * History.options.doubleCheckInterval
		 * How long should the interval be before we perform a double check
		 */
		History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;

		/**
		 * History.options.storeInterval
		 * How long should we wait between store calls
		 */
		History.options.storeInterval = History.options.storeInterval || 1000;

		/**
		 * History.options.busyDelay
		 * How long should we wait between busy events
		 */
		History.options.busyDelay = History.options.busyDelay || 250;

		/**
		 * History.options.debug
		 * If true will enable debug messages to be logged
		 */
		History.options.debug = History.options.debug || false;

		/**
		 * History.options.initialTitle
		 * What is the title of the initial state
		 */
		History.options.initialTitle = History.options.initialTitle || document.title;


		// ----------------------------------------------------------------------
		// Interval record

		/**
		 * History.intervalList
		 * List of intervals set, to be cleared when document is unloaded.
		 */
		History.intervalList = [];

		/**
		 * History.clearAllIntervals
		 * Clears all setInterval instances.
		 */
		History.clearAllIntervals = function(){
			var i, il = History.intervalList;
			if (typeof il !== "undefined" && il !== null) {
				for (i = 0; i < il.length; i++) {
					clearInterval(il[i]);
				}
				History.intervalList = null;
			}
		};
		History.Adapter.bind(window,"beforeunload",History.clearAllIntervals);
		History.Adapter.bind(window,"unload",History.clearAllIntervals);


		// ----------------------------------------------------------------------
		// Debug

		/**
		 * History.debug(message,...)
		 * Logs the passed arguments if debug enabled
		 */
		History.debug = function(){
			if ( (History.options.debug||false) ) {
				History.log.apply(History,arguments);
			}
		};

		/**
		 * History.log(message,...)
		 * Logs the passed arguments
		 */
		History.log = function(){
			// Prepare
			var
				consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
				textarea = document.getElementById('log'),
				message,
				i,n
				;

			// Write to Console
			if ( consoleExists ) {
				var args = Array.prototype.slice.call(arguments);
				message = args.shift();
				if ( typeof console.debug !== 'undefined' ) {
					console.debug.apply(console,[message,args]);
				}
				else {
					console.log.apply(console,[message,args]);
				}
			}
			else {
				message = ("\n"+arguments[0]+"\n");
			}

			// Write to log
			for ( i=1,n=arguments.length; i<n; ++i ) {
				var arg = arguments[i];
				if ( typeof arg === 'object' && typeof JSON !== 'undefined' ) {
					try {
						arg = JSON.stringify(arg);
					}
					catch ( Exception ) {
						// Recursive Object
					}
				}
				message += "\n"+arg+"\n";
			}

			// Textarea
			if ( textarea ) {
				textarea.value += message+"\n-----\n";
				textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight;
			}
			// No Textarea, No Console
			else if ( !consoleExists ) {
				alert(message);
			}

			// Return true
			return true;
		};

		// ----------------------------------------------------------------------
		// Emulated Status

		/**
		 * History.getInternetExplorerMajorVersion()
		 * Get's the major version of Internet Explorer
		 * @return {integer}
		 * @license Public Domain
		 * @author Benjamin Arthur Lupton <contact@balupton.com>
		 * @author James Padolsey <https://gist.github.com/527683>
		 */
		History.getInternetExplorerMajorVersion = function(){
			var result = History.getInternetExplorerMajorVersion.cached =
					(typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
				?	History.getInternetExplorerMajorVersion.cached
				:	(function(){
						var v = 3,
								div = document.createElement('div'),
								all = div.getElementsByTagName('i');
						while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
						return (v > 4) ? v : false;
					})()
				;
			return result;
		};

		/**
		 * History.isInternetExplorer()
		 * Are we using Internet Explorer?
		 * @return {boolean}
		 * @license Public Domain
		 * @author Benjamin Arthur Lupton <contact@balupton.com>
		 */
		History.isInternetExplorer = function(){
			var result =
				History.isInternetExplorer.cached =
				(typeof History.isInternetExplorer.cached !== 'undefined')
					?	History.isInternetExplorer.cached
					:	Boolean(History.getInternetExplorerMajorVersion())
				;
			return result;
		};

		/**
		 * History.emulated
		 * Which features require emulating?
		 */
		History.emulated = {
			pushState: !Boolean(
				window.history && window.history.pushState && window.history.replaceState
				&& !(
					(/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
					|| (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
				)
			),
			hashChange: Boolean(
				!(('onhashchange' in window) || ('onhashchange' in document))
				||
				(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
			)
		};

		/**
		 * History.enabled
		 * Is History enabled?
		 */
		History.enabled = !History.emulated.pushState;

		/**
		 * History.bugs
		 * Which bugs are present
		 */
		History.bugs = {
			/**
			 * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
			 * https://bugs.webkit.org/show_bug.cgi?id=56249
			 */
			setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),

			/**
			 * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
			 * https://bugs.webkit.org/show_bug.cgi?id=42940
			 */
			safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),

			/**
			 * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
			 */
			ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),

			/**
			 * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
			 */
			hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
		};

		/**
		 * History.isEmptyObject(obj)
		 * Checks to see if the Object is Empty
		 * @param {Object} obj
		 * @return {boolean}
		 */
		History.isEmptyObject = function(obj) {
			for ( var name in obj ) {
				return false;
			}
			return true;
		};

		/**
		 * History.cloneObject(obj)
		 * Clones a object
		 * @param {Object} obj
		 * @return {Object}
		 */
		History.cloneObject = function(obj) {
			var hash,newObj;
			if ( obj ) {
				hash = JSON.stringify(obj);
				newObj = JSON.parse(hash);
			}
			else {
				newObj = {};
			}
			return newObj;
		};

		// ----------------------------------------------------------------------
		// URL Helpers

		/**
		 * History.getRootUrl()
		 * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
		 * @return {String} rootUrl
		 */
		History.getRootUrl = function(){
			// Create
			var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
			if ( document.location.port||false ) {
				rootUrl += ':'+document.location.port;
			}
			rootUrl += '/';

			// Return
			return rootUrl;
		};

		/**
		 * History.getBaseHref()
		 * Fetches the `href` attribute of the `<base href="...">` element if it exists
		 * @return {String} baseHref
		 */
		History.getBaseHref = function(){
			// Create
			var
				baseElements = document.getElementsByTagName('base'),
				baseElement = null,
				baseHref = '';

			// Test for Base Element
			if ( baseElements.length === 1 ) {
				// Prepare for Base Element
				baseElement = baseElements[0];
				baseHref = baseElement.href.replace(/[^\/]+$/,'');
			}

			// Adjust trailing slash
			baseHref = baseHref.replace(/\/+$/,'');
			if ( baseHref ) baseHref += '/';

			// Return
			return baseHref;
		};

		/**
		 * History.getBaseUrl()
		 * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
		 * @return {String} baseUrl
		 */
		History.getBaseUrl = function(){
			// Create
			var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();

			// Return
			return baseUrl;
		};

		/**
		 * History.getPageUrl()
		 * Fetches the URL of the current page
		 * @return {String} pageUrl
		 */
		History.getPageUrl = function(){
			// Fetch
			var
				State = History.getState(false,false),
				stateUrl = (State||{}).url||document.location.href;

			// Create
			var pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
				return (/\./).test(part) ? part : part+'/';
			});

			// Return
			return pageUrl;
		};

		/**
		 * History.getBasePageUrl()
		 * Fetches the Url of the directory of the current page
		 * @return {String} basePageUrl
		 */
		History.getBasePageUrl = function(){
			// Create
			var basePageUrl = document.location.href.replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
				return (/[^\/]$/).test(part) ? '' : part;
			}).replace(/\/+$/,'')+'/';

			// Return
			return basePageUrl;
		};

		/**
		 * History.getFullUrl(url)
		 * Ensures that we have an absolute URL and not a relative URL
		 * @param {string} url
		 * @param {Boolean} allowBaseHref
		 * @return {string} fullUrl
		 */
		History.getFullUrl = function(url,allowBaseHref){
			// Prepare
			var fullUrl = url, firstChar = url.substring(0,1);
			allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;

			// Check
			if ( /[a-z]+\:\/\//.test(url) ) {
				// Full URL
			}
			else if ( firstChar === '/' ) {
				// Root URL
				fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
			}
			else if ( firstChar === '#' ) {
				// Anchor URL
				fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
			}
			else if ( firstChar === '?' ) {
				// Query URL
				fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
			}
			else {
				// Relative URL
				if ( allowBaseHref ) {
					fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
				} else {
					fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
				}
				// We have an if condition above as we do not want hashes
				// which are relative to the baseHref in our URLs
				// as if the baseHref changes, then all our bookmarks
				// would now point to different locations
				// whereas the basePageUrl will always stay the same
			}

			// Return
			return fullUrl.replace(/\#$/,'');
		};

		/**
		 * History.getShortUrl(url)
		 * Ensures that we have a relative URL and not a absolute URL
		 * @param {string} url
		 * @return {string} url
		 */
		History.getShortUrl = function(url){
			// Prepare
			var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();

			// Trim baseUrl
			if ( History.emulated.pushState ) {
				// We are in a if statement as when pushState is not emulated
				// The actual url these short urls are relative to can change
				// So within the same session, we the url may end up somewhere different
				shortUrl = shortUrl.replace(baseUrl,'');
			}

			// Trim rootUrl
			shortUrl = shortUrl.replace(rootUrl,'/');

			// Ensure we can still detect it as a state
			if ( History.isTraditionalAnchor(shortUrl) ) {
				shortUrl = './'+shortUrl;
			}

			// Clean It
			shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');

			// Return
			return shortUrl;
		};

		// ----------------------------------------------------------------------
		// State Storage

		/**
		 * History.store
		 * The store for all session specific data
		 */
		History.store = amplify ? (amplify.store('History.store')||{}) : {};
		History.store.idToState = History.store.idToState||{};
		History.store.urlToId = History.store.urlToId||{};
		History.store.stateToId = History.store.stateToId||{};

		/**
		 * History.idToState
		 * 1-1: State ID to State Object
		 */
		History.idToState = History.idToState||{};

		/**
		 * History.stateToId
		 * 1-1: State String to State ID
		 */
		History.stateToId = History.stateToId||{};

		/**
		 * History.urlToId
		 * 1-1: State URL to State ID
		 */
		History.urlToId = History.urlToId||{};

		/**
		 * History.storedStates
		 * Store the states in an array
		 */
		History.storedStates = History.storedStates||[];

		/**
		 * History.savedStates
		 * Saved the states in an array
		 */
		History.savedStates = History.savedStates||[];

		/**
		 * History.getState()
		 * Get an object containing the data, title and url of the current state
		 * @param {Boolean} friendly
		 * @param {Boolean} create
		 * @return {Object} State
		 */
		History.getState = function(friendly,create){
			// Prepare
			if ( typeof friendly === 'undefined' ) { friendly = true; }
			if ( typeof create === 'undefined' ) { create = true; }

			// Fetch
			var State = History.getLastSavedState();

			// Create
			if ( !State && create ) {
				State = History.createStateObject();
			}

			// Adjust
			if ( friendly ) {
				State = History.cloneObject(State);
				State.url = State.cleanUrl||State.url;
			}

			// Return
			return State;
		};

		/**
		 * History.getIdByState(State)
		 * Gets a ID for a State
		 * @param {State} newState
		 * @return {String} id
		 */
		History.getIdByState = function(newState){

			// Fetch ID
			var id = History.extractId(newState.url);
			if ( !id ) {
				// Find ID via State String
				var str = History.getStateString(newState);
				if ( typeof History.stateToId[str] !== 'undefined' ) {
					id = History.stateToId[str];
				}
				else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
					id = History.store.stateToId[str];
				}
				else {
					// Generate a new ID
					while ( true ) {
						id = new Date().getTime() + ~~(Math.random()*1000);
						if ( typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined' ) {
							break;
						}
					}

					// Apply the new State to the ID
					History.stateToId[str] = id;
					History.idToState[id] = newState;
				}
			}

			// Return ID
			return id;
		};

		/**
		 * History.normalizeState(State)
		 * Expands a State Object
		 * @param {object} State
		 * @return {object}
		 */
		History.normalizeState = function(oldState){
			// Prepare
			if ( !oldState || (typeof oldState !== 'object') ) {
				oldState = {};
			}

			// Check
			if ( typeof oldState.normalized !== 'undefined' ) {
				return oldState;
			}

			// Adjust
			if ( !oldState.data || (typeof oldState.data !== 'object') ) {
				oldState.data = {};
			}

			// ----------------------------------------------------------------------

			// Create
			var newState = {};
			newState.normalized = true;
			newState.title = oldState.title||'';
			newState.url = History.getFullUrl(History.unescapeString(oldState.url||document.location.href));
			newState.hash = History.getShortUrl(newState.url);
			newState.data = History.cloneObject(oldState.data);

			// Fetch ID
			newState.id = History.getIdByState(newState);

			// ----------------------------------------------------------------------

			// Clean the URL
			newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
			newState.url = newState.cleanUrl;

			// Check to see if we have more than just a url
			var dataNotEmpty = !History.isEmptyObject(newState.data);

			// Apply
			if ( newState.title || dataNotEmpty ) {
				// Add ID to Hash
				newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
				if ( !/\?/.test(newState.hash) ) {
					newState.hash += '?';
				}
				newState.hash += '&_suid='+newState.id;
			}

			// Create the Hashed URL
			newState.hashedUrl = History.getFullUrl(newState.hash);

			// ----------------------------------------------------------------------

			// Update the URL if we have a duplicate
			if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
				newState.url = newState.hashedUrl;
			}

			// ----------------------------------------------------------------------

			// Return
			return newState;
		};

		/**
		 * History.createStateObject(data,title,url)
		 * Creates a object based on the data, title and url state params
		 * @param {object} data
		 * @param {string} title
		 * @param {string} url
		 * @return {object}
		 */
		History.createStateObject = function(data,title,url){
			// Hashify
			var State = {
				'data': data,
				'title': title,
				'url': url
			};

			// Expand the State
			State = History.normalizeState(State);

			// Return object
			return State;
		};

		/**
		 * History.getStateById(id)
		 * Get a state by it's UID
		 * @param {String} id
		 */
		History.getStateById = function(id){
			// Prepare
			id = String(id);

			// Retrieve
			var State = History.idToState[id] || History.store.idToState[id] || undefined;

			// Return State
			return State;
		};

		/**
		 * Get a State's String
		 * @param {State} passedState
		 */
		History.getStateString = function(passedState){
			// Prepare
			var State = History.normalizeState(passedState);

			// Clean
			var cleanedState = {
				data: State.data,
				title: passedState.title,
				url: passedState.url
			};

			// Fetch
			var str = JSON.stringify(cleanedState);

			// Return
			return str;
		};

		/**
		 * Get a State's ID
		 * @param {State} passedState
		 * @return {String} id
		 */
		History.getStateId = function(passedState){
			// Prepare
			var State = History.normalizeState(passedState);

			// Fetch
			var id = State.id;

			// Return
			return id;
		};

		/**
		 * History.getHashByState(State)
		 * Creates a Hash for the State Object
		 * @param {State} passedState
		 * @return {String} hash
		 */
		History.getHashByState = function(passedState){
			// Prepare
			var hash, State = History.normalizeState(passedState);

			// Fetch
			hash = State.hash;

			// Return
			return hash;
		};

		/**
		 * History.extractId(url_or_hash)
		 * Get a State ID by it's URL or Hash
		 * @param {string} url_or_hash
		 * @return {string} id
		 */
		History.extractId = function ( url_or_hash ) {
			// Prepare
			var id;

			// Extract
			var parts,url;
			parts = /(.*)\&_suid=([0-9]+)$/.exec(url_or_hash);
			url = parts ? (parts[1]||url_or_hash) : url_or_hash;
			id = parts ? String(parts[2]||'') : '';

			// Return
			return id||false;
		};

		/**
		 * History.isTraditionalAnchor
		 * Checks to see if the url is a traditional anchor or not
		 * @param {String} url_or_hash
		 * @return {Boolean}
		 */
		History.isTraditionalAnchor = function(url_or_hash){
			// Check
			var isTraditional = !(/[\/\?\.]/.test(url_or_hash));

			// Return
			return isTraditional;
		};

		/**
		 * History.extractState
		 * Get a State by it's URL or Hash
		 * @param {String} url_or_hash
		 * @return {State|null}
		 */
		History.extractState = function(url_or_hash,create){
			// Prepare
			var State = null;
			create = create||false;

			// Fetch SUID
			var id = History.extractId(url_or_hash);
			if ( id ) {
				State = History.getStateById(id);
			}

			// Fetch SUID returned no State
			if ( !State ) {
				// Fetch URL
				var url = History.getFullUrl(url_or_hash);

				// Check URL
				id = History.getIdByUrl(url)||false;
				if ( id ) {
					State = History.getStateById(id);
				}

				// Create State
				if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
					State = History.createStateObject(null,null,url);
				}
			}

			// Return
			return State;
		};

		/**
		 * History.getIdByUrl()
		 * Get a State ID by a State URL
		 */
		History.getIdByUrl = function(url){
			// Fetch
			var id = History.urlToId[url] || History.store.urlToId[url] || undefined;

			// Return
			return id;
		};

		/**
		 * History.getLastSavedState()
		 * Get an object containing the data, title and url of the current state
		 * @return {Object} State
		 */
		History.getLastSavedState = function(){
			return History.savedStates[History.savedStates.length-1]||undefined;
		};

		/**
		 * History.getLastStoredState()
		 * Get an object containing the data, title and url of the current state
		 * @return {Object} State
		 */
		History.getLastStoredState = function(){
			return History.storedStates[History.storedStates.length-1]||undefined;
		};

		/**
		 * History.hasUrlDuplicate
		 * Checks if a Url will have a url conflict
		 * @param {Object} newState
		 * @return {Boolean} hasDuplicate
		 */
		History.hasUrlDuplicate = function(newState) {
			// Prepare
			var hasDuplicate = false;

			// Fetch
			var oldState = History.extractState(newState.url);

			// Check
			hasDuplicate = oldState && oldState.id !== newState.id;

			// Return
			return hasDuplicate;
		};

		/**
		 * History.storeState
		 * Store a State
		 * @param {Object} newState
		 * @return {Object} newState
		 */
		History.storeState = function(newState){
			// Store the State
			History.urlToId[newState.url] = newState.id;

			// Push the State
			History.storedStates.push(History.cloneObject(newState));

			// Return newState
			return newState;
		};

		/**
		 * History.isLastSavedState(newState)
		 * Tests to see if the state is the last state
		 * @param {Object} newState
		 * @return {boolean} isLast
		 */
		History.isLastSavedState = function(newState){
			// Prepare
			var isLast = false;

			// Check
			if ( History.savedStates.length ) {
				var
					newId = newState.id,
					oldState = History.getLastSavedState(),
					oldId = oldState.id;

				// Check
				isLast = (newId === oldId);
			}

			// Return
			return isLast;
		};

		/**
		 * History.saveState
		 * Push a State
		 * @param {Object} newState
		 * @return {boolean} changed
		 */
		History.saveState = function(newState){
			// Check Hash
			if ( History.isLastSavedState(newState) ) {
				return false;
			}

			// Push the State
			History.savedStates.push(History.cloneObject(newState));

			// Return true
			return true;
		};

		/**
		 * History.getStateByIndex()
		 * Gets a state by the index
		 * @param {integer} index
		 * @return {Object}
		 */
		History.getStateByIndex = function(index){
			// Prepare
			var State = null;

			// Handle
			if ( typeof index === 'undefined' ) {
				// Get the last inserted
				State = History.savedStates[History.savedStates.length-1];
			}
			else if ( index < 0 ) {
				// Get from the end
				State = History.savedStates[History.savedStates.length+index];
			}
			else {
				// Get from the beginning
				State = History.savedStates[index];
			}

			// Return State
			return State;
		};

		// ----------------------------------------------------------------------
		// Hash Helpers

		/**
		 * History.getHash()
		 * Gets the current document hash
		 * @return {string}
		 */
		History.getHash = function(){
			var hash = History.unescapeHash(document.location.hash);
			return hash;
		};

		/**
		 * History.unescapeString()
		 * Unescape a string
		 * @param {String} str
		 * @return {string}
		 */
		History.unescapeString = function(str){
			// Prepare
			var result = str;

			// Unescape hash
			var tmp;
			while ( true ) {
				tmp = window.unescape(result);
				if ( tmp === result ) {
					break;
				}
				result = tmp;
			}

			// Return result
			return result;
		};

		/**
		 * History.unescapeHash()
		 * normalize and Unescape a Hash
		 * @param {String} hash
		 * @return {string}
		 */
		History.unescapeHash = function(hash){
			// Prepare
			var result = History.normalizeHash(hash);

			// Unescape hash
			result = History.unescapeString(result);

			// Return result
			return result;
		};

		/**
		 * History.normalizeHash()
		 * normalize a hash across browsers
		 * @return {string}
		 */
		History.normalizeHash = function(hash){
			var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');

			// Return result
			return result;
		};

		/**
		 * History.setHash(hash)
		 * Sets the document hash
		 * @param {string} hash
		 * @return {History}
		 */
		History.setHash = function(hash,queue){
			// Handle Queueing
			if ( queue !== false && History.busy() ) {
				// Wait + Push to Queue
				//History.debug('History.setHash: we must wait', arguments);
				History.pushQueue({
					scope: History,
					callback: History.setHash,
					args: arguments,
					queue: queue
				});
				return false;
			}

			// Log
			//History.debug('History.setHash: called',hash);

			// Prepare
			var adjustedHash = History.escapeHash(hash);

			// Make Busy + Continue
			History.busy(true);

			// Check if hash is a state
			var State = History.extractState(hash,true);
			if ( State && !History.emulated.pushState ) {
				// Hash is a state so skip the setHash
				//History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);

				// PushState
				History.pushState(State.data,State.title,State.url,false);
			}
			else if ( document.location.hash !== adjustedHash ) {
				// Hash is a proper hash, so apply it

				// Handle browser bugs
				if ( History.bugs.setHash ) {
					// Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249

					// Fetch the base page
					var pageUrl = History.getPageUrl();

					// Safari hash apply
					History.pushState(null,null,pageUrl+'#'+adjustedHash,false);
				}
				else {
					// Normal hash apply
					document.location.hash = adjustedHash;
				}
			}

			// Chain
			return History;
		};

		/**
		 * History.escape()
		 * normalize and Escape a Hash
		 * @return {string}
		 */
		History.escapeHash = function(hash){
			var result = History.normalizeHash(hash);

			// Escape hash
			result = window.escape(result);

			// IE6 Escape Bug
			if ( !History.bugs.hashEscape ) {
				// Restore common parts
				result = result
					.replace(/\%21/g,'!')
					.replace(/\%26/g,'&')
					.replace(/\%3D/g,'=')
					.replace(/\%3F/g,'?');
			}

			// Return result
			return result;
		};

		/**
		 * History.getHashByUrl(url)
		 * Extracts the Hash from a URL
		 * @param {string} url
		 * @return {string} url
		 */
		History.getHashByUrl = function(url){
			// Extract the hash
			var hash = String(url)
				.replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
				;

			// Unescape hash
			hash = History.unescapeHash(hash);

			// Return hash
			return hash;
		};

		/**
		 * History.setTitle(title)
		 * Applies the title to the document
		 * @param {State} newState
		 * @return {Boolean}
		 */
		History.setTitle = function(newState){
			// Prepare
			var title = newState.title;

			// Initial
			if ( !title ) {
				var firstState = History.getStateByIndex(0);
				if ( firstState && firstState.url === newState.url ) {
					title = firstState.title||History.options.initialTitle;
				}
			}

			// Apply
			try {
				document.getElementsByTagName('title')[0].innerHTML = title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ');
			}
			catch ( Exception ) { }
			document.title = title;

			// Chain
			return History;
		};

		// ----------------------------------------------------------------------
		// Queueing

		/**
		 * History.queues
		 * The list of queues to use
		 * First In, First Out
		 */
		History.queues = [];

		/**
		 * History.busy(value)
		 * @param {boolean} value [optional]
		 * @return {boolean} busy
		 */
		History.busy = function(value){
			// Apply
			if ( typeof value !== 'undefined' ) {
				//History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
				History.busy.flag = value;
			}
			// Default
			else if ( typeof History.busy.flag === 'undefined' ) {
				History.busy.flag = false;
			}

			// Queue
			if ( !History.busy.flag ) {
				// Execute the next item in the queue
				clearTimeout(History.busy.timeout);
				var fireNext = function(){
					if ( History.busy.flag ) return;
					for ( var i=History.queues.length-1; i >= 0; --i ) {
						var queue = History.queues[i];
						if ( queue.length === 0 ) continue;
						var item = queue.shift();
						History.fireQueueItem(item);
						History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
					}
				};
				History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
			}

			// Return
			return History.busy.flag;
		};

		/**
		 * History.fireQueueItem(item)
		 * Fire a Queue Item
		 * @param {Object} item
		 * @return {Mixed} result
		 */
		History.fireQueueItem = function(item){
			return item.callback.apply(item.scope||History,item.args||[]);
		};

		/**
		 * History.pushQueue(callback,args)
		 * Add an item to the queue
		 * @param {Object} item [scope,callback,args,queue]
		 */
		History.pushQueue = function(item){
			// Prepare the queue
			History.queues[item.queue||0] = History.queues[item.queue||0]||[];

			// Add to the queue
			History.queues[item.queue||0].push(item);

			// Chain
			return History;
		};

		/**
		 * History.queue (item,queue), (func,queue), (func), (item)
		 * Either firs the item now if not busy, or adds it to the queue
		 */
		History.queue = function(item,queue){
			// Prepare
			if ( typeof item === 'function' ) {
				item = {
					callback: item
				};
			}
			if ( typeof queue !== 'undefined' ) {
				item.queue = queue;
			}

			// Handle
			if ( History.busy() ) {
				History.pushQueue(item);
			} else {
				History.fireQueueItem(item);
			}

			// Chain
			return History;
		};

		/**
		 * History.clearQueue()
		 * Clears the Queue
		 */
		History.clearQueue = function(){
			History.busy.flag = false;
			History.queues = [];
			return History;
		};


		// ----------------------------------------------------------------------
		// IE Bug Fix

		/**
		 * History.stateChanged
		 * States whether or not the state has changed since the last double check was initialised
		 */
		History.stateChanged = false;

		/**
		 * History.doubleChecker
		 * Contains the timeout used for the double checks
		 */
		History.doubleChecker = false;

		/**
		 * History.doubleCheckComplete()
		 * Complete a double check
		 * @return {History}
		 */
		History.doubleCheckComplete = function(){
			// Update
			History.stateChanged = true;

			// Clear
			History.doubleCheckClear();

			// Chain
			return History;
		};

		/**
		 * History.doubleCheckClear()
		 * Clear a double check
		 * @return {History}
		 */
		History.doubleCheckClear = function(){
			// Clear
			if ( History.doubleChecker ) {
				clearTimeout(History.doubleChecker);
				History.doubleChecker = false;
			}

			// Chain
			return History;
		};

		/**
		 * History.doubleCheck()
		 * Create a double check
		 * @return {History}
		 */
		History.doubleCheck = function(tryAgain){
			// Reset
			History.stateChanged = false;
			History.doubleCheckClear();

			// Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
			// Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
			if ( History.bugs.ieDoubleCheck ) {
				// Apply Check
				History.doubleChecker = setTimeout(
					function(){
						History.doubleCheckClear();
						if ( !History.stateChanged ) {
							//History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
							// Re-Attempt
							tryAgain();
						}
						return true;
					},
					History.options.doubleCheckInterval
				);
			}

			// Chain
			return History;
		};

		// ----------------------------------------------------------------------
		// Safari Bug Fix

		/**
		 * History.safariStatePoll()
		 * Poll the current state
		 * @return {History}
		 */
		History.safariStatePoll = function(){
			// Poll the URL

			// Get the Last State which has the new URL
			var
				urlState = History.extractState(document.location.href),
				newState;

			// Check for a difference
			if ( !History.isLastSavedState(urlState) ) {
				newState = urlState;
			}
			else {
				return;
			}

			// Check if we have a state with that url
			// If not create it
			if ( !newState ) {
				//History.debug('History.safariStatePoll: new');
				newState = History.createStateObject();
			}

			// Apply the New State
			//History.debug('History.safariStatePoll: trigger');
			History.Adapter.trigger(window,'popstate');

			// Chain
			return History;
		};

		// ----------------------------------------------------------------------
		// State Aliases

		/**
		 * History.back(queue)
		 * Send the browser history back one item
		 * @param {Integer} queue [optional]
		 */
		History.back = function(queue){
			//History.debug('History.back: called', arguments);

			// Handle Queueing
			if ( queue !== false && History.busy() ) {
				// Wait + Push to Queue
				//History.debug('History.back: we must wait', arguments);
				History.pushQueue({
					scope: History,
					callback: History.back,
					args: arguments,
					queue: queue
				});
				return false;
			}

			// Make Busy + Continue
			History.busy(true);

			// Fix certain browser bugs that prevent the state from changing
			History.doubleCheck(function(){
				History.back(false);
			});

			// Go back
			history.go(-1);

			// End back closure
			return true;
		};

		/**
		 * History.forward(queue)
		 * Send the browser history forward one item
		 * @param {Integer} queue [optional]
		 */
		History.forward = function(queue){
			//History.debug('History.forward: called', arguments);

			// Handle Queueing
			if ( queue !== false && History.busy() ) {
				// Wait + Push to Queue
				//History.debug('History.forward: we must wait', arguments);
				History.pushQueue({
					scope: History,
					callback: History.forward,
					args: arguments,
					queue: queue
				});
				return false;
			}

			// Make Busy + Continue
			History.busy(true);

			// Fix certain browser bugs that prevent the state from changing
			History.doubleCheck(function(){
				History.forward(false);
			});

			// Go forward
			history.go(1);

			// End forward closure
			return true;
		};

		/**
		 * History.go(index,queue)
		 * Send the browser history back or forward index times
		 * @param {Integer} queue [optional]
		 */
		History.go = function(index,queue){
			//History.debug('History.go: called', arguments);

			// Prepare
			var i;

			// Handle
			if ( index > 0 ) {
				// Forward
				for ( i=1; i<=index; ++i ) {
					History.forward(queue);
				}
			}
			else if ( index < 0 ) {
				// Backward
				for ( i=-1; i>=index; --i ) {
					History.back(queue);
				}
			}
			else {
				throw new Error('History.go: History.go requires a positive or negative integer passed.');
			}

			// Chain
			return History;
		};


		// ----------------------------------------------------------------------
		// Initialise

		/**
		 * Create the initial State
		 */
		History.saveState(History.storeState(History.extractState(document.location.href,true)));

		/**
		 * Bind for Saving Store
		 */
		if ( amplify ) {
			History.onUnload = function(){
				// Prepare
				var
					currentStore = amplify.store('History.store')||{},
					item;

				// Ensure
				currentStore.idToState = currentStore.idToState || {};
				currentStore.urlToId = currentStore.urlToId || {};
				currentStore.stateToId = currentStore.stateToId || {};

				// Sync
				for ( item in History.idToState ) {
					if ( !History.idToState.hasOwnProperty(item) ) {
						continue;
					}
					currentStore.idToState[item] = History.idToState[item];
				}
				for ( item in History.urlToId ) {
					if ( !History.urlToId.hasOwnProperty(item) ) {
						continue;
					}
					currentStore.urlToId[item] = History.urlToId[item];
				}
				for ( item in History.stateToId ) {
					if ( !History.stateToId.hasOwnProperty(item) ) {
						continue;
					}
					currentStore.stateToId[item] = History.stateToId[item];
				}

				// Update
				History.store = currentStore;

				// Store
				amplify.store('History.store',currentStore);
			};
			// For Internet Explorer
			History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
			// For Other Browsers
			History.Adapter.bind(window,'beforeunload',History.onUnload);
			History.Adapter.bind(window,'unload',History.onUnload);
			// Both are enabled for consistency
		}


		// ----------------------------------------------------------------------
		// HTML5 State Support

		if ( History.emulated.pushState ) {
			/*
			 * Provide Skeleton for HTML4 Browsers
			 */

			// Prepare
			var emptyFunction = function(){};
			History.pushState = History.pushState||emptyFunction;
			History.replaceState = History.replaceState||emptyFunction;
		}
		else {
			/*
			 * Use native HTML5 History API Implementation
			 */

			/**
			 * History.onPopState(event,extra)
			 * Refresh the Current State
			 */
			History.onPopState = function(event){
				// Reset the double check
				History.doubleCheckComplete();

				// Check for a Hash, and handle apporiatly
				var currentHash	= History.getHash();
				if ( currentHash ) {
					// Expand Hash
					var currentState = History.extractState(currentHash||document.location.href,true);
					if ( currentState ) {
						// We were able to parse it, it must be a State!
						// Let's forward to replaceState
						//History.debug('History.onPopState: state anchor', currentHash, currentState);
						History.replaceState(currentState.data, currentState.title, currentState.url, false);
					}
					else {
						// Traditional Anchor
						//History.debug('History.onPopState: traditional anchor', currentHash);
						History.Adapter.trigger(window,'anchorchange');
						History.busy(false);
					}

					// We don't care for hashes
					History.expectedStateId = false;
					return false;
				}

				// Prepare
				var newState = false;

				// Prepare
				event = event||{};
				if ( typeof event.state === 'undefined' ) {
					// jQuery
					if ( typeof event.originalEvent !== 'undefined' && typeof event.originalEvent.state !== 'undefined' ) {
						event.state = event.originalEvent.state||false;
					}
					// MooTools
					else if ( typeof event.event !== 'undefined' && typeof event.event.state !== 'undefined' ) {
						event.state = event.event.state||false;
					}
				}

				// Ensure
				event.state = (event.state||false);

				// Fetch State
				if ( event.state ) {
					// Vanilla: Back/forward button was used
					newState = History.getStateById(event.state);
				}
				else if ( History.expectedStateId ) {
					// Vanilla: A new state was pushed, and popstate was called manually
					newState = History.getStateById(History.expectedStateId);
				}
				else {
					// Initial State
					newState = History.extractState(document.location.href);
				}

				// The State did not exist in our store
				if ( !newState ) {
					// Regenerate the State
					newState = History.createStateObject(null,null,document.location.href);
				}

				// Clean
				History.expectedStateId = false;

				// Check if we are the same state
				if ( History.isLastSavedState(newState) ) {
					// There has been no change (just the page's hash has finally propagated)
					//History.debug('History.onPopState: no change', newState, History.savedStates);
					History.busy(false);
					return false;
				}

				// Store the State
				History.storeState(newState);
				History.saveState(newState);

				// Force update of the title
				History.setTitle(newState);

				// Fire Our Event
				History.Adapter.trigger(window,'statechange');
				History.busy(false);

				// Return true
				return true;
			};
			History.Adapter.bind(window,'popstate',History.onPopState);

			/**
			 * History.pushState(data,title,url)
			 * Add a new State to the history object, become it, and trigger onpopstate
			 * We have to trigger for HTML4 compatibility
			 * @param {object} data
			 * @param {string} title
			 * @param {string} url
			 * @return {true}
			 */
			History.pushState = function(data,title,url,queue){
				//History.debug('History.pushState: called', arguments);

				// Check the State
				if ( History.getHashByUrl(url) && History.emulated.pushState ) {
					throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
				}

				// Handle Queueing
				if ( queue !== false && History.busy() ) {
					// Wait + Push to Queue
					//History.debug('History.pushState: we must wait', arguments);
					History.pushQueue({
						scope: History,
						callback: History.pushState,
						args: arguments,
						queue: queue
					});
					return false;
				}

				// Make Busy + Continue
				History.busy(true);

				// Create the newState
				var newState = History.createStateObject(data,title,url);

				// Check it
				if ( History.isLastSavedState(newState) ) {
					// Won't be a change
					History.busy(false);
				}
				else {
					// Store the newState
					History.storeState(newState);
					History.expectedStateId = newState.id;

					// Push the newState
					history.pushState(newState.id,newState.title,newState.url);

					// Fire HTML5 Event
					History.Adapter.trigger(window,'popstate');
				}

				// End pushState closure
				return true;
			};

			/**
			 * History.replaceState(data,title,url)
			 * Replace the State and trigger onpopstate
			 * We have to trigger for HTML4 compatibility
			 * @param {object} data
			 * @param {string} title
			 * @param {string} url
			 * @return {true}
			 */
			History.replaceState = function(data,title,url,queue){
				//History.debug('History.replaceState: called', arguments);

				// Check the State
				if ( History.getHashByUrl(url) && History.emulated.pushState ) {
					throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
				}

				// Handle Queueing
				if ( queue !== false && History.busy() ) {
					// Wait + Push to Queue
					//History.debug('History.replaceState: we must wait', arguments);
					History.pushQueue({
						scope: History,
						callback: History.replaceState,
						args: arguments,
						queue: queue
					});
					return false;
				}

				// Make Busy + Continue
				History.busy(true);

				// Create the newState
				var newState = History.createStateObject(data,title,url);

				// Check it
				if ( History.isLastSavedState(newState) ) {
					// Won't be a change
					History.busy(false);
				}
				else {
					// Store the newState
					History.storeState(newState);
					History.expectedStateId = newState.id;

					// Push the newState
					history.replaceState(newState.id,newState.title,newState.url);

					// Fire HTML5 Event
					History.Adapter.trigger(window,'popstate');
				}

				// End replaceState closure
				return true;
			};

			// Be aware, the following is only for native pushState implementations
			// If you are wanting to include something for all browsers
			// Then include it above this if block

			/**
			 * Setup Safari Fix
			 */
			if ( History.bugs.safariPoll ) {
				History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
			}

			/**
			 * Ensure Cross Browser Compatibility
			 */
			if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
				/**
				 * Fix Safari HashChange Issue
				 */

				// Setup Alias
				History.Adapter.bind(window,'hashchange',function(){
					History.Adapter.trigger(window,'popstate');
				});

				// Initialise Alias
				if ( History.getHash() ) {
					History.Adapter.onDomLoad(function(){
						History.Adapter.trigger(window,'hashchange');
					});
				}
			}

		} // !History.emulated.pushState

	}; // History.initCore

	// Try and Initialise History
	History.init();

})(window);

jQuery.namespace=function(F,B){var C,A=F.split("."),E=window,D=false;if(/[^a-zA-Z.]/.test(F)){return false}for(C=0;C<A.length;C++){if(!E[A[C]]){E[A[C]]={};D=true}E=E[A[C]]}if(!!B){return D}return true};
/**
 * Progress Bar jQuery plugin
 *
 * Options:
 * - value  {number}    Default: 0
 *      The value of the progressBar.
 *      Can be set when initialising (first creating) the progressBar.
 *          eg. $(".selector").progressBar({ value: 40 });
 *      Get or set the value option after initialisation:
 *          //getter
 *          var value = $(".selector").progressBar("option", "value");
 *          //setter
 *          $(".selector").progressBar("option", "value", 40);
 *
 * - text   {string}    Default: &nbsp;
 *      The text shown in the progressBar.
 *      Can be set when initialising (first creating) the progressBar.
 *          eg. $(".selector").progressBar({ text: "40% complete" });
 *      Get or set the value option after initialisation:
 *          //getter
 *          var text = $(".selector").progressBar("option", "text");
 *          //setter
 *          $(".selector").progressBar("option", "text", "40% complete");
 *
 * Initialisation:
 * $("#myBar").progressBar();
 *
 * This will turn the target element (in this case <div id="myBar"></div>) into a progress bar using the
 * default options. If the HTML for the progress bar is already contained within the target element the plugin will
 * initialise by extracting the data from the HTML, which from then onward can be updated using the plugin methods.
 *
 * You could also pass an object as the first parameter containing your own options with which to initialise the
 * progress bar. eg. $("#myBar").progressBar({ value: 40, text: "40% complete" });
 *
 * Methods:
 * - progressBar("destroy")
 *      Removes any data and bindings that were added to the element by the plugin leaving just the HTML.
 *
 * - progressBar("option", optionName, [value])
 *      Get or set any progressBar option. If no value is specified, will act as a getter.
 *
 * - progressBar("option", [options])
 *      Get or set multiple progressBar options at once by providing an options object. If options is not specified,
 *      will act as a getter.
 * 
 */
(function ($) {
    $.fn.progressBar = function (options) {
        if (typeof options == "string") {
            if (options == "option") {
                if (arguments.length == 1) { // getter
                    var retArr = [];
                    this.each(function () {
                        retArr.push($(this).data("options"));
                    });
                    return retArr;
                } else if (arguments.length == 2 && typeof arguments[1] == "string") { // individual option getter
                    var ret,
                        opt = arguments[1];
                    this.each(function () {
                        var $el = $(this);
                        ret = (typeof ret == "undefined") ? $el.data("options")[opt] : ret + $el.data("options")[opt];
                    });
                    return ret;
                } else if (arguments.length == 2 && typeof arguments[1] == "object") { // option object setter
                    var newOpts = arguments[1];
                    if (typeof newOpts.text != "undefined" && (newOpts.text == null || newOpts.text == "")) {
                        newOpts.text = $.fn.progressBar.defaults.text;
                    }
                    return this.each(function () {
                        var $el = $(this);
                        $el.data("options", $.extend($el.data("options"), newOpts)).trigger("updateProgressBar");
                    });
                } else if (arguments.length == 3 && typeof arguments[1] == "string") { // individual option setter
                    var key = arguments[1],
                        newVal = arguments[2];
                    if (key == "text" && (newVal == null || newVal == "")) {
                        newVal = $.fn.progressBar.defaults.text;
                    }
                    return this.each(function () {
                        var $el = $(this);
                        var currentOptions = $el.data("options");
                        currentOptions[key] = newVal;
                        $el.data("options", currentOptions).trigger("updateProgressBar");
                    });
                }
            } else if (options == "destroy") {
                return this.each(function () {
                    $(this).removeData("options").removeData("bar").removeData("text").unbind("updateProgressBar");
                });
            }
        } else { // init
            if (typeof options != "undefined" && typeof options.text != "undefined" && (options.text == null || options.text == "")) {
                delete options.text;
            }
            var opts = $.extend({}, $.fn.progressBar.defaults, options);
            return this.each(function () {
                var $el = $(this);
                $el.bind("updateProgressBar", function (e) {
                    var $el = $(this),
                        options = $el.data("options");
                    $el.data("bar").width(Math.max(0, Math.min(100, options.value)) + "%");
                    $el.data("text").html(options.text);
                });
                if ($(".progress-bar, .progress-text", this).length == 2) { // check if HTML for progressBar already exists
                    var bar = $(".progress-bar", this),
                        text = $(".progress-text", this),
                        optsFromExisting = {};
                    if (typeof options == "undefined") {
                        var barWidth = bar.css("width"),
                            barText = text.text();
                        optsFromExisting.value = parseFloat(barWidth);
                        if (barText != null && barText != "") {
                            optsFromExisting.text = barText;
                        }
                    }
                    $el.data("options", $.extend({}, opts, optsFromExisting))
                       .data("bar", bar)
                       .data("text", text)
                       .trigger("updateProgressBar");
                } else {
                    $el.empty()
                       .data("options", opts)
                       .data("bar", $('<div class="progress-bar" style="width: ' + Math.max(0, Math.min(100, opts.value)) + '%;" />').appendTo(this))
                       .data("text", $('<div class="progress-text">' + opts.text + '</div>').appendTo(this));
                }
                if (!$el.hasClass("progress")) {
                    $el.addClass("progress");
                }
            });
        }
    };
    $.fn.progressBar.defaults = {
        value: 0,
        text: "&nbsp;"
    };
})(jQuery);
(function ($)
{
    /**
     * Creates a Cron builder on the page for a specific field.  The builder makes up two form components, the text display
     * (showing the pretty cron expression) and a hidden field (with the raw cron expression)
     * The value to be submitted can only be updated via the cron buidler dialog.
     *
     * USAGE
     * ------
     * Call against display field e.g:
     *
     *   AJS.$("#displayFieldId").cronBuilder({});
     *
     * Arguments (all required)
     *
     * opts {
     *  hiddenFieldSelector:    selector for the field that will be submited as part of the form (usually a hidden field)
     *  dialogTrigger:          html for the cron builder trigger
     *  eventNamespace:         unique namespace for this dialog click event
     *  contextPath:            context path for bamboo instance (used when generating urls;)
     *  dialogSubmitButtonText: text for the dialog submit button
     *  dialogHeadingText:      text for the dialog heading
     * }
     });
     */
    $.fn.cronBuilder = function (opts) {
        return this.each( function () {
            var $this = $(this),
                initialCron = $(opts.hiddenFieldSelector).val(),
                $dialogTrigger = $(opts.dialogTrigger),

                addCronExpression = function (result) {
                    //update fields
                    $(opts.hiddenFieldSelector).val(result.cronExpression);
                    $this.text(result.prettyCronExpression);

                    // need to remove the old dialog and reattach with the new cron expression as the arg.
                    $($dialogTrigger).unbind("click." + opts.eventNamespace);
                    attachCronDialog(result.cronExpression);
                },

                attachCronDialog = function (cron) {
                    simpleDialogForm($dialogTrigger, opts.contextPath + "/ajax/editCronExpression.action?cronExpression=" + encodeURIComponent(cron),
                                     620, 380, opts.dialogSubmitButtonText, "ajax", addCronExpression, null, opts.dialogHeadingText, opts.eventNamespace);
                };

            // generate pretty string
            $.get(opts.contextPath + "/ajax/getPrettyCronExpression.action?cronExpression=" + encodeURIComponent(initialCron), function(result) {
                $this.text(result.prettyCronExpression);
            });

            // add the link to the right spot - needed cause it avoids playing with the form templates.
            $dialogTrigger.insertAfter($this);

            attachCronDialog(initialCron);
        });

    };

/**
 * Replaces an element containing a cron expression with the pretty version of that expression.
 *
 * Usage:  e.g. AJS.$("#element").cronBuilder(${req.contextPath});
 *
 */
    $.fn.cronDisplay = function (contextPath) {
        return this.each(function () {
            var $this = $(this),
                cron = $this.text();

            // generate pretty string
            $.get(contextPath + "/ajax/getPrettyCronExpression.action?cronExpression=" + encodeURIComponent(cron), function(result) {
                $this.text(result.prettyCronExpression);
            });
        });
    };
})(jQuery);
(function ($) {
    $.fn.reloadImage = function (options) {
        var defaults = {
            text: "Reload image",
            cssClass: "image-reload"
        };
        var opts = $.extend(defaults, options);

        return this.each(function () {
            var $this = $(this);
            $('<span class="' + opts.cssClass + '" title="' + opts.text + '" />').insertAfter($this).click(function (e) {
                var src = $this.attr("src"),
                    pos = src.indexOf("?"),
                    date = new Date();
                if (pos >= 0) {
                    src = src.substr(0, pos);
                }
                $this.attr("src", src + "?v=" + date.getTime());
                e.preventDefault();
            });
        });
    }
})(jQuery);

var BuildResult = function ($) {
    var opts = {
        currentKey: null,
        getStatusUrl: null,
        buildStatus: null,
        jobStatus: null
    },
    $planNavigator,
    $stageElements,
    $statusRibbon,
    $progressBar,
    $buildingFor,
    getBuildStatus = function (build) {
        if (build.finished) {
            return build.state;
            /* The REST for plan results doesn't contain a "state" (e.g. Successful, Failed, NotBuilt), so build.state will be undefined
               but will cause the page to reload anyway, at which point this JS shouldn't be executed because the build is no longer "active".
               Ideally we'd have the plan result build state returned in the REST. */
        } else if (build.progress && build.progress.buildTime) {
            return "InProgress";
        } else {
            return "Queued";
        }
    },
    getJobStatus = function (job) {
        if (job.finished) {
            return job.state;
        } else if (job.waiting) {
            return "Pending";
        } else if (job.progress && !job.queued) {
            if (job.updatingSource) {
                return "updatingSource";
            } else {
                return "InProgress";
            }
        } else {
            return "Queued";
        }
    },
    isJobResult,
    updateTimeout,
    update = function () {
        $.ajax({
            url: opts.getStatusUrl,
            cache: false,
            data: {
                expand: "stages.stage.results.result"
            },
            dataType: "json",
            contentType: "application/json",
            success: function (json) {
                if (json.finished) {
                    window.location.reload(true);
                    return;
                }

                refreshBuildRibbon(json);
                refreshPlanNavigator(json);

                // Update again in 5 seconds
                updateTimeout = setTimeout(update, 5000);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // Error occurred when doing the update, try again in 30 sec
                updateTimeout = setTimeout(update, 30000);
            }
        });
    },
    updateIcon = function ($icon, iconType) {
        var fullIconType = "icon-" + iconType;
        if (!$icon.hasClass(fullIconType)) {
            $icon.attr("class", "icon " + fullIconType);
        }
    },
    refreshBuildRibbon = function (json) {
        if (opts.buildStatus != getBuildStatus(json)) {
            window.location.reload(true);
            return;
        }
        if (!isJobResult) {
            if (!json.progress.buildTime) {
                $buildingFor.text(json.prettyQueuedTime);
            } else {
                $progressBar.progressBar("option", "value", Math.ceil(100 - (json.progress.percentageCompleted * 100)));
                if (json.progress.averageBuildDuration > 0) {
                    $buildingFor.text("- " + json.progress.prettyTimeRemaining);
                } else {
                    $buildingFor.text("- " + json.progress.prettyBuildTime);
                }
                refreshDetails(json);
            }
        }
    },
    refreshJobRibbon = function (job) {
        if (opts.jobStatus != getJobStatus(job)) {
            window.location.reload(true);
            return;
        }
        if (job.queued) {
            $buildingFor.text(job.prettyQueuedTime);
        } else if (job.updatingSource) {
            $buildingFor.text(job.prettyVcsUpdateDuration);
        } else if (job.progress) {
            $progressBar.progressBar("option", "value", Math.ceil(100 - (job.progress.percentageCompleted * 100)));
            if (job.progress.averageBuildDuration > 0) {
                $buildingFor.text("- " + job.progress.prettyTimeRemaining);
            } else {
                $buildingFor.text("- " + job.progress.prettyBuildTime);
            }
            refreshDetails(job);
        }
    },
    refreshDetails = function (json) {
        if (json.progress) {
            $(".started + dd > time").attr("datetime", json.progress.startedTimeFormatted).html(json.progress.startedTime + ' &ndash; <span>' + json.progress.prettyStartedTime + '</span>');
        }
    },
    refreshPlanNavigator = function (json) {
        var jobs = [];
        if (json.stages.stage.length > 0) {
            for (var i=0, ii=json.stages.stage.length, k=json.stages.stage[0].index; i<ii; i++, k++) {
                var stage = json.stages.stage[i],
                    $stageElement = $($stageElements[k]),
                    $stageIcon = $(".stageIcon", $stageElement);
                jobs = jobs.concat(stage.results.result);
                if (stage.isBuilding) {
                    $stageElement.removeClass("Pending").addClass("InProgress");
                    if ($stageIcon.length) {
                        updateIcon($stageIcon, "stage-InProgress stageIcon");
                    }
                } else if (stage.isCompleted) {
                    $stageElement.removeClass("Pending InProgress").addClass(stage.isSuccessful ? "Successful" : "Failed");
                    if ($stageIcon.length) {
                        updateIcon($stageIcon, stage.isSuccessful ? "stage-Successful stageIcon" : "stage-Failed stageIcon");
                    }
                } else {
                    $stageElement.addClass("Pending");
                    if ($stageIcon.length) {
                        updateIcon($stageIcon, "stage-Pending stageIcon");
                    }
                }
            }
            for (var j=0, jj=jobs.length; j<jj; j++) {
                var job = jobs[j],
                    $job = $("#job-" + job.key),
                    $icon = $(".icon", $job[0]),
                    $progress = $(".progress", $job[0]);
                if (isJobResult && job.key == opts.currentKey) {
                    refreshJobRibbon(job);
                }
                if (job.finished) {
                    updateIcon($icon, job.state);
                    if ($progress.length) {
                        $progress.remove();
                    }
                } else if (job.progress && !job.queued) {
                    updateIcon($icon, "InProgress");
                    if (!$progress.length) {
                        $progress = $("<div />", { id: "navPb" + job.key }).progressBar().prependTo($job);
                    }
                    $progress.progressBar("option", "value", Math.ceil(100 - (job.progress.percentageCompleted * 100)));
                } else {
                    updateIcon($icon, "Queued");
                }
            }
        }
    };
    return {
        init: function (options) {
            $.extend(true, opts, options);

            $planNavigator = $("#plan-navigator");
            $statusRibbon = $("#status-ribbon");
            isJobResult = $statusRibbon.hasClass("has-job");
            $progressBar = $("#sr-pb-" + opts.currentKey);
            $buildingFor = $(".operationTime", $statusRibbon[0]);
            $stageElements = $("> ul > li", $planNavigator[0]);

            update();
        }
    }
}(jQuery);

//  ######
//  #     #  ######  #####   #####   ######   ####     ##     #####  ######  #####
//  #     #  #       #    #  #    #  #       #    #   #  #      #    #       #    #
//  #     #  #####   #    #  #    #  #####   #       #    #     #    #####   #    #
//  #     #  #       #####   #####   #       #       ######     #    #       #    #
//  #     #  #       #       #   #   #       #    #  #    #     #    #       #    #
//  ######   ######  #       #    #  ######   ####   #    #     #    ######  #####

// Constants
var BAMBOO_DASH_DISPLAY_TOGGLES = "bamboo.dash.display.toggles",
    BAMBOO_EVENT_ON_DASHBOARD_RELOADED = "BAMBOO_EVENT_ON_DASHBOARD_RELOADED";

BAMBOO.reloadDashboardTimeout = 20;
//
// Display the given help page in a separate window
//
function openHelp(helpPage) {
    window.open(helpPage, 'manualPopup', 'width=770,height=550,scrollbars=yes,status=yes,resizable=yes');
}

function isDefinedObject(reference) {
    return (typeof reference !== "undefined") && (reference !== null);
}

/**
 * Any href clicked with rel=help (e.g. our help bubbles) will open in new window.
 * Any element with id=addPlanLabel will trigger the edit labels dialog
 * Applies to all of Bamboo.
**/
AJS.$(document).delegate("a[rel~='help']", "click", function (e) {
    e.preventDefault();
    window.open(this.href);
}).delegate("#addPlanLabel", "click", function () {
    AJS.$(".labels-edit").click();
});


/**
 * Workaround for Cancel links in Dialog which append a hash to URL by default
 */
AJS.$("a.button-panel-link[href='#']").live("click", function (e) {
    e.preventDefault();
});

/**
 * AJS.BambooDialog
 */
AJS.BambooDialog = function(options, onSubmitCallback, onCancelCallback) {
    var dialog;
    options = options || {};
    options = jQuery.extend({}, options, {
        keypressListener: function(e) {
            if (e.which == jQuery.ui.keyCode.ESCAPE) {
                 if (isDefinedObject(onCancelCallback)) {
                     onCancelCallback(dialog);
                 } else {
                     dialog.remove();
                 }
            } else if (e.which == jQuery.ui.keyCode.ENTER && isDefinedObject(onSubmitCallback)) {
                onSubmitCallback(dialog);
                if (options.submitMode && options.submitMode == "ajax") {
                    e.preventDefault();
                }
            }
        }
    });
    dialog = new AJS.Dialog(options);
    return dialog;
};
AJS.Dialog.prototype.addHelpText = function (template, args) {
    if (!template) {
        // Don't do anything if there is no text to add.
        // This stops us printing 'undefined'.
        return;
    }

    var text = template;
    if (args) {
        text = AJS.template(template).fill(args).toString();
    }

    var page = this.page[this.curpage];
    if (!page.buttonpanel) {
        page.addButtonPanel();
    }

    // The text may include html i.e. links or strongs
    var tip = AJS.$("<div class='dialog-tip'></div>").html(text);
    page.buttonpanel.append(tip);
    tip.find("a").click(function() {
        window.open(this.href, '_blank').focus();
        return false;
    });
};

// Text used in the title attribute for elements that have keyboard shortcuts - ideally would be internationalised...
AJS.params.keyType = "Type";
AJS.params.keyThen = "then";

String.prototype.replaceAll = function(pcFrom, pcTo) {
    var MARKER = "js___bmbo_mrk",
        i = this.indexOf(pcFrom),
        c = this;
    while (i > -1) {
        c = c.replace(pcFrom, MARKER);
        i = c.indexOf(pcFrom);
    }

    i = c.indexOf(MARKER);
    while (i > -1) {
        c = c.replace(MARKER, pcTo);
        i = c.indexOf(MARKER);
    }

    return c;
};


if (!jQuery.generateId) {
  jQuery.generateId = function() {
    return arguments.callee.prefix + arguments.callee.count++;
  };
  jQuery.generateId.prefix = 'jq-';
  jQuery.generateId.count = 0;

  jQuery.fn.generateId = function() {
    return this.each(function() {
      this.id = jQuery.generateId();
    });
  };
}


/*
 Runs on a change of a
*/
function handleOnSelectShowHide(sel)
{
    var hideClassName = ("dependsOn" + sel.name).replaceAll(".", "\\."),
        switchValue = getSwitchValue(sel);
    if (!switchValue && sel.type == 'radio') return;

    var selector = "#" + sel.form.id + " ." + hideClassName,
        showPattern = "showOn" + switchValue,
        hidePattern = "showOn__" + switchValue;

    AJS.$(selector).each(function() {
        var $deps = AJS.$(this);
        if ($deps.attr("class").indexOf("showOn__") != -1) {
            if ($deps.hasClass(hidePattern)) {
                $deps.hide();
            } else {
                $deps.show();
            }
        } else {
            if ($deps.hasClass(showPattern)) {
                $deps.show();
            } else {
                $deps.hide();
            }
        }
        if ($deps.hasClass(hidePattern)) {
            $deps.hide();
        }
    });
}

/**
 * JSOn listData looks like:
 *
 *  [data: [{value: 'key1', text: 'name for the screen', supportedValues: ['dependencyKey1', 'dependencyKey2']},
 *   {value: 'key2', text: "name 2", supportedValues: ['dependencyKey1']}]]
 *
 * If supportedValues is empty it will be shown for all selections in selParentJQ.
 *
 * @param selParentJQ - the select list that the your data depends on
 * @param selToMutateJQ - the select list that you want to mutate based on the contents of the selDependency
 * @param listDataJson - the json containing all information required to generate the selToMutate
 */
function mutateSelectListContent(selParentJQ, selToMutateJQ, listDataJson)
{
    var selParent = selParentJQ[0];
    var selToMutate = selToMutateJQ[0];
    var currentSelectedValue = selToMutateJQ.val();
    var switchValue = getSwitchValue(selParent);
    //wipe existing items
    selToMutate.options.length = 0;

    var listData = listDataJson.data;
    // got through selToMutate check if each item is in allowed Items, if not remove?
    for (var i = 0; i<listData.length; i++){
        var value = listData[i].value;
        var text = listData[i].text;
        var allowedOptions = listData[i].supportedValues;

        var show = allowedOptions === null || allowedOptions.length <= 0 || !switchValue;
        if (!show)
        {
            for (var x = 0; x < allowedOptions.length; x++)
            {
                var allowedOption = allowedOptions[x];
                if (switchValue === allowedOption)
                {
                    show = true;
                    break;
                }
            }
        }

        if (show)
        {
            selToMutate.options[selToMutate.options.length]=new Option(text, value, false, value === currentSelectedValue);
        }
    }

    // make sure we update the dependents of the mutated list.
    handleOnSelectShowHide(selToMutate)
}

function getSwitchValue(obj)
{
    if (obj.options && obj.selectedIndex > -1)
    {
        var opt = obj.options[obj.selectedIndex];
        //  Special uiSwitch* class prefix
        if (opt.className.indexOf('uiSwitch') != -1)
        {
            var uiSwitch = opt.className.substring(opt.className.lastIndexOf("uiSwitch") + 8);
            return uiSwitch;
        }
        else
        {
            return opt.value;
        }
    }
    else if (obj.type == 'radio')
    {
        if (obj.checked)
            return obj.value;
        else
            return null;
    }
    else if (obj.type == 'checkbox')
    {
        if (obj.checked)
            return obj.value;
        else
            return 'false';
    }
    else
    {
        return obj.value;
    }
}


/*
 Toggles hide / unhide an element. Also attemots to change the "elementId + header" element to have the headerOpened / headerClosed class.
 Also saves the state in a cookie
*/
function toggleElement(elementId, suffix)
{
    var elem = document.getElementById(elementId);
    if (elem)
    {
        if (readFromConglomerateCookie("bamboo.conglomerate.general.cookie", elementId, '1') == '1')
        {
            elem.style.display = "none";
            var toggler = document.getElementById(elementId + "Toggle");
            if (toggler)
            {
                toggler.innerHTML = "show" + (suffix ? " " + suffix : "");
            }
            //            removeClassName(elementId + 'header', 'headerOpened');
            //            addClassName(elementId + 'header', 'headerClosed');
            saveToConglomerateCookie("bamboo.conglomerate.general.cookie", elementId, '0');
        }
        else
        {
            elem.style.display = "";
            var toggler = document.getElementById(elementId + "Toggle");
            if (toggler)
            {
                toggler.innerHTML = "hide" + (suffix ? " " + suffix : "");
            }
            //            removeClassName(elementId + 'header', 'headerClosed');
            //            addClassName(elementId + 'header', 'headerOpened');
            eraseFromConglomerateCookie("bamboo.conglomerate.general.cookie", elementId);
        }
    }
}

function toggleDivsWithCookie(elementShowId, elementHideId)
{
    var elementShow = document.getElementById(elementShowId);
    var elementHide = document.getElementById(elementHideId);
    if (elementShow.style.display == 'none')
    {
        elementHide.style.display = 'none';
        elementShow.style.display = 'block';
        saveToConglomerateCookie("bamboo.viewissue.cong.general.cookie", elementShowId, null);
        saveToConglomerateCookie("bamboo.viewissue.cong.general.cookie", elementHideId, '0');
    }
    else
    {
        elementShow.style.display = 'none';
        elementHide.style.display = 'block';
        saveToConglomerateCookie("bamboo.viewissue.cong.general.cookie", elementHideId, null);
        saveToConglomerateCookie("bamboo.viewissue.cong.general.cookie", elementShowId, '0');
    }
}

/*
 Similar to toggle. Run this on page load.
*/
function restoreDivFromCookie(elementId, cookieName, defaultValue, suffix)
{
    if (defaultValue == null)
        defaultValue = '1';

    var elem = document.getElementById(elementId);
    if (elem)
    {
        if (readFromConglomerateCookie(cookieName, elementId, defaultValue) != '1')
        {
            elem.style.display = "none";
            var toggler = document.getElementById(elementId + "Toggle");
            if (toggler)
            {
                toggler.innerHTML = "show" + (suffix ? " " + suffix : "");
            }
            //            removeClassName(elementId + 'header', 'headerOpened');
            //            addClassName(elementId + 'header', 'headerClosed')
        }
        else
        {
            elem.style.display = "";
            var toggler = document.getElementById(elementId + "Toggle");
            if (toggler)
            {
                toggler.innerHTML = "hide" + (suffix ? " " + suffix : "");
            }
            //            removeClassName(elementId + 'header', 'headerClosed');
            //            addClassName(elementId + 'header', 'headerOpened')
        }
    }
}

/*
 Similar to toggle. Run this on page load.
*/
function restoreElement(elementId, suffix)
{
    restoreDivFromCookie(elementId, "bamboo.conglomerate.general.cookie", '1', suffix);
}

// Cookie handling functions

function saveToConglomerateCookie(cookieName, name, value)
{
    var cookieValue = getCookieValue(cookieName);
    cookieValue = addOrAppendToValue(name, value, cookieValue);

    saveCookie(cookieName, cookieValue, 365);
}

function readFromConglomerateCookie(cookieName, name, defaultValue)
{
    var cookieValue = getCookieValue(cookieName);
    var value = getValueFromCongolmerate(name, cookieValue);
    if (value != null)
    {
        return value;
    }

    return defaultValue;
}

function eraseFromConglomerateCookie(cookieName, name)
{
    saveToConglomerateCookie(cookieName, name, "");
}

function getValueFromCongolmerate(name, cookieValue)
{
    var newCookieValue = null;
    // a null cookieValue is just the first time through so create it
    if (cookieValue == null)
    {
        cookieValue = "";
    }
    var eq = name + "-";
    var cookieParts = cookieValue.split('|');
    for (var i = 0; i < cookieParts.length; i++)
    {
        var cp = cookieParts[i];
        while (cp.charAt(0) == ' ')
        {
            cp = cp.substring(1, cp.length);
        }
        // rebuild the value string exluding the named portion passed in
        if (cp.indexOf(name) == 0)
        {
            return cp.substring(eq.length, cp.length);
        }
    }
    return null;
}

//either append or replace the value in the cookie string
function addOrAppendToValue(name, value, cookieValue)
{
    var newCookieValue = "";
    // a null cookieValue is just the first time through so create it
    if (cookieValue == null)
    {
        cookieValue = "";
    }

    var cookieParts = cookieValue.split('|');
    for (var i = 0; i < cookieParts.length; i++)
    {
        var cp = cookieParts[i];

        // ignore any empty tokens
        if (cp != "")
        {
            while (cp.charAt(0) == ' ')
            {
                cp = cp.substring(1, cp.length);
            }
            // rebuild the value string exluding the named portion passed in
            if (cp.indexOf(name) != 0)
            {
                newCookieValue += cp + "|";
            }
        }
    }

    // always append the value passed in if it is not null or empty
    if (value != null && value != '')
    {
        var pair = name + "-" + value;
        if ((newCookieValue.length + pair.length) < 4020)
        {
            newCookieValue += pair;
        }
    }
    return newCookieValue;
}

function getCookieValue(name, defaultString)
{
    var eq = 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(eq) == 0)
        {
            return c.substring(eq.length, c.length);
        }
    }

    return defaultString;
}

function saveCookie(name, value, days)
{
    var ex;
    if (days)
    {
        var d = new Date();
        d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
        ex = "; expires=" + d.toGMTString();
    }
    else
    {
        ex = "";
    }
    document.cookie = name + "=" + value + ex + ";path=" + (!BAMBOO.contextPath.length ? "/" : BAMBOO.contextPath);
}

/*
Reads a cookie. If none exists, then it returns and
*/
function readCookie(name, defaultValue)
{
    var cookieVal = getCookieValue(name);
    if (cookieVal != null)
    {
        return cookieVal;
    }

    // No cookie found, then save a new one as on!
    if (defaultValue)
    {
        saveCookie(name, defaultValue, 365);
        return defaultValue;
    }
    else
    {
        return null;
    }
}

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

function addUniversalOnload(myFunction)
{
    AJS.$(document).ready(myFunction);
}

function attachHandler(object, event, myFunction)
{
    AJS.$("#" + object).bind(event, myFunction);
}

function toggleOn(e, toggleGroup_id)
{
    var onToggle = document.getElementById(toggleGroup_id + "_toggler_on");
    var offToggle = document.getElementById(toggleGroup_id + "_toggler_off");
    var target = document.getElementById(toggleGroup_id + "_target");
    onToggle.style.display = 'block';
    offToggle.style.display = 'none';
    target.style.display = 'block';
    saveToConglomerateCookie(BAMBOO_DASH_DISPLAY_TOGGLES, toggleGroup_id, null);
}

function toggleOff(e, toggleGroup_id)
{
    var onToggle = document.getElementById(toggleGroup_id + "_toggler_on");
    var offToggle = document.getElementById(toggleGroup_id + "_toggler_off");
    var target = document.getElementById(toggleGroup_id + "_target");
    onToggle.style.display = 'none';
    offToggle.style.display = 'block';
    target.style.display = 'none';
    saveToConglomerateCookie(BAMBOO_DASH_DISPLAY_TOGGLES, toggleGroup_id, '0');
}

function restoreTogglesFromCookie(toggleGroup_id)
{
    var elem = document.getElementById(toggleGroup_id + "_target");
    if (elem)
    {
        if (readFromConglomerateCookie(BAMBOO_DASH_DISPLAY_TOGGLES, toggleGroup_id, null) == '0')
        {
            toggleOff(null, toggleGroup_id);
        }
        else
        {
            toggleOn(null, toggleGroup_id);
        }
    }
}

// Forms JS
function toggleContainingCheckbox(e)
{
    if (e && e.target.tagName == "INPUT")
    {
        return true;
    }

    AJS.$(this).find("input:checkbox").each(function(){
        this.checked = !this.checked;
    });

    return true;
}



// ------------------------------------------------------------------------------------------------- Common Ajax Objects

function ajaxSubmitHandler(e, updateDivId)
{
    e.preventDefault();
    e.stopPropagation();

    var updater = getEl(updateDivId).getUpdateManager();
    var form = e.findTarget(null, 'form');

    updater.formUpdate(form);

    //alert('e: ' + e + ' ctx: ' + updater + ' this: ' + link.href);
}


function ajaxClickHandlerForDiv(e, updateDivId)
{

    var updater = getEl(updateDivId).getUpdateManager();
    var link = e.findTarget('internalLink', 'a');

    if (link != null)
    {
        e.preventDefault();
        updater.update(link.href, null, null, true);
    }

}

// This method will leak if used in a reloading panel. Use with care!
function rewriteForms(el, oResponseObject)
{
    var updater = el.getUpdateManager();
    var forms = el.getChildrenByTagName('form');
    for (var i = 0; i < forms.length; i++)
    {
        forms[i].addManagedListener('submit', ajaxSubmitHandler, el.id);
    }
}

function clearHandlers(el)
{

    var forms = el.getChildrenByTagName('form');
    for (var i = 0; i < forms.length; i++)
    {
        forms[i].removeAllListeners();
    }

    var evented = el.getChildrenByClassName('evented');
    for (var i = 0; i < evented.length; i++)
    {
        evented[i].removeAllListeners();
    }

    return true;
}


function toggleFavourite(url)
{
    AJS.$.get(url);
    return false;
}

/*
  Toggles the image's icon between having the suffix of '_on' and '_off'. This also clears the title.
*/
function toggleIcon(e)
{
    AJS.$(this).find("img").each(function(){
        var dom = this;
        if (dom.src)
        {
        if (dom.src.indexOf('_on.') != -1)
        {
            toggleIconOff(dom);
        }
        else if (dom.src.indexOf('_off') != -1)
        {
            toggleIconOn(dom);
        }
        }
    });

    return true;
}

function toggleIconOff(dom)
{
    dom.src = dom.src.replace('_on.', '_off.');
}

function toggleIconOn(dom)
{
    dom.src = dom.src.replace('_off.', '_on.');
}

function checkFormChanged(form)
{
    var domForm;
    if (form.dom)
    {
        domForm = form.dom;
    }
    else
    {
        domForm = form;
    }

    var textFields = domForm.getElementsByTagName("INPUT");
    for (var i = 0; i < textFields.length; i++)
    {
        var textField = textFields[i];
        if (textField.type == "text"){
            if (textField.value != textField.defaultValue) return true;
        } else if (textField.type == "textarea") {
            if (textField.value != textField.defaultValue) return true;
        } else if (textField.type == "checkbox") {
            if (textField.checked != textField.defaultChecked) return true;
        } else if (textField.type == "radio") {
            if (textField.checked != textField.defaultChecked) return true;
        } else if (textField.type == "password") {
            if (textField.value != textField.defaultValue) return true;
        }
    }

   var selectFields = domForm.getElementsByTagName("select");
    for (var y = 0; y < selectFields.length; y++)
    {
       var mySelect = selectFields[y];
        for (var z=0; z < mySelect.options.length; z++)
        {
            if (mySelect.options[z].defaultSelected) {
               if (!mySelect.options[z].selected) {
                   return true;
               } else {
                   break;
               }
            }
        }
    }

    var textAreas = domForm.getElementsByTagName("textarea");
    for (var x = 0; x < textAreas.length; x++)
    {
       var textArea = textAreas[x];
       if (textArea.value != textArea.defaultValue) return true;
    }

    return false;
};

/*
*   For user picker - when you click "Check All' all the select boxes are changed
*/
    var selectedBoxes = [];

    function setCheckboxes()
    {
        var numelements = document.selectorform.elements.length;
        var item0 = document.selectorform.elements[0];
        var item1;

        for (var i=1 ; i < numelements ; i++)
        {
            item1 = document.selectorform.elements[i];
            item1.checked = item0.checked;
            if (!selectedBoxes[item1.name])
                selectedBoxes[item1.name] = [];
            selectedBoxes[item1.name][item1.value] = item1.checked;
        }
    }

/**
 * Checks if the form has changed. If it hasn't then returns to the URL. If it has, submits the form with the returnUrl set to the URL
 * @param elem         DOM element or jQuery selector
 * @param contextPath
 * @param url
 */
function submitFormIfChanged(elem, contextPath, url)
{
    var theForm = elem.form ? elem.form : AJS.$(elem).get(0);

    if (checkFormChanged(theForm))
    {
        theForm.action = theForm.action + (theForm.action.indexOf('?') == -1 ? '?' : '&') + 'returnUrl=' + url;
        theForm.submit();
    }
    else
    {
        location.href = contextPath + url;
    }
}

/*
*  For User Picker - checkboxes are named after users so by compiling a list of all selected checkboxes
*   we have a list of users (comma seperated)
*/
    function getEntityNames()
    {
        var numelements = document.selectorform.elements.length;
        var item;
        var checkedList = "";

        var sep = "";
        for (var i = 0 ; i < numelements ; i++)
        {
            item = document.selectorform.elements[i];
            if (item != null && item.type == "checkbox" && item.name != "all" && item.checked == true)
            {
                var itemValue = item.value;
                itemValue = itemValue.replace(/\\/g, "\\\\").replace(/,/g, "\\,");
                checkedList  = checkedList + sep + itemValue;
                sep = ", ";
            }
        }

        return checkedList;
    }

/*
*   For User Picker - takes comma seperated list of users and places them in specified field.
*/
   function addUsers(commaDelimitedUserNames, fieldID, multiSelect)
    {
        var element = document.getElementById(fieldID);
        var currentUsers = element.value;
        if (!multiSelect) {
            element.value = commaDelimitedUserNames;
        } else if (currentUsers != null && currentUsers != ""){
            element.value = currentUsers + ", " + commaDelimitedUserNames;
        } else {
            element.value = commaDelimitedUserNames;
        }
    }

var STATUS_PREFIX = 'statusSection';
var REASON_PREFIX = 'reasonSummary';
var DURATION_PREFIX = 'durationSummary';
var LAST_BUILT = 'lastBuiltSummary';
var TESTCOUNT_PREFIX = 'testSummary';
var LATEST_BUILD_PREFIX = 'latestBuild';
var PLAN_PROPS = [LATEST_BUILD_PREFIX, REASON_PREFIX, DURATION_PREFIX, TESTCOUNT_PREFIX, LAST_BUILT];

function updatePlan(plan)
{
    try
    {
        var planKey = plan.planKey;

        //the following for loops have len initialised as such for improved performance
        for (var i = 0, len = PLAN_PROPS.length; i < len; i++)
        {
            var propPrefix =  PLAN_PROPS[i];
            var elem = AJS.$("#" + propPrefix + planKey);
            if (LATEST_BUILD_PREFIX == propPrefix)
            {
                // Update the status when first item and clear the existing classes on this element

                elem.closest(".planKeySection").attr('class', 'planKeySection ' + plan.statusClass);
            }
            elem.html(plan[propPrefix]);
        }
        var imgs = AJS.$("#" + STATUS_PREFIX + planKey).find("img");
        for (var i = 0, len = imgs.length; i < len; i++)
        {
            var statusIcon = imgs.get(i);
            var newPath = BAMBOO.contextPath + plan.statusIconPath;
            if (newPath != statusIcon.src)
            {
                statusIcon.src = newPath;
                statusIcon.title = plan.statusText;
            }
        }

        // Update favourites
        var faves = AJS.$('#favouriteIconFor_' + planKey);
        for (var i = 0, len = faves.length; i < len; i++)
        {
            var fave = faves.get(i);
            if (plan.favourite)
            {
                toggleIconOn(fave);
            }
            else
            {
                toggleIconOff(fave);
            }
        }

        if (plan.suspendedFromBuilding) {
            AJS.$('#resumeBuild_' + planKey).show();
            AJS.$('#stopSingleBuild_' + planKey).hide();
            AJS.$('#stopMultipleBuilds_' + planKey).hide();
            AJS.$('#manualBuild_' + planKey).hide();
        } else {
            AJS.$('#resumeBuild_' + planKey).hide();
            if (plan.allowStop) {            
                AJS.$('#manualBuild_' + planKey).hide();
                if (plan.numberOfCurrentlyBuildingPlans > 1) {
                    AJS.$('#stopSingleBuild_' + planKey).hide();
                    AJS.$('#stopMultipleBuilds_' + planKey).show();
                } else {
                    AJS.$('#stopSingleBuild_' + planKey).show();
                    AJS.$('#stopMultipleBuilds_' + planKey).hide();
                }
            } else {
                AJS.$('#stopSingleBuild_' + planKey).hide();
                AJS.$('#stopMultipleBuilds_' + planKey).hide();
                AJS.$('#manualBuild_' + planKey).show();
            }
        }
    }
    catch(ex)
    {
        //alert(ex);
        console.warn(ex);
    }
}

function updatePlans(sinceSystemTime) {
    // Make the call to the server for JSON data
    if (!sinceSystemTime) sinceSystemTime = 0;
    // Define the callbacks for the asyncRequest
    var timeout,
        panelId = 'dashboardUpdatePlans',
        callbacks = {
            dataType: 'json',
            url:BAMBOO.contextPath + "/ajax/viewPlanUpdates.action?sinceSystemTime=" + sinceSystemTime,
            success : function (response) {
                if (!BAMBOO.reloadDashboard) return; // do nudda

                // Process the JSON data returned from the server
                try {
                    if (response.plans) {
                        var plans = response.plans;
                        for (var i = 0, len = plans.length; i < len; i++) {
                            var plan = plans[i];
                            updatePlan(plan);
                        }
                    }
                }
                catch (x) {
                    console.warn("JSON Parse failed! " + x + "\n", response);
                }

                var currentTime = 0;
                //var currentTime = holder.currentTime;
                BAMBOO.panelTimeouts[panelId] = setTimeout(function () { updatePlans(currentTime); }, BAMBOO.reloadDashboardTimeout * 1000);
                hideAjaxErrorMessage();
                AJS.$("body").trigger(BAMBOO_EVENT_ON_DASHBOARD_RELOADED);
            },
            error : function (XMLHttpRequest) {
                showAjaxErrorMessage(XMLHttpRequest);
            },
            timeout : 60000
        };

    if (typeof BAMBOO.panelTimeouts === "undefined") {
        BAMBOO.panelTimeouts = {};
    } else {
        timeout = BAMBOO.panelTimeouts[panelId];
        clearTimeout(timeout);
    }

    AJS.$.ajax(callbacks);
}

function reloadPanel(id, url, reloadEvery, loadScripts, previousText, callback) {
    var timeout;
    if (typeof BAMBOO.panelTimeouts === "undefined") {
        BAMBOO.panelTimeouts = {};
    } else {
        timeout = BAMBOO.panelTimeouts[id];
        clearTimeout(timeout);
    }
    AJS.$.get(processReloadUrl(url), function(data) {
        var reponseText = data;

        if (!document.getElementById(id)) { return false; } // don't bother updating if the target isn't available to update

        if (!previousText || previousText != reponseText) {
            // only update if the previous response is different
            updateDomObject(reponseText, id, loadScripts, callback);
        }
        if (reloadEvery) {
            BAMBOO.panelTimeouts[id] = setTimeout(function () { reloadPanel(id, url, reloadEvery, loadScripts, reponseText, callback); }, reloadEvery * 1000);
        }
    });
}

function ajaxLoadPanel(id, url, loadScripts, callback)
{
    AJS.$.get(processReloadUrl(url),
              { 'bamboo.successReturnMode': 'json', decorator: 'rest', confirm: true },
              function(data)
              {
                  // only update if the previous response is different
                  updateDomObject(data, id, loadScripts, callback);
              }
    );
}

function processReloadUrl(url)
{
    if (BAMBOO.buildLastCurrentStatus)
    {
        var indexOfCurrentStatus = url.indexOf("&lastCurrentStatus");
        if (indexOfCurrentStatus != -1)
        {
            url = url.substring(0, indexOfCurrentStatus);
        }

        return url + "&lastCurrentStatus=" + BAMBOO.buildLastCurrentStatus;

    }
    else
    {
        return url;
    }
}

function updateDomObject(html, targetId, loadScripts, callback)
{
    if(typeof html == 'undefined'){
        html = '';
    }
    if(loadScripts !== true){
        AJS.$("#" + targetId).html(html);
        if (AJS.$.isFunction(callback))
        {
            AJS.$("#" + targetId).each(callback);
        }
        return;
    }
    var id = AJS.$.generateId();
    html += '<span id="' + id + '"></span>';

    AJS.$("#" + id).ready(function(){
        var hd = document.getElementsByTagName("head")[0];
        var re = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/img;
        var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
        var match;
        while(match = re.exec(html)){
            var srcMatch = match[0].match(srcRe);
            if(srcMatch && srcMatch[2]){
                var s = document.createElement("script");
                s.src = srcMatch[2];
                hd.appendChild(s);
            }else if(match[1] && match[1].length > 0){
                eval(match[1]);
            }
        }
        var el = document.getElementById(id);
        if(el){el.parentNode.removeChild(el);}
    });
    var newHtml = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/img, '');
    AJS.$("#" + targetId).html(newHtml);

    if (AJS.$.isFunction(callback))
    {
        AJS.$("#" + targetId).each(callback);
    }
    return;
}


function updateInlineSection(url, sectionName)
{
     AJS.$.get(processReloadUrl(url), function(data)
      {
          updateDomObject(data, sectionName, "true", "null");
      });
}


function addConfirmationToLinks() {
    AJS.$('.requireConfirmation').click(function(e) {
        var $el = AJS.$(this);
        return confirm('Please confirm that you are about to \n' + ($el.attr("title") ? $el.attr("title") : AJS.$.trim($el.text())));
    });
}

function selectFirstFieldOfForm(formId) {
    var $form = AJS.$("#" + formId),
        $firstError = $form.find(":input:visible:enabled.errorField:first").focus();
    if (!$firstError.length) {
        $form.find(":input:visible:enabled:first").focus();
    }
}

function reloadIfNoFormChanged()
{
    var forms = document.forms;
    for (var i = 0; i < forms.length; i++)
    {
        var form = forms[i];
        if (checkFormChanged(form))
        {
            return;
        }
    }
    window.location.reload();
}

/**
 * Build queue related stuff
 */
var buildQueue = function()
{
    AJS.$(document).ready(function() {buildQueue.portletReloadCallback();});

    return {
        /**
         * Shows and hides Build Queue's action panels
         */
        displayActions : function(actionsId)
        {
            var prevActionsId = readFromConglomerateCookie(BAMBOO_DASH_DISPLAY_TOGGLES, "buildQueueActions", actionsId);
            AJS.$("#builders").removeClass(prevActionsId);
            AJS.$("#builders").addClass(actionsId);

            saveToConglomerateCookie(BAMBOO_DASH_DISPLAY_TOGGLES, "buildQueueActions", actionsId);
        },

        restoreDisplayActionsFromCookie : function()
        {
            this.displayActions(readFromConglomerateCookie(BAMBOO_DASH_DISPLAY_TOGGLES, "buildQueueActions", "actions-queueControl"));
        },

        portletReloadCallback : function()
        {
            buildQueue.restoreDisplayActionsFromCookie();
        }
    };
}();


function initCommitsTooltip(targetId, planKey, buildNumber)
{
    AJS.InlineDialog(AJS.$("#" + targetId),
                 targetId,
                 BAMBOO.contextPath + "/build/ajax/viewBuildCommits.action?buildKey=" + planKey + "&buildNumber=" + buildNumber,
                {onHover: true, fadeTime: 50, hideDelay: 0, showDelay: 100, width: 300, offsetX: 0,offsetY: 10});
}

function initCommentTooltip(targetId, planKey, buildNumber)
{
    var link = AJS.$("#" + targetId);
    AJS.InlineDialog(link,
             targetId,
             BAMBOO.contextPath + "/build/ajax/viewBuildComments.action?buildKey=" + planKey + "&buildNumber=" + buildNumber,
            {onHover: true, fadeTime: 50, hideDelay: 0, showDelay: 100, width: 300, offsetX: 0,offsetY: 10});
}

/**
 * This function is not mentioned to be used directly but rather via @dj.simpleDialogForm FTL macro defined in dojo.ftl
 *
 * All the input params are also described in the dojo.ftl
 */
function simpleDialogForm(triggerSelector, getDialogBodyUrl, dialogWidth, dialogHeight, submitLabel, submitMode, submitCallback, cancelCallback, header, eventNamespace)
{
    function clearAllErrors(formJQ)
    {
        formJQ.find('.error,.aui-message').remove();
    }

    function addActionError(formJQ, errors)
    {
        formJQ.find(".field-group:first").before(BAMBOO.buildAUIErrorMessage(errors));
    }

    function applyErrors(formJQ, result)
    {
        if (result.fieldErrors) {
            for (var fieldName in result.fieldErrors) {
                BAMBOO.addFieldErrors(formJQ, fieldName, result.fieldErrors[fieldName]);
            }
        }

        if (result.errors) {
            addActionError(formJQ, result.errors);
        }
    }

    /**
     * This is called where callee requests non-ajax submit.
     * 1st phase is to call validation via AJAX using form's action attribute and then submit form in a classical way.
     *
     * @param formJQ  form to be submitted
     */
    function validateSubmitForm(formJQ)
    {
        clearAllErrors(formJQ);

        function validationCallback(result)
        {
            if (result.status.toUpperCase() == "OK")
            {
                formJQ.submit();
            }
            else
            {
               applyErrors(formJQ, result);
            }
        }

        AJS.$.post(formJQ.attr("action"), formJQ.serialize() + '&bamboo.enableJSONValidation=true', validationCallback, "json");
    }

    /**
     * For Ajax submit there's no separate validation phase.
     * Assumption is made that action will validate itself and will return proper JSON response in case of validation errors.
     *
     * @param formJQ          jQuery wrapper for form
     * @param submitCallback
     */
    function ajaxSubmitForm(formJQ, submitCallback)
    {
        clearAllErrors(formJQ);

        function successCallback(result)
        {
            if (result.status.toUpperCase()  == "OK")
            {
                submitCallback(result);
            }
            else
            {
               applyErrors(formJQ, result);
            }
        }

         function errorCallback(result)
        {
            if (result.status == 500)
            {
                addActionError(formJQ, Array("An internal server error has occurred. Please check the logs for more details."));
            }
            else
            {
                addActionError(formJQ, Array("An unknown error has occurred."));
            }
        }

        AJS.$.ajax({
            type: "POST",
            url: formJQ.attr("action"),
            data: formJQ.serialize(),
            success: successCallback,
            error: errorCallback,
            dataType: "json"
        });
    }

    function showDialog(linkElementJQ) {
        var $loading = AJS.$('<span class="icon icon-loading aui-dialog-content-loading" />'),
            $dialogForm = AJS.$("<div id='simpleDialogForm'/>").html($loading),
            setFocus = function () {
                var $firstError = $dialogForm.find(":input:visible:enabled.errorField:first").focus();
                if (!$firstError.length) {
                    $dialogForm.find(":input:visible:enabled:first").focus();
                }
            },
            onSubmitCallback = function(dialog) {
                var formJQ = AJS.$("#simpleDialogForm form");

                if (submitMode == "ajax") {
                    ajaxSubmitForm(formJQ, function(result) {
                        if (AJS.$.isFunction(submitCallback)) {
                            submitCallback(result);
                        }
                        dialog.remove();
                        $dialogForm.html($loading);
                    });
                } else {
                    validateSubmitForm(formJQ);
                }
            },
            onCancelCallback = function(dialog) {
                if (AJS.$.isFunction(cancelCallback)) {
                    cancelCallback();
                }
                dialog.remove();
                $dialogForm.html($loading);
            },
            $popup = new AJS.BambooDialog({width: dialogWidth, height: dialogHeight, submitMode: submitMode}, onSubmitCallback, onCancelCallback);

        $popup.addHeader(header != null ? header : linkElementJQ.attr('title'))
              .addPanel("I am invisible", $dialogForm)
              .addCancel("Cancel", onCancelCallback);

        AJS.$.get(getDialogBodyUrl, function(data) {
            $dialogForm.html(data);
            $popup.addSubmit(submitLabel, onSubmitCallback);
            $popup.getPage(0).button[1].moveLeft();
            setFocus();
        });
        $popup.show();
    }

    if (triggerSelector) {
        var namespace = "click";
        if (eventNamespace && eventNamespace.length) {
            namespace += "." + eventNamespace;
        }

        AJS.$(triggerSelector).bind(namespace, function(e) {
            showDialog(AJS.$(this));
            //disable the default behaviour (we don't want link to be followed when we display dialog)
            e.preventDefault();
        });
    } else {
        showDialog(AJS.$(this));
    }

}

/**
 * Asynchronous form handler
 * @param options
 *  - target        String - selector targeting the form
 *  - success       Function - handles JSON response from successful form submission
 *  - cancel        Function - handles what to do when the cancel link is clicked
 *  - formReplaced  Function - is fired after the form is replaced
 *  - $delegator    jQuery Object - where the event handler should be bound
 */
BAMBOO.asyncForm = function (options) {
    var $ = AJS.$,
        defaults = {
            target: null,
            success: null,
            cancel: null,
            formReplaced: null,
            error: null,
            $delegator: $(document)
        },
        handleSubmit = function (e) {
            var $form = $(this);

            e.preventDefault();
            $form.ajaxSubmit({
                data: {
                    "bamboo.successReturnMode": "json",
                    decorator: "rest",
                    confirm: true
                },
                dataType: "html",
                beforeSerialize: function ($form, options) {
                    var fileInputs = $form.find('input:file').length > 0,
                        mp = 'multipart/form-data',
                        multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);

                    if (options.iframe !== false && (fileInputs || options.iframe || multipart)) {
                        this.data["bamboo.successReturnMode"] = "json-as-html";
                    }
                },
                beforeSubmit: function (formData, $form) {
                    $form
                        .find(".buttons").prepend('<span class="icon icon-loading"/>')
                        .find('input:submit').attr('disabled', 'disabled').end()
                        .find('.cancel').addClass('disabled').removeAttr('href').click(function (e) { e.stopPropagation(); });
                },
                success: function (data) {
                    var $data, json;

                    if (typeof data == "object") {
                        // Returned data is JSON
                        json = data;
                    } else {
                        // Returned data is string
                        try {
                            // Try to parse string as JSON
                            json = $.parseJSON(data);
                        }
                        catch (e1) {
                            // Must be HTML
                            $data = $(data);
                            try {
                                // Check if the response only contains a textarea, if so it probably just contains JSON
                                if ($data.length == 1 && !$data.children().length && $data.is("textarea")) {
                                    json = $.parseJSON($data[0].value);
                                }
                            }
                            catch (e2) {}
                        }
                    }

                    if (json) {
                        options.success(json);
                    } else if ($data) {
                        // Returned data isn't JSON, isn't JSON in a textarea, assume it's straight HTML
                        if (!$data.is("form")) {
                            // Should have been a form, probably IE stripping the form element, will just replace form contents instead
                            $form.html($data);
                        } else {
                            $form.replaceWith($data);
                        }
                        if ($.isFunction(options.formReplaced)) {
                            options.formReplaced($data);
                        }
                    }
                },
                error: ($.isFunction(options.error) ? options.error : function (jqXHR, textStatus, errorThrown) {
                    var $dummy = $('<div />'), $stackTrace;

                    try {
                        $stackTrace = $(jqXHR.responseText).filter('pre');
                    }
                    catch (e) {}

                    if (!$stackTrace || !$stackTrace.length) {
                        $stackTrace = $('<p/>', { text: errorThrown });
                    }

                    AJS.messages.error($dummy, { title: "An unexpected error has occurred", body: $stackTrace.wrap('<div/>').parent().html(), closeable: false });
                    $form.replaceWith($dummy.children());
                })
            });
        },
        handleCancel = function (e) {
            e.preventDefault();
            options.cancel(e);
        };

    options = $.extend(defaults, options);

    if ($.isFunction(options.success)) { // No point in an async form if there's no success callback to handle a successful post
        options.$delegator.undelegate(options.target, "submit").delegate(options.target, "submit", handleSubmit);
    }

    if ($.isFunction(options.cancel)) {
        options.$delegator.undelegate(options.target + " .cancel", "click").delegate(options.target + " .cancel", "click", handleCancel);
    }
};

/**
 * Handles form input in dialogs
 * @param options
 *  - trigger       String - selector targeting the element that triggers the popup
 *  - dialogWidth   Number - dialog width
 *  - dialogHeight  Number - dialog height
 *  - success       Function - handles JSON response from successful form submission
 *  - cancel        Function - handles what to do when the cancel link is clicked
 *  - header        String - header for the dialog
 */
BAMBOO.simpleDialogForm = function (options) {
    var defaults = {
        trigger: null,
        dialogWidth: null,
        dialogHeight: null,
        success: null,
        cancel: null,
        header: null
    };
    options = AJS.$.extend(defaults, options);
    var $trigger,
        $loading = AJS.$('<span class="icon icon-loading aui-dialog-content-loading" />'),
        $formContainer = AJS.$('<div class="aui-dialog-content"/>').html($loading),
        dialog,
        setFocus = function () {
            var $firstError = $formContainer.find(":input:visible:enabled.errorField:first").focus();
            if (!$firstError.length) {
                $formContainer.find(":input:visible:enabled:first").focus();
            }
        },
        setupDialogContent = function (html) {
            $formContainer.html(html);
            setFocus();
            BAMBOO.asyncForm({
                $delegator: $formContainer,
                target: "form",
                success: function (data) {
                    if (AJS.$.isFunction(options.success)) {
                        options.success(data);
                    }
                    dialog.remove();
                    $formContainer.html($loading);
                },
                cancel: function (e) {
                    e.preventDefault();
                    if (AJS.$.isFunction(options.cancel)) {
                        options.cancel(e);
                    }
                    dialog.remove();
                    $formContainer.html($loading);
                },
                formReplaced: setFocus
            });
        },
        showDialog = function () {
            dialog = new AJS.Dialog({
                width: options.dialogWidth,
                height: options.dialogHeight,
                keypressListener: function (e) {
                    if (e.which == jQuery.ui.keyCode.ESCAPE) {
                        dialog.remove();
                        $formContainer.html($loading);
                    }
                }
            });
            var header = options.header ? options.header : $trigger.attr("title");
            if (header) {
                dialog.addHeader(header);
            }
            dialog.addPanel("", $formContainer);

            // $trigger.attr("data-dialog-href") won't be needed once we're on jQuery 1.4.3
            AJS.$.ajax({
                url: $trigger.attr("href") || $trigger.data("dialog-href") ||  $trigger.attr("data-dialog-href"),
                data: { 'bamboo.successReturnMode': 'json', decorator: 'rest', confirm: true },
                success: setupDialogContent,
                cache: false
            });

            dialog.show();
        };

    if (options.trigger) {
        var namespace = "click";
        if (options.eventNamespace && options.eventNamespace.length) {
            namespace += "." + options.eventNamespace;
        }

        AJS.$(document).delegate(options.trigger, namespace, function (e) {
            $trigger = AJS.$(this);
            e.preventDefault();
            showDialog();
        });
    } else {
        showDialog();
    }
};

/**
 * Displays confirmation dialog that is consistent in style with simpleDialogForm but with content
 * generated without additional server request.
 */
function simpleConfirmationDialog(dialogWidth, dialogHeight, content, header, submitLabel, cancelLabel, onSubmit, onCancel) {
    var confirmDialog = new AJS.BambooDialog({width: dialogWidth, height: dialogHeight, submitMode: submitMode}),
            doSubmit = function(dialog)
            {
                if (AJS.$.isFunction(onSubmit)) {
                    onSubmit();
                }
                dialog.remove();
            },
            doCancel = function(dialog)
            {
                if (AJS.$.isFunction(onCancel))
                {
                    onCancel();
                }
                dialog.remove();
            };
    confirmDialog.addHeader(header);

    // @TODO a workaround to some bug... We should revisit this post AUI 2.0 upgrade
    confirmDialog.addPanel("nothing", "nothing");
    confirmDialog.addButton(submitLabel, doSubmit);
    confirmDialog.addCancel(cancelLabel, doCancel);

    confirmDialog.getCurrentPanel().html("<div id='simpleDialogForm'>" + content + "</div>");
    confirmDialog.show();
}

/**
 * General checkbox tree utilities.
 */
var checkboxTree = function() {
    return {
        DONT_ENABLE_PARENT_ON_ALL_CHILDREN_ENABLED : 1 << 0,
        DISABLE_CHILDREN_ON_PARENT_CHECKED : 1 << 1,
        /**
         * Cascade state of a parent checkbox to collection of children checkboxes.
         * @param jqParent    parent checkbox (jQuery object)
         * @param jqChildren  children checkboxes (jQuery object)
         */
        cascadeToChildren : function(jqParent, jqChildren, options) {
            if (jqParent.is(":checked")) {
                jqChildren.attr("checked", "checked");
            } else {
                jqChildren.removeAttr("checked");
            }
            if (options & this.DISABLE_CHILDREN_ON_PARENT_CHECKED) {
                if (jqParent.is(":checked")) {
                    jqChildren.attr("disabled", "disabled");
                } else {
                    jqChildren.removeAttr("disabled");
                }
            }
        },

        /**
         * Propagate state of children checkboxes to parent checkbox.
         * @param jqParent    parent checkbox (jQuery object)
         * @param jqChildren  children checkboxes (jQuery object)
         * @param options     options that modify default behavior
         */
        propagateToParent : function(jqParent, jqChildren, options) {
            if (jqChildren.is(":not(:checked)")) {
                jqParent.removeAttr("checked");
            } else {
                if (!(options & this.DONT_ENABLE_PARENT_ON_ALL_CHILDREN_ENABLED))
                {
                    jqParent.attr("checked", "checked");
                }
            }
        }
    };
}();

function enableShowSnapshotsForMaven2Dependencies(showAllSelector, showOnlySnapshotsSelector, tableSelector, hasSnapshots)
{
    AJS.$(document).ready(function() {
        var showAllLink = AJS.$(showAllSelector);
        var showOnlySnapshotsLink = AJS.$(showOnlySnapshotsSelector);
        var table = AJS.$(tableSelector);

        showAllLink.click(function() {
            showOnlySnapshotsLink.show();
            showAllLink.hide();
            AJS.$('.gav-tbody-releases').show();
        });

        showOnlySnapshotsLink.click(function() {
            showAllLink.show();
            showOnlySnapshotsLink.hide();
            AJS.$('.gav-tbody-releases').hide();
        });

        if (hasSnapshots) {
            showOnlySnapshotsLink.click();
        } else {
            showAllLink.hide();
            showOnlySnapshotsLink.hide();
        }
    });
}

function removeError(errorNumber)
{
    var removeErrorForm = window.opener.AJS.$('#removeErrorHiddenForm_' + errorNumber);
    removeErrorForm.submit();
    window.close();
}

function addAliasSubmitCallback(result) {
    AJS.$("select.selectAlias").append(AJS.$("<option />", { text: result.aliasName, selected: "selected", val: result.aliasId }))
                               .val(result.aliasId);
}

/*per plan action tooltip, originally for requirements tooltip on plan config page
 * @param args - some are compulsory for hitting the action to display content, the rest are for styling
 * targetId: (compulsory) the id of the content that the tooltip should appear over
 * actionName: (compulsory) the action to hit
 * planKey: (compulsory) the key of the plan
 * fadeTime: (optional)
 * hideDelay: (optional)
 * showDelay: (optional)
 * width: (optional)
 * offsetX: (optional)
 * offsetY: (optional)
 */
function attachActionToTooltip(args)
{
    AJS.InlineDialog(AJS.$("#" + args.targetId),
                 args.targetId,
                 BAMBOO.contextPath + "/ajax/" + args.actionName + ".action?planKey=" + args.planKey,
                {onHover: true,
                 fadeTime: (args.fadeTime || 200),
                 hideDelay: (args.hideDelay || 150),
                 showDelay: (args.showDelay || 150),
                 width: (args.width || 300),
                 offsetX: (args.offsetX || 0),
                 offSetY: (args.offsetY || 10)
                });
}

/**
 * Checks if any forms on the page need a submit on change hook.
 */
AJS.$(function($){
    $(".submitOnChange").change(function(){ $(this).closest("form").submit(); });
});

/**
 * Current Activity screen
 */
var CurrentActivity = {
    // Default options
    options: {
        contextPath: null,
        getBuildsUrl: null,
        viewAgentUrl: null,
        reorderBuildUrl: null,
        stopBuildUrl: null,
        manageElasticInstancesUrl: null,
        emptyQueueText: null,
        emptyBuildingText: null,
        cancellingBuildText: null,
        cancelBuildText: null,
        queueOutOfDateText: null,
        canBuildElastically: null,
        canBuildElasticallyAdmin: null,
        fetchingBuildData: null,
        hasAdminPermission: false,
        caParent: null,
        buildingParent: null,
        queueParent: null,
        activityStream: null,
        agentSummary: null
    },
    updateTimeout: null, // ID of timeout which determines when the data will be next fetched from the server
    building: null, // jQuery object referring to the list holding the currently building builds (set on init)
    queue: null, // jQuery object referring to the list holding the queued builds (set on init)
    noBuilding: null, // jQuery object referring to the message shown when there are no currently building builds (set on init)
    noQueued: null, // jQuery object referring to the message shown when there are no queued builds (set on init)
    loadingBuilding: null, // jQuery object referring to the loading indicator shown while currently building data is being fetched the first time (set on init)
    loadingQueued: null, // jQuery object referring to the loading indicator shown while queue data is being fetched the first time (set on init)
    queueOutOfDate: null, // jQuery object referring to the message shown when the queue order has been updated remotely and is not reflected locally (set on init)
    updateTimestamp: null, // Timestamp (represented as milliseconds since the Unix epoch) that the builds were last updated
    isBeingSorted: false, // Is the queue currently being sorted?
    disabledStopHTML: '', // HTML to replace the stop button with if it's disabled (set on init)
    /**
     * Generates a nice, readable string of Agents that the Plan can build on
     * @param executableAgents - Array of Agent objects
     * @returns {String} A readable sentence containing the list of agents
     */
    generateBuildableAgentsText: function (executableAgents) {
        var agentNames = [];
        
        for (var i = 0; i < executableAgents.length; i++) {
            agentNames.push(executableAgents[i].name);
        }
        return "Can build on " + agentNames.join(", ");
    },
    /**
     * Generates the list item
     * @param build - Build object
     * @returns {Object} containing the list item or false if no list item is built (would require build.status to be something other than BUILDING or QUEUED)
     */
    generateListItem: function (build) {
        var ca = CurrentActivity,
            o = ca.options,
            el = "";

        if (build.hasReadPermission) {
            var buildLink = '<a href="' + o.contextPath + '/browse/' + build.planResultKey + '/">' + build.projectName + ' &rsaquo; ' + build.chainName + ' &rsaquo; #' + build.buildNumber + '</a> &rsaquo; <a href="' + o.contextPath + '/browse/' + build.buildResultKey + '/">' + build.jobName + '</a>';

            if (build.status == "BUILDING") {
                var msgHtml = build.messageType == "PROGRESS" ? '<div class="progress-bar" style="width:' + build.percentageComplete + '%;"></div><div class="progress-text">' + build.messageText + '</div>' : build.messageText;
                var buildAgentInfo = build.agent ? ' building on <a href="' + o.viewAgentUrl + '?agentId=' + build.agent.id + '" class="' + build.agent.type.toLowerCase() + '">' + build.agent.name + '</a>' : '';
                el = '<li id="b' + build.buildResultKey + '" class="buildRow"><div class="buildInfo">' + buildLink + buildAgentInfo + '</div><div class="message ' + build.messageType.toLowerCase() + '">' + msgHtml + '</div>'; //Current Activity
                if (build.hasBuildPermission) {
                    var stopButtonHTML = (build.isBeingStopped) ? ca.disabledStopHTML : '<a href="' + o.stopBuildUrl + '?planResultKey=' + build.buildResultKey + '" title="' + o.cancelBuildText + '" class="build-stop">' + o.cancelBuildText + '</a>';
                    el += '<ul class="buildActions"><li>' + stopButtonHTML + '</li></ul>';
                }
                el += '</li>';
            } else if (build.status == "QUEUED") {
                var title = build.executableAgents ? ' title="' + ca.generateBuildableAgentsText(build.executableAgents) + '"' : '',
                    handle = o.hasAdminPermission ? '<span class="handle"></span>' : '';
                el = '<li id="b' + build.buildResultKey + '" class="buildRow"><div class="buildInfo">' + handle + buildLink + '</div><div class="message ' + build.messageType.toLowerCase() + '"' + title + '>' + build.messageText + '</div>';  //Current Activity
                if (build.executableElasticImages || build.hasBuildPermission) {
                    el += '<ul class="buildActions">';
                    if (build.executableElasticImages) {
                        if (o.hasAdminPermission) {
                            el += '<li><a href="' + o.manageElasticInstancesUrl + '" title="' + o.canBuildElasticallyAdmin + '" class="build-elastic">' + o.canBuildElasticallyAdmin + '</a></li>';
                        } else {
                            el += '<li><span title="' + o.canBuildElastically + '" class="build-elastic-disabled">' + o.canBuildElastically + '</span></li>';
                        }
                    }
                    if (build.hasBuildPermission) {
                        el += '<li><a href="' + o.stopBuildUrl + '?planResultKey=' + build.buildResultKey + '" title="' + o.cancelBuildText + '" class="build-stop">' + o.cancelBuildText + '</a></li>'
                    }
                    el += '</ul>';
                }
                el += '</li>';
            }
        } else {
            el = '<li id="b' + build.buildResultKey + '" class="buildRow"><div class="buildInfo">' + build.planName + '</div><span class="message ' + build.messageType.toLowerCase() + '">' + build.messageText + '</span></li>';
        }
        return (el.length == 0 ? false : AJS.$(el));
    },
    /**
     * Checks if an activity stream is available, and if it is (and there are no activity stream comment forms open -
     * which would indicate the user is probably in the middle of adding a comment) then trigger a refresh.
     */
    updateActivityStream: function () {
        var o = CurrentActivity.options;

        if (o.activityStream && AJS.$(".activity-item-comment-form:visible", document.getElementById("feedContainer-" + o.activityStream.feedId)).length == 0) {
            o.activityStream.populateFeed();
        }
    },
    /**
     * Checks the time the build was last updated with the time the last data was retrieved.
     * Removes the build if it's older than the last update.
     * @param li - List item containing the build
     * @returns {Boolean} indicating whether the build was removed or not
     */
    checkLastUpdated: function (li) {
        var b = AJS.$(li);

        if (b.data("lastUpdated") < CurrentActivity.updateTimestamp) {
            b.remove();
            return true;
        } else {
            return false;
        }
    },
    /**
     * Checks if build lists are empty and if so, hide the list and display a message, otherwise show the list and hide the message.
     */
    checkListsHaveBuilds: function () {
        var ca = CurrentActivity;

        if (ca.building.children().length == 0) {
            ca.building.hide();
            ca.noBuilding.show();
        } else {
            ca.building.show();
            ca.noBuilding.hide();
        }
        if (ca.queue.children().length == 0) {
            ca.queue.hide();
            ca.noQueued.show();
            // If queue is empty but "queue is out-of-date" message is being displayed then hide the message and re-enable sorting
            if (ca.queueOutOfDate.is(":visible")) {
                ca.queue.sortable("enable");
                ca.queueOutOfDate.hide();
            }
        } else {
            ca.queue.show();
            ca.noQueued.hide();
        }
    },
    /**
     * Checks if current activity container exists and is in DOM
     * @returns {Boolean} indicating whether the container exists in the DOM
     */
    isCurrentActivityPresent: function () {
        var o = CurrentActivity.options;
        
        return (!o.caParent || !o.caParent.length || !o.caParent.parent().length);
    },
    /**
     * Retrieves the build JSON from the server and adds/removes/changes builds in the currently building and queue as needed.
     * @param callback - Allows the ability to execute a callback once the update has completed
     */
    updateBuilds: function (callback) {
        var ca = CurrentActivity,
            o = ca.options;

        ca.updateTimestamp = (new Date()).getTime();
        // Get builds from API
        AJS.$.ajax({
            url: o.getBuildsUrl,
            dataType: 'json',
            cache: false,
            success: function (json) {
                if (ca.isCurrentActivityPresent()) {
                    return false;
                }

                // If a callback was supplied to updateBuilds, fire it
                if (callback && AJS.$.isFunction(callback)) {
                    callback.call();
                }
                // Update agent summary text if available
                if (o.agentSummary) {
                    o.agentSummary.text(json.agentSummary);
                }
                // Go through each build returned and either update or insert as required
                AJS.$.each(json.builds, function () {
                    var build = AJS.$("#b" + this.buildResultKey),
                        msg, progress, messageType, stopButton;

                    if (build.length > 0) { // Check if the build already exists in building/queue
                        if (this.status == "BUILDING") {
                            // Check if build has started, if so move to building
                            if (build.closest(".buildContainer")[0] == o.queueParent[0]) {
                                build.remove();
                                build = ca.generateListItem(this).appendTo(ca.building);
                                progress = AJS.$(".progress", build[0]);
                                if (progress.length > 0) {
                                    progress.progressBar();
                                }
                            } else {
                                msg = AJS.$(".message", build[0]);
                                messageType = this.messageType.toLowerCase();

                                if (messageType == "progress" && msg.hasClass(messageType)) {
                                    msg.progressBar("option", { value: this.percentageComplete, text: this.messageText });
                                } else if (messageType == "progress") {
                                    msg.attr("class", "message").progressBar({ value: this.percentageComplete, text: this.messageText });
                                } else {
                                    if (msg.hasClass("progress")) {
                                        msg.progressBar("destroy");
                                    }
                                    if (!msg.hasClass(messageType)) {
                                        msg.attr("class", "message " + messageType).text(this.messageText);
                                    } else {
                                        msg.text(this.messageText);
                                    }
                                }
                                if (this.hasBuildPermission && this.isBeingStopped) {
                                    stopButton = AJS.$(".build-stop", build[0]);
                                    if (stopButton.length > 0) {
                                        stopButton.replaceWith(ca.disabledStopHTML);
                                    }
                                }
                            }
                        } else if (this.status == "QUEUED") {
                            msg = AJS.$(".message", build[0]).text(this.messageText).attr("title", (this.executableAgents ? ca.generateBuildableAgentsText(this.executableAgents) : null));
                            if (!msg.hasClass(this.messageType.toLowerCase())) {
                                msg.attr("class", "message " + this.messageType.toLowerCase());
                            }
                        }
                    } else {
                        if (this.status == "BUILDING") {
                            build = ca.generateListItem(this).appendTo(ca.building);
                            progress = AJS.$(".progress", build[0]);
                            if (progress.length > 0) {
                                progress.progressBar();
                            }
                        } else if (this.status == "QUEUED") {
                            build = ca.generateListItem(this).appendTo(ca.queue);
                        }
                    }
                    // Check if queue order is correct and reorder if required
                    if (!ca.isBeingSorted && typeof(this.queueIndex) != "undefined" && this.queueIndex != build.prevAll().length) {
                        build.insertBefore(ca.queue.children("li:eq(" + this.queueIndex + ")"));
                    }
                    build.data("lastUpdated", ca.updateTimestamp);
                });

                // Clean up builds not returned in JSON
                var numRemoved = 0;
                ca.building.children().each(function () {
                    if (ca.checkLastUpdated(this)) { numRemoved++; }
                });
                ca.queue.children().each(function () {
                    if (ca.checkLastUpdated(this)) { numRemoved++; }
                });
                if (numRemoved > 0) { ca.updateActivityStream(); }

                if (o.hasAdminPermission) {
                    // Refresh sorting
                    ca.queue.sortable("refresh");
                }

                ca.checkListsHaveBuilds();

                // Clear timeout to ensure we don't have multiple running
                clearTimeout(ca.updateTimeout);

                // Update again in 5 seconds
                ca.updateTimeout = setTimeout(ca.updateBuilds, 5000);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (ca.isCurrentActivityPresent()) {
                    return false;
                }

                // Clear timeout to ensure we don't have multiple running
                clearTimeout(ca.updateTimeout);

                // Error occurred when doing the update, try again in 30 sec, making sure the callback is passed so that it will actually get executed when it finally succeeds
                ca.updateTimeout = setTimeout(function () { ca.updateBuilds(callback); }, 30000);
            }
        });
    },
    /**
     * Strips a build list item's id down to a build result key
     * @param buildListItemID - String containing the build list item's id - eg. bBAM-FUNC-1234
     * @returns {String} containing the build result key - eg. BAM-FUNC-1234
     */
    buildListItemIDToBuildResultKey: function (buildListItemID) {
        return buildListItemID.substr(1);
    },
    /**
     * Initialisation for the Current Activity
     * @param options - Object containing the options to overwrite our defaults
     */
    init: function (options) {
        var ca = CurrentActivity,
            o = ca.options;

        AJS.$.extend(o, options);

        ca.building = AJS.$("<ul/>").appendTo(o.buildingParent).hide();
        ca.queue = AJS.$("<ul/>").appendTo(o.queueParent).hide();
        ca.noBuilding = AJS.$("<p>" + o.emptyBuildingText + "</p>").appendTo(o.buildingParent).hide();
        ca.noQueued = AJS.$("<p>" + o.emptyQueueText + "</p>").appendTo(o.queueParent).hide();
        ca.queueOutOfDate = AJS.$("<p>" + o.queueOutOfDateText + "</p>").insertBefore(ca.queue).hide();
        ca.loadingBuilding = AJS.$('<p class="loading">' + o.fetchingBuildData + '</p>').appendTo(o.buildingParent);
        ca.loadingQueued = AJS.$('<p class="loading">' + o.fetchingBuildData + '</p>').appendTo(o.queueParent);
        ca.disabledStopHTML = '<span class="build-stop-disabled" title="' + o.cancellingBuildText + '">' + o.cancellingBuildText + '</span>';

        clearTimeout(ca.updateTimeout);
        ca.updateTimestamp = null;

        o.caParent.delegate(".buildActions a.build-stop", "click", function (e) {
            var el = AJS.$(this),
                li = el.closest(".buildRow");
            AJS.$.post(this.href, function () {
                // Only remove from the queue immediately - currently building builds may take a while to stop and clean up - let the next updateBuilds() that runs clean it up
                if (li.closest(".buildContainer")[0] == o.queueParent[0]) {
                    li.remove();
                }
                ca.checkListsHaveBuilds();
            });
            el.replaceWith(ca.disabledStopHTML);
            e.preventDefault();
        });
        AJS.$("a", ca.queueOutOfDate[0]).click(function (e) {
            clearTimeout(ca.updateTimeout);
            ca.queue.empty().sortable("enable");
            AJS.$(this).parent().hide();
            ca.updateBuilds();
            ca.updateActivityStream();
            e.preventDefault();
        });
        if (o.hasAdminPermission) {
            ca.queue.sortable({
                handle: "span.handle",
                update: function (event, ui) {
                    var self = AJS.$(ui.item),
                        buildResultKey = ca.buildListItemIDToBuildResultKey(self.attr("id")),
                        checkListItemExists = function ($el) {
                            if ($el.length > 0) {
                                return ca.buildListItemIDToBuildResultKey($el.attr("id"));
                            } else {
                                return "";
                            }
                        },
                        prevBuildResultKey = checkListItemExists(self.prev()),
                        nextBuildResultKey = checkListItemExists(self.next());
                    AJS.$.post(o.reorderBuildUrl,
                        { buildResultKey: buildResultKey, prevBuildResultKey: prevBuildResultKey, nextBuildResultKey: nextBuildResultKey },
                        function (json) {
                            // If an error is returned show the queue out of date message. The next update will restore the correct queue order.
                            if (json.status == "ERROR") {
                                ca.queueOutOfDate.show();
                                ca.queue.sortable("disable");
                            }
                        }, "json");
                },
                start: function (event, ui) {
                    ca.isBeingSorted = true;
                },
                stop: function (event, ui) {
                    ca.isBeingSorted = false;
                }
            });
        }
        ca.updateBuilds(function () {
            ca.loadingBuilding.hide();
            ca.loadingQueued.hide();
        });
    }
};

/**
 * Agent Manager dropdown
 */
var AgentManager = {
    // Default options
    options: {
        contextPath: null,
        getAgentsUrl: null,
        enableAgentUrl: null,
        disableAgentUrl: null,
        enableAllAgentsUrl: null,
        disableAllAgentsUrl: null,
        viewAgentUrl: null,
        enableAgentText: null,
        disableAgentText: null,
        enableAllAgentsText: null,
        disableAllAgentsText: null,
        onlineAgentsText: null,
        defaultRemoteAgentSummaryText: null,
        onlineOnly: false,
        includeRemoteAgentSummary: false,
        triggerId: null
    },
    $agentList: null, // jQuery object referring to the list holding the agents
    $dialog: null, // jQuery object referring to the AUI Inline Dialog
    $remoteAgentSummary: null, // jQuery object referring to the paragraph containing the remote agent summary text
    /**
     * Generates the list item
     * @param agent - Agent object
     * @returns {Object} containing the list item or false if no list item is built
     */
    generateListItem: function (agent) {
        var am = AgentManager,
            o = am.options,
            el = "";
        el = '<li class="' + agent.type.toLowerCase() + ' ' + (agent.enabled ? "enabled" : "disabled") + '"><h3><a href="' + o.viewAgentUrl + '?agentId=' + agent.id + '">' + agent.name + '</a></h3><span>' + (agent.agentStatus == "Building" ? agent.agentStatus + ' - <a href="' + o.contextPath + agent.buildLogUrl + '">' + agent.buildResultKey + '</a>' : agent.agentStatus) + '</span> <button class="' + (agent.enabled ? "disable" : "enable") + '">' + (agent.enabled ? o.disableAgentText : o.enableAgentText) + '</button></li>';
        return (el.length == 0 ? false : AJS.$(el).data("agentId", agent.id));
    },
    /**
     * Updates the list of agents
     * @param $contents - jQuery element of the Inline Dialog's contents
     * @param $trigger - jQuery element that is triggering the popup
     * @param doShowPopup - function to display the popup
     */
    updateAgents: function ($contents, $trigger, doShowPopup) {
        var am = AgentManager,
            o = am.options;
        AJS.$.ajax({
            url: o.getAgentsUrl,
            data: { onlineOnly: o.onlineOnly, includeRemoteAgentSummary: o.includeRemoteAgentSummary },
            dataType: 'json',
            cache: false,
            success: function (json) {
                if (o.includeRemoteAgentSummary && json.remoteAgentSummary) {
                    am.$remoteAgentSummary.html(json.remoteAgentSummary);
                } else if (o.includeRemoteAgentSummary) {
                    am.$remoteAgentSummary.html(o.defaultRemoteAgentSummaryText);
                }
                am.$agentList.empty();
                AJS.$.each(json.agents, function () {
                    am.$agentList.append(am.generateListItem(this));
                });
                if (doShowPopup) {
                    doShowPopup();
                }
            }
        });
    },
    /**
     * Initialisation for the Agent Manager
     * @param options - Object containing the options to overwrite our defaults
     */
    init: function (options) {
        var am = AgentManager,
            o = am.options;

        // Don't init if already created
        if (am.$dialog) { return false; }

        AJS.$.extend(o, options);

        am.$dialog = AJS.InlineDialog("#" + o.triggerId, o.triggerId, am.updateAgents, {
            onHover: true,
            width: 400,
            offsetX: 0,
            offsetY: 3,
            cacheContent: false,
            useLiveEvents: true
        });
        var $contents = am.$dialog.find(".contents").addClass("agentManager");
        am.$agentList = AJS.$('<ul />').appendTo($contents).before('<h2>' + o.onlineAgentsText + '</h2>');
        if (o.includeRemoteAgentSummary) {
            am.$remoteAgentSummary = AJS.$('<p>' + o.defaultRemoteAgentSummaryText + '</p>').insertBefore(am.$agentList);
        }
        var $buttons = AJS.$('<div class="buttons"></div>').appendTo($contents);
        AJS.$('<button>' + o.enableAllAgentsText + '</button>').appendTo($buttons).click(function () {
            var el = AJS.$(this);
            el.attr("disabled", "disabled");
            AJS.$.post(o.enableAllAgentsUrl, function () {
                el.removeAttr("disabled");
                am.updateAgents();
            });
        });
        AJS.$('<button>' + o.disableAllAgentsText + '</button>').appendTo($buttons).click(function () {
            var el = AJS.$(this);
            el.attr("disabled", "disabled");
            AJS.$.post(o.disableAllAgentsUrl, function () {
                el.removeAttr("disabled");
                am.updateAgents();
            });
        });
        // FF not firing buttons on click for some reason, mouseup is okay though?!!
        var dialogId = am.$dialog.attr("id");
        AJS.$("#" + dialogId + " button.enable").live("mouseup", function () {
            var el = AJS.$(this),
                li = el.closest("li");
            var agentId = li.data("agentId");
            el.attr("disabled", "disabled");
            AJS.$.post(o.enableAgentUrl, { agentId: agentId }, function () {
                el.text(o.disableAgentText).attr("class", "disable").removeAttr("disabled").parent().removeClass("disabled");
            });
        });
        AJS.$("#" + dialogId + " button.disable").live("mouseup", function () {
            var el = AJS.$(this),
                li = el.closest("li");
            var agentId = li.data("agentId");
            el.attr("disabled", "disabled");
            AJS.$.post(o.disableAgentUrl, { agentId: agentId }, function () {
                el.text(o.enableAgentText).attr("class", "enable").removeAttr("disabled").parent().addClass("disabled");
            });
        });
    }
};

var SelectionActions = function() {
    return {
        init: function (formId) {
            registerSelectionActions();

            function registerSelectionActions() {
                AJS.$("span[selector='"+formId+"_all']").click( function() {
                    clearSelectionStatus();

                    getSelectAllWarning().show();
                    getAllPagesSelectedInfo().hide();

                    getAllCheckBoxes("").attr("checked", "checked");
                });
                AJS.$("span[selector='"+formId+"_none']").click( function() {
                    clearSelectionStatus();
                });
                AJS.$("span[selector='"+formId+"_disabled']").click( function() {
                    clearSelectionStatus();
                    getAllCheckBoxes("[class~='selectorAgentEnabled_false']").attr("checked", "checked");
                });
                AJS.$("span[selector='"+formId+"_idle']").click( function() {
                    clearSelectionStatus();
                    getAllCheckBoxes("[class~='selectorAgentStatus_Idle']").attr("checked", "checked");
                });
                AJS.$("span[selector='"+formId+"_allPages']").click( function() {
                    setCompleteContentSelected(true);
                    getSelectAllWarning().hide();
                    getAllPagesSelectedInfo().show();
                });
            }

            function getAllCheckBoxes(selector) {
                return AJS.$("input:checkbox.selectorAgentType_"+formId+"[name='selectedAgents']"+selector);
            }

            function setCompleteContentSelected(newValue) {
                AJS.$('.'+formId+'_completeContentSelected').val(newValue);
            }

            function clearSelectionStatus() {
                AJS.$('.'+formId+'_paginatedWarning').hide();
                getAllCheckBoxes("").removeAttr("checked");
                setCompleteContentSelected(false);
            }

            function getSelectAllWarning() {
                return AJS.$('.'+formId+'_paginatedSelectAllWarning');
            }

            function getAllPagesSelectedInfo() {
                return AJS.$('.'+formId+'_paginatedAllPagesSelected');
            }
        }
    };
}();

var BulkSelectionActions = function() {
    return {
        init: function (formId) {
            registerSelectionActions();

            function registerSelectionActions() {
                AJS.$("span[selector='bulk_selector_all']").click( function() {
                    clearSelectionStatus();
                    getAllCheckBoxes("").attr("checked", "checked");
                });
                AJS.$("span[selector='bulk_selector_none']").click( function() {
                    clearSelectionStatus();
                });
                AJS.$("span[selector='bulk_selector_plans']").click( function() {
                    clearSelectionStatus();
                    getAllCheckBoxes("Plan").attr("checked", "checked");
                });
                AJS.$("span[selector='bulk_selector_jobs']").click( function() {
                    clearSelectionStatus();
                    getAllCheckBoxes("Job").attr("checked", "checked");
                });
            }

            function getAllCheckBoxes(selector) {
                return AJS.$("input:checkbox.bulk"+selector);
            }

            function setCompleteContentSelected(newValue) {
                AJS.$('.'+formId+'_completeContentSelected').val(newValue);
            }

            function clearSelectionStatus() {
                getAllCheckBoxes("").removeAttr("checked");
                setCompleteContentSelected(false);
            }
        }
    };
}();

var BulkSubtreeSelectionActions = function() {
    return {
        init: function (formId, enableProjectCheckbox) {
            registerSelectionActions(enableProjectCheckbox);

            function registerSelectionActions(enableProjectCheckbox) {
                AJS.$("span[selector='bulk_selector_sub_"+formId+"']").click( function() {
                    clearSelectionStatus();
                    getAllCheckBoxes(formId).attr("checked", "checked");
                });
                AJS.$("span[selector='bulk_selector_sub_none_"+formId+"']").click( function() {
                    clearSelectionStatus();
                });
                AJS.$("span[selector='bulk_selector_sub_plans_"+formId+"']").click( function() {
                    clearSelectionStatus();
                    getAllCheckBoxes("Plan" + formId).attr("checked", "checked");
                });
                AJS.$("span[selector='bulk_selector_sub_jobs_"+formId+"']").click( function() {
                    clearSelectionStatus();
                    getAllCheckBoxes("Job" + formId).attr("checked", "checked");
                });

                if (enableProjectCheckbox) {
                    AJS.$("#checkbox_"+formId).change( function() {
                        var val = AJS.$(this).is(":checked");
                        clearSelectionStatus();
                        if (val) {
                            getAllCheckBoxes(formId).attr("checked", "checked");
                        }
                    });
                }
            }

            function getAllCheckBoxes(selector) {
                return AJS.$("input:checkbox.bulk"+selector);
            }

            function clearSelectionStatus() {
                getAllCheckBoxes(formId).removeAttr("checked");
            }
        }
    };
}();

var ConfigurableSelectionActions = function() {
    return {
        init: function (formId) {
            var formIdSelector = formId.replace(/([\.:])/g, "\\$1");
            registerSelectionActions();

            function registerSelectionActions() {
                AJS.$("span[selector='"+formId+"_all']").click( function() {
                    getAllCheckBoxes("").attr("checked", "checked");
                });
                AJS.$("span[selector='"+formId+"_none']").click( function() {
                    clearSelectionStatus();
                });

                AJS.$("span[selector^='"+formId+"_'][selector!='"+formId+"_none'][selector!='"+formId+"_all']").each(function () {
                    var span = AJS.$(this),
                        selector = span.attr("selector").substring(formId.length + 1);
                    span.click( function() {
                        clearSelectionStatus();
                        getAllCheckBoxes("[class~='selector_"+selector+"_true']").attr("checked", "checked");
                    });
                });
            }

            function getAllCheckBoxes(selector) {
                return AJS.$("input:checkbox.selectorScope_"+formIdSelector+selector);
            }

            function clearSelectionStatus() {
                getAllCheckBoxes("").removeAttr("checked");
            }
        }
    };
}();

/**
 * Live Activity for Plans
 */
var LiveActivity = function ($) {
    var opts = {
        planKey: null,
        container: null,
        getBuildsUrl: null,
        getBuildsUrl: null,
        getChangesUrl: null,
        queueEmptyText: null,
        cancellingBuildText: null,
        noAdditionalInfoText: null,
        defaultIssueIconUrl: null,
        defaultIssueType: null,
        slideSpeed: 600,
        templates: {
            buildListItemTemplate: null,
            buildingOnTemplate: null,
            buildMessageTemplate: null,
            jiraIssueTemplate: null,
            codeChangeTemplate: null,
            codeChangeChangesetLinkTemplate: null,
            codeChangeChangesetDisplayTemplate: null,
            currentStageTemplate: null,
            disabledStopButton: AJS.template('<span class="build-stop-disabled" title="{title}">{text}</span>'),
            toggleDetailsButton: AJS.template('<span class="toggle-details"></span>')
        }
    },
    $buildList, // jQuery object referring to the list holding the builds
    $noBuilds, // jQuery object referring to the message that shows when there are no builds
    disabledStopHTML, // HTML fragment that replaces the stop button when a user clicks it (so it can't be clicked multiple times)
    toggleDetailsHTML, // HTML fragment inserted to enable the user to toggle the display of additional information
    /**
     * Checks if build list is empty and if so, hide the list and display a message, otherwise show the list and hide the message.
     */
    checkListHasBuilds = function () {
        if ($buildList.children().length == 0) {
            $buildList.hide();
            $noBuilds.show();
        } else {
            $buildList.show();
            $noBuilds.hide();
        }
    },
    updateTimeout, // ID of timeout which determines when the data will be next fetched from the server
    updateTimestamp, // Timestamp (represented as milliseconds since the Unix epoch) that the builds were last updated
    /**
     * Retrieves the build JSON from the server and adds/removes/changes builds in the build list as needed.
     */
    update = function () {
        updateTimestamp = (new Date()).getTime();
        $.ajax({
            url: opts.getBuildsUrl,
            data: { planKey: opts.planKey },
            dataType: "json",
            cache: false,
            success: function (json) {
                // Go through each build returned and either update or insert as required
                $.each(json.builds, function () {
                    var $build = $("#b" + this.buildResultKey),
                        messageType = this.messageType.toLowerCase(),
                        status = this.status.toLowerCase();
                    if ($build.length > 0) { // Check if the build already exists in list
                        var $msg = $(".message", $build[0]),
                            $stageInfo = $(".stage-info", $build[0]),
                            $agentInfo = $(".agent-info", $build[0]);
                        if (messageType == "progress" && $msg.hasClass(messageType)) {
                            $msg.progressBar("option", { value: this.percentageComplete, text: this.messageText });
                        } else if (messageType == "progress") {
                            $msg.attr("class", "message").progressBar({ value: this.percentageComplete, text: this.messageText });
                        } else {
                            if ($msg.hasClass("progress")) {
                                $msg.progressBar("destroy");
                            }
                            if (!$msg.hasClass(messageType)) {
                                $msg.attr("class", "message " + messageType).text(this.messageText);
                            } else {
                                $msg.text(this.messageText);
                            }
                        }
                        if (status == "building") {
                            if ($agentInfo.length == 0 && this.agent != null) {
                                var buildingOnHTML = status == "building" ? AJS.template.load(opts.templates.buildingOnTemplate).fill({ agentId: this.agent.id, agentType: this.agent.type.toLowerCase(), agentName: this.agent.name }).toString() : "";
                                $(".build-description", $build[0]).append(buildingOnHTML);
                            }
                            if (this.stage != null && $stageInfo.length > 0) {
                                var currentStageHTML = (status == "building" ? AJS.template.load(opts.templates.currentStageTemplate).fill({ stageName: this.stage.name, stageNumber: this.stage.number, totalStages: this.stage.totalStages }).toString() : "");
                                $stageInfo.html($.trim(currentStageHTML));
                            }
                        }
                        if (!$build.hasClass(status)) {
                            $build.removeClass(status == "building" ? "queued" : "building").addClass(status);
                        }
                    } else {
                        var buildingOnHTML = (status == "building" && this.agent != null) ? AJS.template.load(opts.templates.buildingOnTemplate).fill({ agentId: this.agent.id, agentType: this.agent.type.toLowerCase(), agentName: this.agent.name }).toString() : "",
                            currentStageHTML = (status == "building" && this.stage != null) ? AJS.template.load(opts.templates.currentStageTemplate).fill({stageName: this.stage.name, stageNumber: this.stage.number, totalStages: this.stage.totalStages }).toString() : "",
                            buildMessageHTML = AJS.template.load(opts.templates.buildMessageTemplate).fill({ type: messageType, text: this.messageText }).toString(),
                            listItemHTML = AJS.template.load(opts.templates.buildListItemTemplate).fill({
                                buildResultKey: this.buildResultKey,
                                cssClass: status,
                                planKey: this.planKey
                            }).fillHtml({
                                buildingOn: buildingOnHTML,
                                triggerReason: this.triggerReason,
                                currentStage: currentStageHTML,
                                buildMessage: buildMessageHTML
                            }).toString();
                        $build = $(listItemHTML).appendTo($buildList);
                        var $msg = $(".message", $build[0]);
                        $build.addClass("collapsed").prepend(toggleDetailsHTML);
                        $(".additional-information", $build).hide();
                        if (messageType == "progress") {
                            $msg.progressBar({ value: this.percentageComplete, text: this.messageText });
                        }
                    }
                    $build.data("lastUpdated", updateTimestamp);
                });

                // Clean up builds not returned in JSON
                $buildList.children().each(function () {
                    var b = $(this);
                    if (b.data("lastUpdated") < updateTimestamp) {
                        b.fadeOut(500, function () {
                            $(this).remove();
                            checkListHasBuilds();
                        })
                    }
                });

                checkListHasBuilds();

                // Update again in 5 seconds
                updateTimeout = setTimeout(update, 5000);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // Error occurred when doing the update, try again in 30 sec
                updateTimeout = setTimeout(update, 30000);
            }
        });
    };
    return {
        /**
         * Initialisation for the Live Activity
         * @param options - Object containing the options to overwrite our defaults
         */
        init: function (options) {
            $.extend(true, opts, options);
            disabledStopHTML = opts.templates.disabledStopButton.fill({ title: opts.cancellingBuildText, text: opts.cancellingBuildText }).toString();
            toggleDetailsHTML = opts.templates.toggleDetailsButton.toString();

            $buildList = $("> ul", opts.container);
            if ($buildList.length == 0) {
                $buildList = $("<ul />").hide().prependTo(opts.container);
            } else {
                $buildList.children().addClass("collapsed").prepend(toggleDetailsHTML);
                $(".additional-information", $buildList).hide();
            }
            $noBuilds = $("> p", opts.container);
            if ($noBuilds.length == 0) {
                $noBuilds = $("<p>" + opts.queueEmptyText + "</p>").hide().appendTo(opts.container);
            }

            $("#" + opts.container.attr("id") + " a.build-stop").live("click", function (e) {
                var el = $(this),
                    li = el.closest("li");
                $.post(this.href, function () {
                    // Only remove from the queue immediately - currently building builds may take a while to stop and clean up - let the next updateBuilds() that runs clean it up
                    if (li.hasClass("queued")) {
                        li.fadeOut(500, function () {
                            $(this).remove();
                            checkListHasBuilds();
                        })
                    }
                });
                el.replaceWith(disabledStopHTML);
                e.preventDefault();
            });

            $("#" + opts.container.attr("id") + " .collapsed .toggle-details").live("click", function (e) {
                var el = $(this),
                    li = el.closest("li"),
                    additionalInfo = $(".additional-information", li[0]),
                    buildResultKey = li.attr("id").substring(1);

                if (!additionalInfo.data("data-retrieved")) {
                    li.removeClass("collapsed");
                    $.ajax({
                        url: opts.getChangesUrl + buildResultKey,
                        data: {
                            expand: "jiraIssues,vcsRevisions.vcsRevision.changes.change"
                        },
                        dataType: "json",
                        contentType: "application/json",
                        success: function (json) {
                            var issues = "";
                            if (json.jiraIssues && json.jiraIssues.size > 0) {
                                $.each(json.jiraIssues.issue, function () {
                                    if (this.url && this.url.href && this.key && this.summary) {
                                        issues += AJS.template.load(opts.templates.jiraIssueTemplate).fill({
                                            url: this.url.href,
                                            issueType: (this.issueType && this.issueType.length > 0) ? this.issueType : opts.defaultIssueType,
                                            issueIconUrl: (this.iconUrl && this.iconUrl.length > 0) ? this.iconUrl : opts.defaultIssueIconUrl,
                                            key: this.key,
                                            details: this.summary
                                        }).toString();
                                    }
                                });
                            }

                            var changes = "";
                            if (json.vcsRevisions && json.vcsRevisions.size > 0) {
                                $.each(json.vcsRevisions.vcsRevision, function() {
                                    if (this.changes && this.changes.size > 0) {
                                        $.each(this.changes.change, function () {
                                            if (this.author && this.comment) {
                                                changes += AJS.template.load(opts.templates.codeChangeTemplate).fill({
                                                    authorOrUser: (this.userName && this.userName.length > 0) ? "user" : "author",
                                                    author: (this.userName && this.userName.length > 0) ? this.userName : this.author,
                                                    displayName: (this.fullName && this.fullName.length > 0) ? this.fullName : this.author,
                                                    comment: this.comment
                                                }).fillHtml({
                                                    changesetInfo: this.changesetId ? AJS.template.load(this.commitUrl ? opts.templates.codeChangeChangesetLinkTemplate : opts.templates.codeChangeChangesetDisplayTemplate).fill({
                                                        commitUrl: this.commitUrl ? this.commitUrl : null,
                                                        changesetId: this.changesetId
                                                    }).toString() : ""
                                                }).toString();
                                            }
                                        });
                                    }
                                });
                            }

                            if (issues.length == 0 && changes.length == 0) {
                                additionalInfo.text(opts.noAdditionalInfoText);
                            } else {
                                if (issues.length == 0) {
                                    $(".issueSummary", additionalInfo[0]).remove();
                                } else {
                                    $(".issueSummary", additionalInfo[0]).append("<ul>" + issues + "</ul>");
                                }
                                if (changes.length == 0) {
                                    $(".changesSummary", additionalInfo[0]).remove();
                                } else {
                                    $(".changesSummary", additionalInfo[0]).append("<ul>" + changes + "</ul>");
                                }
                            }

                            li.addClass("expanded");
                            additionalInfo.data("data-retrieved", true, true).stop(true).slideDown(opts.slideSpeed);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            li.addClass("collapsed");
                        }
                    });
                } else {
                    li.removeClass("collapsed").addClass("expanded");
                    additionalInfo.stop(true, true).slideDown(opts.slideSpeed);
                }
            });

            $("#" + opts.container.attr("id") + " .expanded .toggle-details").live("click", function (e) {
                var el = $(this),
                    li = el.closest("li");
                li.removeClass("expanded").addClass("collapsed");
                $(".additional-information", li[0]).stop(true, true).slideUp(opts.slideSpeed);
            });

            // Trigger the first update
            update();
        }
    }
}(jQuery);


function showAjaxErrorMessage(XMLHttpRequest) {
    AJS.$(".ajaxErrorMessage").html("["+XMLHttpRequest.statusText+"]");
    AJS.$("#ajaxErrorHolder").removeClass("hidden").show();
}

function hideAjaxErrorMessage() {
    AJS.$(".ajaxErrorMessage").empty();
    AJS.$("#ajaxErrorHolder").hide();
}

/**
 * Usage: init(selector, reloadEvent) . Calling init function multiple times on the same page is safe regardless of used selectors.
 *
 * @param selector the jQuery selector used to mark asynchronously executed links
 * @param resetLinkStateEventName (optional, nullable) the event causing the "executed" status of links to be cleared
 * @param onUrlCallFinished (optional) handler to call when url processing is finished
 */
var AsynchronousRequestManager = function() {
    var IN_PROGRESS_KEY = "isInProgress";
    var registeredResetLinkStateHandlers = {};

    function isInProgress(link) {
        return link.data(IN_PROGRESS_KEY);
    }

    function setInProgress(link, newValue) {
        link.data(IN_PROGRESS_KEY, newValue);
        if (newValue) {
            link.fadeTo("slow", 0.4);
        } else {
            link.fadeTo("slow", 1);
        }
    }

    var onAsynchronousLinkClick = function (event) {
        var $this = AJS.$(this);
        if (!isInProgress($this)) {
            AJS.$.ajax({
                url: this.href,
                error: function (XMLHttpRequest) {
                    setInProgress($this, false);
                    if (event.data.failureHandler) {
                        event.data.failureHandler();
                    }
                    showAjaxErrorMessage(XMLHttpRequest);
                },
                success: function () {
                            if (event.data.successHandler) {
                                event.data.successHandler();
                            }
                            setInProgress($this, false);
                }
            });
            setInProgress($this, true);
        }
        event.preventDefault();
    };

    function makePair(first, second) {
        return first + "##" + second;
    }

    return {
        init: function (selector, resetLinkStateEventName, onUrlCallFinished) {
            var $selector = AJS.$(selector);
            if (resetLinkStateEventName) {
                var pair = makePair(resetLinkStateEventName, selector);
                if (!(pair in registeredResetLinkStateHandlers)) {
                    AJS.$("body").bind(resetLinkStateEventName, function () {
                        $selector.filter(":visible").each(function () {
                            setInProgress(AJS.$(this), false);
                        });
                    });
                    registeredResetLinkStateHandlers[pair] = true;
                }
            }

            $selector.die("click", onAsynchronousLinkClick).live("click", {
                                                                     successHandler: onUrlCallFinished,
                                                                     failureHandler: onUrlCallFinished
                                                                 }, onAsynchronousLinkClick);
        }
    }
}();



/**
 * JobResultSummary page
 */
var JobResultSummaryLiveActivity = function ($) {
    var opts = {
        buildResultKey: null,
        buildLifeCycleState: null,
        container: null,
        getBuildUrl: null,
        reloadUrl: null,
        templates: {
            disabledStopButton: null,
            logTableRow: null,
            progressOverAverage: null,
            progressUnderAverage: null,
            queueDurationDescription: null,
            queuePositionDescription: null,
            updatingSourceFor: null
        }
    },
    linesOfLogToDisplay = 10,
    $linesOfLogToDisplaySelect,
    $logBody,
    $logContainer,
    $logLoading,
    $progressBarContainer,
    $queueDurationDescriptionContainer,
    $queuePositionDescriptionContainer,
    queueDuration,
    updateTimeout,
    update = function () {

        clearTimeout(updateTimeout);

        var ajaxData = $logContainer.is(":visible") ? {
            expand: 'logEntries[-' + linesOfLogToDisplay + ':]',
            'max-results': linesOfLogToDisplay
        } : {};

        $.ajax({
            url: opts.getBuildUrl,
            data: ajaxData,
            dataType: "json",
            contentType: "application/json",
            cache: false,
            success: function (buildResult) {
                if (buildResult.lifeCycleState != opts.buildLifeCycleState) {
                    document.location = opts.reloadUrl;
                    return;
                } else if (buildResult.lifeCycleState == "Pending" || buildResult.lifeCycleState == "Queued") {
                    if (queueDuration != buildResult.queueDuration) {
                        var queueDurationMarkup = AJS.template.load(opts.templates.queueDurationDescription)
                                .fill({ durationDescription: DurationUtils.getPrettyPrint(buildResult.queueDuration)}).toString();
                        $queueDurationDescriptionContainer.html(queueDurationMarkup);
                        $queueDurationDescriptionContainer.show();
                        queueDuration = buildResult.queueDuration;
                    }

                    var queuePositionMarkup = AJS.template.load(opts.templates.queuePositionDescription)
                            .fill({
                                position: buildResult.queue.position + 1,
                                length: buildResult.queue.length
                            }).toString();
                    $queuePositionDescriptionContainer.html(queuePositionMarkup);
                    $queuePositionDescriptionContainer.show();

                } else if (buildResult.lifeCycleState == "InProgress") {
                    if (buildResult.progress) {

                        var pbOptions = {};

                        if (buildResult.buildStartedTime) {
                            pbOptions.value = buildResult.progress.percentageCompleted * 100;
                            if (buildResult.progress.isUnderAverageTime) {
                                pbOptions.text = AJS.template.load(opts.templates.progressUnderAverage).fill({
                                    elapsed: buildResult.progress.prettyBuildTime,
                                    remaining: buildResult.progress.prettyTimeRemainingLong
                                }).toString();
                            } else {
                                pbOptions.text = AJS.template.load(opts.templates.progressOverAverage).fill({
                                    elapsed: buildResult.progress.prettyBuildTime,
                                    remaining: buildResult.progress.prettyTimeRemainingLong
                                }).toString();
                            }
                        } else {
                            pbOptions.value = 0;
                            pbOptions.text = AJS.template.load(opts.templates.updatingSourceFor).fill({
                                prettyVcsUpdateDuration: buildResult.prettyVcsUpdateDuration
                            }).toString();
                        }

                        $progressBarContainer.progressBar(pbOptions);
                    }

                    if (buildResult.logEntries && buildResult.logEntries.logEntry) {

                        var newLogBody = '';

                        for (var i = 0, ii = buildResult.logEntries.logEntry.length; i < ii; i++) {
                            var logEntry = buildResult.logEntries.logEntry[i];
                            newLogBody += AJS.template.load(opts.templates.logTableRow)
                                    .fill({ time: logEntry.formattedDate })
                                    .fillHtml({ log: logEntry.log }).toString();
                        }
                        if ($logBody.html() != newLogBody) {
                            $logBody.html(newLogBody);
                        }
                        if ($logLoading.is(":visible")) {
                            $logLoading.hide();
                            $logBody.parent().removeClass("hidden");
                        }
                    }
                }

                // Update again in 5 seconds
                updateTimeout = setTimeout(update, 5000);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // Error occurred when doing the update, try again in 30 sec
                updateTimeout = setTimeout(update, 30000);
            }
        });
    };
    return {
        init: function (options) {
            $.extend(true, opts, options);

            $linesOfLogToDisplaySelect = $("#linesToDisplay");
            $logBody = $("#buildLog tbody");
            $logContainer = $logBody.parent().parent();
            $logLoading = $(".loading", $logContainer[0]);
            $progressBarContainer = $("#pb" + opts.buildResultKey);
            $queueDurationDescriptionContainer = $("#queueDurationDescription");
            $queuePositionDescriptionContainer = $("#queuePositionDescription");

            // Get our default in line with what was set previously
            linesOfLogToDisplay = $linesOfLogToDisplaySelect.val();

            $linesOfLogToDisplaySelect.change(function () {
                linesOfLogToDisplay = $(this).val();
                saveCookie("BAMBOO-MAX-DISPLAY-LINES", linesOfLogToDisplay, 365);
                update();
            });

            var disabledStopHTML = opts.templates.disabledStopButton.toString();
            $("#buildResults a.build-stop").live("click", function (e) {
                var $el = $(this);
                $.post(this.href);
                $el.replaceWith(disabledStopHTML);
                e.preventDefault();
            });

            // Trigger the first update
            update();
        }
    }
}(jQuery);


var DurationUtils = function() {
    var opts = {
        format: "{value} {unit}",
        units: {
            SEC: ["second", "seconds"],
            MIN: ["minute", "minutes"]
        }
    },
    MILLIS_IN_MINUTE = 60 * 1000,
    MILLIS_IN_SECOND = 1000,
    describeValueAs = function(value, unit) {
        return opts.format.replace("{value}", value).replace("{unit}", value == 1 ? unit[0] : unit[1]);
    };
    return {
        init: function (options) {
            $.extend(true, opts, options);
        },
        getPrettyPrint: function(elapsedTimeMillis) {
            if (elapsedTimeMillis >= MILLIS_IN_MINUTE) {
                return describeValueAs(Math.floor(elapsedTimeMillis / MILLIS_IN_MINUTE), opts.units.MIN)
            } else if (elapsedTimeMillis >= MILLIS_IN_SECOND) {
                return describeValueAs(Math.floor(elapsedTimeMillis / MILLIS_IN_SECOND), opts.units.SEC)
            } else {
                return "< 1 {unit}".replace("{unit}", opts.units.SEC[0]);
            }
        }
    }
}();

var ChainResultSummary = function ($) {
    var opts = {
        slideSpeed: 400,
        $list: null,
        getStageResultsUrl: null,
        buildResultKey: null,
        autoUpdate: false,
        templates: {
            buildResultDetails: null,
            buildInProgress: null,
            progressOverAverage: null,
            progressUnderAverage: null,
            updatingSourceFor: null,
            noAgentsForJob: null
        }
    },
    updateTimeout,
    progressBarContainer,
    update = function () {
        $.ajax({
            url: opts.getStageResultsUrl,
            cache: false,
            data: {
                expand: "stages.stage.results.result"
            },
            dataType: "json",
            contentType: "application/json",
            success: function (json) {
                if (json.lifeCycleState == "Finished") {
                    window.location.reload(true);
                    return;
                }

                if (json.lifeCycleState == "InProgress" && $("#buildResultsSummary").hasClass("queued")) {
                    window.location.reload(true);
                }

                if (json.lifeCycleState == "Pending" || json.lifeCycleState == "Queued" || json.lifeCycleState == "InProgress") {
                    if (json.progress) {

                        var pbOptions = {};

                        if (json.buildStartedTime) {
                            pbOptions.value = json.progress.percentageCompleted * 100;
                            if (json.progress.isUnderAverageTime) {
                                pbOptions.text = AJS.template.load(opts.templates.progressUnderAverage).fill({
                                    elapsed: json.progress.prettyBuildTime,
                                    remaining: json.progress.prettyTimeRemainingLong
                                }).toString();
                            } else {
                                pbOptions.text = AJS.template.load(opts.templates.progressOverAverage).fill({
                                    elapsed: json.progress.prettyBuildTime,
                                    remaining: json.progress.prettyTimeRemainingLong
                                }).toString();
                            }
                        } else {
                            pbOptions.value = 0;
                            pbOptions.text = AJS.template.load(opts.templates.updatingSourceFor).fill({
                                prettyVcsUpdateDuration: json.prettyVcsUpdateDuration
                            }).toString();
                        }

                        progressBarContainer.progressBar(pbOptions);
                    }
                }

                // Go through each stage returned and update
                if (json.stages.stage) {
                    $.each(json.stages.stage, function () {
                        var $stage = $("#stage_" + this.id),
                            status = this.lifeCycleState;
                        if ($stage.length > 0) { // Check if the stage exists in list
                            var $stageStatus = $("> div > dl > dd", $stage[0]),
                                $jobs = $("> div > ul", $stage[0]),
                                stageClass = this.displayClass,
                                successfulBuildResults = 0,
                                failedBuildResults = 0,
                                isCollapsed = $stage.hasClass("collapsed"),
                                isNotCollapsible = $stage.hasClass("not-collapsible"),
                                isCollapsedByDefault = this.collapsedByDefault;
                            if ($stageStatus.text() != this.displayMessage) {
                                $stageStatus.text(this.displayMessage);
                            }
                            if (!$stage.hasClass(stageClass)) {
                                $stage.removeClass("Failed Successful NotBuilt Pending InProgress").addClass(stageClass);
                            }
                            if (this.results.result) {
                                $.each(this.results.result, function () {
                                    var $build = $("#job_" + this.key);
                                    if ($build.length > 0) {
                                        var $buildResultDetails = $("> dl", $build[0]),
                                            buildClass = (this.lifeCycleState == "Finished") ? this.state : this.lifeCycleState,
                                            $progress = $("#pb" + this.key),
                                            $errorMessage = $(".jobError", $build);
                                        if (!$build.hasClass(buildClass)) {
                                            $build.attr("class", buildClass);
                                        }
                                        $("> #stopBuildLink_" + this.id, $build).remove();

                                        if (this.lifeCycleState == "Finished" && this.buildDurationDescription && this.buildTestSummary && $buildResultDetails.length == 0) {
                                            $build.append(AJS.template.load(opts.templates.buildResultDetails).fill({
                                                durationDescription: this.buildDurationDescription,
                                                testSummary: this.buildTestSummary
                                            }).toString());
                                            if ($progress.length) {
                                                $progress.remove();
                                            }
                                            if ($errorMessage.length) {
                                                $errorMessage.remove();
                                            }
                                        } else {
                                            if (this.lifeCycleState == "InProgress") {
                                                $build.append(AJS.template.load(opts.templates.buildInProgress).fill({
                                                    id: this.id,
                                                    chainResultKey: json.key,
                                                    buildResultKey: this.key
                                                }).toString());
                                                if (this.progress && !$progress.length) {
                                                    $progress = $("<div />", { id: "pb" + this.key }).progressBar().appendTo($build);
                                                }
                                                if (this.progress && this.progress.percentageCompleted) {
                                                    if (this.progress.averageBuildDuration > 0) {
                                                        $progress.progressBar("option", {
                                                            value: Math.floor(this.progress.percentageCompleted * 100),
                                                            text: this.progress.prettyTimeRemaining
                                                        });
                                                    } else {
                                                        $progress.progressBar("option", {
                                                            value: 0,
                                                            text: AJS.template.load(opts.templates.progressOverAverage).fill({elapsed: this.progress.prettyBuildTime}).toString()
                                                        });
                                                    }
                                                }
                                            }
                                            if ((this.lifeCycleState == "Pending" || this.lifeCycleState == "Queued") && !this.hasExecutableAgents) {
                                                if ($errorMessage.length == 0) {
                                                    $build.append(AJS.template.load(opts.templates.noAgentsForJob).toString());
                                                }
                                            } else {
                                                if ($errorMessage.length) {
                                                    $errorMessage.remove();
                                                }
                                            }
                                        }
                                    }
                                    if (this.state == "Successful") {
                                        successfulBuildResults++;
                                    }
                                    if (this.state == "Failed") {
                                        failedBuildResults++;
                                    }
                                });
                            }
                            if (!isNotCollapsible && isCollapsed != isCollapsedByDefault && !$stage.data("userAlteredDisplayState")) {
                                if (!isCollapsedByDefault) {
                                    $jobs.slideDown(opts.slideSpeed, function () {
                                        $stage.removeClass("collapsed");
                                    });
                                } else {
                                    $jobs.slideUp(opts.slideSpeed, function () {
                                        $stage.addClass("collapsed");
                                    });
                                }
                            }
                        }
                    });
                }

                // Update again in 5 seconds
                updateTimeout = setTimeout(update, 5000);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // Error occurred when doing the update, try again in 30 sec
                updateTimeout = setTimeout(update, 30000);
            }
        });
    };
    return {
        init: function (options) {
            $.extend(true, opts, options);
            opts.$list.children(":last-child").addClass("last");

            opts.$list.delegate("li > div > dl > dt", "click", function () {
                var $stage = $(this).closest("li"),
                    $jobs = $("> div > ul", $stage[0]);
                if ($stage.hasClass("collapsed")) {
                    $jobs.slideDown(opts.slideSpeed, function () {
                        $stage.removeClass("collapsed").data("userAlteredDisplayState", true);
                    });
                } else if (!$stage.hasClass("not-collapsible")) {
                    $jobs.slideUp(opts.slideSpeed, function () {
                        $stage.addClass("collapsed").data("userAlteredDisplayState", true);
                    });
                }
            });
            
            progressBarContainer = $("#pb" + opts.buildResultKey);
            
            if (opts.autoUpdate) {
                update();
            }
        }
    }
}(jQuery);


/**
 * BuildResultSummary page
 */
var BuildResultSummaryLiveActivity = function ($) {
    var opts = {
        getBuildUrl: null,
        templates: {
            logMessagePending: null,
            logMessageQueued: null,
            logMessageFinished: null,
            logTableRow: null
        }
    },
    displayLogActivity = function(logBody) {
        $logMessage.hide();
        $logLoading.hide();
        if ($logBody.html() != logBody) {
            $logBody.html(logBody);
        }
        $logBody.parent().show();
        $logContainer.show();
    },
    displayLogLoading = function() {
        $logMessage.hide();
        $logBody.parent().hide();
        $logLoading.show();
        $logContainer.show();
    },
    displayLogMessage = function(template) {
        $logContainer.hide();
        $logMessage.html(AJS.template.load(template).fill({job: jobName})).show();
    },
    $jobResultKeyForLogDisplaySelect,
    jobResultKey,
    jobName,
    linesOfLogToDisplay = 10,
    $linesOfLogToDisplaySelect,
    $logBody,
    $logContainer,
    $logLoading,
    $logMessage,
    updateTimeout,
    update = function () {

        clearTimeout(updateTimeout);

        $.ajax({
            url: opts.getBuildUrl.replace("@KEY@", jobResultKey),
            data: {
                expand: 'logEntries[-' + linesOfLogToDisplay + ':]',
                'max-results': linesOfLogToDisplay
            },
            dataType: "json",
            contentType: "application/json",
            cache: false,
            success: function (buildResult) {
                if (buildResult.lifeCycleState == "Pending") {
                    displayLogMessage(opts.templates.logMessagePending);
                } else if (buildResult.lifeCycleState == "Queued") {
                    displayLogMessage(opts.templates.logMessageQueued);
                } else if (buildResult.lifeCycleState == "InProgress") {
                    if (buildResult.logEntries && typeof(buildResult.logEntries.logEntry) != "undefined") {
                        var newLogBody = '';
                        for (var i = 0, ii = buildResult.logEntries.logEntry.length; i < ii; i++) {
                            var logEntry = buildResult.logEntries.logEntry[i];
                            newLogBody += AJS.template.load(opts.templates.logTableRow)
                                    .fill({ time: logEntry.formattedDate })
                                    .fillHtml({ log: logEntry.log }).toString();
                        }
                        displayLogActivity(newLogBody);
                    } else {
                        displayLogLoading();
                    }
                } else if (buildResult.lifeCycleState == "Finished") {
                    displayLogMessage(opts.templates.logMessageFinished);
                }

                // Update again in 5 seconds
                updateTimeout = setTimeout(update, 5000);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // Error occurred when doing the update, try again in 30 sec
                updateTimeout = setTimeout(update, 30000);
            }
        });
    };
    return {
        init: function(options) {
            $.extend(true, opts, options);
            $jobResultKeyForLogDisplaySelect = $("#jobResultKeyForLogDisplay");
            $linesOfLogToDisplaySelect = $("#linesToDisplay");
            $logContainer = $("#buildResultSummaryLogs");
            $logBody = $("table > tbody", $logContainer[0]);
            $logLoading = $(".loading", $logContainer[0]);
            $logMessage = $("#buildResultSummaryLogMessage");

            // Get our default in line with what was set previously
            linesOfLogToDisplay = $linesOfLogToDisplaySelect.val();

            $jobResultKeyForLogDisplaySelect.change(function () {
                jobResultKey = $jobResultKeyForLogDisplaySelect.val();
                jobName = $jobResultKeyForLogDisplaySelect.find("option:selected").text();
                update();
            });

            $linesOfLogToDisplaySelect.change(function () {
                linesOfLogToDisplay = $linesOfLogToDisplaySelect.val();
                saveCookie("BAMBOO-MAX-DISPLAY-LINES", linesOfLogToDisplay, 365);
                update();
            });

            // Trigger the first update
            $jobResultKeyForLogDisplaySelect.change();
        }
    }
}(jQuery);


var ChainConfiguration = function ($) {
    var opts = {
        $list: null,
        moveStageUrl: null,
        moveJobUrl: null,
        confirmStageMoveUrl: null,
        confirmJobMoveJobUrl: null,
        chainKey: null,
        canReorder: false,
        stageMoveHeader: "Move Stage",
        jobMoveHeader: "Move Job"
    };
    return {
        init: function (options) {
            $.extend(true, opts, options);
            opts.$list.children(":last-child").addClass("last");

            opts.$list.find("li > div > dl > dd > .actions").dropDown("Standard");

            if (!opts.canReorder) {
                return;
            }
            
            opts.$list.sortable({
                cursor: "move",
                distance: 5,
                handle: "dl",
                start: function (event, ui) {
                    var $self = $(ui.item);
                    $self.data("movedFromPos", $self.prevAll().length);
                },
                update: function (event, ui) {
                    var $self = $(ui.item),
                        revertMove = function(index) {
                            if ((opts.$list.children().length - 1) == $self.data("movedFromPos")) {
                                $self.appendTo(opts.$list).removeData("movedFromPos");
                            } else {
                                $self.insertBefore(opts.$list.children("li:eq(" + ($self.data("movedFromPos") + (($self.data("movedFromPos") > index)?1:0)) + ")")).removeData("movedFromPos");
                            }
                        },
                        showError = function () {
                            var message = arguments.length ? arguments[0] : "There was a problem moving your stage.",
                                errorDialog = new AJS.Dialog(400, 150);
                            errorDialog.addHeader("Stage move failed").addPanel("errorPanel", '<div class="fieldError errorText">' + message + '</div>').addButton("Close", function (dialog) {
                                dialog.hide();
                            });
                            errorDialog.show();
                            revertMove();
                        },
                        callMoveAction = function() {
                            var stageId = $self.attr("id").split("_")[1],
                                index = $self.prevAll().length;
                            $.ajax({
                                type: "POST",
                                url: opts.moveStageUrl,
                                data: { buildKey: opts.chainKey, stageId: stageId, index: index},
                                success: function (json) {
                                    if (json.status == "ERROR") {
                                        if (json.errors && json.errors.length > 0) {
                                            var message = json.errors.join("<br>");
                                            showError(message);
                                        } else {
                                            showError();
                                        }
                                    } else if (json.status == "CONFIRM") {
                                        var cancelCallback = function (dialog) {
                                            revertMove(index);
                                        };
                                        simpleDialogForm(null, opts.confirmStageMoveUrl + "?buildKey=" + opts.chainKey + "&stageId=" + stageId + "&index=" + index, 600, 500, opts.stageMoveHeader, "ajax", null, cancelCallback, opts.stageMoveHeader);
                                    } else {
                                        opts.$list.children(":last-child").addClass("last").siblings().removeClass("last");
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    showError();
                                },
                                dataType: "json"
                            });
                        };
                    callMoveAction();
                }
            });

            var jobLists = opts.$list.find("> li > div > ul");
            jobLists.children("[id^='job_']").draggable({
                cursor: "move",
                handle: ".handle",
                revert: "invalid",
                revertDuration: 300,
                scope: "jobs",
                start: function (event, ui) {
                    var $self = $(this);
                    $self.data("movedFrom", $self.parent()).data("movedFromPos", $self.prevAll().length);

                    // Add a z-index to the stage when someone drags a job to fix IE7's crappy stacking
                    if ($.browser.msie && parseInt($.browser.version, 10) == 7) {
                        $self.closest("li[id^='stage_']").css("zIndex", 1).siblings().css("zIndex", "")
                    }
                }
            });
            jobLists.droppable({
                accept: function (li) {
                    return (this != li.parent()[0]); // prevents being able to drop to the same stage
                },
                activeClass: "ui-state-active",
                drop: function (event, ui) {
                    var $self = ui.draggable,
                        revertMove = function () {
                            var $originalFollowingElement = $self.data("movedFrom").children("li:eq(" + $self.data("movedFromPos") + ")");
                            if ($originalFollowingElement.length == 0)  {
                                $self.appendTo($self.data("movedFrom")).removeData("movedFrom").removeData("movedFromPos");
                            } else  {
                                $self.insertBefore($originalFollowingElement).removeData("movedFrom").removeData("movedFromPos");
                            }
                        },
                        showError = function () {
                            var message = arguments.length ? arguments[0] : "There was a problem moving your Job.",
                                errorDialog = new AJS.Dialog(400, 150);

                            errorDialog.addHeader("Job move failed").addPanel("errorPanel", '<div class="fieldError errorText">' + message + '</div>').addButton("Close", function (dialog) {
                                 dialog.hide();
                            });
                            errorDialog.show();
                            revertMove();
                        },
                        callMoveAction = function() {
                            var stageId = $self.closest("li[id^='stage_']").attr("id").split("_")[1],
                                jobKey = $self.attr("id").split("_")[1];
                            $.ajax({
                                type: "POST",
                                url: opts.moveJobUrl,
                                data: { buildKey: opts.chainKey, stageId: stageId, jobKey: jobKey },
                                success: function (json) {
                                    if (json.status == "ERROR") {
                                        if (json.errors && json.errors.length > 0) {
                                            var message = json.errors.join("<br>");
                                            showError(message);
                                        } else {
                                            showError();
                                        }
                                    } else if (json.status == "CONFIRM") {
                                        var cancelCallback = function () {
                                            revertMove();
                                        };
                                        simpleDialogForm(null, opts.confirmJobMoveJobUrl + "?buildKey=" + opts.chainKey + "&stageId=" + stageId + "&jobKey=" + jobKey, 600, 500, opts.jobMoveHeader, "ajax", null, cancelCallback, opts.jobMoveHeader);
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    showError();
                                },
                                dataType: "json"
                            });
                        };
                    $self.prependTo(this).css({ left: "", top: "" });
                    callMoveAction();
                },
                hoverClass: "ui-state-hover",
                scope: "jobs"
            });
        }
    }
}(jQuery);

var ArtifactDefinitionEdit = function ($) {
    var opts = {
        html: {
            artifactSharingToggleContentShared: null,
            artifactSharingToggleContentUnshared: null
        },
        i18n: {
            artifact_definition_shareToggle_error: null,
            artifact_definition_shareToggle_error_header: null,
            global_buttons_close: null
        },
        deleteArtifactDefinition: {
            actionUrl: null,
            submitLabel: null,
            title: null
        },
        editArtifactDefinition: {
            actionUrl: null,
            submitLabel: null,
            title: null
        },
        renameArtifactDefinitionToEnableSharing: {
            actionUrl: null,
            submitLabel: null,
            title: null
        },
        toggleArtifactDefinitionSharing: {
            actionUrl: null,
            submitLabel: null,
            title: null
        },
        confirmToggleArtifactDefinitionSharing: {
            actionUrl: null,
            submitLabel: null,
            title: null
        }
    },
    $artifactDefinitionsTable,
    deleteArtifactDefinitionCallback = function (result) {
        var artifact = result.artifactDefinition;

        (($("tbody > tr", $artifactDefinitionsTable).length == 1) ? $artifactDefinitionsTable : $("#artifactDefinition-" + artifact.id)).remove();
    },
    deleteArtifactDefinitionOnClick = function() {
        var artifactId = this.id.split("-")[1],
            hasSubscriptions = $(this).hasClass("hasSubscriptions");

        simpleDialogForm(null,
                         opts.deleteArtifactDefinition.actionUrl + "&artifactId=" + artifactId,
                         hasSubscriptions ? 600 : 400,
                         hasSubscriptions ? 500 : 200,
                         opts.deleteArtifactDefinition.submitLabel,
                         "ajax",
                         deleteArtifactDefinitionCallback,
                         null,
                         opts.deleteArtifactDefinition.title,
                         null);
    },
    editArtifactDefinitionOnClick = function() {
        var artifactId = this.id.split("-")[1];

        simpleDialogForm(null,
                         opts.editArtifactDefinition.actionUrl + "&artifactId=" + artifactId,
                         800,
                         450,
                         opts.editArtifactDefinition.submitLabel,
                         "ajax",
                         updateArtifactDefinitionCallback,
                         null,
                         opts.editArtifactDefinition.title,
                         null);
    },
    toggleArtifactDefinitionSharingOnClick = function() {
        var artifactId = this.id.split("-")[1],
            showError = function () {
                var message = arguments.length ? arguments[0] : opts.i18n.artifact_definition_shareToggle_error,
                    errorDialog = new AJS.Dialog(400, 150);
                errorDialog.addHeader(opts.i18n.artifact_definition_shareToggle_error_header)
                        .addPanel("errorPanel", '<div class="fieldError errorText">' + message + '</div>')
                        .addCancel(opts.i18n.global_buttons_close, function (dialog) { dialog.hide(); })
                        .show();
            };

        AJS.$.ajax({
            type: "POST",
            url: opts.toggleArtifactDefinitionSharing.actionUrl,
            data: { artifactId: artifactId },
            success: function (json) {
                if (json.status == "ERROR") {
                    if (json.errors && json.errors.length) {
                        showError(json.errors.join("<br>"));
                    } else if (json.fieldErrors) {
                        if (json.fieldErrors.name && json.fieldErrors.name.length) {
                            simpleDialogForm(null,
                                             opts.renameArtifactDefinitionToEnableSharing.actionUrl + "&artifactId=" + artifactId,
                                             700, 300,
                                             opts.renameArtifactDefinitionToEnableSharing.submitLabel,
                                             "ajax",
                                             updateArtifactDefinitionCallback, null,
                                             opts.renameArtifactDefinitionToEnableSharing.title);
                        } else {
                            var errorMessages = [];
                            for (var fieldError in json.fieldErrors) {
                                errorMessages.push(json.fieldErrors[fieldError].join("<br>"));
                            }
                            showError(errorMessages.join("<br>"));
                        }
                    } else {
                        showError();
                    }
                } else {
                    if (json.status == "CONFIRM") {
                        simpleDialogForm(null,
                                         opts.confirmToggleArtifactDefinitionSharing.actionUrl + "&artifactId=" + artifactId,
                                         600, 500,
                                         opts.confirmToggleArtifactDefinitionSharing.submitLabel,
                                         "ajax",
                                         updateArtifactDefinitionCallback, null,
                                         opts.confirmToggleArtifactDefinitionSharing.title);
                    } else {
                        updateArtifactDefinitionCallback(json);
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                showError();
            },
            dataType: "json"
        });
    },
    updateArtifactDefinitionCallback = function (result) {
        var artifact = result.artifactDefinition,
            $cells = $("#artifactDefinition-" + artifact.id + " > td");

        $($cells[0]).find("span.artifactName").text(artifact.name);
        $($cells[0]).find("span.icon").attr("class", artifact.sharedArtifact ? "icon icon-artifact-shared" : "icon icon-artifact");

        $($cells[1]).text(artifact.location);
        $($cells[2]).text(artifact.copyPattern);

        $("#toggleArtifactDefinitionSharing-" + artifact.id).html(artifact.sharedArtifact ? opts.html.artifactSharingToggleContentShared : opts.html.artifactSharingToggleContentUnshared);

        $artifactDefinitionsTable.trigger("update").trigger("sorton", [$artifactDefinitionsTable.get(0).config.sortList]);
    };

    return {
        init: function (options) {
            $.extend(true, opts, options);

            $artifactDefinitionsTable = $("#artifactDefinitions");

            // initialize table sorter
            $artifactDefinitionsTable.tablesorter({
                headers: {3:{sorter:false},4:{sorter:false}},
                sortList: [[0,0]]
            });
            $artifactDefinitionsTable.delegate("a.deleteArtifactDefinition", "click", deleteArtifactDefinitionOnClick)
                                     .delegate("a.editArtifactDefinition", "click", editArtifactDefinitionOnClick)
                                     .delegate("a.toggleArtifactDefinitionSharing", "click", toggleArtifactDefinitionSharingOnClick);
        }
    }
}(jQuery);


var LinkedJiraProjects = function ($) {
    var defaults = {
        deleteItem: {
            title: null
        }
    },
    $table,
    deleteItemCallback = function (result) {
        var item = result.linkedJiraProject;
        (($("tbody > tr", $table).length == 1) ? $table : $(BAMBOO.escapeIdToJQuerySelector("#linkedJiraProject-" + item.id))).remove();
    };

    return {
        init: function (options) {
            options = AJS.$.extend(defaults, options);

            $table = $("#linkedJiraProjects");

            // initialize table sorter
            $table.tablesorter({
                headers: {2:{sorter:false}},
                sortList: [[0,0]]
            });

            BAMBOO.simpleDialogForm({
                trigger: '#linkedJiraProjects a.deleteLinkedJiraProject',
                dialogWidth: 400,
                dialogHeight: 200,
                success: deleteItemCallback,
                header: options.deleteItem.title
            });
        }
    }
}(jQuery);


/* Tests Tables */
AJS.$(document).delegate(".tests-table > tbody > tr > .twixie > span", "click", function (e) {
    var $twixie = AJS.$(this),
        $tr = $twixie.closest("tr"),
        $stack = $tr.next(),
        newTwixieText = !$twixie.hasClass("icon-collapse") ? "Collapse" : "Expand"; //negated because we toggle the class later
    $stack[$tr.hasClass("collapsed") ? "show" : "hide"]();
    $tr.toggleClass("collapsed expanded");
    $twixie.toggleClass("icon-collapse icon-expand").attr("title", newTwixieText).html("<span>" + newTwixieText + "</span>");
});
AJS.$(document).delegate(".tests-table > thead > tr > .twixie span[role]", "click", function (e) {
    var $trigger = AJS.$(this),
        $li = $trigger.closest("li"),
        $table = $trigger.closest("table");
    if ($li.hasClass("expand-all")) {
        $table.find("tbody > .collapsed .twixie > span").click();
    } else if ($li.hasClass("collapse-all")) {
        $table.find("tbody > .expanded .twixie > span").click();
    }
});


/**
 * Strip given prefix from input.
 * Can handle String and jQuery object input.
 *
 * @param prefix String                   prefix to be stripped from input
 * @param input  String or jQuery object
 */
BAMBOO.stripPrefixFromId = function(prefix, input) {
    if (typeof(input) == 'string') {
        if (input.indexOf(prefix) == 0) {
            return input.slice(prefix.length);
        } else {
            return input;
        }
    } else {
        return this.stripPrefixFromId(prefix, AJS.$(input).attr("id"));
    }
};

/**
 * Unsafe (for jQuery id's) character regex
 * Reference: http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_select_an_element_by_an_ID_that_has_characters_used_in_CSS_notation.3F
 */
BAMBOO.unsafeIdCharacterRegex = /(:|\.)/g;

/**
 * Escape characters in element id to use it as jQuery selector
 * @param id
 */
BAMBOO.escapeIdToJQuerySelector = function(id) {
    return id.replace(BAMBOO.unsafeIdCharacterRegex, '\\$1');
};

BAMBOO.buildAUIErrorMessage = function(errors) {
    var $dummy = AJS.$('<div/>');
    if (errors.length == 1) {
        AJS.messages.error($dummy, {title: errors[0], closeable: false});
    } else if (errors.length > 1) {
        var list = ['<ul>'];
        for (var i = 0, ii = errors.length; i < ii; i++) {
            list.push('<li>', errors[i], '</li>');
        }
        list.push('</ul>');
        AJS.messages.error($dummy, {body: list.join(''), closeable: false});
    }
    return $dummy.children();
};

BAMBOO.buildFieldError = function(errors) {
    var $dummy = AJS.$('<div/>');
    for (var i = 0, ii = errors.length; i < ii; i++) {
        $dummy.append(AJS.$('<div class="error"/>').html(errors[i]));
    }
    return $dummy.children();
};

BAMBOO.addFieldErrors = function($form, fieldName, errors) {
    var $field = AJS.$('#fieldArea_' + $form.attr('id') + '_' + fieldName.replace(".", "_")),
        $input = AJS.$('#' + $form.attr('id') + '_' + fieldName.replace(".", "_")),
        $description = $field.find('.description'),
        $errors = BAMBOO.buildFieldError(errors);

    if ($description.length) {
        $description.before($errors);
    } else if ($field.length) {
        $field.append($errors);
    } else {
        $input.after($errors);
    }
};

BAMBOO.ViewInfoList = function($) {
    var opts = {
            elementSelector: null,
            collapseAll: null,
            expandAll: null,
            target: null,
            i18n: {
                collapse: null,
                expand: null
            }
        },
        $container = null,
        collapseAll = function() {
            $container.find(opts.elementSelector + ".expanded > .summary > a.toggle").click();
        },
        expandAll = function() {
            $container.find(opts.elementSelector + ".collapsed > .summary > a.toggle").click();
        },
        toggle = function() {
            var $toggle = $(this),
                $element = $toggle.closest(opts.elementSelector),
                $icon = $toggle.children("span.icon");

            if ($element.hasClass("collapsed")) {
                $icon.toggleClass("icon-expand icon-collapse").attr({title: opts.i18n.collapse}).children().text(opts.i18n.collapse);
                $element.children(".details").stop(true, true).slideDown(function() {
                    $element.toggleClass("expanded collapsed");
                });
            } else {
                $icon.toggleClass("icon-expand icon-collapse").attr({title: opts.i18n.expand}).children().text(opts.i18n.expand);
                $element.children(".details").stop(true, true).slideUp(function() {
                    $element.toggleClass("expanded collapsed");
                });
            }
        };
    return {
        init: function(options) {
            $.extend(true, opts, options);

            $(function(){
                $container = $(opts.target);
                $container.delegate(opts.elementSelector + " > .summary > a.toggle", "click", toggle);
                if (opts.collapseAll) {
                    $(opts.collapseAll).click(collapseAll);
                }
                if (opts.expandAll) {
                    $(opts.expandAll).click(expandAll);
                }
            });
        }
    }
}(jQuery);


(function ($) {
    var i18nCollapse = "Collapse",
        i18nExpand = "Expand";

    $(document).delegate(".collapsible-section > .summary > h3, .collapsible-section > .summary > .icon", "click", function (e) {
        var $summary = $(this).parent(),
            $section = $summary.closest(".collapsible-section"),
            $details = $section.children(".collapsible-details"),
            $icon = $summary.children(".icon");

        if ($section.hasClass("collapsed")) {
            $icon.addClass("icon-collapse").removeClass("icon-expand").attr({ title: i18nCollapse }).children().text(i18nCollapse);
            $details.stop(true, true).slideDown(function() {
                $section.removeClass("collapsed");
            });
        } else {
            $icon.addClass("icon-expand").removeClass("icon-collapse").attr({ title: i18nExpand }).children().text(i18nExpand);
            $details.stop(true, true).slideUp(function() {
                $section.addClass("collapsed");
            });
        }
    });
})(AJS.$);

/**
 * TODO: extend this with automatic link adding (which will work also for AJAX loaded forms).
 */
BAMBOO.JdkBuilderSelectWidget = function(options) {
    var opts = {
            dialog: {
                height: 320,
                width: 540
            }
        };

    AJS.$.extend(true, opts, options);

    BAMBOO.simpleDialogForm({
        trigger: options.clickTarget,
        dialogWidth: opts.dialog.width,
        dialogHeight: opts.dialog.height,
        success: function(result) {
            AJS.$(opts.displayTarget).append(AJS.$("<option />", { val: result.capability.label, text: result.capability.label })).val(result.capability.label);
        }
    });
};

AJS.$(function ($) {
    addConfirmationToLinks();

    /* Default options for jQuery's tablesorter plugin */
    // use 'zebra' plugin by default
    $.tablesorter.defaults.widgets = ['zebra'];
    // use AUI compatible classes
    $.tablesorter.defaults.widgetZebra = {css: ['', 'zebra']};

    // handleOnSelectShowHide functionality for input[type="checkbox"]
    $('input:checkbox.handleOnSelectShowHide').each( function() { handleOnSelectShowHide(this); });
});

// handleOnSelectShowHide functionality for input[type="checkbox"]
AJS.$(document).delegate('input:checkbox.handleOnSelectShowHide', 'click', function() { handleOnSelectShowHide(this); });

BAMBOO.JdkBuilderSelectWidget({clickTarget: "a.addSharedJdkCapability", displayTarget: "select.jdkSelectWidget"});
BAMBOO.JdkBuilderSelectWidget({clickTarget: "a.addSharedBuilderCapability", displayTarget: "select.builderSelectWidget"});

BAMBOO.ConfigPanelEditor = function () {
    var $ = AJS.$,
        defaults = {
            editor: null,
            configContainer: null,
            itemList: null,
            deleteItemKey: null,
            configFormSuccess: $.noop,
            checkListHasItems: $.noop,
            templates: {
                item: null,
                icon: null
            },
            i18n: {
                confirmAbandonItem: null,
                itemDeleteSuccess: null,
                sortingHasUnsavedItemError: null,
                sortingHasUnspecifiedError: null,
                sortingErrorDialogHeader: null,
                defaultDisplayText: null,
                defaultDisplayTextDescription: null
            },
            sortable: {
                items: "> li",
                moveItem: $.noop
            }
        },
        options,
        $editor,
        $configContainer,
        $itemList,
        displayMessages = function (messages) {
            var $dummy = $("<div/>"),
                $messages,
                $form = $configContainer.children("form"),
                defaultMsgType = "success";

            for (var i = 0, ii = messages.length; i < ii; i++) {
                var message = messages[i],
                    msgType = message.type || defaultMsgType;
                
                AJS.messages[msgType]($dummy, { title: message.title, closeable: (msgType != defaultMsgType), body: message.body });
            }

            $messages = $dummy.children();

            if ($form.length) {
                $form.css("visibility", "hidden").slideUp(function () { $(this).remove(); }).before($messages);
            } else {
                $configContainer.append($messages);
            }

            $messages.filter("." + defaultMsgType).delay(3000).fadeOut(function () {
                $(this).remove();
            });
            insertDefaultText();
        },
        setFocus = function () {
            var $firstError = $configContainer.find(":input:visible:enabled.errorField:first").focus();

            if (!$firstError.length) {
                $configContainer.find(":input:visible:enabled:first").focus();
            }
        },
        insertDefaultText = function () {
            var noItemId = "no-item-selected",
                $noItem = $("#" + noItemId);

            if (!$noItem.length) {
                $noItem = $("<div/>", { "id": noItemId })
                    .append($("<h2/>", { text: options.i18n.defaultDisplayText }))
                    .append($("<p/>", { text: options.i18n.defaultDisplayTextDescription }))
                    .hide()
                    .prependTo($configContainer)
                    .fadeIn();
            }
            return $noItem;
        },
        setupAsyncForm = function ($item) {
            BAMBOO.asyncForm({
                $delegator: $configContainer,
                target: "form",
                success: function (data) {
                    var $newItem = options.configFormSuccess(data, $item.hasClass("unsaved"));
                    $item.replaceWith($newItem);
                    setTimeout(function () { $newItem.removeClass("active"); }, 0); // this is so that the class doesn't get removed immediately after the DOM element is replaced which would causes the CSS transition (fading) not to be applied
                },
                cancel: function () {
                    $configContainer.children("form").css("visibility", "hidden").slideUp(function () { $(this).remove(); });
                    if ($item.hasClass("unsaved")) {
                        $item.remove();
                        checkListHasItems();
                    } else {
                        $item.removeClass("active");
                    }
                    insertDefaultText();
                },
                formReplaced: asyncFormReplaced
            });
        },
        asyncFormReplaced = function () {
            handleOnShow();
            setFocus();
        },
        hasUnsavedItem = function () {
            var $unsaved = $itemList.find(".unsaved");

            return ($unsaved.length ? $unsaved : false);
        },
        isOkayToProceedWithUnsavedItem = function () {
            var $unsavedItem = hasUnsavedItem();

            if ($unsavedItem) {
                if (confirm(options.i18n.confirmAbandonItem)) {
                    $unsavedItem.remove();
                    $configContainer.empty();
                    checkListHasItems();
                } else {
                    return false;
                }
            }
            return true;
        },
        checkListHasItems = function () {
            var hasItems = $itemList.children(".item").length;

            $editor.toggleClass("no-items", !hasItems);
            options.checkListHasItems(hasItems);
        },
        add = function (url, $item, attachMethod, attachTarget) {
            return $.ajax({
                url: url,
                data: { decorator: 'rest', confirm: true },
                success: function (html) {
                    $item[attachMethod](attachTarget).addClass("active unsaved").siblings().removeClass("active");
                    $configContainer.html(html);
                    handleOnShow();
                    setupAsyncForm($item);
                    checkListHasItems();
                    setFocus();
                },
                cache: false
            });
        },
        edit = function (e) {
            var $item = $(this), $target = $(e.target), $configLink, $loadingConfigurationIndicator;

            if (!$target.hasClass("delete") && !$target.hasClass("icon-delete") && !$target.is(":input")) {
                e.preventDefault();
                if ($item.hasClass("active") || !isOkayToProceedWithUnsavedItem()) {
                    setFocus();
                } else {
                    $configLink = $item.find("> a").not(".delete");
                    $loadingConfigurationIndicator = $(AJS.template.load(options.templates.icon).fill({ type: "loading" }).toString()).insertAfter($configLink);

                    $.ajax({
                        url: $configLink.attr("href"),
                        data: { decorator: 'rest', confirm: true },
                        success: function (html) {
                            $configContainer.html(html);
                            handleOnShow();
                            $loadingConfigurationIndicator.remove();
                            $item.addClass("active").siblings().removeClass("active");
                            setupAsyncForm($item);
                            setFocus();
                        },
                        cache: false
                    });
                }
            }
        },
        sortUpdate = function (event, ui) {
            if (hasUnsavedItem()) {
                alert(options.i18n.sortingHasUnsavedItemError);
                $itemList.sortable("cancel");
                return;
            }
            var $item = $(ui.item),
                showSortingError = function () {
                    var message = arguments.length ? arguments[0] : BAMBOO.buildAUIErrorMessage([ options.i18n.sortingHasUnspecifiedError ]),
                        errorDialog = new AJS.Dialog(400, 180),
                        index = $item.prevAll().length;

                    errorDialog.addHeader(options.i18n.sortingErrorDialogHeader).addPanel("errorPanel", message).addButton("Close", function (dialog) {
                        dialog.hide();
                    });
                    errorDialog.show();

                    if (($itemList.children().length - 1) == $item.data("movedFromPos")) {
                        $item.appendTo($itemList).removeData("movedFromPos");
                    } else {
                        $item.insertBefore($itemList.children("li:eq(" + ($item.data("movedFromPos") + (($item.data("movedFromPos") > index) ? 1 : 0)) + ")")).removeData("movedFromPos");
                    }
                },
                jqXHR = options.sortable.moveItem($item);

            if (jqXHR) {
                jqXHR.done(function (json) {
                    if (json.status == "ERROR") {
                        if (json.errors && json.errors.length) {
                            showSortingError(BAMBOO.buildAUIErrorMessage(json.errors));
                        } else {
                            showSortingError();
                        }
                    }
                }).fail(function () {
                    showSortingError();
                });
            }
        },
        sortStart = function (event, ui) {
            var $self = $(ui.item);

            $self.data("movedFromPos", $self.prevAll().length);
        },
        handleOnShow = function () {
            $configContainer.find(".handleOnSelectShowHide").each(function () {
                handleOnSelectShowHide(this);
            });
        };

    return {
        init: function (opts) {
            options = $.extend(true, defaults, opts);

            $(document)
                .delegate(options.itemList + " > .item", "click", edit)
                .delegate("#finalisePlanCreation, #finaliseJobCreation", "submit", function (e) {
                    if (!isOkayToProceedWithUnsavedItem()) {
                        e.preventDefault();
                    }
                });

            $(function () {
                $editor = $(options.editor);
                $configContainer = $(options.configContainer);
                $itemList = $(options.itemList).sortable({
                    cursor: "move",
                    items: options.sortable.items,
                    update: sortUpdate,
                    start: sortStart
                });

                BAMBOO.simpleDialogForm({
                    $delegator: $itemList,
                    trigger: "a.delete",
                    dialogWidth: 540,
                    dialogHeight: 160,
                    success: function (data) {
                        displayMessages([{ title: options.i18n.itemDeleteSuccess }]);
                        $("#item-" + data[options.deleteItemKey].id).remove();
                        checkListHasItems();
                    }
                });
                insertDefaultText();
            });
        },
        add: add,
        setFocus: setFocus,
        displayMessages: displayMessages,
        isOkayToProceedWithUnsavedItem: isOkayToProceedWithUnsavedItem,
        checkListHasItems: checkListHasItems,
        updateUnspecifiedSortingErrorText: function (updatedText) {
            options.i18n.sortingHasUnspecifiedError = updatedText;
        }
    }
};

BAMBOO.TASKS = {};

BAMBOO.TASKS.tasksConfig = function ($) {
    var defaults = {
        addTaskTrigger: null,
        taskSetupContainer: null,
        taskConfigContainer: null,
        taskList: null,
        defaultTaskToSelect: null,
        taskTypeCategories: { categories: [] },
        taskTypesDialog: {
            id: "task-types-dialog",
            header: "Task Types",
            width: 865,
            height: 530,
            filterForm: null
        },
        templates: {
            taskListItem: null,
            iconTemplate: null,
            getMoreOnPac: null
        },
        i18n: {
            cancel: "Cancel",
            confirmAbandonTask: "The new Task has not yet been saved. If you continue you will abandon the new Task.\n\nAre you sure you want to continue?",
            tasksAddSuccess: "Task created successfully.",
            tasksAddSuccessWarning: "Possible conflicting requirements found.",
            tasksEditSuccess: "Task saved successfully.",
            tasksEditSuccessWarning: "Possible conflicting requirements found.",
            tasksDeleteSuccess: "Task deleted successfully.",
            sortingHasUnsavedTaskError: "Please save the new Task before reordering.",
            sortingHasUnspecifiedError: "There was a problem moving your task.",
            sortingErrorDialogHeader: "Task move failed",
            defaultDisplayText: "No Task Selected",
            defaultDisplayTextDescription: "Select a task from the list on the left to configure it."
        },
        agentAvailabilityDescriptionContainer: null,
        agentAvailabilityDescriptionUrl: null,
        moveTaskUrl: null,
        moveFinalBarUrl: null
    },
    options,
    editor = new BAMBOO.ConfigPanelEditor(),
    $filterForm,
    $taskTypesDialog,
    $taskSetupContainer,
    $taskConfigContainer,
    $taskList,
    $loadingIndicator,
    $finalTasksBar,
    taskTypesDialog,
    updateAgentAvailabilityDescription = function () {
        $.get(options.agentAvailabilityDescriptionUrl, function (data) {
            $(options.agentAvailabilityDescriptionContainer).html(data);
        });
    },
    displaySuccessMessageAndPossibleWarning = function (isNew, data) {
        var list,
            messages = [{ title: (isNew ? options.i18n.tasksAddSuccess : options.i18n.tasksEditSuccess) }];

        if (data.taskResult.warning.requirementsConflicts) {
            list = ["<ul>"];
            for (var r = 0, rr = data.taskResult.warning.requirementsConflicts.length; r < rr; r++) {
                var req = data.taskResult.warning.requirementsConflicts[r],
                    reqKey = req.group,
                    conflicts = req.labels;

                list.push("<li>", reqKey, "</li><ul>");
                for (var i = 0, ii = conflicts.length; i < ii; i++) {
                    list.push("<li>", conflicts[i], "</li>");
                }
                list.push("</ul>");
            }
            list.push("</ul>");
            messages.unshift({ title: (isNew ? options.i18n.tasksAddSuccessWarning : options.i18n.tasksEditSuccessWarning), type: "warning", body: list.join("") });
        }
        editor.displayMessages(messages);
    },
    configFormSuccess = function (data, isUnsaved) {
        updateAgentAvailabilityDescription();
        displaySuccessMessageAndPossibleWarning(isUnsaved, data);
        return $(AJS.template.load(options.templates.taskListItem).fill({ name: data.taskResult.task.name, description: data.taskResult.task.description, id: data.taskResult.task.id, valid : data.taskResult.task.valid }).toString()).addClass("active");
    },
    addTask = function (e) {
        var $taskTypeListItem = $(this).append($(AJS.template.load(options.templates.iconTemplate).fill({ type: "loading" }).toString())),
            $taskConfigLink = $taskTypeListItem.find(".task-type-title > a"),
            $taskListItem = $(AJS.template.load(options.templates.taskListItem).fill({ name: $taskConfigLink.text(), description: "", id: "" , valid : true }).toString());

        e.preventDefault();

        editor.add($taskConfigLink.attr("href"), $taskListItem, "insertBefore", $finalTasksBar).success(function () {
            taskTypesDialog.remove();
        });
    },
    setupTaskTypesDialogContent = function (html) {
        var $html = $(html);

        $loadingIndicator.hide();

        taskTypesDialog.addPanel("All", $html);
        for (var i = 0, ii = options.taskTypeCategories.categories.length; i < ii; i++) {
            var category = options.taskTypeCategories.categories[i],
                $categoryTasks = $html.clone();
            $categoryTasks.children(":not(.task-type-category-" + category.key + ")").remove();
            taskTypesDialog.addPanel(category.label, $categoryTasks);
        }

        taskTypesDialog.show().gotoPanel(0);

        $taskTypesDialog = $("#" + options.taskTypesDialog.id).delegate(".task-type-list > li", "click", addTask);

        if (options.taskTypesDialog.filterForm) {
            $filterForm.find("> input").focus();
        }
    },
    showTaskTypesPicker = function (e) {
        var $addTaskTrigger = $(this),
            header = options.taskTypesDialog.header ? options.taskTypesDialog.header : $addTaskTrigger.text();

        e.preventDefault();

        if (!editor.isOkayToProceedWithUnsavedItem()) {
            editor.setFocus();
            return false;
        }

        if (!$loadingIndicator) {
            $loadingIndicator = $(AJS.template.load(options.templates.iconTemplate).fill({ type: "loading" }).toString()).insertAfter($addTaskTrigger.closest(".aui-toolbar"));
        } else {
            $loadingIndicator.show();
        }

        taskTypesDialog = new AJS.Dialog({
            id: options.taskTypesDialog.id,
            width: options.taskTypesDialog.width,
            height: options.taskTypesDialog.height,
            keypressListener: function (e) {
                if (e.which == jQuery.ui.keyCode.ESCAPE) {
                    taskTypesDialog.remove();
                }
            }
        });

        if (header) {
            taskTypesDialog.addHeader(header);

            if (options.taskTypesDialog.filterForm) {
                $filterForm = $(options.taskTypesDialog.filterForm).appendTo(taskTypesDialog.page[0].header);

                $filterForm.submit(function (e) { e.preventDefault(); }).find("> input").bind("keyup click", function () {
                    var textToLookFor = $(this).val().toUpperCase();

                    $taskTypesDialog.find(".task-type-list > li").each(function () {
                        var $li = $(this);

                        $li[( $li.text().toUpperCase().indexOf(textToLookFor) >= 0 ? "show" : "hide" )]();
                    });
                });
            }
        }
        taskTypesDialog.addCancel(options.i18n.cancel, function () { taskTypesDialog.remove(); })
                       .addHelpText(options.templates.getMoreOnPac, { pac: "https://plugins.atlassian.com/search/category/41386" });

        $.ajax({
            url: $addTaskTrigger.attr("href"),
            data: { decorator: "rest", confirm: true },
            success: setupTaskTypesDialogContent,
            cache: false
        });
    },
    moveTask = function ($taskListItem) {
        var isMovedToFinal, status,
            requestComplete = function () {
                if (!status || status == "ERROR") {
                    triggerReflowOnPrompt();
                }
            };

        triggerReflowOnPrompt();

        if ($taskListItem.hasClass("final-tasks-bar")) {
            editor.updateUnspecifiedSortingErrorText("There was a problem moving the final tasks bar.");

            return $.ajax({
                type: "POST",
                url: options.moveFinalBarUrl,
                data: {
                    afterId: $taskListItem.nextAll(".item:first").data("item-id"),
                    beforeId: $taskListItem.prevAll(".item:first").data("item-id")
                },
                dataType: "json",
                complete: requestComplete
            }).done(function (json) {
                status = json.status;
                if (status != "ERROR") {
                    $taskListItem.nextAll(".item").addClass("final").end().prevAll(".item").removeClass("final");
                }
            });
        } else {
            isMovedToFinal = !!$taskListItem.prevAll(".final-tasks-bar").length;
            editor.updateUnspecifiedSortingErrorText(options.i18n.sortingHasUnspecifiedError);

            return $.ajax({
                type: "POST",
                url: options.moveTaskUrl,
                data: {
                    taskId: $taskListItem.data("item-id"),
                    afterId: $taskListItem.nextAll(".item:first").data("item-id"),
                    beforeId: $taskListItem.prevAll(".item:first").data("item-id"),
                    finalising: isMovedToFinal
                },
                dataType: "json",
                complete: requestComplete
            }).done(function (json) {
                status = json.status;
                if (status != "ERROR") {
                    $taskListItem.toggleClass("final", isMovedToFinal);
                }
            });
        }
    },
    triggerReflowOnPrompt = function () {
        var prompt;

        if ($.browser.msie && parseInt($.browser.version, 10) <= 8) {
            prompt = $("#final-tasks-prompt")[0];
            prompt.style.zoom = "100%";
            prompt.style.zoom = "normal";
        }
    };

    return {
        init: function (opts) {
            options = $.extend(true, defaults, opts);

            editor.init({
                editor: options.taskSetupContainer,
                configContainer: options.taskConfigContainer,
                itemList: options.taskList,
                deleteItemKey: "taskResult",
                configFormSuccess: configFormSuccess,
                templates: {
                    item: options.templates.taskListItem,
                    icon: options.templates.iconTemplate
                },
                i18n: {
                    confirmAbandonItem: options.i18n.confirmAbandonTask,
                    itemDeleteSuccess: options.i18n.tasksDeleteSuccess,
                    sortingHasUnsavedItemError: options.i18n.sortingHasUnsavedTaskError,
                    sortingHasUnspecifiedError: options.i18n.sortingHasUnspecifiedError,
                    sortingErrorDialogHeader: options.i18n.sortingErrorDialogHeader,
                    defaultDisplayText: options.i18n.defaultDisplayText,
                    defaultDisplayTextDescription: options.i18n.defaultDisplayTextDescription
                },
                sortable: {
                    items: "> li:not(#final-tasks-prompt)",
                    moveItem: moveTask
                }
            });

            $(document).delegate(options.addTaskTrigger, "click", showTaskTypesPicker);

            BAMBOO.simpleDialogForm({
                trigger: options.taskConfigContainer + " .delete .toolbar-trigger, " + options.taskConfigContainer + " .aui-message .delete",
                dialogWidth: 540,
                dialogHeight: 160,
                success: function (data) {
                    updateAgentAvailabilityDescription();
                    editor.displayMessages([{ title: options.i18n.tasksDeleteSuccess }]);
                    $taskList.find(".active").remove();
                    editor.checkListHasItems();
                },
                cancel: null
            });

            $(function () {
                $taskSetupContainer = $(options.taskSetupContainer);
                $taskList = $(options.taskList);
                $taskConfigContainer = $(options.taskConfigContainer);
                $finalTasksBar = $taskList.find(".final-tasks-bar");

                options.defaultTaskToSelect && $taskList.find("#item-" + options.defaultTaskToSelect).click();
            });
        }
    }
}(jQuery);

BAMBOO.REPOSITORY = {};

BAMBOO.REPOSITORY.repositoryConfig = function ($) {
    var defaults = {
        addRepositoryTrigger: null,
        repositorySetupContainer: null,
        repositoryConfigContainer: null,
        repositoryList: null,
        templates: {
            repositoryListItem: null,
            iconTemplate: null
        },
        i18n: {
            cancel: "Cancel",
            confirmAbandonRepository: "The new Repository has not yet been saved. If you continue you will abandon the new Repository.\n\nAre you sure you want to continue?",
            repositoryAddSuccess: "Repository created successfully.",
            repositoryEditSuccess: "Repository updated successfully.",
            repositoryDeleteSuccess: "Repository deleted successfully.",
            sortingHasUnsavedRepositoryError: "Please save the new Repository before reordering.",
            defaultDisplayText: "No Repository Selected",
            defaultDisplayTextDescription: "Select a Repository from the list on the left to configure it.",
            repositoryMovingError: AJS.I18n.getText("There was a problem moving your repository."),
            repositoryMovingFailure: AJS.I18n.getText("Repository move failed")
        },
        moveRepositoryUrl: null
    },
    options,
    editor = new BAMBOO.ConfigPanelEditor(),
    $repositorySetupContainer,
    $repositoryConfigContainer,
    $repositoryList,
    $loadingIndicator,
    configFormSuccess = function (data, isUnsaved) {
        editor.displayMessages([{ title: (isUnsaved ? options.i18n.repositoryAddSuccess : options.i18n.repositoryEditSuccess) }]);
        return $(AJS.template.load(options.templates.repositoryListItem).fill({ name: data.repositoryResult.name, id: data.repositoryResult.id }).toString()).addClass("active");
    },
    addRepository = function (e) {
        var $addRepositoryTrigger = $(this),
            $repositoryListItem = $(AJS.template.load(options.templates.repositoryListItem).fill({ name: "New Repository", id: "" }).toString());

        e.preventDefault();

        if (!editor.isOkayToProceedWithUnsavedItem()) {
            editor.setFocus();
            return false;
        }

        if (!$loadingIndicator) {
            $loadingIndicator = $(AJS.template.load(options.templates.iconTemplate).fill({ type: "loading" }).toString()).insertAfter($addRepositoryTrigger.closest(".aui-toolbar"));
        } else {
            $loadingIndicator.show();
        }

        editor.add($addRepositoryTrigger.attr("href"), $repositoryListItem, "appendTo", $repositoryList).success(function () {
            $loadingIndicator.hide();
        });
    },
    moveRepository = function ($repositoryListItem) {
        return $.post(options.moveRepositoryUrl, {
            repositoryId: $repositoryListItem.data("item-id"),
            afterPosition: $repositoryListItem.nextAll(".item:first").data("item-id"),
            beforePosition: $repositoryListItem.prevAll(".item:first").data("item-id")
        }, "json");
    };

    return {
        init: function (opts) {
            options = $.extend(true, defaults, opts);

            editor.init({
                editor: options.repositorySetupContainer,
                configContainer: options.repositoryConfigContainer,
                itemList: options.repositoryList,
                deleteItemKey: "repositoryResult",
                configFormSuccess: configFormSuccess,
                templates: {
                    item: options.templates.repositoryListItem,
                    icon: options.templates.iconTemplate
                },
                i18n: {
                    confirmAbandonItem: options.i18n.confirmAbandonRepository,
                    itemDeleteSuccess: options.i18n.repositoryDeleteSuccess,
                    sortingHasUnsavedItemError: options.i18n.sortingHasUnsavedRepositoryError,
                    sortingHasUnspecifiedError: options.i18n.repositoryMovingError,
                    sortingErrorDialogHeader: options.i18n.repositoryMovingFailure,
                    defaultDisplayText: options.i18n.defaultDisplayText,
                    defaultDisplayTextDescription: options.i18n.defaultDisplayTextDescription
                },
                sortable: {
                    items: "> li:not(#repository-trigger-item)",
                    moveItem: moveRepository
                }
            });

            $(document).delegate(options.addRepositoryTrigger, "click", addRepository);

            $(function () {
                $repositorySetupContainer = $(options.repositorySetupContainer);
                $repositoryList = $(options.repositoryList);
                $repositoryConfigContainer = $(options.repositoryConfigContainer);

                editor.checkListHasItems();
            });
        }
    }
}(jQuery);


BAMBOO.REPOSITORY.buildStrategyToggle = function ($) {
    var defaults = {
        noVcsStrategyOptions : null,
        vcsStrategyOptions : null,
        strategyList: null
    },
    options,
    $strategyList,
    toggleStrategiesForCreate = function () {
        if (!$strategyList) {
            $strategyList = $(options.strategyList);
        }
        var value = $strategyList.val();
        $strategyList.attr("disabled", "disabled");
        if ($(this).val() == "nullRepository") {
            $strategyList.html(options.noVcsStrategyOptions);
        } else {
            $strategyList.html(options.vcsStrategyOptions);
        }
        $strategyList.removeAttr("disabled").val(value).change();
    };
    return {
        init: function (opts) {
            options = $.extend(true, defaults, opts);
            $(document).delegate("#selectedRepository", "change", toggleStrategiesForCreate);
        }
    }
}(jQuery);

BAMBOO.REPOSITORY.CheckoutTaskConfiguration = (function ($) {
    var defaults = {
            addCheckoutSelector: null,
            removeCheckoutSelector: '.toolbar-trigger',
            checkoutListSelector: null,
            checkoutDirectorySelector: null,
            selectedRepositorySelector: 'select[name^="selectedRepository_"]',
            templates: {
                checkoutListItem: null
            },
            i18n: {
                checkoutDirectoryInUse: null
            }
        },
        options,
        $list,
        $form,
        addCheckoutListItem = function () {
            var newIndex, $lastCheckout;

            $lastCheckout = $list.children(':last');
            newIndex = ($lastCheckout.length ? (parseInt($lastCheckout.attr('data-checkout-id'), 10) + 1) : 0);

            $(AJS.template.load(options.templates.checkoutListItem).fill({ index: newIndex }).toString())
                .hide().appendTo($list)
                .find(options.selectedRepositorySelector).change().end()
                .slideDown();
        },
        removeCheckoutListItem = function () {
            $(this).closest('.aui-toolbar').closest('li').slideUp(function () { $(this).remove(); });
        },
        validateForm = function (e) {
            var checkoutDirectories = {},
                hasError = false,
                checkField = function () {
                    var $field = $(this),
                        val = $field.val();

                    if (checkoutDirectories.hasOwnProperty(val)) {
                        $('<div/>', { 'class': 'error', text: options.i18n.checkoutDirectoryInUse }).insertAfter($field.next('.description'));
                        hasError = true;
                    } else {
                        checkoutDirectories[val] = true;
                    }
                },
                $trigger = $(this),
                $fieldsToCheck = $form.find(options.checkoutDirectorySelector);

            $form.find('.error').remove();

            if ($trigger.is(':text')) {
                $fieldsToCheck = $fieldsToCheck.not($trigger);
                $fieldsToCheck.each(checkField);
                checkField.apply(this);
            } else {
                $fieldsToCheck.each(checkField);
                if (hasError) {
                    e.preventDefault();
                    e.stopPropagation();
                }
            }
        };

    return {
        init: function (opts) {
            options = $.extend(true, defaults, opts);

            $(function () {
                $list = $(options.checkoutListSelector)
                            .delegate(options.removeCheckoutSelector, 'click', removeCheckoutListItem)
                            .delegate(options.checkoutDirectorySelector, 'blur', validateForm)
                            .delegate(options.selectedRepositorySelector, 'change', function () { handleOnSelectShowHide(this); });

                $form = $list.closest('form').submit(validateForm);
                $(options.addCheckoutSelector).click(addCheckoutListItem);
            });
        }
    };
})(jQuery);
(function ($) {
    var BAMBOO = window.BAMBOO || {};
    BAMBOO.LABELS = (function () {
        var defaults = {
                trigger: ".labels-edit",
                labelView: ".label-list, .label-none",
                labelsDialog: {
                    id: "labels-dialog",
                    header: null,
                    width: 550,
                    height: 235,
                    shortcutKey: "L"
                },
                i18n: {
                    close: "Close"
                },
                templates: {
                    iconTemplate: '<span class="icon icon-{type}"></span>',
                    shortcutKeyTemplate: null
                }
            },
            options,
            $loadingIndicator,
            dialog,
            setupDialogContent = function (html) {
                var $html = $(html);
                $loadingIndicator.hide();

                dialog.addPanel("All", $html).show();
            },
            showDialog = function (e) {
                e.preventDefault();
                var $trigger = $(this);

                if (!$loadingIndicator) {
                    $loadingIndicator = $(AJS.template(options.templates.iconTemplate).fill({ type: "loading" }).toString()).insertAfter($trigger);
                } else {
                    $loadingIndicator.show();
                }

                dialog = new AJS.Dialog({
                    id: options.labelsDialog.id,
                    width: options.labelsDialog.width,
                    height: options.labelsDialog.height,
                    keypressListener: function (e) {
                        if (e.which == jQuery.ui.keyCode.ESCAPE) {
                            dialog.remove();
                        }
                    }
                });

                dialog.addCancel(options.i18n.close, function () { dialog.remove(); })
                      .addHeader(options.labelsDialog.header)
                      .addHelpText(options.templates.shortcutKeyTemplate, { shortcut: options.labelsDialog.shortcutKey });

                $.ajax({
                    url: $trigger.attr("href"),
                    data: { decorator: 'rest', confirm: true },
                    success: setupDialogContent,
                    cache: false
                });
            },
            addLabels = function (e) {
                e.preventDefault();

                var $form = $(this),
                    $input = $form.find("input:text").attr("readonly", "readonly"),
                    $submit = $form.find("input:submit").attr("disabled", "disabled"),
                    $loading = $(AJS.template(options.templates.iconTemplate).fill({ type: "loading" }).toString()).insertAfter($submit);

                $.post($form.attr("action"), $form.serialize(), function (data) {
                    $form.find(".error,.aui-message").remove();
                    if (typeof data == "object") {
                        // Returned data is JSON
                        if (data.fieldErrors) {
                            for (var fieldName in data.fieldErrors) {
                                BAMBOO.addFieldErrors($form, fieldName, data.fieldErrors[fieldName]);
                            }
                        }
                        if (data.errors) {
                            $form.prepend(BAMBOO.buildAUIErrorMessage(data.errors));
                        }
                    } else {
                        // Returned data isn't JSON, assume it's HTML
                        $(options.labelView).replaceWith(data);
                        $form.find("input:text").val("");
                    }
                    $input.removeAttr("readonly");
                    $submit.removeAttr("disabled");
                    $loading.remove();
                    $form.find("input:text").focus();
                });
            },
            deleteLabel = function (e) {
                e.preventDefault();

                $.post(this.href, function (data) {
                    $(options.labelView).replaceWith(data);
                });
            };
        return {
            init: function (opts) {
                options = $.extend(true, defaults, opts);

                $(document).delegate(options.trigger, "click", showDialog)
                           .delegate("#" + options.labelsDialog.id + " form", "submit", addLabels)
                           .delegate("#" + options.labelsDialog.id + " .remove-label", "click", deleteLabel);

                $(function(){
                    AJS.whenIType(options.labelsDialog.shortcutKey).click(options.trigger);
                });
            }
        }
    })();
})(AJS.$);

/* Chain Log Tables */
(function ($) {
    var BAMBOO = window.BAMBOO || {};
    BAMBOO.LOGS = {};
    BAMBOO.LOGS.chainTableLiveView = (function () {
        var opts = {
            getBuildUrl: null,
            chainStatus: "",
            noLogsFound: 'No logs were found for this Job',
            templates: {
                logTableRow: null
            }
        },
        updateTimeout,
        update = function () {
            clearTimeout(updateTimeout);
            updateLogDisplay();

            //If build not finished update again in 5 seconds
            if (opts.chainStatus != "Finished" && opts.chainStatus != "NotBuilt") {
                updateTimeout = setTimeout(update, 5000);
            }
        },
        updateLogDisplay = function() {
            $(".chain-logs-table > tbody > tr > .code table").each(function() {
                var $logContainer = $(this),
                    $tr = $logContainer.closest("tr").prev();

                if ($tr.hasClass("expanded")) {
                    updateSingleLog($tr.prev().find(".twixie > span"));
                }
            });
        },
        updateSingleLog = function ($twixie) {
            var $tr = $twixie.closest("tr"),
                $stack = $tr.next(),
                $logContainer = $stack.find("table"),
                $loading = $('<span />', { 'class': 'icon icon-loading' });

            if ($logContainer.data('dontUpdate')) {
                return;
            }
            $twixie.hide().before($loading);

            $.ajax({
                url: opts.getBuildUrl.replace("@KEY@", $logContainer.attr("id")),
                data: {
                    expand: 'logEntries[-' + 25 + ':]',
                    'max-results': 25
                },
                dataType: "json",
                contentType: "application/json",
                cache: false,
                success: function (buildResult) {
                    var newLogBody = '';

                    if (buildResult.lifeCycleState == "Finished" || buildResult.lifeCycleState == "NotBuilt") {
                        //if build result is finished there will be no more log changes
                        $logContainer.data('dontUpdate', true);
                    }
                    if (buildResult.logEntries && typeof(buildResult.logEntries.logEntry) != "undefined") {
                        for (var i = 0, ii = buildResult.logEntries.logEntry.length; i < ii; i++) {
                            var logEntry = buildResult.logEntries.logEntry[i];

                            newLogBody += AJS.template.load(opts.templates.logTableRow)
                                .fill({ time: logEntry.formattedDate })
                                .fillHtml({ log: logEntry.log }).toString();
                        }
                    }

                    if ($.trim(newLogBody).length) {
                        $logContainer.html(newLogBody);
                    } else {
                        $logContainer.html(AJS.template.load(opts.templates.logTableRow)
                            .fill({time : ''})
                            .fillHtml({ log: opts.noLogsFound }).toString());
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    // Error occurred when doing the update, try again in 30 sec
                    $logContainer.html(opts.noLogsFound);
                },
                complete: function (jqXHR, textStatus) {
                    $loading.remove();
                    $twixie.show();
                }
            });
        };

        return {
            init: function(options) {
                var twixieSelector = ".chain-logs-table > tbody > tr > .twixie > span",
                    twixieAllSelector = ".chain-logs-table > thead > tr > .twixie span[role]";

                $.extend(true, opts, options);

                $(document)
                    .undelegate(twixieSelector, "click")
                    .delegate(twixieSelector, "click", function (e) {
                        var $twixie = $(this),
                                $tr = $twixie.closest("tr"),
                                $stack = $tr.next(),
                                newTwixieText = !$twixie.hasClass("icon-collapse") ? "Collapse" : "Expand"; //negated because we toggle the class later

                        $stack[$tr.hasClass("collapsed") ? "show" : "hide"]();
                        $tr.toggleClass("collapsed expanded");
                        $twixie.toggleClass("icon-collapse icon-expand").attr("title", newTwixieText).html("<span>" + newTwixieText + "</span>");
                        if ($tr.hasClass("expanded")) {
                            updateSingleLog($twixie);
                        }
                    })
                    .undelegate(twixieAllSelector, "click")
                    .delegate(twixieAllSelector, "click", function (e) {
                        var $trigger = $(this),
                                $li = $trigger.closest("li"),
                                $table = $trigger.closest("table");

                        if ($li.hasClass("expand-all")) {
                            $table.find("tbody > .collapsed .twixie > span").click();
                        } else if ($li.hasClass("collapse-all")) {
                            $table.find("tbody > .expanded .twixie > span").click();
                        }
                    });

                update();
            }
        }
    })();
})(jQuery);

(function($) {
    var BAMBOO = window.BAMBOO || {};
    BAMBOO.STAGES = {};
    BAMBOO.STAGES.manualStagesSelection = (function () {
        return {
            init: function() {
               $("#stageContainer").delegate("input:checkbox", "click", function(e) {
                    var $checkbox = $(this),
                        checked = $checkbox.is(":checked"),
                        $selectedStage = $("#selectedStage"),
                        prevManualFound = false;

                    if (checked) {
                        $selectedStage.val($checkbox.val());
                    } else {
                        $selectedStage.val("");
                    }

                    $checkbox.closest(".checkbox").toggleClass("selected", checked).prevAll(".checkbox").each(
                        function (i) {
                            var $checkboxContainer = $(this),
                                    $checkbox = $checkboxContainer.children("input:checkbox"),
                                    isManual = $checkboxContainer.hasClass("manual");
                            if (checked) {
                                $checkboxContainer.addClass("selected");
                                if (isManual) {
                                    $checkbox.attr("checked", "checked").attr("disabled", "disabled");
                                }
                            } else {
                                if (isManual && !prevManualFound) {
                                    $selectedStage.val($checkbox.val());
                                    $checkbox.removeAttr("disabled");
                                    prevManualFound = true;
                                }
                            }
                        }).end().nextAll(".checkbox").each(function (i) {
                                                               var $checkboxContainer = $(this);
                                                               if ($checkboxContainer.hasClass("manual")) {
                                                                   return false; // breaks the loop
                                                               }  else {
                                                                   $checkboxContainer.toggleClass("selected", checked);
                                                               }
                                                           });
                });
            }
        }
    })();
})(jQuery);

(function ($) {
    var BAMBOO = window.BAMBOO || {};
    BAMBOO.JIRAISSUES = (function () {
        var opts = {
            resultSummaryKey: null,
            getIssuesUrl: null,
        currentFullUrl: null,
            defaultIssueIconUrl: null,
            defaultIssueType: null,
            defaultIssueDetails: null,
            templates: {
                jiraIssueTemplate: null,
                jiraIssueNoConnectionTemplate: null,
                authenticationRequiredTemplate: null
            }
        };
        return {
            /**
             * @param options - Object containing the options to overwrite our defaults
             */
            init: function (options) {
                    $.extend(true, opts, options);
                    AJS.$(function () {
                        var $issuesPanel = $(".issueSummary");
                        $.ajax({
                            url: opts.getIssuesUrl + opts.resultSummaryKey,
                            data: {
                            expand: "jiraIssues[0:1]",
                            returnUrl: opts.currentFullUrl
                            },
                            dataType: "json",
                            contentType: "application/json",
                            success: function (json) {
                                var issues = "";
                                if (json.jiraIssues && json.jiraIssues.issue && json.jiraIssues.issue.length) {
                                    $.each(json.jiraIssues.issue, function () {
                                        if (this.url && this.url.href && this.key && this.summary) {
                                            issues += AJS.template.load(opts.templates.jiraIssueTemplate).fill({
                                                url: this.url.href,
                                                issueType: (this.issueType ? this.issueType : opts.defaultIssueType),
                                                issueIconUrl: (this.iconUrl ? this.iconUrl : opts.defaultIssueIconUrl),
                                                key: this.key,
                                                details: this.summary
                                            }).toString();
                                        } else {
                                            issues += AJS.template.load(opts.templates.jiraIssueNoConnectionTemplate).fill({
                                                    key: this.key
                                                }).toString();
                                        }
                                    });
                                }
                                $issuesPanel.find("> div.loading-indicator").remove();
                                if (!issues.length) {
                                    $issuesPanel.hide();
                                } else {
                                    $issuesPanel.find("> ul").html(issues);
                                    $issuesPanel.show();
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                var response = $.parseJSON(XMLHttpRequest.responseText);
                                $issuesPanel.find("> ul > li, > p.moreLink, > div.toolbar > a").remove();
                                if (response.authenticationRedirectUrl) {
                                    $issuesPanel.append(AJS.template.load(opts.templates.authenticationRequiredTemplate).fill({authenticationUrl: response.authenticationRedirectUrl}).toString());
                                }
                            }
                        });
                    });
                }
        }
    })();
})(AJS.$);

(function ($) {
    var jiraTeaserPopup,
        dialogOptions = {
            width: 420,
            hideDelay: 36e5
        },
        generatePopup = function ($contents, trigger, doShowPopup) {
            // hide popup hooks
            var doHidePopup = function () {
                jiraTeaserPopup.hide();
                return false;
            };

            $(document).keyup(function (e) {
                if (e.which == jQuery.ui.keyCode.ESCAPE) {
                    doHidePopup();
                    $(document).unbind("keyup", arguments.callee);
                    return false;
                }
                return true;
            });

            // replace container contents with teaser
            $contents
                .html(AJS.template.load("jira-teaser-popup").fill())
                .find(".close-dialog").click(doHidePopup).end()
                .find(".jiraTeaserCheckbox").change(function (e) {
                    var val = $(this).is(":checked");
                    $.ajax({
                        url: BAMBOO.contextPath + "/rest/pref/latest/user",
                        type: "post",
                        data: {
                            "bamboo.user.jira.teaser.hide" : val
                        }
                    });
                });
            
            doShowPopup();
        };

    AJS.toInit(function ($) {
        if ($("#jira-teaser-template").length) {
            jiraTeaserPopup = AJS.InlineDialog($("#changesSummary .jiraIssueLink:last"), "jiraChangesSummary", generatePopup, dialogOptions);
            jiraTeaserPopup.show();
        }
    });
})(AJS.$);

var JiraIssueLinkManager = (function ($) {
    var globalBambooProjectKey,
        addLink = function () {
            var $this = $(this),
                jiraIssueKey = $this.data("issue-key"),
                bambooProjectKey = $this.data("bamboo-project-key") || globalBambooProjectKey,
                href = BAMBOO.contextPath + "/project/jiraRedirect.action?jiraIssueKey=" + jiraIssueKey;

            if (bambooProjectKey) {
                href += "&bambooProjectKey=" + bambooProjectKey;
            }
            $this.attr("href", href);
        };

    return {
        init: function (bambooProjectKey) {
            globalBambooProjectKey = bambooProjectKey;
            $(function () {
                $("a.jiraIssueLink").each(addLink);
           });
        }
    };
})(AJS.$);

/**
 * Inline Editing
 * @param options
 *  - target        String - selector targeting the span/element to make inline-editable
 *  - submit        Function - handles what to do when value is submitted
 *  - cancel        Function - handles what to do when cancel is triggered
 *  - focus         Function - handles what to do when focus is given to the edit field
 *  - $delegator    jQuery Object - where the event handler should be bound
 */
BAMBOO.inlineEdit = function (options) {
    var $ = AJS.$,
        defaults = {
            target: null,
            submit: null,
            cancel: null,
            focus: null,
            $delegator: $(document)
        },
        revertField = function (e) {
            var $input = $(e.currentTarget),
                $target = $input.prev(".inline-edit-view"),
                lastValidValue = $input.data("lastValidValue");

            $input.val(lastValidValue);
            $target.text(lastValidValue);
        },
        handleEdit = function (e) {
            var $target = $(this),
                $input = $target.next("input.inline-edit-field");

            if (!$input.length) {
                $input = $("<input/>", {
                    "type": "text",
                    "class": "inline-edit-field text",
                    "autocomplete": "off",
                    "keydown": handleKeyDown,
                    "blur": handleBlur,
                    "val": $target.text(),
                    "data": { hasInlineEditHandlers: true, lastValidValue: $target.text() }
                }).insertAfter($target);
            }
            if (!$input.data("hasInlineEditHandlers")) {
                $input.keydown(handleKeyDown).blur(handleBlur).data("hasInlineEditHandlers", true).data("lastValidValue", $input.val());
            }
            $input.addClass("focus");
            $target.hide();
            $input.show().focus();
            if ($.isFunction(options.focus)) {
                options.focus(e);
            }
        },
        handleKeyDown = function (e) {
            var keyCode = e.which;

            if (keyCode == $.ui.keyCode.ESCAPE) {
                revertField(e);
                $(e.currentTarget).blur();
            } else if (keyCode == $.ui.keyCode.ENTER) {
                e.preventDefault();
                $(e.currentTarget).blur();
            }
        },
        handleBlur = function (e) {
            var $input = $(e.currentTarget),
                $target = $input.prev(".inline-edit-view"),
                inputVal = $input.val(),
                targetText = $target.text();

            if (targetText != inputVal) {
                $target.text(inputVal);
                $input.hide().removeClass("focus");
                $target.show();
                if ($.isFunction(options.submit)) {
                    options.submit(e);
                }
            } else {
                $input.hide().removeClass("focus");
                $target.show();
                if ($.isFunction(options.cancel)) {
                    options.cancel(e);
                }
            }
        };

    options = $.extend(true, defaults, options);

    if (options.target) {
        options.$delegator.delegate(options.target, "click focus", handleEdit);
    }
};


/**
 * ConfigureVariables screen (both global and chain)
 */
BAMBOO.ConfigureVariables = function ($) {
    var opts = {
            target: null,
            updateVariableUrl: null,
            $loadingIndicator: $("<span/>", { "class": "icon icon-loading" })
        },
        $container,
        $addVariable,
        clearAllErrors = function () {
            $container.find('.error,.aui-message').remove();
        },
        clearFieldErrors = function ($field) {
            $field.nextAll(".error").remove();
        },
        createNewVariable = function (e) {
            e.preventDefault();
            clearAllErrors();
            $.post($container.attr("action"), $addVariable.find(":input").serialize() + "&bamboo.successReturnMode=json&decorator=rest&confirm=true", function (result) {
                if (result.status.toUpperCase() == "OK") {
                    window.location.reload();
                } else if (result.status.toUpperCase() == "ERROR") {
                    if (result.fieldErrors) {
                        for (var fieldName in result.fieldErrors) {
                            $addVariable.find("input[name='" + fieldName + "']").after(BAMBOO.buildFieldError(result.fieldErrors[fieldName]));
                        }
                    }
                    if (result.errors) {
                        $container.prepend(BAMBOO.buildAUIErrorMessage(result.errors));
                    }
                    var $firstError = $addVariable.find(":input:visible:enabled.errorField:first").focus();
                    if (!$firstError.length) {
                        $addVariable.find(":input:visible:enabled:first").focus();
                    }
                }
            });
        },
        deleteVariable = function (e) {
            var $this = $(this),
                id = BAMBOO.stripPrefixFromId('deleteVariable_', $this.attr("id"));

            e.preventDefault();
            $.post($this.attr("href"), { 'bamboo.successReturnMode': 'json', decorator: 'rest', confirm: true }, function (result) {
                if (result.status.toUpperCase() == "OK") {
                    $this.closest("tr").remove();
                }
            });
        },
        handleEditSubmit = function (e) {
            var $input = $(e.currentTarget),
                $loading = opts.$loadingIndicator.clone(),
                name = $input.attr("name"),
                id, $key, $value;

            if (name.indexOf('key_') == 0) {
                id = BAMBOO.stripPrefixFromId('key_', name);
                $key = $input;
                $value = $container.find("input:text[name='value_" + id + "']");
            } else if (name.indexOf('value_') == 0) {
                id = BAMBOO.stripPrefixFromId('value_', name);
                $key = $container.find("input:text[name='key_" + id + "']");
                $value = $input;
            }
            if (id && $key && $value) {
                $loading.insertAfter($input[0]);
                clearFieldErrors($input);
                $.post(opts.updateVariableUrl, {
                    variableId: id,
                    variableKey: $key.val(),
                    variableValue: $value.val(),
                    "bamboo.successReturnMode": "json",
                    decorator: 'rest',
                    confirm: true
                }, function (result) {
                    $loading.remove();
                    var $tr = $input.closest("tr");
                    if (!$tr.find(".focus").length) {
                        $tr.removeClass("active");
                    }
                    if (result.status.toUpperCase() == "OK") {
                        $input.data("lastValidValue", $input.val());
                        if (!$container.find(".focus").length) {
                            $addVariable.removeClass("inactive").find("input").removeAttr("disabled");
                        }
                    } else if (result.status.toUpperCase() == "ERROR") {
                        if (result.fieldErrors) {
                            for (var fieldName in result.fieldErrors) {
                                var $field = (fieldName == "variableValue" ? $value : $key);
                                clearFieldErrors($field);
                                $field.after(BAMBOO.buildFieldError(result.fieldErrors[fieldName]));
                            }
                        }
                        if (result.errors) {
                            $key.after(BAMBOO.buildAUIErrorMessage(result.errors));
                        }
                    }
                });
            }
        },
        handleEditFocus = function (e) {
            $(e.currentTarget).closest("tr").addClass("active");
            $addVariable.addClass("inactive");
        },
        handleEditCancel = function (e) {
            clearFieldErrors($(e.currentTarget).closest("tr").removeClass("active").end());
            $addVariable.removeClass("inactive");
        };
    return {
        init: function (options) {
            $.extend(true, opts, options);

            $(function () {
                $container = $(opts.target).submit(createNewVariable);
                $addVariable = $("#addVariable");
                $container.delegate("a.deleteVariable", "click", deleteVariable);
                BAMBOO.inlineEdit({
                    target: ".inline-edit-view",
                    $delegator: $container,
                    submit: handleEditSubmit,
                    focus: handleEditFocus,
                    cancel: handleEditCancel
                });
            });
        }
    }
}(AJS.$);
(function (window, undefined) {
    var History = window.History,
        $ = window.jQuery,
        document = window.document;

    if (!History.enabled) {
        return false;
    }

    $(function () {
        var $tabsContainer = $('.aui-tabs.aui-tabs-disabled'),
            $content = $tabsContainer.children('.tabs-pane').filter(':first'),
            $planNavigator = $('#plan-navigator'),
            $plan,
            $jobs,
            planKey,
            activeJobKey,
            request,
            contextPath = AJS.contextPath() || '';

        // If not a tabbed page don't do any history manipulation
        if (!$tabsContainer.length || $tabsContainer.hasClass('history-xhr-disabled')) {
            return false;
        }

        // Get active tab on page load and store that data against this history entry
        History.replaceState({ tabId: BAMBOO.escapeIdToJQuerySelector($tabsContainer.find('> .tabs-menu > .menu-item.active-tab > a').attr('id')) }, document.title, null);

        if ($planNavigator.length) {
            $plan = $planNavigator.find('h3');
            planKey = $plan.attr('data-plan-key');
            $jobs = $planNavigator.find('ul ul > li');
            activeJobKey = $jobs.filter('.active').attr('data-job-key');
        }

        $tabsContainer.children('.tabs-menu').find('a').click(function (e) {
            var $this = $(this),
                url = $this.attr('href'),
                title = $this.attr('title') || null;

            // Continue as normal for cmd clicks etc
            if (e.which == 2 || e.metaKey) { return true; }

            History.pushState({ tabId: BAMBOO.escapeIdToJQuerySelector($this.attr('id')) }, title, url);
            e.preventDefault();
        });

        $(window).bind('statechange', function () {
            var State = History.getState(),
                url = State.url,
                tabId = State.data.tabId,
                $tab = $('#' + tabId);

            if (request && request.readyState < 4) {
                request.abort();
            }

            $tabsContainer.addClass('loading');
            $tab.parent().addClass('active-tab').siblings().removeClass('active-tab');

            if ($planNavigator.length) {
                // Update urls in plan navigator
                if (activeJobKey) {
                    // Update job urls
                    $jobs.each(function () {
                        var $li = $(this),
                            $a = $li.children('a').last(),
                            jobKey = $li.attr('data-job-key');

                        $a.attr('href', (jobKey == activeJobKey ? url : url.replace(activeJobKey, jobKey)));
                    });
                } else {
                    // Update plan url
                    $plan.children('a').attr('href', url);
                }
            }
            
            request = $.ajax({
                cache: false,
                url: url,
                beforeSend: function (jqXHR) {
                    jqXHR.setRequestHeader('X-History-XHR', true);
                },
                success: function (data, textStatus, jqXHR) {
                    var title, planURL, jobURL;

                    // If no data is returned, or an entire web page, go directly to that page for normal error handling
                    if (!$.trim(data) || /<html/i.test(data)) {
                        return window.location = url;
                    }

                    $content.html(data);

                    title = jqXHR.getResponseHeader('X-Page-Title') || $.trim($content.find('title,.document-title').remove().filter(':first').text());
                    if (title) {
                        document.title = title;
                        try {
                            document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ');
                        }
                        catch ( Exception ) { }
                    }

                    planURL = jqXHR.getResponseHeader('X-Plan-URL');
                    jobURL = jqXHR.getResponseHeader('X-Job-URL');
                    if ($planNavigator.length) {
                        if (activeJobKey && planURL) {
                            // Update plan url (url is returned with current job key, replace it with the plan key)
                            $plan.children('a').attr('href', contextPath + planURL.replace(activeJobKey, planKey));
                        } else if (!activeJobKey && jobURL) {
                            // Update job urls (url is returned with plan key, replace it with the appropriate job key)
                            $jobs.each(function () {
                                var $li = $(this),
                                    $a = $li.children('a').last(),
                                    jobKey = $li.attr('data-job-key');

                                $a.attr('href', contextPath + jobURL.replace(planKey, jobKey));
                            });
                        }
                    }

                    $tabsContainer.removeClass('loading');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (textStatus != 'abort') {
                        return window.location = url;
                    }
                }
            });
        });
    });
})(window);

// Inspired by base2 and Prototype
(function(){

begetObject = function (obj)
{
    var f = function()
    {};
    f.prototype = obj;
    return new f();
};
    

  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function() {

      var prop;

      var _super = this.prototype;

    if (arguments.length > 1) {

        var interfaces = AJS.$.makeArray(arguments);

        prop = interfaces.pop();

        var completeInterface;

        AJS.$.each(interfaces, function (i, inter) {
            if (completeInterface) {
                completeInterface = completeInterface.extend(inter);
            } else {
                completeInterface = inter;
            }
        });

        return completeInterface.extend(this.prototype).extend(prop);

    } else {
        prop = arguments[0];
    }


    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function

        if (prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name])) {
            prototype[name] = (function(name, fn){
              return function() {
                var tmp = this._super;

                // Add a new ._super() method that is the same method
                // but on the super-class
                this._super = _super[name];

                // The method only need to be bound temporarily, so we
                // remove it when we're done executing
                var ret = fn.apply(this, arguments);
                this._super = tmp;

                return ret;
              };
            })(name, prop[name]);
        } else if (typeof _super[name] === "object") {
            var newObj = begetObject(prop[name]);

            AJS.$.each(_super[name], function (name, obj) {
                if (!newObj[name]) {
                    newObj[name] = obj;
                } else if (typeof newObj[name] === "object") {
                    var newSubObj = begetObject(newObj[name]);
                    AJS.$.each(obj, function (subName, subObj) {
                        if (!newSubObj[subName]) {
                            newSubObj[subName] = subObj;
                        }
                    });
                    newObj[name] = newSubObj;
                }
            });

            prototype[name] = newObj;
        } else {
            prototype[name] = prop[name];
        }
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

var Interface = Class.extend({});
/**
 * Ajax autocomplete
 *
 * @module jira.widget.autocomplete
 * @author Scott Harwood
 * @requires jQuery > v1.2, jira.widget.fauxSelect
 * @since 4.0
 *
 */


jQuery.namespace("jira.widget.autocomplete");

/**
 * Designed for prototypial inheritance !!Abstract only
 * @abstract autocomplete
 */
jira.widget.autocomplete = function() {

    var inFocus;

    /**
     * Calls a callback after specified delay
     * @method {private} delay
     * @param {Number} l - length of delay in <em>seconds</em>
     * @param {Function} callback - function to call after delay
     */
    var delay = function(callback,l) {
        if (delay.t) {
            clearTimeout(delay.t);
            delay.t = undefined;
        }
        delay.t = setTimeout(callback, l * 1000);
    };

    var INVALID_KEYS = {
          9: true,
         13: true,
         14: true,
         25: true,
         27: true,
         38: true,
         40: true,
        224: true
    };

    return {

        /**
        * Checks whether a saved version (cached) of the request exists, if not performs a request and saves response,
        * then dispatches saved response to <em>renderSuggestions</em> method.
        *
        * @method {public} dispatcher
        */
        dispatcher: function() {},


        /**
         * Gets cached response
         *
         * @method {public} getSavedResponse
         * @param {String} val
         * @returns {Object}
         */
        getSavedResponse: function() {},

        /**
         * Saves response
         *
         * @method {public} saveResponse
         * @param {String} val
         * @param {Object} response
         */
        saveResponse: function() {},

        /**
         * Called to render suggestions. Used to define interface only.
         * Rendering is difficult to make generic, best to leave this to extending prototypes.
         *
         * @method {public} renderSuggestions
         * @param {Object} res - results object
         */
        renderSuggestions: function() {},

        /**
         * Disables autocomplete. Useful for shared inputs.
         * i.e The selection of a radio button may disable the instance
         * @method {Public} disable
         */
        disable: function() {
            this.disabled = true;
        },

        /**
         * Enables autocomplete. Useful for shared inputs.
         * i.e The selection of a radio button may disable the instance
         * @method {Public} enable
         */
        enable: function() {
            this.disabled = false;
        },

        /**
         * Sets instance variables from options object
         * to do: make function create getters and setters
         * @method {public} set
         * @param {Object} options
         */
        set: function(options) {
            for (var name in options) {
                // safeguard to stop looping up the inheritance chain
                if (options.hasOwnProperty(name)) {
                    this[name] = options[name];
                }
            }
        },

        /**
         * Adds value to input field
         * @method {public} completeField
         * @param {String} value
         */
        completeField: function(value) {
            if (value) {
                this.field.val(value).focus();
            }
        },

        /**
         * Returns the text from the start of the field up to the end of
         * the position where suggestions are generated from.
         */
        textToSuggestionCursorPosition: function () {
            return this.field.val();
        },


        /**
         * Allows users to navigate/select suggestions using the keyboard
         * @method {public} addSuggestionControls
         */
         addSuggestionControls: function(suggestionNodes) {

            // reference to this for closures
            var that = this;

            /**
             * Make sure the index is within the threshold
             * Looks ugly! Has to be a better way.
             * @method {private} evaluateIndex
             * @param {Integer} idx
             * @param {Integer} max
             * @return {Integer} valid threshold
             */
            var evaluateIndex = function(idx, max) {
                var minBoundary = (that.autoSelectFirst === false) ? -1 : 0;
                if (that.allowArrowCarousel) {
                    if (idx > max) {
                        return minBoundary;
                    } else if (idx < minBoundary) {
                        return max;
                    } else {
                        return idx;
                    }
                }
                else {
                    if (idx > max) {
                        return max;
                    } else if (idx < minBoundary) {
                        that.responseContainer.scrollTop(0);
                        return minBoundary;
                    } else {
                        return idx;
                    }
                }
            };

            /**
             * Highlights focused node and removes highlight from previous.
             * Actual highlight styles to come from css, adding and removing classes here.
             * @method {private} setActive
             * @param {Integer} idx - Index of node to be highlighted
             */
            var setActive = function(idx) {

                    // if nothing is selected, select the first suggestion
                    if (that.selectedIndex !== undefined && that.selectedIndex > -1) {
                        that.suggestionNodes[that.selectedIndex][0].removeClass("active");
                    }
                    that.selectedIndex = evaluateIndex(idx, that.suggestionNodes.length-1);
                    if (that.selectedIndex > -1) {
                        that.suggestionNodes[that.selectedIndex][0].addClass("active");
                    }
            };

             /**
              * Checks to see if there is actually a suggestion in focus before attempting to use it
              * @method {private} evaluateIfActive
              * @returns {boolean}
              */
             var evaluateIfActive = function() {
                return that.suggestionNodes && that.suggestionNodes[that.selectedIndex] &&
                       that.suggestionNodes[that.selectedIndex][0].hasClass("active");
             };


            /**
             * When the responseContainer (dropdown) is visible listen for keyboard events
             * that represent focus or selection.
             * @method {private} keyPressHandler
             * @param {Object} e - event object
             */
            var keyPressHandler = function(e) {
                // only use keyboard events if dropdown is visible
                if (that.responseContainer.is(":visible")) {
                    // if enter key is pressed check that there is a node selected, then hide dropdown and complete field
                    if (e.keyCode === 13) {
                        if (evaluateIfActive() && !that.pendingRequest) {
                            that.completeField(that.suggestionNodes[that.selectedIndex][1]);
                        }
                        e.preventDefault();
                    }
                }
            };

            /**
            * sets focus on suggestion nodes using the "up" and "down" arrows
            * These events need to be fired on mouseup as modifier keys don't register on keypress
            * @method {private} keyUpHandler
            * @param {Object} e - event object
            */
            var keyboardNavigateHandler = function(e) {

                // only use keyboard events if dropdown is visible
                if (that.responseContainer.is(":visible")) {

                    // keep cursor inside input field
                    if (that.field[0] !== document.activeElement){
                        that.field.focus();
                    }
                    // move selection down when down arrow is pressed
                    if (e.keyCode === 40) {
                        setActive(that.selectedIndex + 1);
                        if (that.selectedIndex >= 0) {
                            // move selection up when up arrow is pressed
                            var containerHeight = that.responseContainer.height();
                            var bottom = that.suggestionNodes[that.selectedIndex][0].position().top + that.suggestionNodes[that.selectedIndex][0].outerHeight() ;

                            if (bottom - containerHeight > 0){
                                that.responseContainer.scrollTop(that.responseContainer.scrollTop() + bottom - containerHeight + 2);
                            }
                        } else {
                            that.responseContainer.scrollTop(0);
                        }
                        e.preventDefault();
                    } else if (e.keyCode === 38) {
                        setActive(that.selectedIndex-1);
                        if (that.selectedIndex >= 0) {
                            // if tab key is pressed check that there is a node selected, then hide dropdown and complete field
                            var top = that.suggestionNodes[that.selectedIndex][0].position().top;
                            if (top < 0){
                                that.responseContainer.scrollTop(that.responseContainer.scrollTop() + top - 2);
                            }
                        }
                        e.preventDefault();
                    } else if (e.keyCode === 9) {
                        if (evaluateIfActive()) {
                            that.completeField(that.suggestionNodes[that.selectedIndex][1]);
                            e.preventDefault();
                        } else {
                            that.dropdownController.hideDropdown();
                        }
                    }
                }
            };

            if (suggestionNodes.length) {

                this.selectedIndex = 0;
                this.suggestionNodes = suggestionNodes;

                for (var i=0; i < that.suggestionNodes.length; i++) {
                    var eventData = { instance: this, index: i };
                    this.suggestionNodes[i][0]
                        .bind("mouseover", eventData, activate)
                        .bind("mouseout", eventData, deactivate)
                        .bind("click", eventData, complete);
                }

                // make sure we don't bind more than once
                if (!this.keyboardHandlerBinded) {
                    jQuery(this.field).keypress(keyPressHandler);
                    if (jQuery.browser.mozilla) {
                        jQuery(this.field).keypress(keyboardNavigateHandler);
                    } else {
                        jQuery(this.field).keydown(keyboardNavigateHandler);
                    }
                    this.keyboardHandlerBinded = true;
                }

                // automatically select the first in the list
                if(that.autoSelectFirst === false) {
                    setActive(-1);
                } else {
                    setActive(0);
                }

                // sets the autocomplete singleton infocus var to this instance
                // is used to toggle event propagation. In short, the instance that it is set to will not hide the
                // dropdown each time you click the input field
                inFocus = this;
            }

            function activate(event) {
                if (that.dropdownController.displayed) {
                    setActive(event.data.index);
                }
            }
            function deactivate(event) {
                if (event.data.index === 0) {
                    that.selectedIndex = -1;
                }
                jQuery(this).removeClass("active");
            }
            function complete(event) {
                that.completeField(that.suggestionNodes[event.data.index][1]);
            }
        },


        /**
         * Uses jquery empty command, this is VERY important as it unassigns handlers
         * used for mouseover, click events which expose an opportunity for memory leaks
         * @method {public} clearResponseContainer
         */
        clearResponseContainer: function() {
            this.responseContainer.empty();
            this.suggestionNodes = undefined;
        },

        /**
         * function {Privileged} delay
         * @param response
         */
        delay: delay,

        /**
         * Builds HTML container for suggestions.
         * Positions container top position to be that of the field height
         * @method {public} buildResponseContainer
         */
        buildResponseContainer: function() {
            var inputParent = this.field.parent().addClass('atlassian-autocomplete');
            this.responseContainer = jQuery(document.createElement("div"));
            this.responseContainer
                .addClass("suggestions")
                .css({top: this.field.outerHeight() + "px"})
                .appendTo(inputParent);
        },

        /**
         * Validates the keypress by making sure the field value is beyond the set threshold and the key was either an
         * up or down arrow
         * @method {public} keyUpHandler
         * @param {Object} e - event object
         */
        keyUpHandler: (function () {
            var isIe8 = jQuery.browser.msie && jQuery.browser.version == 8;
            function callback() {
                if (!this.responseContainer) {
                    this.buildResponseContainer();
                }
                // send value to dispatcher to check if we have already got the response or if we need to go
                // back to the server
                this.dispatcher(this.field.val());
            }

            return function (e) {
                // only initialises once the field length is past set length
                if (this.field.val().length >= this.minQueryLength) {
                    // don't do anything if the key pressed is "enter" or "down" or "up" or "right" "left"
                    if (!(e.keyCode in INVALID_KEYS) || (this.responseContainer && !this.responseContainer.is(":visible") && (e.keyCode == 38 || e.keyCode == 40))) {
                        if (isIe8) {
                            // Performance workaround for IE8 (but not IE7): excessive DOM manipulation (JRADEV-3142)
                            delay(jQuery.proxy(callback, this), 0.200);
                        } else {
                            callback.call(this);
                        }
                    }
                }
                return e;
            };
        })(),

        /**
         * Adds in methods via AOP to handle multiple selections
         * @method {Public} addMultiSelectAdvice
         */
        addMultiSelectAdvice: function(delim) {

            // reference to this for closures
            var that = this;

            /**
             * Alerts user if value already exists
             * @method {private} alertUserValueAlreadyExists
             * @param {String} val - value that already exists, will be displayed in message to user.
             */
            var alertUserValueAlreadyExists = function(val) {

                // check if there is an existing alert before adding another
                if (!alertUserValueAlreadyExists.isAlerting) {

                    alertUserValueAlreadyExists.isAlerting = true;

                    // create alert node and append it to the input field's parent, fade it in then out with a short
                    // delay in between.
                    //TODO: JRA-1800 - Needs i18n!  
                    var userAlert = jQuery(document.createElement("div"))
                    .css({"float": "left", display: "none"})
                    .addClass("warningBox")
                    .html("Oops! You have already entered the value <em>" + val + "</em>" )
                    .appendTo(that.field.parent())
                    .show("fast", function(){
                        // display message for 4 seconds before fading out
                        that.delay(function(){
                            userAlert.hide("fast",function(){
                                // removes element from dom
                                userAlert.remove();
                                alertUserValueAlreadyExists.isAlerting = false;
                            });
                        }, 4);
                    });
                }
            };

          // rather than request the entire field return the last comma seperated value
            jQuery.aop.before({target: this, method: "dispatcher"}, function(innvocation){
                // matches everything after last comma
                var val = this.field.val();
                innvocation[0] = jQuery.trim(val.slice(val.lastIndexOf(delim) + 1));
                return innvocation;
            });

            // rather than replacing this field just append the new value
            jQuery.aop.before({target: this, method: "completeField"}, function(args){
                var valueToAdd = args[0],
                // create array of values
                untrimmedVals = this.field.val().split(delim);
                // trim the values in the array so we avoid extra spaces being appended to the usernames - see JRA-20657
                var trimmedVals = jQuery(untrimmedVals).map(function() {
                        return jQuery.trim(this);
                   }).get();
                // check if the value to append already exists. If it does then call alert to to tell user and sets
                // the last value to "". The value to add will either appear:
                // 1) at the start of the string
                // 2) after some whitespace; or
                // 3) directly after the delimiter
                // It is assumed that the value is delimited by the delimiter character surrounded by any number of spaces.
                if (!this.allowDuplicates && new RegExp("(?:^|[\\s" + delim + "])" + valueToAdd + "\\s*" + delim).test(this.field.val())) {
                    alertUserValueAlreadyExists(valueToAdd);
                    trimmedVals[trimmedVals.length-1] = "";
                } else {
                    // add the new value to the end of the array and then an empty value so we
                    // can get an extra delimiter at the end of the joined string
                    trimmedVals[trimmedVals.length-1] = valueToAdd;
                    trimmedVals[trimmedVals.length] = "";
                }

                // join the array of values with the delimiter plus an extra space to make the list of values readable
                args[0] = trimmedVals.join(delim.replace(/([^\s]$)/,"$1 "));

                return args;
            });
        },


        /**
         * Adds and manages state of dropdown control
         * @method {Public} addDropdownAdvice
         */
        addDropdownAdvice: function() {
            var that = this;

            // add dropdown functionality to response container
            jQuery.aop.after({target: this, method: "buildResponseContainer"}, function(args){
                this.dropdownController = jira.widget.dropdown.Autocomplete({target: this, method: "renderSuggestions"}, this.responseContainer);

                if (AJS.$.browser.msie) { // We need to remove this class for IE as it has position relative which causes content further down the dom to show through the suggestions
                    jQuery.aop.before({ target: this.dropdownController, method: "displayDropdown" }, function () {
                        that.field.parent().addClass("atlassian-autocomplete");
                    });

                    jQuery.aop.after({ target: this.dropdownController, method: "hideDropdown" }, function () {
                        that.field.parent().removeClass("atlassian-autocomplete");
                    });
                }

                return args;
            });

            // display dropdown afer suggestions are updated
            jQuery.aop.after({target: this, method: "renderSuggestions"}, function(args){
                if (args && args.length > 0) {
                    this.dropdownController.displayDropdown();
                } else {
                    this.dropdownController.hideDropdown();
                }
                return args;
            });

            // hide dropdown after suggestion value is applied to field
            jQuery.aop.after({target: this, method: "completeField"}, function(args){
                this.dropdownController.hideDropdown();
                return args;
            });

            jQuery.aop.after({target: this, method: "keyUpHandler"}, function(e) {
                // only initialises once the field length is past set length
                if ((!(this.field.val().length >= this.minQueryLength) || e.keyCode === 27)
                        && this.dropdownController && this.dropdownController.displayed) {
                    this.dropdownController.hideDropdown();
                    if (e.keyCode === 27) {
                        e.stopPropagation();
                    }
                }
                return e;
            });
        },

        /**
         * Initialises autocomplete by setting options, and assigning event handler to input field.
         * @method {public} init
         * @param {Object} options
         */
        init: function(options) {
            var that = this;
            this.set(options);
            this.field = this.field || jQuery("#" + this.fieldID);
             // turn off browser default autocomplete
            this.field.attr("autocomplete","off")
            .keyup(function(e){
                if (!that.disabled) {
                    that.keyUpHandler(e);
                }
            })
            .keydown(function (e) {
                var ESC_KEY = 27;
                // do not clear field in IE
                if (e.keyCode === ESC_KEY && that.responseContainer && that.responseContainer.is(":visible")) {
                    e.preventDefault();
                }
            })
            // this will stop the dropdown with the suggestions hiding whenever you click the field
            .click(function(e){
                if (inFocus === that) {
                    e.stopPropagation();
                }
            });

            this.addDropdownAdvice();

            if (options.delimChar) {
                this.addMultiSelectAdvice(options.delimChar);
            }
        }
    };

}();


/**
 * Designed for prototypial inheritance !!Abstract only
 * @abstract REST
 */
jira.widget.autocomplete.REST = function() {

    // prototypial inheritance (http://javascript.crockford.com/prototypal.html)
    var that = begetObject(jira.widget.autocomplete);

   /**
    * Checks whether a saved version (cached) of the request exists, if not performs a request and saves response,
    * then dispatches saved response to <em>renderSuggestions</em> method.
    * @method {public} dispatcher
    * @param {String} reqFieldVal
    */
    that.dispatcher = function(reqFieldVal) {

        // reference to "this" for use in closures
         var that = this;

         if (reqFieldVal.length < this.minQueryLength) {
             return;
         }

         if (!this.getSavedResponse(reqFieldVal)) {



            // Add a delay so that we don't go the server for every keypress,
            // some people type fast and may have already typed an entire word by the time the server comes
            // back with a response

            this.delay(function(){

                that.pendingRequest = true;

                var params = that.getAjaxParams();
                params.data.query = reqFieldVal;
                params.success = function(data){
                    // for use later so we don't have to go back to the server for the same query
                    that.saveResponse(reqFieldVal, data);
                    // creates html elements from JSON object
                    that.responseContainer.scrollTop(0);
                    that.renderSuggestions(data);
                };

                params.complete = function () {
                    that.pendingRequest = false;
                };

                AJS.$.ajax(params);

            }, that.queryDelay);

        } else {
            that.renderSuggestions(that.getSavedResponse(reqFieldVal));
            that.responseContainer.scrollTop(0);
        }
    };


    that.getAjaxParams = function(){};

    /**
     * Gets cached response from <em>requested</em> object
     * @method {public} getSavedResponse
     * @param {String} val
     * @returns {Object}
     */
    that.getSavedResponse = function(val) {
        if (!this.requested) {
            this.requested = {};
        }
        return this.requested[val];
    };

    /**
     * Saves response to <em>requested</em> object
     * @method {public} saveResponse
     * @param {String} val
     * @param {Object} response
     */
    that.saveResponse = function(val, response) {
        if (typeof val === "string" && typeof response === "object") {
            if (!this.requested) {
                this.requested = {};
            }
            this.requested[val] = response;
        }
    };

    return that;

}();

/**
 * User picker - converted from YUI based autocomplete. There is some code in here that probably isn't necessary,
 * if removed though selenium tests would need to be re-written.
 * @constructer Users
 * @param options
 * @returns {Object}
 */
jira.widget.autocomplete.Users = function(options) {

    // prototypial inheritance (http://javascript.crockford.com/prototypal.html)
    var that = begetObject(jira.widget.autocomplete.REST);

    that.getAjaxParams = function(){
        return {
            url: contextPath + "/rest/api/1.0/users/picker",
            data: {
                fieldName: options.fieldID
            },
            dataType: "json",
            type: "GET"
        };
    };

    /**
     * Create html elements from JSON object
     * @method renderSuggestions
     * @param {Object} response - JSON object
     * @returns {Array} Multidimensional array, one column being the html element and the other being its
     * corresponding complete value.
     */
    that.renderSuggestions = function(response) {


        var resultsContainer, suggestionNodes = [];

        // remove previous results
        this.clearResponseContainer();


        if (response && response.users && response.users.length > 0) {

            resultsContainer = jQuery("<ul/>").appendTo(this.responseContainer);

            jQuery(response.users).each(function() {

                // add html element and corresponding complete value  to sugestionNodes Array
                suggestionNodes.push([jQuery("<li/>")
                .html(this.html)
                .appendTo(resultsContainer), this.name]);

            });
        }

        if (response.footer) {
            this.responseContainer.append(jQuery("<div/>")
            .addClass("yui-ac-ft")
            .html(response.footer)
            .css("display","block"));
        }

        if (suggestionNodes.length > 0) {
            that.addSuggestionControls(suggestionNodes);
            AJS.$('.atlassian-autocomplete div.yad, .atlassian-autocomplete .labels li').textOverflow('&#x2026;',true);
        }

        return suggestionNodes;

    };

    // Use autocomplete only once the field has at least 2 characters
    options.minQueryLength = 2;

    // wait 1/4 of after someone starts typing before going to server
    options.queryDelay = 0.25;

    that.init(options);

    return that;

};

/**
 * @constructor Issues
 * @param options
 */
jira.widget.autocomplete.Issues = function(options) {

    // prototypial inheritance (http://javascript.crockford.com/prototypal.html)
    var that = begetObject(jira.widget.autocomplete.REST);


    that.getAjaxParams = function(){
        return {
            url: contextPath + "/rest/api/1.0/issues/picker",
            data: options.ajaxData,
            dataType: "json",
            type: "GET"
        };
    };

    /**
     * @method renderSuggestions
     * @param {Object} response
     */
    that.renderSuggestions = function(response) {

        var resultsContainer, suggestionNodes = [];

        // remove previous results
        this.clearResponseContainer();

        if (response && response.sections && response.sections.length > 0) {

            resultsContainer = AJS.$("<ul/>").appendTo(this.responseContainer);

            AJS.$(response.sections).each(function() {
                var section = this;
                var subSection = AJS.$("<div/>").attr("id", options.fieldID + "_s_" + section.id).addClass("yag").text(section.label);
                if (section.sub){
                    subSection.append(AJS.$("<span/>").addClass("yagt").text("(" + section.sub + ")"));
                }
                resultsContainer.append(AJS.$("<li/>").append(subSection).mouseover(function(){
                        AJS.$(this).addClass("active");
                    }).mouseout(function(){
                        AJS.$(this).removeClass("active");
                    })
                );

                if (section.msg){
                    // add message node
                    var msg = AJS.$("<div/>").attr("id", options.fieldID + "_i_" + section.id + "_n").addClass("yad").text(section.msg);
                    resultsContainer.append(AJS.$("<li/>").append(msg).mouseover(function(){
                            AJS.$(this).addClass("active");
                        }).mouseout(function(){
                            AJS.$(this).removeClass("active");
                        })
                    );
                }

                if (section.issues && section.issues.length > 0){
                    AJS.$(section.issues).each(function(){
                        // add issue
                        var imgUrl;
                        if (/^http/.test(this.img)){
                            imgUrl = this.img;
                        } else {
                            imgUrl =  contextPath + this.img;
                        }
                        var issueNode = AJS.$("<li/>").append(
                            AJS.$("<div/>").attr("id", options.fieldID + "_i_" + section.id + "_" + this.key).addClass("yad").append(
                                AJS.$("<table/>").addClass("yat").attr({
                                    cellpadding: "0",
                                    cellspacing: "0"
                                }).append(
                                    AJS.$("<tr/>").append(
                                        AJS.$("<td/>").append(
                                            AJS.$("<img/>").attr("src", imgUrl)
                                        )
                                    ).append(
                                         AJS.$("<td/>").append(
                                            AJS.$("<div/>").addClass("yak").html(this.keyHtml)
                                        )
                                    ).append(
                                         AJS.$("<td/>").css("width", "100%").html(this.summary)
                                    )
                                )
                            )
                        );

                        resultsContainer.append(issueNode);
                        suggestionNodes.push([issueNode, this.key]);
                    });                    
                }
            });

            that.addSuggestionControls(suggestionNodes);

            return suggestionNodes;

        }
    };
    options.minQueryLength = 1;
    options.queryDelay = 0.25;

    that.init(options);

    return that;

};

jira.widget.autocomplete.Users.init = function(parent){
    AJS.$("fieldset.user-picker-params", parent).each(function(){
        var params = AJS.parseOptionsFromFieldset(AJS.$(this)),
            field = (params.fieldId || params.fieldName),
            $container = AJS.$("#" + field + "_container");


        $container.find("a.popup-trigger").click(function(e){
            var url = contextPath,
                vWinUsers;

            e.preventDefault();

            if (!params.formName)
            {
                params.formName = $container.find("#" + field).parents("form").attr("name");
            }

            if (params.actionToOpen) {
                url = url + params.actionToOpen;
            } else {
                url = url + '/secure/popups/UserPickerBrowser.jspa';
            }
            url += '?formName=' + params.formName + '&';
            url += 'multiSelect=' + params.multiSelect + '&';
            url += 'element=' + field;

            vWinUsers = window.open(url, 'UserPicker', 'status=yes,resizable=yes,top=100,left=200,width=580,height=750,scrollbars=yes');
            vWinUsers.opener = self;
            vWinUsers.focus();
        });


        if (params.userPickerEnabled === true ){
            jira.widget.autocomplete.Users({
                field: parent ? parent.find("#" + field) : null,
                fieldID: field,
                delimChar: params.multiSelect === false ? undefined : ",",
                ajaxData: {
                    fieldName: params.fieldName
                }
            });
        }
    });
};
AJS.$(document).bind("dialogContentReady", function(e, dialog){
    jira.widget.autocomplete.Users.init(dialog.get$popupContent());
});

jira.widget.autocomplete.Issues.init = function(){

    jQuery.namespace("jira.issuepicker");

    AJS.$("fieldset.issue-picker-params").each(function(){
        var params = AJS.parseOptionsFromFieldset(AJS.$(this)),
            $container = AJS.$("#" + params.fieldId + "-container").add("#" + params.fieldName + "_container");

        $container.find("a.popup-trigger").click(function(e){
            var url = contextPath + '/secure/popups/IssuePicker.jspa?';
            url += 'currentIssue=' + params.currentIssueKey + '&';
            url += 'singleSelectOnly=' + params.singleSelectOnly + '&';
            url += 'showSubTasks=' + params.showSubTasks + '&';
            url += 'showSubTasksParent=' + params.showSubTaskParent;
            if (params.currentProjectId && params.currentProjectId != "")
            {
                url += '&selectedProjectId=' + params.currentProjectId;
            }

            /**
             * Provide a callback to the window for execution when the user selects an issue. This implies that only one
             * popup can be displayed at a time.
             * 
             * @param keysMap the issue keys selected.
             */
            jira.issuepicker.callback = function(keysMap){
                var $formElement, keys = [];

                keysMap = JSON.parse(keysMap);

                if (params.fieldId && keys) {
                    $formElement = AJS.$("#" + params.fieldId);
                    if ($formElement){
                        AJS.$.each(keysMap, function () {
                            keys.push(this.value);
                        });
                        $formElement.val(keys.join(", "));
                    }
                }
            };

            var vWinUsers = window.open(url, 'IssueSelectorPopup', 'status=no,resizable=yes,top=100,left=200,width=620,height=500,scrollbars=yes,resizable');
            vWinUsers.opener = self;
            vWinUsers.focus();
            e.preventDefault();
        });

        if (!params.fieldId) {
            params.fieldId = params.fieldName;
        }
        
        if (params.issuePickerEnabled === true){
            jira.widget.autocomplete.Issues({
                fieldID: params.fieldId,
                delimChar: params.singleSelectOnly === true ? undefined : ",",
                ajaxData: params
            });
        }
    });
};
AJS.$(function(){
    jira.widget.autocomplete.Users.init();
    jira.widget.autocomplete.Issues.init();
});

AJS.$(function(){
    AJS.$("fieldset.user-searcher-params").each(function(){
        var params = AJS.parseOptionsFromFieldset(AJS.$(this)),
            $container = AJS.$("#" + params.fieldId + "_container");

        if (params.userPickerEnabled === true){
            var autocompleter = jira.widget.autocomplete.Users({
                fieldID: params.fieldId,
                delimChar: params.multiSelect === true ? "," : undefined,
                ajaxData: {
                    fieldName: params.fieldName
                }
            });
        }

        var setupFields = function(related){
            var field = AJS.$("#" + params.fieldId);
            var userImage = AJS.$("#" + params.fieldId + "Image");
            var groupImage = AJS.$("#" + params.fieldId + "GroupImage");
            var fieldDesc = AJS.$("#" + params.fieldId + "_desc");
            if (related === "select.list.none"){
                field.val("").attr("disabled", "true");
                userImage.hide();
                groupImage.hide();
                fieldDesc.hide();
            } else{
                field.removeAttr("disabled");
                if (related === "select.list.group"){
                    userImage.hide();
                    groupImage.show();
                    if (params.userPickerEnabled === true){
                        autocompleter.disable();
                        fieldDesc.hide();
                    }
                } else {
                    userImage.show();
                    groupImage.hide();
                    if (params.userPickerEnabled === true){
                        autocompleter.enable();
                        fieldDesc.show();
                    }
                }
            }
        };

        AJS.$("#" + params.userSelect).change(function(){
            var related = AJS.$(this).find("option:selected").attr("rel");
            setupFields(related);
        }).find("option:selected").each(function(){
            setupFields(AJS.$(this).attr("rel"));
        });

        $container.find("a.user-popup-trigger").click(function(e){
            var url = contextPath + '/secure/popups/UserPickerBrowser.jspa?';
            url += 'formName=' + params.formName + '&';
            url += 'multiSelect=' + params.multiSelect + '&';
            url += 'element=' + params.fieldId;

            var vWinUsers = window.open(url, 'UserPicker', 'status=yes,resizable=yes,top=100,left=200,width=580,height=750,scrollbars=yes');
            vWinUsers.opener = self;
            vWinUsers.focus();
            e.preventDefault();
        });

        $container.find("a.group-popup-trigger").click(function(e){
            var url = contextPath + '/secure/popups/GroupPickerBrowser.jspa?';
            url += 'formName=' + params.formName + '&';
            url += 'multiSelect=' + params.multiSelect + '&';
            url += 'element=' + params.fieldId;

            var vWinUsers = window.open(url, 'GroupPicker', 'status=yes,resizable=yes,top=100,left=200,width=580,height=750,scrollbars=yes');
            vWinUsers.opener = self;
            vWinUsers.focus();
            e.preventDefault();
        });
    });
});
/**
 * Creates a dropdown list from a JSON obect
 * @module dropdown
 * @author Scott Harwood
 * @requires jQuery > v1.2
 */


jQuery.namespace("jira.widget.dropdown");

/**
 * @abstract dropdown
 */
jira.widget.dropdown = function() {

    // private

    var instances = [];

    return {

        // public

        /**
         * Adds this instance to private var <em>instances</em>
         * This reference can be used to access all instances
         * @function {public} addInstance
         */
        addInstance: function() {
            instances.push(this);
        },


        /**
         * Calls the hideList method on all instances of <em>dropdown</em>
         * @function {public} hideInstances
         */
        hideInstances: function() {
            var that = this;
            jQuery(instances).each(function(){
                if (that !== this) {
                    this.hideDropdown();
                }
            });
        },

        
        getHash: function () {
            if (!this.hash) {
                this.hash = {
                    container: this.dropdown,
                    hide: this.hideDropdown,
                    show: this.displayDropdown
                };
            }
            return this.hash;
        },

        /**
         * Calls <em>hideInstances</em> method to hide all other dropdowns.
         * Adds <em>active</em> class to <em>dropdown</em> and styles to make it visible.
         * @function {public} displayDropdown
         */
        displayDropdown: function() {
            if (jira.widget.dropdown.current === this) {
                return;
            }

            this.hideInstances();
            jira.widget.dropdown.current = this;
            this.dropdown.css({display: "block"});

            this.displayed = true;

            var dd = this.dropdown;
            setTimeout(function() {
                // Scroll dropdown into view
                var win = jQuery(window);
                var minScrollTop = dd.offset().top + dd.attr("offsetHeight") - win.height() + 10;

                if (win.scrollTop() < minScrollTop) {
                    jQuery("html,body").animate({scrollTop: minScrollTop}, 300, "linear");
                }
            }, 100);
        },

        /**
         *
         * Removes <em>active</em> class from <em>dropdown</em> and styles to make it hidden.
         * @function {public} hideDropdown
         */
        hideDropdown: function() {
            if (this.displayed === false) {
                return;
            }

            jira.widget.dropdown.current = null;
            this.dropdown.css({display: "none"});

            this.displayed = false;
        },

        /**
         * Initialises instance by, applying primary handler, user options and a Internet Explorer hack.
         * function {public} init
         * @param {HTMLelement} trigger
         * @param {HTMLelement} dropdown
         */
        init: function(trigger, dropdown) {

            var that = this;

            this.addInstance(this);
            this.dropdown = jQuery(dropdown);

            this.dropdown.css({display: "none"});

            // hide dropdown on tab
            jQuery(document).keydown(function(e){
                if(e.keyCode === 9) {
                    that.hideDropdown();
                }
            });

            // this instance is triggered by a method call
            if (trigger.target) {
                jQuery.aop.before(trigger, function(){
                    if (!that.displayed) {
                        that.displayDropdown();
                    }
                });

            // this instance is triggered by a click event
            } else {
                that.dropdown.css("top",jQuery(trigger).outerHeight() + "px");
                trigger.click(function(e){
                    if (!that.displayed) {
                        that.displayDropdown();
                        e.stopPropagation();
                        // lets not follow the link (if it is a link)
                    } else {
                        that.hideDropdown();
                    }
                    e.preventDefault();
                });
            }

            // hide dropdown when click anywhere other than on this instance
            jQuery(document.body).click(function(){
                if (that.displayed) {
                    that.hideDropdown();
                }
            });
        }
    };

}();

/**
 * Standard dropdown constructor 
 * @constucter Standard
 * @param {HTMLelement} trigger
 * @param {HTMLelement} dropdown
 * @return {Object} - instance
 */
jira.widget.dropdown.Standard = function(trigger, dropdown) {

    var that = begetObject(jira.widget.dropdown);
    that.init(trigger, dropdown);

    return that;
};

/**
 * Standard dropdown constructor
 * @constucter Standard
 * @param {HTMLelement} trigger
 * @param {HTMLelement} dropdown
 * @return {Object} - instance
 */
jira.widget.dropdown.Autocomplete = function(trigger, dropdown) {

    var that = begetObject(jira.widget.dropdown);

    that.init = function(trigger, dropdown) {

        this.addInstance(this);
        this.dropdown = jQuery(dropdown).click(function(e){
            // lets not hide dropdown when we click on it
            e.stopPropagation();
        });
        this.dropdown.css({display: "none"});

        // this instance is triggered by a method call
        if (trigger.target) {
            jQuery.aop.before(trigger, function(){
                if (!that.displayed) {
                    that.displayDropdown();
                }
            });

        // this instance is triggered by a click event
        } else {
            trigger.click(function(e){
                if (!that.displayed) {
                    that.displayDropdown();
                    e.stopPropagation();
                }
            });
        }

        // hide dropdown when click anywhere other than on this instance
        jQuery(document.body).click(function(){
            if (that.displayed) {
                that.hideDropdown();
            }
        });
    };

    that.init(trigger, dropdown);

    return that;
};

AJS.$.namespace("BAMBOO.widget.autocomplete");


BAMBOO.widget.autocomplete.Variables = function(options) {

    // prototypial inheritance (http://javascript.crockford.com/prototypal.html)
    var that = begetObject(jira.widget.autocomplete.REST);

    that.getAjaxParams = function(){
        return {
            url: 'rest/api/latest/plan/%PLAN%?expand=variableContext'.replace('%PLAN%', that.planKey),
            data: options.ajaxData,
            dataType: "json",
            type: "GET"
        };
    };

    that.dispatcher = function(val) {
        var that = this,
            selectionRange = that.field.selectionRange(),
            parseValue = val.substring(0, selectionRange.start),
            match = parseValue.match(that.variableRegEx);
    };

    var defaults = {
        minQueryLength: 1,
        variableRegEx: /\$\{([a-z0-9\.]*)$/i
    };

    options = AJS.$.extend(true, defaults, options);
    that.init(options);

    return that;
};

BAMBOO.widget.autocomplete.Variables.init = function(parent) {
    AJS.$(".field-group .autocomplete-variables", parent).each(function() {
        var $item = AJS.$(this);
        BAMBOO.widget.autocomplete.Variables({
            field: $item,
            planKey: BAMBOO.currentPlan.key
        });
    })
}


AJS.$(document).bind("dialogContentReady", function(e, dialog){
    BAMBOO.widget.autocomplete.Variables.init(dialog.get$popupContent());
});

AJS.$(function(){
    BAMBOO.widget.autocomplete.Variables.init();
});

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*
 * jQuery UI Tabs 1.8.1
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function(d){var s=0,u=0;d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading&#8230;</em>",tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>'},_create:function(){this._tabify(true)},_setOption:function(c,e){if(c=="selected")this.options.collapsible&&e==this.options.selected||
this.select(e);else{this.options[c]=e;this._tabify()}},_tabId:function(c){return c.title&&c.title.replace(/\s/g,"_").replace(/[^A-Za-z0-9\-_:\.]/g,"")||this.options.idPrefix+ ++s},_sanitizeSelector:function(c){return c.replace(/:/g,"\\:")},_cookie:function(){var c=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+ ++u);return d.cookie.apply(null,[c].concat(d.makeArray(arguments)))},_ui:function(c,e){return{tab:c,panel:e,index:this.anchors.index(c)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var c=
d(this);c.html(c.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function e(g,f){g.css({display:""});!d.support.opacity&&f.opacity&&g[0].style.removeAttribute("filter")}this.list=this.element.find("ol,ul").eq(0);this.lis=d("li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0]});this.panels=d([]);var a=this,b=this.options,h=/^#.+/;this.anchors.each(function(g,f){var j=d(f).attr("href"),l=j.split("#")[0],p;if(l&&(l===location.toString().split("#")[0]||
(p=d("base")[0])&&l===p.href)){j=f.hash;f.href=j}if(h.test(j))a.panels=a.panels.add(a._sanitizeSelector(j));else if(j!="#"){d.data(f,"href.tabs",j);d.data(f,"load.tabs",j.replace(/#.*$/,""));j=a._tabId(f);f.href="#"+j;f=d("#"+j);if(!f.length){f=d(b.panelTemplate).attr("id",j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(a.panels[g-1]||a.list);f.data("destroy.tabs",true)}a.panels=a.panels.add(f)}else b.disabled.push(g)});if(c){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");
this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(b.selected===undefined){location.hash&&this.anchors.each(function(g,f){if(f.hash==location.hash){b.selected=g;return false}});if(typeof b.selected!="number"&&b.cookie)b.selected=parseInt(a._cookie(),10);if(typeof b.selected!="number"&&this.lis.filter(".ui-tabs-selected").length)b.selected=
this.lis.index(this.lis.filter(".ui-tabs-selected"));b.selected=b.selected||(this.lis.length?0:-1)}else if(b.selected===null)b.selected=-1;b.selected=b.selected>=0&&this.anchors[b.selected]||b.selected<0?b.selected:0;b.disabled=d.unique(b.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(g){return a.lis.index(g)}))).sort();d.inArray(b.selected,b.disabled)!=-1&&b.disabled.splice(d.inArray(b.selected,b.disabled),1);this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");
if(b.selected>=0&&this.anchors.length){this.panels.eq(b.selected).removeClass("ui-tabs-hide");this.lis.eq(b.selected).addClass("ui-tabs-selected ui-state-active");a.element.queue("tabs",function(){a._trigger("show",null,a._ui(a.anchors[b.selected],a.panels[b.selected]))});this.load(b.selected)}d(window).bind("unload",function(){a.lis.add(a.anchors).unbind(".tabs");a.lis=a.anchors=a.panels=null})}else b.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"));this.element[b.collapsible?"addClass":
"removeClass"]("ui-tabs-collapsible");b.cookie&&this._cookie(b.selected,b.cookie);c=0;for(var i;i=this.lis[c];c++)d(i)[d.inArray(c,b.disabled)!=-1&&!d(i).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");b.cache===false&&this.anchors.removeData("cache.tabs");this.lis.add(this.anchors).unbind(".tabs");if(b.event!="mouseover"){var k=function(g,f){f.is(":not(.ui-state-disabled)")&&f.addClass("ui-state-"+g)},n=function(g,f){f.removeClass("ui-state-"+g)};this.lis.bind("mouseover.tabs",
function(){k("hover",d(this))});this.lis.bind("mouseout.tabs",function(){n("hover",d(this))});this.anchors.bind("focus.tabs",function(){k("focus",d(this).closest("li"))});this.anchors.bind("blur.tabs",function(){n("focus",d(this).closest("li"))})}var m,o;if(b.fx)if(d.isArray(b.fx)){m=b.fx[0];o=b.fx[1]}else m=o=b.fx;var q=o?function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.hide().removeClass("ui-tabs-hide").animate(o,o.duration||"normal",function(){e(f,o);a._trigger("show",
null,a._ui(g,f[0]))})}:function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");a._trigger("show",null,a._ui(g,f[0]))},r=m?function(g,f){f.animate(m,m.duration||"normal",function(){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");e(f,m);a.element.dequeue("tabs")})}:function(g,f){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");a.element.dequeue("tabs")};this.anchors.bind(b.event+".tabs",
function(){var g=this,f=d(this).closest("li"),j=a.panels.filter(":not(.ui-tabs-hide)"),l=d(a._sanitizeSelector(this.hash));if(f.hasClass("ui-tabs-selected")&&!b.collapsible||f.hasClass("ui-state-disabled")||f.hasClass("ui-state-processing")||a._trigger("select",null,a._ui(this,l[0]))===false){this.blur();return false}b.selected=a.anchors.index(this);a.abort();if(b.collapsible)if(f.hasClass("ui-tabs-selected")){b.selected=-1;b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs",function(){r(g,
j)}).dequeue("tabs");this.blur();return false}else if(!j.length){b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this));this.blur();return false}b.cookie&&a._cookie(b.selected,b.cookie);if(l.length){j.length&&a.element.queue("tabs",function(){r(g,j)});a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this))}else throw"jQuery UI Tabs: Mismatching fragment identifier.";d.browser.msie&&this.blur()});this.anchors.bind("click.tabs",
function(){return false})},destroy:function(){var c=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var e=d.data(this,"href.tabs");if(e)this.href=e;var a=d(this).unbind(".tabs");d.each(["href","load","cache"],function(b,h){a.removeData(h+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){d.data(this,
"destroy.tabs")?d(this).remove():d(this).removeClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-hover ui-state-focus ui-state-disabled ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide")});c.cookie&&this._cookie(null,c.cookie);return this},add:function(c,e,a){if(a===undefined)a=this.anchors.length;var b=this,h=this.options;e=d(h.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,e));c=!c.indexOf("#")?c.replace("#",""):this._tabId(d("a",e)[0]);e.addClass("ui-state-default ui-corner-top").data("destroy.tabs",
true);var i=d("#"+c);i.length||(i=d(h.panelTemplate).attr("id",c).data("destroy.tabs",true));i.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(a>=this.lis.length){e.appendTo(this.list);i.appendTo(this.list[0].parentNode)}else{e.insertBefore(this.lis[a]);i.insertBefore(this.panels[a])}h.disabled=d.map(h.disabled,function(k){return k>=a?++k:k});this._tabify();if(this.anchors.length==1){h.selected=0;e.addClass("ui-tabs-selected ui-state-active");i.removeClass("ui-tabs-hide");
this.element.queue("tabs",function(){b._trigger("show",null,b._ui(b.anchors[0],b.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[a],this.panels[a]));return this},remove:function(c){var e=this.options,a=this.lis.eq(c).remove(),b=this.panels.eq(c).remove();if(a.hasClass("ui-tabs-selected")&&this.anchors.length>1)this.select(c+(c+1<this.anchors.length?1:-1));e.disabled=d.map(d.grep(e.disabled,function(h){return h!=c}),function(h){return h>=c?--h:h});this._tabify();this._trigger("remove",
null,this._ui(a.find("a")[0],b[0]));return this},enable:function(c){var e=this.options;if(d.inArray(c,e.disabled)!=-1){this.lis.eq(c).removeClass("ui-state-disabled");e.disabled=d.grep(e.disabled,function(a){return a!=c});this._trigger("enable",null,this._ui(this.anchors[c],this.panels[c]));return this}},disable:function(c){var e=this.options;if(c!=e.selected){this.lis.eq(c).addClass("ui-state-disabled");e.disabled.push(c);e.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[c],this.panels[c]))}return this},
select:function(c){if(typeof c=="string")c=this.anchors.index(this.anchors.filter("[href$="+c+"]"));else if(c===null)c=-1;if(c==-1&&this.options.collapsible)c=this.options.selected;this.anchors.eq(c).trigger(this.options.event+".tabs");return this},load:function(c){var e=this,a=this.options,b=this.anchors.eq(c)[0],h=d.data(b,"load.tabs");this.abort();if(!h||this.element.queue("tabs").length!==0&&d.data(b,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(c).addClass("ui-state-processing");
if(a.spinner){var i=d("span",b);i.data("label.tabs",i.html()).html(a.spinner)}this.xhr=d.ajax(d.extend({},a.ajaxOptions,{url:h,success:function(k,n){d(e._sanitizeSelector(b.hash)).html(k);e._cleanup();a.cache&&d.data(b,"cache.tabs",true);e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.success(k,n)}catch(m){}},error:function(k,n){e._cleanup();e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.error(k,n,c,b)}catch(m){}}}));e.element.dequeue("tabs");return this}},
abort:function(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup();return this},url:function(c,e){this.anchors.eq(c).removeData("cache.tabs").data("load.tabs",e);return this},length:function(){return this.anchors.length}});d.extend(d.ui.tabs,{version:"1.8.1"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function(c,e){var a=this,b=this.options,h=a._rotate||(a._rotate=
function(i){clearTimeout(a.rotation);a.rotation=setTimeout(function(){var k=b.selected;a.select(++k<a.anchors.length?k:0)},c);i&&i.stopPropagation()});e=a._unrotate||(a._unrotate=!e?function(i){i.clientX&&a.rotate(null)}:function(){t=b.selected;h()});if(c){this.element.bind("tabsshow",h);this.anchors.bind(b.event+".tabs",e);h()}else{clearTimeout(a.rotation);this.element.unbind("tabsshow",h);this.anchors.unbind(b.event+".tabs",e);delete this._rotate;delete this._unrotate}return this}})})(jQuery);
;

/*
 * jQuery UI Droppable 1.8.2
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Droppables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.mouse.js
 *	jquery.ui.draggable.js
 */
(function(d){d.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"},_create:function(){var a=this.options,b=a.accept;this.isover=0;this.isout=1;this.accept=d.isFunction(b)?b:function(c){return c.is(b)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};d.ui.ddmanager.droppables[a.scope]=d.ui.ddmanager.droppables[a.scope]||[];d.ui.ddmanager.droppables[a.scope].push(this);
a.addClasses&&this.element.addClass("ui-droppable")},destroy:function(){for(var a=d.ui.ddmanager.droppables[this.options.scope],b=0;b<a.length;b++)a[b]==this&&a.splice(b,1);this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");return this},_setOption:function(a,b){if(a=="accept")this.accept=d.isFunction(b)?b:function(c){return c.is(b)};d.Widget.prototype._setOption.apply(this,arguments)},_activate:function(a){var b=d.ui.ddmanager.current;this.options.activeClass&&
this.element.addClass(this.options.activeClass);b&&this._trigger("activate",a,this.ui(b))},_deactivate:function(a){var b=d.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass);b&&this._trigger("deactivate",a,this.ui(b))},_over:function(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.addClass(this.options.hoverClass);
this._trigger("over",a,this.ui(b))}},_out:function(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);this._trigger("out",a,this.ui(b))}},_drop:function(a,b){var c=b||d.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0])return false;var e=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var g=
d.data(this,"droppable");if(g.options.greedy&&!g.options.disabled&&g.options.scope==c.options.scope&&g.accept.call(g.element[0],c.currentItem||c.element)&&d.ui.intersect(c,d.extend(g,{offset:g.element.offset()}),g.options.tolerance)){e=true;return false}});if(e)return false;if(this.accept.call(this.element[0],c.currentItem||c.element)){this.options.activeClass&&this.element.removeClass(this.options.activeClass);this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);this._trigger("drop",
a,this.ui(c));return this.element}return false},ui:function(a){return{draggable:a.currentItem||a.element,helper:a.helper,position:a.position,offset:a.positionAbs}}});d.extend(d.ui.droppable,{version:"1.8.2"});d.ui.intersect=function(a,b,c){if(!b.offset)return false;var e=(a.positionAbs||a.position.absolute).left,g=e+a.helperProportions.width,f=(a.positionAbs||a.position.absolute).top,h=f+a.helperProportions.height,i=b.offset.left,k=i+b.proportions.width,j=b.offset.top,l=j+b.proportions.height;
switch(c){case "fit":return i<e&&g<k&&j<f&&h<l;case "intersect":return i<e+a.helperProportions.width/2&&g-a.helperProportions.width/2<k&&j<f+a.helperProportions.height/2&&h-a.helperProportions.height/2<l;case "pointer":return d.ui.isOver((a.positionAbs||a.position.absolute).top+(a.clickOffset||a.offset.click).top,(a.positionAbs||a.position.absolute).left+(a.clickOffset||a.offset.click).left,j,i,b.proportions.height,b.proportions.width);case "touch":return(f>=j&&f<=l||h>=j&&h<=l||f<j&&h>l)&&(e>=i&&
e<=k||g>=i&&g<=k||e<i&&g>k);default:return false}};d.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(a,b){var c=d.ui.ddmanager.droppables[a.options.scope]||[],e=b?b.type:null,g=(a.currentItem||a.element).find(":data(droppable)").andSelf(),f=0;a:for(;f<c.length;f++)if(!(c[f].options.disabled||a&&!c[f].accept.call(c[f].element[0],a.currentItem||a.element))){for(var h=0;h<g.length;h++)if(g[h]==c[f].element[0]){c[f].proportions.height=0;continue a}c[f].visible=c[f].element.css("display")!=
"none";if(c[f].visible){c[f].offset=c[f].element.offset();c[f].proportions={width:c[f].element[0].offsetWidth,height:c[f].element[0].offsetHeight};e=="mousedown"&&c[f]._activate.call(c[f],b)}}},drop:function(a,b){var c=false;d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(this.options){if(!this.options.disabled&&this.visible&&d.ui.intersect(a,this,this.options.tolerance))c=c||this._drop.call(this,b);if(!this.options.disabled&&this.visible&&this.accept.call(this.element[0],a.currentItem||
a.element)){this.isout=1;this.isover=0;this._deactivate.call(this,b)}}});return c},drag:function(a,b){a.options.refreshPositions&&d.ui.ddmanager.prepareOffsets(a,b);d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(!(this.options.disabled||this.greedyChild||!this.visible)){var c=d.ui.intersect(a,this,this.options.tolerance);if(c=!c&&this.isover==1?"isout":c&&this.isover==0?"isover":null){var e;if(this.options.greedy){var g=this.element.parents(":data(droppable):eq(0)");if(g.length){e=
d.data(g[0],"droppable");e.greedyChild=c=="isover"?1:0}}if(e&&c=="isover"){e.isover=0;e.isout=1;e._out.call(e,b)}this[c]=1;this[c=="isout"?"isover":"isout"]=0;this[c=="isover"?"_over":"_out"].call(this,b);if(e&&c=="isout"){e.isout=0;e.isover=1;e._over.call(e,b)}}}})}}})(jQuery);
;


(function($){$.extend({tablesorter:new function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'.',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}var rows=table.tBodies[0].rows;if(table.tBodies[0].rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,cells[i]);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,node){var l=parsers.length;for(var i=1;i<l;i++){if(parsers[i].is($.trim(getElementText(table.config,node)),table,node)){return parsers[i];}}return parsers[0];}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=table.tBodies[0].rows[i],cols=[];cache.row.push($(c));for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c.cells[j]),table,c.cells[j]));}cols.push(i);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){if(!node)return"";var t="";if(config.textExtraction=="simple"){if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){t=node.childNodes[0].innerHTML;}else{t=node.innerHTML;}}else{if(typeof(config.textExtraction)=="function"){t=config.textExtraction(node);}else{t=$(node).text();}}return t;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){rows.push(r[n[i][checkCell]]);if(!table.config.appender){var o=r[n[i][checkCell]];var l=o.length;for(var j=0;j<l;j++){tableBody[0].appendChild(o[j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false,tableHeadersRows=[];for(var i=0;i<table.tHead.rows.length;i++){tableHeadersRows[i]=0;};$tableHeaders=$("thead th",table);$tableHeaders.each(function(index){this.count=0;this.column=index;this.order=formatSortingOrder(table.config.sortInitialOrder);if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(!this.sortDisabled){$(this).addClass(table.config.cssHeader);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){i=(v.toLowerCase()=="desc")?1:0;}else{i=(v==(0||1))?v:0;}return i;}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(getCachedSortType(table.config.parsers,c)=="text")?((order==0)?"sortText":"sortTextDesc"):((order==0)?"sortNumeric":"sortNumericDesc");var e="e"+i;dynamicExp+="var "+e+" = "+s+"(a["+c+"],b["+c+"]); ";dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function sortText(a,b){return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){$this.trigger("sortStart");var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){var $cell=$(this);var i=this.column;this.order=this.count++%2;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){var DECIMAL='\\'+config.decimal;var exp='/(^[+]?0('+DECIMAL+'0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)'+DECIMAL+'(0*[1-9][0-9]*)))$)|(^[-+]?[1-9]+[0-9]*'+DECIMAL+'0+$)/';return RegExp(exp).test($.trim(s));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[£$€?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}$("tr:visible",table.tBodies[0]).filter(':even').removeClass(table.config.widgetZebra.css[1]).addClass(table.config.widgetZebra.css[0]).end().filter(':odd').removeClass(table.config.widgetZebra.css[0]).addClass(table.config.widgetZebra.css[1]);if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);
BAMBOO.ADMIN = {};
BAMBOO.ADMIN.SERVERSTATE = {};

BAMBOO.ADMIN.SERVER_STATUS_UPDATED_EVENT = "serverStatusChangedEvent";
BAMBOO.ADMIN.SERVER_STATUS_POLLING_EVENT = "serverStatusPollingEvent";
BAMBOO.ADMIN.SERVER_STATUS_ACTION_EVENT = "serverStatusActionEvent";

BAMBOO.ADMIN.STATUS_RUNNING = "RUNNING";
BAMBOO.ADMIN.STATUS_PAUSED = "PAUSED";
BAMBOO.ADMIN.STATUS_PAUSING = "PAUSING";
BAMBOO.ADMIN.STATUS_POLLING = "POLLING";
BAMBOO.ADMIN.STATUS_ERROR = "ERROR";

BAMBOO.ADMIN.ACTION_PAUSE = "ACTION_PAUSE";
BAMBOO.ADMIN.ACTION_RESUME = "ACTION_RESUME";

BAMBOO.ADMIN.SERVERSTATE.serverStateUpdater = function ($) {
    var defaults = {
            statusUrl: AJS.contextPath() + "/rest/api/latest/server",
            pauseUrl: AJS.contextPath() + "/rest/api/latest/server/pause",
            resumeUrl: AJS.contextPath() + "/rest/api/latest/server/resume"
        },
        options,
        state,
        $statusElement,
        doPoll = true,
        doRequest = function (type, url) {
            statusPolling();
            $.ajax({
                type: type,
                url: url,
                cache: false,
                dataType: "json",
                success: function (json) {
                    if (json && json.state) {
                        updateStatus(json.state, null);
                    } else {
                        updateStatus(BAMBOO.ADMIN.STATUS_ERROR, null);
                    }
                },
                error: function (request, textStatus, errorThrown) {
                    updateStatus(BAMBOO.ADMIN.STATUS_ERROR, textStatus + ": " + errorThrown);
                }
            });
        },
        update = function () {
            doRequest("GET", options.statusUrl);
        },
        statusPolling = function () {
            $statusElement.attr("data-server-state", BAMBOO.ADMIN.STATUS_POLLING);
            $statusElement.trigger(BAMBOO.ADMIN.SERVER_STATUS_POLLING_EVENT);
        },
        updateStatus = function (newState, additionalInfo) {
            var oldState = state;
            state = newState;
            $statusElement.attr("data-server-state", newState);
            if (additionalInfo) {
                $statusElement.attr("data-additional-info", additionalInfo);
            } else {
                $statusElement.removeAttr("data-additional-info");
            }
            $statusElement.trigger(BAMBOO.ADMIN.SERVER_STATUS_UPDATED_EVENT, [oldState, state, additionalInfo]);
        },
        pollInterval = function () {
            if (state == BAMBOO.ADMIN.STATUS_RUNNING || state == BAMBOO.ADMIN.STATUS_PAUSED || state == BAMBOO.ADMIN.STATUS_ERROR) {
                return 30000;
            } else {
                return 5000;
            }
        },
        poll = function (interval) {
            setTimeout(function () {
                if (doPoll) {
                    update();
                    poll(pollInterval());
                }
            }, interval);
        };

    return {
        init: function (opts) {
            options = $.extend(true, defaults, opts);
            $(function ($){
                $statusElement = $("<input id='bamboo-server-status' type='hidden'>").appendTo("body");
                if (doPoll) {
                    update();
                    poll(pollInterval());
                }
            });
        },

        pause: function () {
            $statusElement.trigger(BAMBOO.ADMIN.SERVER_STATUS_ACTION_EVENT, BAMBOO.ADMIN.ACTION_PAUSE);
            doRequest("POST", options.pauseUrl);
            poll(1000);
        },

        resume: function () {
            $statusElement.trigger(BAMBOO.ADMIN.SERVER_STATUS_ACTION_EVENT, BAMBOO.ADMIN.ACTION_RESUME);
            doRequest("POST", options.resumeUrl);
        },

        onServerStatusPolling: function (callback) {
            $statusElement.bind(BAMBOO.ADMIN.SERVER_STATUS_POLLING_EVENT, callback);
        },

        onServerStatusUpdated: function (callback) {
            $statusElement.bind(BAMBOO.ADMIN.SERVER_STATUS_UPDATED_EVENT, callback);
        },

        onServerStatusAction: function (callback) {
            $statusElement.bind(BAMBOO.ADMIN.SERVER_STATUS_ACTION_EVENT, callback);
        },

        stopPolling: function () {
            doPoll = false;
        }
    }
}(AJS.$);

BAMBOO.ADMIN.SERVERSTATE.serverStateUpdater.init();

BAMBOO.ADMIN.SERVERSTATE.serverState = function ($) {
    var defaults = {
            control: null,
            statusInfo: null,
            buttonLink: null,
            buttonIcon: null,
            buttonText: null,
            pausedMessage: "The server is \u003cstrong>Paused\u003c\/strong>. No builds will be run or queued.",
            pausedButtonLabel: "Resume server",
            pausingMessage: "The server is \u003cstrong>Pausing\u003c\/strong>. No builds will be queued. All currently building Plans will finish but requests for new builds is not allowed.",
            pausingButtonLabel: "Cancel pause",
            serverRunningCallaback: null,
            pollError: "Server could not be contacted and its state is unknown. Please reload the page",
            reloadPage: "Reload"
        },
        options,
        state,
        control,
        buttonLink,
        statusInfo,
        buttonIcon,
        buttonText,
        updateStatus = function (event, oldState, newState) {
            if (buttonIcon) {
                buttonIcon.removeClass('disabled');
            }
            if (state) {
                control.removeClass("server-status-" + state.toLowerCase());
            }
            state = newState;
            control.addClass("server-status-" + state.toLowerCase());

            if (state == BAMBOO.ADMIN.STATUS_RUNNING) {
                if (oldState != BAMBOO.ADMIN.STATUS_RUNNING && options.serverRunningCallaback) {
                    options.serverRunningCallaback();
                }
                control.hide();
                return;
            } else if (state == BAMBOO.ADMIN.STATUS_ERROR) {
                if (oldState == BAMBOO.ADMIN.STATUS_PAUSED || oldState == BAMBOO.ADMIN.STATUS_PAUSING) {
                    if (buttonLink) {
                        buttonText.text(options.reloadPage);
                        buttonLink.click(function () {
                            window.location.reload();
                        });
                    }
                    statusInfo.html(options.pollError);
                    control.show();
                } else if (oldState != BAMBOO.ADMIN.STATUS_ERROR) {
                    control.hide();
                }
                return;
            } else {
                control.show();
            }

            if (state == BAMBOO.ADMIN.STATUS_PAUSED || state == BAMBOO.ADMIN.STATUS_PAUSING) {
                if (buttonLink) {
                    buttonLink.show();
                }
            }

            if (state == BAMBOO.ADMIN.STATUS_PAUSING) {
                if (buttonText) {
                    buttonText.text(options.pausingButtonLabel);
                }
                statusInfo.html(options.pausingMessage);
            } else if (state == BAMBOO.ADMIN.STATUS_PAUSED) {
                if (buttonText) {
                    buttonText.text(options.pausedButtonLabel);
                }
                statusInfo.html(options.pausedMessage);
            }

            if (control.hasClass("hidden")) {
                control.show();
            }

        },
        polling = function (event) {
            if (buttonIcon) {
                buttonIcon.addClass('disabled');
            }
        };

    return {
        init: function (opts) {
            options = $.extend(true, defaults, opts);
            control = $(options.control).addClass("server-status");

            statusInfo = $(options.statusInfo, control);
            buttonLink = $(options.buttonLink, control);
            buttonIcon = $(options.buttonIcon, control);
            buttonText = $(options.buttonText, control);

            if (buttonLink) {
                buttonLink.click(function () {
                    BAMBOO.ADMIN.SERVERSTATE.serverStateUpdater.resume();
                });
            }
            BAMBOO.ADMIN.SERVERSTATE.serverStateUpdater.onServerStatusUpdated(updateStatus);
            BAMBOO.ADMIN.SERVERSTATE.serverStateUpdater.onServerStatusAction(polling);
        }
    }
}(AJS.$);

function JAtom(A){this._parse(A)
}JAtom.prototype={_parse:function(A){var C=jQuery("feed",A).eq(0);
var B=this;
this.version="1.0";
this.title=jQuery(C).find("title:first").text();
this.link=jQuery(C).find("link:first").attr("href");
this.description=jQuery(C).find("subtitle:first").text();
this.language=jQuery(C).attr("xml:lang");
this.updated=jQuery(C).find("updated:first").text();
this.items=new Array();
var D=this;
jQuery("entry",A).each(function(){var E=new JFeedItem();
E.title=jQuery(this).find("title").eq(0).text();
jQuery(this).find("link").each(function(){var F=jQuery(this).attr("rel");
var G=jQuery(this).attr("href");
if(F=="alternate"){E.link=G
}else{if(F=="http://streams.atlassian.com/syndication/reply-to"){E.replyTo=G
}else{if(F=="http://streams.atlassian.com/syndication/icon"){E.icon=G
}}}});
E.summary=jQuery(this).find("summary").eq(0).text();
E.updated=jQuery(this).find("updated").eq(0).text();
E.id=jQuery(this).find("id").eq(0).text();
E.category=jQuery(this).find("category:first").attr("term");
jQuery(this).find("author").each(function(){E.authors.push(B._parsePerson(this))
});
D.items.push(E)
})
},_parsePerson:function(B){var A=new JFeedPerson();
A.name=jQuery(B).find("name").eq(0).text();
A.email=jQuery(B).find("email").eq(0).text();
A.uri=jQuery(B).find("uri").eq(0).text();
A.username=jQuery(B).find("username").eq(0).text();
return A
},_getContentValue:function(C,A){var B=C.find(A+":first");
if(B){return B.text()
}else{return""
}}};
function JFeedItem(){this.authors=new Array()
}JFeedItem.prototype={title:"",link:"",summary:"",updated:"",id:"",category:"",inReplyTo:"",replyTo:"",icon:""};
function JFeedPerson(){}JFeedPerson.prototype={name:"",email:"",uri:"",username:""};
function ActivityFeed(B,E,C,F,A){this.feedId=B;
this.baseUrl=E;
this.resourceUrl=C;
this.feedUrl=F;
this.maxResults=parseInt(A);
var D=this;
jQuery("#showMoreLink-"+B).click(function(G){D.toggleShowMoreLink(false);
D.maxResults+=10;
D.populateFeed()
});
this.COMMENT_ICON_HTML='<img class="activity-item-comment-icon" style="visibility:hidden" src="'+C+'/showcomment" title="Add Comment"/>'
}ActivityFeed.prototype.setFeedUrl=function(A){this.feedUrl=A
};
ActivityFeed.prototype.toggleShowMoreLink=function(A){this.setMoreAndWaitingLinkVisibility(A,!A)
};
ActivityFeed.prototype.hideShowMoreAndWaitingLinks=function(){this.setMoreAndWaitingLinkVisibility(false,false)
};
ActivityFeed.prototype.setMoreAndWaitingLinkVisibility=function(C,A){var D=document.getElementById("showMoreLink-"+this.feedId);
if(D){D.style.display=C?"inline":"none"
}var B=document.getElementById("moreWaiting-"+this.feedId);
if(B){B.style.display=A?"inline":"none"
}};
ActivityFeed.prototype.addItem=function(D,A){var C=this.getOrCreateDateContainer(DateUtils.format(DateUtils.utcStringToDateByHour(D.updated),A));
var B=C.children("ul");
var E=jQuery(document.createElement("li"));
E.addClass("activity-item");
if(D.icon){E.css("backgroundImage","url('"+D.icon+"')")
}E.html(D.summary);
B.append(E)
};
ActivityFeed.prototype.getOrCreateDateContainer=function(E){var C="dateContainer-"+this.feedId+"-"+E.replace(/\s/g,"");
var B=jQuery("#"+C);
if(B.size()==0){var F=jQuery("#feedContainer-"+this.feedId);
B=jQuery(document.createElement("div"));
B.attr("id",C);
F.append(B);
var A=jQuery(document.createElement("h3"));
A.addClass("timestamp");
A.html(E);
B.append(A);
var D=jQuery(document.createElement("ul"));
D.addClass("activityItems");
B.append(D)
}return B
};
ActivityFeed.prototype.getDateFormat=function(A,B){if(A==null||B==null){return"MMMMM dd - hh aa"
}var C=B.getTime()-A.getTime();
if(C<=DateUtils.MILLIS_PER_DAY*2){return"MMMMM dd - hh aa"
}else{if(C<=DateUtils.MILLIS_PER_DAY*30){return"MMMMM dd"
}else{return"MMMMM yyyy"
}}};
ActivityFeed.prototype.addCommentForms=function(C){for(var A=0;
A<C.items.length;
A++){var B=C.items[A];
if(B.replyTo){B.summary=this.COMMENT_ICON_HTML+B.summary+'<form method="POST" class="activity-item-comment-form"><input type="hidden" name="replyTo" value="'+B.replyTo+'"/><textarea name="comment" rows="6" cols="40"></textarea><button type="submit" name="submit">Save</button></form>'
}}};
ActivityFeed.prototype.populateFeed=function(){var C=this.resourceUrl+"/showcomment",B=this.resourceUrl+"/hidecomment";
var E=this;
var A=function(L,N){E.setDivText("feedContainer-"+E.feedId,"");
var K=new JAtom(L);
if(!K||!K.items||K.items.length==0){E.setWarning("No activity was found");
return 
}E.setError(null);
E.setWarning(null);
E.addCommentForms(K);
var M,J;
for(var H=0;
H<K.items.length;
H++){var I=DateUtils.utcStringToDateByHour(K.items[H].updated);
if(H==0){M=I;
J=I
}else{if(I.getTime()>M.getTime()){M=I
}else{if(I.getTime()<J.getTime()){J=I
}}}}var G=E.getDateFormat(J,M);
for(H=0;
H<K.items.length;
H++){E.addItem(K.items[H],G)
}if(K.items.length<E.maxResults){E.hideShowMoreAndWaitingLinks()
}else{E.toggleShowMoreLink(true)
}jQuery(".activity-item:has(.activity-item-comment-icon)").hover(function(){jQuery(this).children("img.activity-item-comment-icon").css("visibility","visible").fadeIn("fast")
},function(){jQuery(this).children("img.activity-item-comment-icon").fadeOut("fast",function(){jQuery(this).css("visibility","hidden").css("display","inline")
})
});
jQuery(".activity-item").hover(function(){jQuery(this).css("background-color","#FFFFF0")
},function(){jQuery(this).css("background-color","")
});
jQuery(".activity-item-comment-icon").click(function(){jQuery(this).parent().children("form.activity-item-comment-form").slideToggle()
}).toggle(function(){jQuery(this).attr("src",B).attr("title","Hide")
},function(){jQuery(this).attr("src",C).attr("title","Add Comment")
});
jQuery(".activity-item-comment-form").children().focus(function(){jQuery(this).parent().children("button").attr("accesskey","s")
}).blur(function(){jQuery(this).parent().children("button").removeAttr("accesskey")
});
jQuery(".activity-item-comment-form").submit(function(P){P.preventDefault();
var O=jQuery(this);
O.children("button").attr("disabled","true");
jQuery.post(E.baseUrl+"/plugins/servlet/streamscomments",jQuery(this).serialize(),function(){O.children("textarea").val("").end();
O.prev(".activity-item-comment-icon").click();
O.children("button").attr("disabled","false");
E.populateFeed()
},"text")
});
E.feedPopulated()
};
var D=function(G,I,H){E.setDivText("feedContainer-"+E.feedId,"");
E.setError("Error communicating with server: "+G.statusText);
E.toggleShowMoreLink(true)
};
var F=this.feedUrl;
if(F.indexOf("?")<0){F+="?"
}else{F+="&"
}F+="maxResults="+this.maxResults;
this.issueRequest("GET",F,null,A,D)
};
ActivityFeed.prototype.issueRequest=function(E,B,C,A,D){jQuery.ajax({type:E,url:B,dataType:"xml",success:A,error:D})
};
ActivityFeed.prototype.feedPopulated=function(){};
ActivityFeed.prototype.setWarning=function(A){this.setMessage("#feedWarning-"+this.feedId,A)
};
ActivityFeed.prototype.setError=function(A){this.setMessage("#feedError-"+this.feedId,A)
};
ActivityFeed.prototype.setMessage=function(C,A){var B=jQuery(C);
B.text(A);
A?B.show():B.hide()
};
ActivityFeed.prototype.setDivText=function(A,B){var C=document.getElementById(A);
if(C){C.innerHTML=B?'<div class="inner">'+B+"</div>":""
}else{alert(B)
}};
ActivityFeed.toggleStackTraces=function(){jQuery(".activityFeed .error .stack-trace").toggle()
};
function isNumeric(B){var D="0123456789";
var A;
for(var C=0;
C<B.length;
C++){A=B.charAt(C);
if(D.indexOf(A)==-1){return false
}}return true
}var DateUtils={format:function(B,A){var C=A.replace("yyyy",B.getFullYear(),"g");
C=C.replace("yy",DateUtils.getShortYear(B),"g");
C=C.replace("MMMMM",DateUtils.getLongMonth(B),"g");
C=C.replace("MMM",DateUtils.getMonthAbbrev(B),"g");
C=C.replace("MM",B.getMonth()+1,"g");
C=C.replace("dd",B.getDate(),"g");
C=C.replace("kk",B.getHours()+1,"g");
C=C.replace("hh",DateUtils.getHourIn12(B),"g");
C=C.replace("aa",DateUtils.getAmOrPm(B),"g");
C=C.replace("mm",B.getMinutes(),"g");
C=C.replace("ss",B.getSeconds(),"g");
return C
},getShortYear:function(A){var B=A.getYear()%100;
return B<10?"0"+B:B
},getLongMonth:function(A){return["January","February","March","April","May","June","July","August","September","October","November","December"][A.getMonth()]
},getMonthAbbrev:function(A){return["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][A.getMonth()]
},getHourIn12:function(A){if(A.getHours()==0){return 12
}else{return A.getHours()>12?A.getHours()-12:A.getHours()
}},getAmOrPm:function(A){return A.getHours()<12?"am":"pm"
},utcStringToDateByHour:function(B){var A=new Date();
A.setUTCFullYear(B.substr(0,4));
A.setUTCMonth(B.substr(5,2)-1);
A.setUTCDate(B.substr(8,2));
A.setUTCHours(B.substr(11,2));
A.setUTCMinutes(0);
A.setUTCSeconds(0);
A.setUTCMilliseconds(0);
return A
}};
function htmlEncode(A){return jQuery("<div/>").text(A).html()
}DateUtils.MILLIS_PER_DAY=1000*60*60*24;

