/*! jQuery v1.6.4 http://jquery.com/ | http://jquery.org/license */
(function(a,b){function cu(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cr(a){if(!cg[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ch||(ch=c.createElement("iframe"),ch.frameBorder=ch.width=ch.height=0),b.appendChild(ch);if(!ci||!ch.createElement)ci=(ch.contentWindow||ch.contentDocument).document,ci.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),ci.close();d=ci.createElement(a),ci.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ch)}cg[a]=e}return cg[a]}function cq(a,b){var c={};f.each(cm.concat.apply([],cm.slice(0,b)),function(){c[this]=a});return c}function cp(){cn=b}function co(){setTimeout(cp,0);return cn=f.now()}function cf(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ce(){try{return new a.XMLHttpRequest}catch(b){}}function b$(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bZ(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 bY(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bA.test(a)?d(a,e):bY(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)bY(a+"["+e+"]",b[e],c,d);else d(a,b)}function bX(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bW(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===bP,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=bW(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bW(a,c,d,e,"*",g));return l}function bV(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bL),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function by(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bt:bu;if(d>0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bv(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function bl(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bd,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bk(a){f.nodeName(a,"input")?bj(a):"getElementsByTagName"in a&&f.grep(a.getElementsByTagName("input"),bj)}function bj(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bi(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function bh(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();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(f.expando)}}function bg(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c=f.expando,d=f.data(a),e=f.data(b,d);if(d=d[c]){var g=d.events;e=e[c]=f.extend({},d);if(g){delete e.handle,e.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)f.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function bf(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function V(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(Q.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function U(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function M(a,b){return(a&&a!=="*"?a+".":"")+b.replace(y,"`").replace(z,"&")}function L(a){var b,c,d,e,g,h,i,j,k,l,m,n,o,p=[],q=[],r=f._data(this,"events");if(!(a.liveFired===this||!r||!r.live||a.target.disabled||a.button&&a.type==="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var s=r.live.slice(0);for(i=0;i<s.length;i++)g=s[i],g.origType.replace(w,"")===a.type?q.push(g.selector):s.splice(i--,1);e=f(a.target).closest(q,a.currentTarget);for(j=0,k=e.length;j<k;j++){m=e[j];for(i=0;i<s.length;i++){g=s[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,d=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,d=f(a.relatedTarget).closest(g.selector)[0],d&&f.contains(h,d)&&(d=h);(!d||d!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){e=p[j];if(c&&e.level>c)break;a.currentTarget=e.elem,a.data=e.handleObj.data,a.handleObj=e.handleObj,o=e.handleObj.origHandler.apply(e.elem,arguments);if(o===!1||a.isPropagationStopped()){c=e.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function J(a,c,d){var e=f.extend({},d[0]);e.type=a,e.originalEvent={},e.liveFired=b,f.event.handle.call(c,e),e.isDefaultPrevented()&&d[0].preventDefault()}function D(){return!0}function C(){return!1}function m(a,c,d){var e=c+"defer",g=c+"queue",h=c+"mark",i=f.data(a,e,b,!0);i&&(d==="queue"||!f.data(a,g,b,!0))&&(d==="mark"||!f.data(a,h,b,!0))&&setTimeout(function(){!f.data(a,g,b,!0)&&!f.data(a,h,b,!0)&&(f.removeData(a,e,!0),i.resolve())},0)}function l(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function k(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(j,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNaN(d)?i.test(d)?f.parseJSON(d):d:parseFloat(d)}catch(g){}f.data(a,c,d)}else d=b}return d}var c=a.document,d=a.navigator,e=a.location,f=function(){function K(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(K,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z]|[0-9])/ig,x=/^-ms-/,y=function(a,b){return(b+"").toUpperCase()},z=d.userAgent,A,B,C,D=Object.prototype.toString,E=Object.prototype.hasOwnProperty,F=Array.prototype.push,G=Array.prototype.slice,H=String.prototype.trim,I=Array.prototype.indexOf,J={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=n.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.6.4",length:0,size:function(){return this.length},toArray:function(){return G.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 d=this.constructor();e.isArray(a)?F.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),B.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(G.apply(this,arguments),"slice",G.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:F,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,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"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;B.resolveWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!B){B=e._Deferred();if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",C,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",C),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&K()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNaN:function(a){return a==null||!m.test(a)||isNaN(a)},type:function(a){return a==null?String(a):J[D.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!E.call(a,"constructor")&&!E.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||E.call(a,d)},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=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(x,"ms-").replace(w,y)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:H?function(a){return a==null?"":H.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?F.call(c,a):e.merge(c,a)}return c},inArray:function(a,b){if(!b)return-1;if(I)return I.call(b,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,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=G.call(arguments,2),g=function(){return a.apply(c,f.concat(G.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=s.exec(a)||t.exec(a)||u.exec(a)||a.indexOf("compatible")<0&&v.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){J["[object "+b+"]"]=b.toLowerCase()}),A=e.uaMatch(z),A.browser&&(e.browser[A.browser]=!0,e.browser.version=A.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?C=function(){c.removeEventListener("DOMContentLoaded",C,!1),e.ready()}:c.attachEvent&&(C=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",C),e.ready())});return e}(),g="done fail isResolved isRejected promise then always pipe".split(" "),h=[].slice;f.extend({_Deferred:function(){var a=[],b,c,d,e={done:function(){if(!d){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=f.type(i),j==="array"?e.done.apply(e,i):j==="function"&&a.push(i);k&&e.resolveWith(k[0],k[1])}return this},resolveWith:function(e,f){if(!d&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(e,f)}finally{b=[e,f],c=0}}return this},resolve:function(){e.resolveWith(this,arguments);return this},isResolved:function(){return!!c||!!b},cancel:function(){d=1,a=[];return this}};return e},Deferred:function(a){var b=f._Deferred(),c=f._Deferred(),d;f.extend(b,{then:function(a,c){b.done(a).fail(c);return this},always:function(){return b.done.apply(b,arguments).fail.apply(this,arguments)},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,pipe:function(a,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[c,"reject"]},function(a,c){var e=c[0],g=c[1],h;f.isFunction(e)?b[a](function(){h=e.apply(this,arguments),h&&f.isFunction(h.promise)?h.promise().then(d.resolve,d.reject):d[g+"With"](this===b?d:this,[h])}):b[a](d[g])})}).promise()},promise:function(a){if(a==null){if(d)return d;d=a={}}var c=g.length;while(c--)a[g[c]]=b[g[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?h.call(arguments,0):c,--e||g.resolveWith(g,h.call(b,0))}}var b=arguments,c=0,d=b.length,e=d,g=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred();if(d>1){for(;c<d;c++)b[c]&&f.isFunction(b[c].promise)?b[c].promise().then(i(c),g.reject):--e;e||g.resolveWith(g,b)}else g!==a&&g.resolveWith(g,d?[a]:[]);return g.promise()}}),f.support=function(){var a=c.createElement("div"),b=c.documentElement,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;a.setAttribute("className","t"),a.innerHTML="   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55$/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.firstChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},m&&f.extend(p,{position:"absolute",left:"-1000px",top:"-1000px"});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0),o.innerHTML="",n.removeChild(o);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var i=/^(?:\{.*\}|\[.*\])$/,j=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.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?f.cache[a[f.expando]]:a[f.expando];return!!a&&!l(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i=f.expando,j=typeof c=="string",k=a.nodeType,l=k?f.cache:a,m=k?a[f.expando]:a[f.expando]&&f.expando;if((!m||e&&m&&l[m]&&!l[m][i])&&j&&d===b)return;m||(k?a[f.expando]=m=++f.uuid:m=f.expando),l[m]||(l[m]={},k||(l[m].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?l[m][i]=f.extend(l[m][i],c):l[m]=f.extend(l[m],c);g=l[m],e&&(g[i]||(g[i]={}),g=g[i]),d!==b&&(g[f.camelCase(c)]=d);if(c==="events"&&!g[c])return g[i]&&g[i].events;j?(h=g[c],h==null&&(h=g[f.camelCase(c)])):h=g;return h}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e=f.expando,g=a.nodeType,h=g?f.cache:a,i=g?a[f.expando]:f.expando;if(!h[i])return;if(b){d=c?h[i][e]:h[i];if(d){d[b]||(b=f.camelCase(b)),delete d[b];if(!l(d))return}}if(c){delete h[i][e];if(!l(h[i]))return}var j=h[i][e];f.support.deleteExpando||!h.setInterval?delete h[i]:h[i]=null,j?(h[i]={},g||(h[i].toJSON=f.noop),h[i][e]=j):g&&(f.support.deleteExpando?delete a[f.expando]:a.removeAttribute?a.removeAttribute(f.expando):a[f.expando]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d=null;if(typeof a=="undefined"){if(this.length){d=f.data(this[0]);if(this[0].nodeType===1){var e=this[0].attributes,g;for(var h=0,i=e.length;h<i;h++)g=e[h].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),k(this[0],g,d[g]))}}return d}if(typeof a=="object")return this.each(function(){f.data(this,a)});var j=a.split(".");j[1]=j[1]?"."+j[1]:"";if(c===b){d=this.triggerHandler("getData"+j[1]+"!",[j[0]]),d===b&&this.length&&(d=f.data(this[0],a),d=k(this[0],a,d));return d===b&&j[1]?this.data(j[0]):d}return this.each(function(){var b=f(this),d=[j[0],c];b.triggerHandler("setData"+j[1]+"!",d),f.data(this,a,c),b.triggerHandler("changeData"+j[1]+"!",d)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,c){a&&(c=(c||"fx")+"mark",f.data(a,c,(f.data(a,c,b,!0)||0)+1,!0))},_unmark:function(a,c,d){a!==!0&&(d=c,c=a,a=!1);if(c){d=d||"fx";var e=d+"mark",g=a?0:(f.data(c,e,b,!0)||1)-1;g?f.data(c,e,g,!0):(f.removeData(c,e,!0),m(c,d,"mark"))}},queue:function(a,c,d){if(a){c=(c||"fx")+"queue";var e=f.data(a,c,b,!0);d&&(!e||f.isArray(d)?e=f.data(a,c,f.makeArray(d),!0):e.push(d));return e||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e;d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),d.call(a,function(){f.dequeue(a,b)})),c.length||(f.removeData(a,b+"queue",!0),m(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){f.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f._Deferred(),!0))h++,l.done(m);m();return d.promise()}});var n=/[\n\t\r]/g,o=/\s+/,p=/\r/g,q=/^(?:button|input)$/i,r=/^(?:button|input|object|select|textarea)$/i,s=/^a(?:rea)?$/i,t=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,u,v;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(o);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(o);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(n," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(o);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(n," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e=this[0];if(!arguments.length){if(e){c=f.valHooks[e.nodeName.toLowerCase()]||f.valHooks[e.type];if(c&&"get"in c&&(d=c.get(e,"value"))!==b)return d;d=e.value;return typeof d=="string"?d.replace(p,""):d==null?"":d}return b}var g=f.isFunction(a);return this.each(function(d){var e=f(this),h;if(this.nodeType===1){g?h=a.call(this,d,e.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c=a.selectedIndex,d=[],e=a.options,g=a.type==="select-one";if(c<0)return null;for(var h=g?c:0,i=g?c+1:e.length;h<i;h++){var j=e[h];if(j.selected&&(f.support.optDisabled?!j.disabled:j.getAttribute("disabled")===null)&&(!j.parentNode.disabled||!f.nodeName(j.parentNode,"optgroup"))){b=f(j).val();if(g)return b;d.push(b)}}if(g&&!d.length&&e.length)return f(e[c]).val();return d},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attrFix:{tabindex:"tabIndex"},attr:function(a,c,d,e){var g=a.nodeType;if(!a||g===3||g===8||g===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);var h,i,j=g!==1||!f.isXMLDoc(a);j&&(c=f.attrFix[c]||c,i=f.attrHooks[c],i||(t.test(c)?i=v:u&&(i=u)));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(i&&"set"in i&&j&&(h=i.set(a,d,c))!==b)return h;a.setAttribute(c,""+d);return d}if(i&&"get"in i&&j&&(h=i.get(a,c))!==null)return h;h=a.getAttribute(c);return h===null?b:h},removeAttr:function(a,b){var c;a.nodeType===1&&(b=f.attrFix[b]||b,f.attr(a,b,""),a.removeAttribute(b),t.test(b)&&(c=f.propFix[b]||b)in a&&(a[c]=!1))},attrHooks:{type:{set:function(a,b){if(q.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(u&&f.nodeName(a,"button"))return u.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(u&&f.nodeName(a,"button"))return u.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e=a.nodeType;if(!a||e===3||e===8||e===2)return b;var g,h,i=e!==1||!f.isXMLDoc(a);i&&(c=f.propFix[c]||c,h=f.propHooks[c]);return d!==b?h&&"set"in h&&(g=h.set(a,d,c))!==b?g:a[c]=d:h&&"get"in h&&(g=h.get(a,c))!==null?g:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):r.test(a.nodeName)||s.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabIndex=f.propHooks.tabIndex,v={get:function(a,c){var d;return f.prop(a,c)===!0||(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},f.support.getSetAttribute||(u=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&d.nodeValue!==""?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})})),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var w=/\.(.*)$/,x=/^(?:textarea|input|select)$/i,y=/\./g,z=/ /g,A=/[^\w\s.|`]/g,B=function(a){return a.replace(A,"\\$&")};f.event={add:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){if(d===!1)d=C;else if(!d)return;var g,h;d.handler&&(g=d,d=g.handler),d.guid||(d.guid=f.guid++);var i=f._data(a);if(!i)return;var j=i.events,k=i.handle;j||(i.events=j={}),k||(i.handle=k=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.handle.apply(k.elem,arguments):b}),k.elem=a,c=c.split(" ");var l,m=0,n;while(l=c[m++]){h=g?f.extend({},g):{handler:d,data:e},l.indexOf(".")>-1?(n=l.split("."),l=n.shift(),h.namespace=n.slice(0).sort().join(".")):(n=[],h.namespace=""),h.type=l,h.guid||(h.guid=d.guid);var o=j[l],p=f.event.special[l]||{};if(!o){o=j[l]=[];if(!p.setup||p.setup.call(a,e,n,k)===!1)a.addEventListener?a.addEventListener(l,k,!1):a.attachEvent&&a.attachEvent("on"+l,k)}p.add&&(p.add.call(a,h),h.handler.guid||(h.handler.guid=d.guid)),o.push(h),f.event.global[l]=!0}a=null}},global:{},remove:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){d===!1&&(d=C);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=f.hasData(a)&&f._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(d=c.handler,c=c.type);if(!c||typeof c=="string"&&c.charAt(0)==="."){c=c||"";for(h in t)f.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("(^|\\.)"+f.map(m.slice(0).sort(),B).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!d){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))f.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=f.event.special[h]||{};for(j=e||0;j<p.length;j++){q=p[j];if(d.guid===q.guid){if(l||n.test(q.namespace))e==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(e!=null)break}}if(p.length===0||e!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&f.removeEvent(a,h,s.handle),g=null,delete 
t[h]}if(f.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,f.isEmptyObject(s)&&f.removeData(a,b,!0)}}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){var h=c.type||c,i=[],j;h.indexOf("!")>=0&&(h=h.slice(0,-1),j=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if(!!e&&!f.event.customEvent[h]||!!f.event.global[h]){c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.exclusive=j,c.namespace=i.join("."),c.namespace_re=new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)");if(g||!e)c.preventDefault(),c.stopPropagation();if(!e){f.each(f.cache,function(){var a=f.expando,b=this[a];b&&b.events&&b.events[h]&&f.event.trigger(c,d,b.handle.elem)});return}if(e.nodeType===3||e.nodeType===8)return;c.result=b,c.target=e,d=d!=null?f.makeArray(d):[],d.unshift(c);var k=e,l=h.indexOf(":")<0?"on"+h:"";do{var m=f._data(k,"handle");c.currentTarget=k,m&&m.apply(k,d),l&&f.acceptData(k)&&k[l]&&k[l].apply(k,d)===!1&&(c.result=!1,c.preventDefault()),k=k.parentNode||k.ownerDocument||k===c.target.ownerDocument&&a}while(k&&!c.isPropagationStopped());if(!c.isDefaultPrevented()){var n,o=f.event.special[h]||{};if((!o._default||o._default.call(e.ownerDocument,c)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)){try{l&&e[h]&&(n=e[l],n&&(e[l]=null),f.event.triggered=h,e[h]())}catch(p){}n&&(e[l]=n),f.event.triggered=b}}return c.result}},handle:function(c){c=f.event.fix(c||a.event);var d=((f._data(this,"events")||{})[c.type]||[]).slice(0),e=!c.exclusive&&!c.namespace,g=Array.prototype.slice.call(arguments,0);g[0]=c,c.currentTarget=this;for(var h=0,i=d.length;h<i;h++){var j=d[h];if(e||c.namespace_re.test(j.namespace)){c.handler=j.handler,c.data=j.data,c.handleObj=j;var k=j.handler.apply(this,g);k!==b&&(c.result=k,k===!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[f.expando])return a;var d=a;a=f.Event(d);for(var e=this.props.length,g;e;)g=this.props[--e],a[g]=d[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=a.target.ownerDocument||c,i=h.documentElement,j=h.body;a.pageX=a.clientX+(i&&i.scrollLeft||j&&j.scrollLeft||0)-(i&&i.clientLeft||j&&j.clientLeft||0),a.pageY=a.clientY+(i&&i.scrollTop||j&&j.scrollTop||0)-(i&&i.clientTop||j&&j.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:f.proxy,special:{ready:{setup:f.bindReady,teardown:f.noop},live:{add:function(a){f.event.add(this,M(a.origType,a.selector),f.extend({},a,{handler:L,guid:a.handler.guid}))},remove:function(a){f.event.remove(this,M(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},f.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)},f.Event=function(a,b){if(!this.preventDefault)return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?D:C):this.type=a,b&&f.extend(this,b),this.timeStamp=f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=D;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=D;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=D,this.stopPropagation()},isDefaultPrevented:C,isPropagationStopped:C,isImmediatePropagationStopped:C};var E=function(a){var b=a.relatedTarget,c=!1,d=a.type;a.type=a.data,b!==this&&(b&&(c=f.contains(this,b)),c||(f.event.handle.apply(this,arguments),a.type=d))},F=function(a){a.type=a.data,f.event.handle.apply(this,arguments)};f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={setup:function(c){f.event.add(this,b,c&&c.selector?F:E,a)},teardown:function(a){f.event.remove(this,b,a&&a.selector?F:E)}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(a,b){if(!f.nodeName(this,"form"))f.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=f.nodeName(b,"input")||f.nodeName(b,"button")?b.type:"";(c==="submit"||c==="image")&&f(b).closest("form").length&&J("submit",this,arguments)}),f.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=f.nodeName(b,"input")||f.nodeName(b,"button")?b.type:"";(c==="text"||c==="password")&&f(b).closest("form").length&&a.keyCode===13&&J("submit",this,arguments)});else return!1},teardown:function(a){f.event.remove(this,".specialSubmit")}});if(!f.support.changeBubbles){var G,H=function(a){var b=f.nodeName(a,"input")?a.type:"",c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?f.map(a.options,function(a){return a.selected}).join("-"):"":f.nodeName(a,"select")&&(c=a.selectedIndex);return c},I=function(c){var d=c.target,e,g;if(!!x.test(d.nodeName)&&!d.readOnly){e=f._data(d,"_change_data"),g=H(d),(c.type!=="focusout"||d.type!=="radio")&&f._data(d,"_change_data",g);if(e===b||g===e)return;if(e!=null||g)c.type="change",c.liveFired=b,f.event.trigger(c,arguments[1],d)}};f.event.special.change={filters:{focusout:I,beforedeactivate:I,click:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(c==="radio"||c==="checkbox"||f.nodeName(b,"select"))&&I.call(this,a)},keydown:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(a.keyCode===13&&!f.nodeName(b,"textarea")||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&I.call(this,a)},beforeactivate:function(a){var b=a.target;f._data(b,"_change_data",H(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in G)f.event.add(this,c+".specialChange",G[c]);return x.test(this.nodeName)},teardown:function(a){f.event.remove(this,".specialChange");return x.test(this.nodeName)}},G=f.event.special.change.filters,G.focus=G.beforeactivate}f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){function e(a){var c=f.event.fix(a);c.type=b,c.originalEvent={},f.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var d=0;f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.each(["bind","one"],function(a,c){f.fn[c]=function(a,d,e){var g;if(typeof a=="object"){for(var h in a)this[c](h,d,a[h],e);return this}if(arguments.length===2||d===!1)e=d,d=b;c==="one"?(g=function(a){f(this).unbind(a,g);return e.apply(this,arguments)},g.guid=e.guid||f.guid++):g=e;if(a==="unload"&&c!=="one")this.one(a,d,e);else for(var i=0,j=this.length;i<j;i++)f.event.add(this[i],a,g,d);return this}}),f.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 d=0,e=this.length;d<e;d++)f.event.remove(this[d],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(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f.data(this,"lastToggle"+a.guid)||0)%d;f.data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var K={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};f.each(["live","die"],function(a,c){f.fn[c]=function(a,d,e,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:f(this.context);if(typeof a=="object"&&!a.preventDefault){for(var o in a)n[c](o,d,a[o],m);return this}if(c==="die"&&!a&&g&&g.charAt(0)==="."){n.unbind(g);return this}if(d===!1||f.isFunction(d))e=d||C,d=b;a=(a||"").split(" ");while((h=a[i++])!=null){j=w.exec(h),k="",j&&(k=j[0],h=h.replace(w,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,K[h]?(a.push(K[h]+k),h=h+k):h=(K[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)f.event.add(n[p],"live."+M(h,m),{data:d,selector:m,handler:e,origType:h,origHandler:e,preType:l});else n.unbind("live."+M(h,m),e)}return this}}),f.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){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.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,d=0,e=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,f,g){f=f||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return f;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(e.call(n)==="[object Array]")if(!u)f.push.apply(f,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]))&&f.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&f.push(j[t]);else p(n,f);o&&(k(o,h,f,g),k.uniqueSort(f));return f};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 e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("parentNode",b,f,a,e,c)},"~":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("previousSibling",b,f,a,e,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]=d++;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 a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},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(e.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var f=a.length;c<f;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){if(a===b){g=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;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)};f.find=k,f.expr=k.selectors,f.expr[":"]=f.expr.filters,f.unique=k.uniqueSort,f.text=k.getText,f.isXMLDoc=k.isXML,f.contains=k.contains}();var N=/Until$/,O=/^(?:parents|prevUntil|prevAll)/,P=/,/,Q=/^.[^:#\[\.,]*$/,R=Array.prototype.slice,S=f.expr.match.POS,T={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(V(this,a,!1),"not",a)},filter:function(a){return this.pushStack(V(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(d=0,e=a.length;d<e;d++)i=a[d],j[i]||(j[i]=S.test(i)?f(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:f(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=S.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(l?l.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(U(c[0])||U(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c),g=R.call(arguments);N.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!T[a]?f.unique(e):e,(this.length>1||P.test(d))&&O.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},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 W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|object|embed|option|style)/i,bb=/checked\s*(?:[^=]|=\s*.checked.)/i,bc=/\/(java|ecma)script/i,bd=/^\s*<!(?:\[CDATA\[|\-\-)/,be={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,"",""]};be.optgroup=be.option,be.tbody=be.tfoot=be.colgroup=be.caption=be.thead,be.th=be.td,f.support.htmlSerialize||(be._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(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 f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(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(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){f(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(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=f(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,f(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.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 f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!be[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(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(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bb.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bf(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bl)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i;b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof a[0]=="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!ba.test(a[0])&&(f.support.checkClone||!bb.test(a[0]))&&(g=!0,h=f.fragments[a[0]],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean
(a,i,e,d)),g&&(f.fragments[a[0]]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bh(a,d),e=bi(a),g=bi(d);for(h=0;e[h];++h)g[h]&&bh(e[h],g[h])}if(b){bg(a,d);if(c){e=bi(a),g=bi(d);for(h=0;e[h];++h)bg(e[h],g[h])}}e=g=null;return d},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=be[l]||be._default,n=m[0],o=b.createElement("div");o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bk(k[i]);else bk(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bc.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.expando,g=f.event.special,h=f.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&f.noData[j.nodeName.toLowerCase()])continue;c=j[f.expando];if(c){b=d[c]&&d[c][e];if(b&&b.events){for(var k in b.events)g[k]?f.event.remove(j,k):f.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[f.expando]:j.removeAttribute&&j.removeAttribute(f.expando),delete d[c]}}}});var bm=/alpha\([^)]*\)/i,bn=/opacity=([^)]*)/,bo=/([A-Z]|^ms)/g,bp=/^-?\d+(?:px)?$/i,bq=/^-?\d/,br=/^([\-+])=([\-+.\de]+)/,bs={position:"absolute",visibility:"hidden",display:"block"},bt=["Left","Right"],bu=["Top","Bottom"],bv,bw,bx;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bv(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=br.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bv)return bv(a,c)},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]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return by(a,b,d);f.swap(a,bs,function(){e=by(a,b,d)});return e}},set:function(a,b){if(!bp.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bn.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNaN(b)?"":"alpha(opacity="+b*100+")",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bm,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bm.test(g)?g.replace(bm,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bv(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bw=function(a,c){var d,e,g;c=c.replace(bo,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bx=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bp.test(d)&&bq.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}),bv=bw||bx,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bz=/%20/g,bA=/\[\]$/,bB=/\r?\n/g,bC=/#.*$/,bD=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bE=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bF=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bG=/^(?:GET|HEAD)$/,bH=/^\/\//,bI=/\?/,bJ=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bK=/^(?:select|textarea)/i,bL=/\s+/,bM=/([?&])_=[^&]*/,bN=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bO=f.fn.load,bP={},bQ={},bR,bS,bT=["*/"]+["*"];try{bR=e.href}catch(bU){bR=c.createElement("a"),bR.href="",bR=bR.href}bS=bN.exec(bR.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bO)return bO.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.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?f("<div>").append(c.replace(bJ,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bK.test(this.nodeName)||bE.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bB,"\r\n")}}):{name:b.name,value:c.replace(bB,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?bX(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),bX(a,b);return a},ajaxSettings:{url:bR,isLocal:bF.test(bS[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","*":bT},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bV(bP),ajaxTransport:bV(bQ),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?bZ(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=b$(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.resolveWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f._Deferred(),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bD.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.done,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bC,"").replace(bH,bS[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bL),d.crossDomain==null&&(r=bN.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bS[1]&&r[2]==bS[2]&&(r[3]||(r[1]==="http:"?80:443))==(bS[3]||(bS[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bW(bP,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bG.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bI.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bM,"$1_="+x);d.url=y+(y===d.url?(bI.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bT+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bW(bQ,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){s<2?w(-1,z):f.error(z)}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)bY(g,a[g],c,e);return d.join("&").replace(bz,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var b_=f.now(),ca=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+b_++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ca.test(b.url)||e&&ca.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ca,l),b.url===j&&(e&&(k=k.replace(ca,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.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(c||!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 cb=a.ActiveXObject?function(){for(var a in cd)cd[a](0,1)}:!1,cc=0,cd;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ce()||cf()}:ce,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cb&&delete cd[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cc,cb&&(cd||(cd={},f(a).unload(cb)),cd[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cg={},ch,ci,cj=/^(?:toggle|show|hide)$/,ck=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cl,cm=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cn;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cq("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cr(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cq("hide",3),a,b,c);for(var d=0,e=this.length;d<e;d++)if(this[d].style){var g=f.css(this[d],"display");g!=="none"&&!f._data(this[d],"olddisplay")&&f._data(this[d],"olddisplay",g)}for(d=0;d<e;d++)this[d].style&&(this[d].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cq("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,d){var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return this[e.queue===!1?"each":"queue"](function(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(f.support.inlineBlockNeedsLayout?(j=cr(this.nodeName),j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)):this.style.display="inline-block"))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)k=new f.fx(this,b,i),h=a[i],cj.test(h)?k[h==="toggle"?d?"show":"hide":h]():(l=ck.exec(h),m=k.cur(),l?(n=parseFloat(l[2]),o=l[3]||(f.cssNumber[i]?"":"px"),o!=="px"&&(f.style(this,i,(n||1)+o),m=(n||1)/k.cur()*m,f.style(this,i,m+o)),l[1]&&(n=(l[1]==="-="?-1:1)*n+m),k.custom(m,n,o)):k.custom(m,h,""));return!0})},stop:function(a,b){a&&this.queue([]),this.each(function(){var a=f.timers,c=a.length;b||f._unmark(!0,this);while(c--)a[c].elem===this&&(b&&a[c](!0),a.splice(c,1))}),b||this.dequeue();return this}}),f.each({slideDown:cq("show",1),slideUp:cq("hide",1),slideToggle:cq("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default,d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue!==!1?f.dequeue(this):a!==!1&&f._unmark(this)};return d},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||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.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=f.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 d.step(a)}var d=this,e=f.fx;this.startTime=cn||co(),this.start=a,this.end=b,this.unit=c||this.unit||(f.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,g.elem=this.elem,g()&&f.timers.push(g)&&!cl&&(cl=setInterval(e.tick,e.interval))},show:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=cn||co(),c=!0,d=this.elem,e=this.options,g,h;if(a||b>=e.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),e.animatedProperties[this.prop]=!0;for(g in e.animatedProperties)e.animatedProperties[g]!==!0&&(c=!1);if(c){e.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){d.style["overflow"+b]=e.overflow[a]}),e.hide&&f(d).hide();if(e.hide||e.show)for(var i in e.animatedProperties)f.style(d,i,e.orig[i]);e.complete.call(d)}return!1}e.duration==Infinity?this.now=b:(h=b-this.startTime,this.state=h/e.duration,this.pos=f.easing[e.animatedProperties[this.prop]](this.state,h,0,1,e.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){for(var a=f.timers,b=0;b<a.length;++b)a[b]()||a.splice(b--,1);a.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cl),cl=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.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}}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cs=/^t(?:able|d|h)$/i,ct=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cu(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);f.offset.initialize();var c,d=b.offsetParent,e=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(f.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.offset.doesNotAddBorder&&(!f.offset.doesAddBorderForTableAndCells||!cs.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.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;f.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={initialize:function(){var a=c.body,b=c.createElement("div"),d,e,g,h,i=parseFloat(f.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>";f.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),d=b.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,this.doesNotAddBorder=e.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,e.style.position="fixed",e.style.top="20px",this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),f.offset.initialize=f.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.offset.initialize(),f.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.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):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=ct.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!ct.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cu(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cu(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a&&a.style?parseFloat(f.css(a,d,"padding")):null},f.fn["outer"+c]=function(a){var b=this[0];return b&&b.style?parseFloat(f.css(b,d,a?"margin":"border")):null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNaN(j)?i:j}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window);
jQuery.noConflict();
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;";case"`":return"&#96;";default:return"&quot;"}}var B=/[&"'<>`]/g;var D={version:"3.6.4",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+"\n"+H.toString())}});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(I){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);AJS.hasFlash=false;var H=/^[^:]*:\/*[^/]*|/;var G=H.exec(location.href)[0];if(AJS.$.browser.msie&&typeof AJS.hasFlash==="undefined"&&I===false){AJS.$("object, embed, iframe").each(function(){if(this.nodeName.toLowerCase()==="iframe"){if(H.exec(this.src)[0]===G&&AJS.$(this).contents().find("object, embed").length===0){return true}}AJS.hasFlash=true;return false})}if(AJS.$.browser.msie&&(I!==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")}}},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 G=AJS.$(window).scrollTop();AJS.$(window).scrollTop(10+5*(G==10)).scrollTop(G)}}},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;
(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}}})();
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;if(X.length===0){return }W.focused=(typeof a==="number")?a:-Z*X.length;if(!AJS.dropDown.current){AJS.log("move - not current, aborting");return true}W.focused+=Z;if(W.focused<0){W.focused=X.length-1}else{if(W.focused>=X.length){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)}})},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.reset=X.reset;Z.reset();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.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)};
/*!
 * 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})()};
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);
/*
 * 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);
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.length===0||(!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=AJS||{};(function(){var A="";A=A.indexOf("%_CONTEXT_PATH")==0?false:A;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{if(typeof B==="function"){return jQuery(window).bind(A,C,B)}else{return jQuery(window).bind(A,C)}}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 B="AJS.conglomerate.cookie",F=/(\\|^"|"$)/g,G=/\|\|+/g,I=/"/g,C=/[.*+?|^$()[\]{\\]/g;function E(L,O){O=O||"";var N=new RegExp(D(L)+"=([^|]+)"),M=O.match(N);return M&&M[1]}function J(L,N,P){var M=new RegExp("(\\s|\\|)*\\b"+D(L)+"=[^|]*[|]*");P=P||"";P=P.replace(M,"|");if(N!==""){var O=L+"="+N;if(P.length+O.length<4020){P+="|"+O}}return P.replace(G,"|")}function H(L){return L.replace(F,"")}function K(L){var N=new RegExp("\\b"+D(L)+"=((?:[^\\\\;]+|\\\\.)*)(?:;|$)"),M=document.cookie.match(N);return M&&H(M[1])}function A(M,O,Q){var N="",P,L='"'+O.replace(I,'\\"')+'"';if(Q){P=new Date();P.setTime(+P+Q*24*60*60*1000);N="; expires="+P.toGMTString()}document.cookie=M+"="+L+N+";path=/"}function D(L){return L.replace(C,"\\$&")}AJS.Cookie={save:function(M,N,L){var O=K(B);O=J(M,N,O);A(B,O,L||365)},read:function(M,L){var O=K(B);var N=E(M,O);if(N!=null){return N}return L},erase:function(L){this.save(L,"")}}})();
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(J,K){var L=AJS.$(J,K);if(L.length){L.focus();return true}return false},H=function(J){if(I.focusSelector){return A(I.focusSelector,J)}var K=":input:visible:enabled:first";if(A(K,AJS.$(".dialog-page-body",J))){return }if(A(K,AJS.$(".dialog-button-panel",J))){return }A(K,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}})();
(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)[0];if(G&&G.nodeName.toLowerCase()==="a"){window.location.href=G.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)})})}};
(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.length===0||(!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)[0];if(G&&G.nodeName.toLowerCase()==="a"){window.location.href=G.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)})})}};

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) {
                // 404 for status means either no such result key exists OR build is not executing
                // both cases are a good reason to reload, otherwise just wait
                if (XMLHttpRequest.status == 404) {
                    window.location.reload(true);
                    return;
                }
                // 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";

window.BAMBOO = (window.BAMBOO || {});
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 reloadThePage() {
    window.location.reload(true);
}

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

if (!jQuery.isNumeric) {
    jQuery.isNumeric = function (n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    };
}

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

// 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;
}

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

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

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

/*
*  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, toHide, toShow)
{
    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) {
            toShow.push('#resumeBuild_' + planKey);
            toHide.push( '#stopSingleBuild_' + planKey, '#stopMultipleBuilds_' + planKey, '#manualBuild_' + planKey);
        } else {
            toHide.push('#resumeBuild_' + planKey);
            if (plan.allowStop) {            
                toHide.push('#manualBuild_' + planKey);
                if (plan.numberOfCurrentlyBuildingPlans > 1) {
                    toHide.push('#stopSingleBuild_' + planKey);
                    toShow.push('#stopMultipleBuilds_' + planKey);
                } else {
                    toShow.push('#stopSingleBuild_' + planKey);
                    toHide.push('#stopMultipleBuilds_' + planKey);
                }
            } else {
                toHide.push('#stopSingleBuild_' + planKey, '#stopMultipleBuilds_' + planKey);
                toShow.push('#manualBuild_' + planKey);
            }
        }
    } 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,
                            toHide = [], toShow = [];
                        //Using toHide/toShow arrays here and deferring hide/show improved performance 20x,
                        //do not change it without heavy performance testing (on 2000 top level plans) please
                        for (var i = 0, len = plans.length; i < len; i++) {
                            var plan = plans[i];
                            updatePlan(plan, toHide, toShow);
                        }
                        if (toHide.length) {
                            AJS.$(toHide.join(',')).hide();
                        }
                        if (toShow.length) {
                            AJS.$(toShow.join(',')).show();
                        }
                    }
                } catch (x) {
                    console.warn("JSON Parse failed! " + x + "\n", response);
                }

                sinceSystemTime = response ? response.currentTime : 0;

                BAMBOO.panelTimeouts[panelId] = setTimeout(function () { updatePlans(sinceSystemTime); }, 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 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())));
    });
}

/**
 * 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: "nothing",
                    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: 'nothing', 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');
            }
        }
    };
}();

/**
 * Generic selection in table control without support for pagination.
 * Selectors need to have 2 attributes :
 *  - data-selector-id (must match name of the checkbox group)
 *  - data-selector-type (ALL, NONE or custom selector that will be match by discriminators)
 *
 * Checkboxes can specify a comma-separated list of discriminators for selection in
 * the 'data-selector-discriminator' attribute.
 *
 */
var GenericSelectionActions = function($) {
    var SELECT_ALL = "ALL", DESELECT_ALL = "NONE";

    return {

        init: function (formId, checkboxName) {
            registerSelectionActions();

            function registerSelectionActions() {
                var $form = $(BAMBOO.escapeIdToJQuerySelector("#" + formId));
                if ($form.length === 0) {
                    return;
                }
                $form.find("span[data-selector-id='"+checkboxName+"']").click(function() {
                        discriminator = $(this).data("selectorType");
                    applyToCheckboxes($form, discriminator);
                });
            }

            function applyToCheckboxes($inForm, discriminator) {
                $inForm.find("input:checkbox").each(function() {
                    var $this = $(this);
                    if (matchesDiscriminator($this, discriminator)) {
                        $this.attr("checked", "checked");
                    } else {
                        $this.removeAttr("checked");
                    }
                });
            }

            function matchesDiscriminator($checkbox, selector) {
                var found = false;
                if (selector === SELECT_ALL) {
                    return true;
                } else if (selector === DESELECT_ALL) {
                    return false;
                } else {
                    $.each($checkbox.data("selectorDiscriminator").split(","), function(index, value) {
                        if (value === selector) {
                            found = true;
                            return true;
                        }
                    });
                    return found;
                }
            }
        }
    };
}(AJS.$);

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 (htmlOrJson) {
                    if (htmlOrJson.status && htmlOrJson.status == "ERROR") {
                        if (event.data.failureHandler) {
                            event.data.failureHandler(htmlOrJson);
                        }
                    } else {
                        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,
        activeJobResultKey: 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
            if (opts.activeJobResultKey) {
                $jobResultKeyForLogDisplaySelect.val(opts.activeJobResultKey);
            }
            $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']};

    // Drop down for user profile
    AJS.$("#header > .global > .secondary .aui-dd-parent").dropDown("Standard", { trigger: "span.aui-dd-trigger" });
});

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

BAMBOO.DynamicFieldParameters = (function ($) {
    var handleOnSelectShowHideSelector = ".handleOnSelectShowHide",
        handleDynamicDescriptionSelector = ".handleDynamicDescription",
        // lifted straight from jQuery, just changed the order
        fxAttrs = [
            // height animations
            [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
            // opacity animations
            [ "opacity" ],
            // width animations
            [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ]
        ],
        // object to handle the methods we make 'public'
        ret = {};

    /**
     * Handles form select field dynamic description updating
     */
    function handleDynamicSelectDescription() {
        var $select = $(this);

        $select.nextAll(".description").html($select.find("option:selected").attr("data-dynamic-select-description") || null);
    }

    /**
     * Syncs form display states for handleOnSelectShowHide fields and select field dynamic description updating
     * @param context (optional) - DOM Element, Document or jQuery object to use as context
     * @param animate (optional) - force transition animations
     */
    ret.syncFieldShowHide = function (context, animate) {
        if (typeof context === "boolean") {
            animate = context;
            context = null;
        }
        $(".handleOnSelectShowHide", context).each(function () { handleOnSelectShowHide.call(this, animate); });
        $(handleDynamicDescriptionSelector, context).each(handleDynamicSelectDescription);
    };

    /**
     * Runs on a change of a field
     */
    function handleOnSelectShowHide(e) {
        var $el = $(this),
            dependsOnSelector = (".dependsOn" + $el.prop("name").replaceAll(".", "\\.")),
            switchValue = getSwitchValue($el),
            showPattern, hidePattern,
            useAnimations = (e instanceof jQuery.Event || (typeof e === "boolean" && e)),
            showFn = !useAnimations ? jQuery.fn.show : function () {
                this.animate(genFx("show", 2), function () { $(this).show(); });
            },
            hideFn = !useAnimations ? jQuery.fn.hide : function () {
                this.animate(genFx("hide", 2), function () { $(this).hide(); });
            };

        if (!(!switchValue && $el.is(":radio"))) {
            showPattern = "showOn" + switchValue;
            hidePattern = "showOn__" + switchValue;

            $el.closest("form").find(dependsOnSelector).each(function () {
                var $deps = $(this);

                if ($deps.prop("class").indexOf("showOn__") != -1) {
                    if ($deps.hasClass(hidePattern)) {
                        hideFn.call($deps);
                    } else {
                        showFn.call($deps);
                    }
                } else {
                    if ($deps.hasClass(showPattern)) {
                        showFn.call($deps);
                    } else {
                        hideFn.call($deps);
                    }
                }
                if ($deps.hasClass(hidePattern)) {
                    hideFn.call($deps);
                }
            });
        }
    }

    /**
     * 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
     */
    ret.mutateSelectListContent = function (selParentJQ, selToMutateJQ, listDataJson) {
        var selToMutate = selToMutateJQ[0],
            currentSelectedValue = selToMutateJQ.val(),
            switchValue = getSwitchValue(selParentJQ),
            listData = listDataJson.data;

        //wipe existing items
        selToMutate.options.length = 0;

        // go 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,
                text = listData[i].text,
                allowedOptions = listData[i].supportedValues,
                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.call(selToMutate)
    };

    function getSwitchValue($el) {
        if ($el.is("select") && $el.prop("selectedIndex") > -1) {
            var $opt = $el.find("option:selected").filter(":first"),
                optClass = $opt.prop("class");

            //  Special uiSwitch* class prefix
            if (optClass.indexOf('uiSwitch') != -1) {
                return optClass.substring(optClass.lastIndexOf("uiSwitch") + 8);
            } else {
                return $el.val();
            }
        } else if ($el.is(":radio") || $el.is(":checkbox")) {
            return ($el.is(":checked") ? $el.val() : false);
        } else {
            return $el.val();
        }
    }

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

        if (!$firstError.length) {
            $form.find(":input:visible:enabled:first").focus();
        }
    };

    /** Generate parameters to create a standard animation
     * This has been lifted straight from jQuery
     * @param type
     * @param num
     */
    function genFx( type, num ) {
        var obj = {};

        jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
            obj[ this ] = type;
        });

        return obj;
    }

    // handleOnSelectShowHide functionality
    $(document)
        .delegate('input' + handleOnSelectShowHideSelector, 'click', handleOnSelectShowHide)
        .delegate('select' + handleOnSelectShowHideSelector, 'change', handleOnSelectShowHide)
        .delegate(handleDynamicDescriptionSelector, 'change', handleDynamicSelectDescription);

    $(function () {
        ret.syncFieldShowHide();
    });

    return ret;
})(jQuery);
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: {
                enabled: true,
                items: "> li",
                moveItem: $.noop
            }
        },
        options,
        $editor,
        $configContainer,
        $itemList,
        $defaultText,
        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: 'nothing', confirm: true },
                success: function (html) {
                    $item[attachMethod](attachTarget).addClass("active unsaved").siblings().removeClass("active");
                    checkListHasItems();
                    $configContainer.html(html);
                    handleOnShow();
                    setupAsyncForm($item);
                    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: 'nothing', 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 () {
            BAMBOO.DynamicFieldParameters.syncFieldShowHide($configContainer);
        };

    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);
                if (options.sortable.enabled) {
                    $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("keypress keyup click", function (e) {
                    var textToLookFor = $(this).val().toUpperCase();

                    e.stopPropagation();
                    $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: "nothing", 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,
        selectRepositorySelector: "#selectedRepository",
        templates: {
            repositoryListItem: null,
            repositoryListItemDefaultMarker: 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,
        markDefault: true,
        getRepoConfigUrl: null,
        preselectItemId: null
    },
    options,
    editor = new BAMBOO.ConfigPanelEditor(),
    $repositorySetupContainer,
    $repositoryConfigContainer,
    $repositoryList,
    $loadingIndicator,
    checkListHasItems = function(hasItems) {
        if (hasItems) {
            markDefaultRepository();
        }
    },
    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");
    },
    markDefaultRepository = function() {
        if (options.markDefault) {
            $repositoryList.find(".item-default").removeClass("item-default").find(".item-default-marker").remove();
            $repositoryList.find(".item:first").addClass("item-default").find(".item-title").append(
                    AJS.template.load(options.templates.repositoryListItemDefaultMarker).toString()
            );
        }
    },
    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();
        });

        markDefaultRepository();
    },
    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"),
            "bamboo.successReturnMode": "json"
        }, function(data) { markDefaultRepository() } );
    },
    loadRepoConfigJqXHR,
    selectRepositoryType = function (e) {
        var $selectRepository = $(this),
            $selectRepositoryFieldGroup = $selectRepository.closest(".field-group"),
            $selectRepositoryError = $selectRepositoryFieldGroup.next(".aui-message.error"),
            val = $selectRepository.val(),
            $loading = $selectRepository.next(".icon-loading"),
            $repoConfig = $("#repository-configuration"),
            $repoAdvanced = $repoConfig.find('.collapsible-section'),
            $repoEdit = $("#repository-edit-" + BAMBOO.escapeIdToJQuerySelector(val)),
            isGlobal = $.isNumeric(val),
            data = {
                decorator: "nothing",
                confirm: true,
                selectedRepository: val // this makes the dependsOn stuff on the ui.bambooSection not add display:none; to the fieldset
            };

        if ($selectRepositoryError.length) {
            $selectRepositoryError.remove();
        }
        if (!$repoEdit.length) {
            e && e.stopPropagation();
            
            if ($loading.length) {
                $loading.show();
            } else {
                $loading = $(AJS.template.load(options.templates.iconTemplate).fill({ type: "loading" }).toString()).insertAfter($selectRepository);
            }

            data[(isGlobal ? "globalRepositoryId" : "repositoryPluginKey")] = val;

            // Cancel pending request (if applicable)
            if (loadRepoConfigJqXHR && loadRepoConfigJqXHR.readyState < 4) {
                loadRepoConfigJqXHR.abort();
            }
            
            loadRepoConfigJqXHR = $.get(options.getRepoConfigUrl, data).done(function (html) {
                var $html = $(html),
                    $basic = $html.filter("#repository-edit-html").children(),
                    $advanced = $html.filter("#repository-advanced-edit-html").children(),
                    $scripts = $html.filter("script");

                if ($basic.length) {
                    $repoAdvanced.before($basic.hide());
                }
                if ($advanced.length) {
                    $repoAdvanced.children(".collapsible-details").prepend($advanced.hide());
                }
                if ($basic.length || $advanced.length) {
                    BAMBOO.DynamicFieldParameters.syncFieldShowHide($repositoryConfigContainer, true);
                }

                // If any scripts were returned append them to the <head> so that they get executed
                if ($scripts.length) {
                    $scripts.appendTo("head");
                }
            }).fail(function (jqXHR, textStatus) {
                if (textStatus != "abort") {
                    $selectRepositoryError = BAMBOO.buildAUIErrorMessage([ "An error occurred while retrieving the configuration for " + $selectRepository.find(":selected").text() ])
                        .append('<p>Try to <a class="try-again">load the configuration</a> again, or if the problem persists please <a href="' + AJS.contextPath() + '/viewAdministrators.action">contact your administrators</a>.</p>')
                        .delegate("a.try-again", "click", function () { selectRepositoryType.call($selectRepository[0]); })
                        .insertAfter($selectRepositoryFieldGroup);
                }
            }).always(function (jqXHR, textStatus) {
                if (textStatus != "abort") {
                    $loading.hide();
                }
            });
        }
    };

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

            editor.init({
                editor: options.repositorySetupContainer,
                configContainer: options.repositoryConfigContainer,
                itemList: options.repositoryList,
                deleteItemKey: "repositoryResult",
                checkListHasItems: checkListHasItems,
                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: {
                    enabled: !!options.moveRepositoryUrl,
                    items: "> li:not(#repository-trigger-item)",
                    moveItem: moveRepository
                }
            });

            $(function () {
                $repositorySetupContainer = $(options.repositorySetupContainer)
                    .delegate(options.addRepositoryTrigger, "click", addRepository)
                    .delegate(options.selectRepositorySelector, "change", selectRepositoryType);
                $repositoryList = $(options.repositoryList);
                $repositoryConfigContainer = $(options.repositoryConfigContainer);

                editor.checkListHasItems();

                if (options.preselectItemId) {
                    $(options.repositoryList).children("#item-" + options.preselectItemId).click();
                }
            });
        }
    }
}(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);

                $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: 'nothing', 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=nothing&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: 'nothing', 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: 'nothing',
                    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(a,b){"use strict";var c=a.History=a.History||{},d=a.jQuery;if(typeof c.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");c.Adapter={bind:function(a,b,c){d(a).bind(b,c)},trigger:function(a,b,c){d(a).trigger(b,c)},extractEventData:function(a,c,d){var e=c&&c.originalEvent&&c.originalEvent[a]||d&&d[a]||b;return e},onDomLoad:function(a){d(a)}},typeof c.init!="undefined"&&c.init()})(window),function(a,b){"use strict";var c=a.console||b,d=a.document,e=a.navigator,f=a.sessionStorage||!1,g=a.setTimeout,h=a.clearTimeout,i=a.setInterval,j=a.clearInterval,k=a.JSON,l=a.alert,m=a.History=a.History||{},n=a.history;k.stringify=k.stringify||k.encode,k.parse=k.parse||k.decode;if(typeof m.init!="undefined")throw new Error("History.js Core has already been loaded...");m.init=function(){return typeof m.Adapter=="undefined"?!1:(typeof m.initCore!="undefined"&&m.initCore(),typeof m.initHtml4!="undefined"&&m.initHtml4(),!0)},m.initCore=function(){if(typeof m.initCore.initialized!="undefined")return!1;m.initCore.initialized=!0,m.options=m.options||{},m.options.hashChangeInterval=m.options.hashChangeInterval||100,m.options.safariPollInterval=m.options.safariPollInterval||500,m.options.doubleCheckInterval=m.options.doubleCheckInterval||500,m.options.storeInterval=m.options.storeInterval||1e3,m.options.busyDelay=m.options.busyDelay||250,m.options.debug=m.options.debug||!1,m.options.initialTitle=m.options.initialTitle||d.title,m.intervalList=[],m.clearAllIntervals=function(){var a,b=m.intervalList;if(typeof b!="undefined"&&b!==null){for(a=0;a<b.length;a++)j(b[a]);m.intervalList=null}},m.debug=function(){(m.options.debug||!1)&&m.log.apply(m,arguments)},m.log=function(){var a=typeof c!="undefined"&&typeof c.log!="undefined"&&typeof c.log.apply!="undefined",b=d.getElementById("log"),e,f,g,h,i;a?(h=Array.prototype.slice.call(arguments),e=h.shift(),typeof c.debug!="undefined"?c.debug.apply(c,[e,h]):c.log.apply(c,[e,h])):e="\n"+arguments[0]+"\n";for(f=1,g=arguments.length;f<g;++f){i=arguments[f];if(typeof i=="object"&&typeof k!="undefined")try{i=k.stri
