// Underscore.js 1.1.7
// (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the MIT license.
// Portions of Underscore are inspired or borrowed from Prototype,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore
(function(){var p=this,C=p._,m={},i=Array.prototype,n=Object.prototype,f=i.slice,D=i.unshift,E=n.toString,l=n.hasOwnProperty,s=i.forEach,t=i.map,u=i.reduce,v=i.reduceRight,w=i.filter,x=i.every,y=i.some,o=i.indexOf,z=i.lastIndexOf;n=Array.isArray;var F=Object.keys,q=Function.prototype.bind,b=function(a){return new j(a)};typeof module!=="undefined"&&module.exports?(module.exports=b,b._=b):p._=b;b.VERSION="1.1.7";var h=b.each=b.forEach=function(a,c,b){if(a!=null)if(s&&a.forEach===s)a.forEach(c,b);else if(a.length===
+a.length)for(var e=0,k=a.length;e<k;e++){if(e in a&&c.call(b,a[e],e,a)===m)break}else for(e in a)if(l.call(a,e)&&c.call(b,a[e],e,a)===m)break};b.map=function(a,c,b){var e=[];if(a==null)return e;if(t&&a.map===t)return a.map(c,b);h(a,function(a,g,G){e[e.length]=c.call(b,a,g,G)});return e};b.reduce=b.foldl=b.inject=function(a,c,d,e){var k=d!==void 0;a==null&&(a=[]);if(u&&a.reduce===u)return e&&(c=b.bind(c,e)),k?a.reduce(c,d):a.reduce(c);h(a,function(a,b,f){k?d=c.call(e,d,a,b,f):(d=a,k=!0)});if(!k)throw new TypeError("Reduce of empty array with no initial value");
return d};b.reduceRight=b.foldr=function(a,c,d,e){a==null&&(a=[]);if(v&&a.reduceRight===v)return e&&(c=b.bind(c,e)),d!==void 0?a.reduceRight(c,d):a.reduceRight(c);a=(b.isArray(a)?a.slice():b.toArray(a)).reverse();return b.reduce(a,c,d,e)};b.find=b.detect=function(a,c,b){var e;A(a,function(a,g,f){if(c.call(b,a,g,f))return e=a,!0});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(w&&a.filter===w)return a.filter(c,b);h(a,function(a,g,f){c.call(b,a,g,f)&&(e[e.length]=a)});return e};
b.reject=function(a,c,b){var e=[];if(a==null)return e;h(a,function(a,g,f){c.call(b,a,g,f)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=!0;if(a==null)return e;if(x&&a.every===x)return a.every(c,b);h(a,function(a,g,f){if(!(e=e&&c.call(b,a,g,f)))return m});return e};var A=b.some=b.any=function(a,c,d){c=c||b.identity;var e=!1;if(a==null)return e;if(y&&a.some===y)return a.some(c,d);h(a,function(a,b,f){if(e|=c.call(d,a,b,f))return m});return!!e};b.include=b.contains=function(a,c){var b=
!1;if(a==null)return b;if(o&&a.indexOf===o)return a.indexOf(c)!=-1;A(a,function(a){if(b=a===c)return!0});return b};b.invoke=function(a,c){var d=f.call(arguments,2);return b.map(a,function(a){return(c.call?c||a:a[c]).apply(a,d)})};b.pluck=function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);var e={computed:-Infinity};h(a,function(a,b,f){b=c?c.call(d,a,b,f):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,
c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);var e={computed:Infinity};h(a,function(a,b,f){b=c?c.call(d,a,b,f):a;b<e.computed&&(e={value:a,computed:b})});return e.value};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(a,b,f){return{value:a,criteria:c.call(d,a,b,f)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}),"value")};b.groupBy=function(a,b){var d={};h(a,function(a,f){var g=b(a,f);(d[g]||(d[g]=[])).push(a)});return d};b.sortedIndex=function(a,c,d){d||
(d=b.identity);for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?e=g+1:f=g}return e};b.toArray=function(a){if(!a)return[];if(a.toArray)return a.toArray();if(b.isArray(a))return f.call(a);if(b.isArguments(a))return f.call(a);return b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=b.head=function(a,b,d){return b!=null&&!d?f.call(a,0,b):a[0]};b.rest=b.tail=function(a,b,d){return f.call(a,b==null||d?1:b)};b.last=function(a){return a[a.length-1]};b.compact=function(a){return b.filter(a,
function(a){return!!a})};b.flatten=function(a){return b.reduce(a,function(a,d){if(b.isArray(d))return a.concat(b.flatten(d));a[a.length]=d;return a},[])};b.without=function(a){return b.difference(a,f.call(arguments,1))};b.uniq=b.unique=function(a,c){return b.reduce(a,function(a,e,f){if(0==f||(c===!0?b.last(a)!=e:!b.include(a,e)))a[a.length]=e;return a},[])};b.union=function(){return b.uniq(b.flatten(arguments))};b.intersection=b.intersect=function(a){var c=f.call(arguments,1);return b.filter(b.uniq(a),
function(a){return b.every(c,function(c){return b.indexOf(c,a)>=0})})};b.difference=function(a,c){return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=f.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e<c;e++)d[e]=b.pluck(a,""+e);return d};b.indexOf=function(a,c,d){if(a==null)return-1;var e;if(d)return d=b.sortedIndex(a,c),a[d]===c?d:-1;if(o&&a.indexOf===o)return a.indexOf(c);d=0;for(e=a.length;d<e;d++)if(a[d]===c)return d;return-1};b.lastIndexOf=function(a,
b){if(a==null)return-1;if(z&&a.lastIndexOf===z)return a.lastIndexOf(b);for(var d=a.length;d--;)if(a[d]===b)return d;return-1};b.range=function(a,b,d){arguments.length<=1&&(b=a||0,a=0);d=arguments[2]||1;for(var e=Math.max(Math.ceil((b-a)/d),0),f=0,g=Array(e);f<e;)g[f++]=a,a+=d;return g};b.bind=function(a,b){if(a.bind===q&&q)return q.apply(a,f.call(arguments,1));var d=f.call(arguments,2);return function(){return a.apply(b,d.concat(f.call(arguments)))}};b.bindAll=function(a){var c=f.call(arguments,1);
c.length==0&&(c=b.functions(a));h(c,function(c){a[c]=b.bind(a[c],a)});return a};b.memoize=function(a,c){var d={};c||(c=b.identity);return function(){var b=c.apply(this,arguments);return l.call(d,b)?d[b]:d[b]=a.apply(this,arguments)}};b.delay=function(a,b){var d=f.call(arguments,2);return setTimeout(function(){return a.apply(a,d)},b)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(f.call(arguments,1)))};var B=function(a,b,d){var e;return function(){var f=this,g=arguments,h=function(){e=null;
a.apply(f,g)};d&&clearTimeout(e);if(d||!e)e=setTimeout(h,b)}};b.throttle=function(a,b){return B(a,b,!1)};b.debounce=function(a,b){return B(a,b,!0)};b.once=function(a){var b=!1,d;return function(){if(b)return d;b=!0;return d=a.apply(this,arguments)}};b.wrap=function(a,b){return function(){var d=[a].concat(f.call(arguments));return b.apply(this,d)}};b.compose=function(){var a=f.call(arguments);return function(){for(var b=f.call(arguments),d=a.length-1;d>=0;d--)b=[a[d].apply(this,b)];return b[0]}};b.after=
function(a,b){return function(){if(--a<1)return b.apply(this,arguments)}};b.keys=F||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var b=[],d;for(d in a)l.call(a,d)&&(b[b.length]=d);return b};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){h(f.call(arguments,1),function(b){for(var d in b)b[d]!==void 0&&(a[d]=b[d])});return a};b.defaults=function(a){h(f.call(arguments,
1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,c){if(a===c)return!0;var d=typeof a;if(d!=typeof c)return!1;if(a==c)return!0;if(!a&&c||a&&!c)return!1;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(a.isEqual)return a.isEqual(c);if(c.isEqual)return c.isEqual(a);if(b.isDate(a)&&b.isDate(c))return a.getTime()===c.getTime();if(b.isNaN(a)&&b.isNaN(c))return!1;
if(b.isRegExp(a)&&b.isRegExp(c))return a.source===c.source&&a.global===c.global&&a.ignoreCase===c.ignoreCase&&a.multiline===c.multiline;if(d!=="object")return!1;if(a.length&&a.length!==c.length)return!1;d=b.keys(a);var e=b.keys(c);if(d.length!=e.length)return!1;for(var f in a)if(!(f in c)||!b.isEqual(a[f],c[f]))return!1;return!0};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(l.call(a,c))return!1;return!0};b.isElement=function(a){return!!(a&&a.nodeType==
1)};b.isArray=n||function(a){return E.call(a)==="[object Array]"};b.isObject=function(a){return a===Object(a)};b.isArguments=function(a){return!(!a||!l.call(a,"callee"))};b.isFunction=function(a){return!(!a||!a.constructor||!a.call||!a.apply)};b.isString=function(a){return!!(a===""||a&&a.charCodeAt&&a.substr)};b.isNumber=function(a){return!!(a===0||a&&a.toExponential&&a.toFixed)};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===!0||a===!1};b.isDate=function(a){return!(!a||!a.getTimezoneOffset||
!a.setUTCFullYear)};b.isRegExp=function(a){return!(!a||!a.test||!a.exec||!(a.ignoreCase||a.ignoreCase===!1))};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.noConflict=function(){p._=C;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e<a;e++)b.call(d,e)};b.mixin=function(a){h(b.functions(a),function(c){H(c,b[c]=a[c])})};var I=0;b.uniqueId=function(a){var b=I++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g};
b.template=function(a,c){var d=b.templateSettings;d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.interpolate,function(a,b){return"',"+b.replace(/\\'/g,"'")+",'"}).replace(d.evaluate||null,function(a,b){return"');"+b.replace(/\\'/g,"'").replace(/[\r\n\t]/g," ")+"__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');";d=new Function("obj",d);return c?d(c):d};
var j=function(a){this._wrapped=a};b.prototype=j.prototype;var r=function(a,c){return c?b(a).chain():a},H=function(a,c){j.prototype[a]=function(){var a=f.call(arguments);D.call(a,this._wrapped);return r(c.apply(b,a),this._chain)}};b.mixin(b);h(["pop","push","reverse","shift","sort","splice","unshift"],function(a){var b=i[a];j.prototype[a]=function(){b.apply(this._wrapped,arguments);return r(this._wrapped,this._chain)}});h(["concat","join","slice"],function(a){var b=i[a];j.prototype[a]=function(){return r(b.apply(this._wrapped,
arguments),this._chain)}});j.prototype.chain=function(){this._chain=!0;return this};j.prototype.value=function(){return this._wrapped}})();
;
//fgnass.github.com/spin.js
(function(a,b,c){function n(a){var b={x:a.offsetLeft,y:a.offsetTop};while(a=a.offsetParent)b.x+=a.offsetLeft,b.y+=a.offsetTop;return b}function m(a,b){for(var d in b)a[d]===c&&(a[d]=b[d]);return a}function l(a,b){for(var c in b)a.style[k(a,c)||c]=b[c];return a}function k(a,b){var e=a.style,f,g;if(e[b]!==c)return b;b=b.charAt(0).toUpperCase()+b.slice(1);for(g=0;g<d.length;g++){f=d[g]+b;if(e[f]!==c)return f}}function j(a,b,c,f){var g=["opacity",b,~~(a*100),c,f].join("-"),h=.01+c/f*100,j=Math.max(1-(1-a)/b*(100-h),a),k,l;if(!e[g]){for(l=0;l<d.length;l++){k=d[l]&&"-"+d[l].toLowerCase()+"-"||"";try{i.insertRule("@"+k+"keyframes "+g+"{"+"0%{opacity:"+j+"}"+h+"%{opacity:"+a+"}"+(h+.01)+"%{opacity:1}"+(h+b)%100+"%{opacity:"+a+"}"+"100%{opacity:"+j+"}"+"}",0)}catch(m){}}e[g]=1}return g}function h(a,b,c){c&&!c.parentNode&&h(a,c),a.insertBefore(b,c||null);return a}function g(a,c){var d=b.createElement(a||"div"),e;for(e in c)d[e]=c[e];return d}var d=["webkit","Moz","ms","O"],e={},f;h(b.getElementsByTagName("head")[0],g("style"));var i=b.styleSheets[b.styleSheets.length-1],o=function(a){this.opts=m(a||{},{lines:12,length:7,width:5,radius:10,color:"#000",speed:1,trail:100,opacity:.25})},p=o.prototype={spin:function(a){var b=this,c=b.el=l(g(),{position:"relative"}),d,e;a&&(e=n(h(a,c,a.firstChild)),d=n(c),l(c,{left:(a.offsetWidth>>1)-d.x+e.x+"px",top:(a.offsetHeight>>1)-d.y+e.y+"px"})),b.lines(c,b.opts);if(!f){var i=b.opts,j=0,k=20/i.speed,m=(1-i.opacity)/(k*i.trail/100),o=k/i.lines;(function p(){j++;for(var a=i.lines;a;a--){var d=Math.max(1-(j+a*o)%k*m,i.opacity);b.opacity(c,i.lines-a,d,i)}b.timeout=b.el&&setTimeout(p,50)})()}return b},stop:function(){var a=this,b=a.el;clearTimeout(a.timeout),b&&b.parentNode&&b.parentNode.removeChild(b),a.el=c;return a}};p.lines=function(a,b){function e(a,d){return l(g(),{position:"absolute",width:b.length+b.width+"px",height:b.width+"px",background:a,boxShadow:d,transformOrigin:"left",transform:"rotate("+~~(360/b.lines*c)+"deg) translate("+b.radius+"px"+",0)",borderRadius:"100em"})}var c=0,d;for(;c<b.lines;c++)d=l(g(),{position:"absolute",top:1+~(b.width/2)+"px",transform:"translate3d(0,0,0)",opacity:b.opacity,animation:j(b.opacity,b.trail,c,b.lines)+" "+1/b.speed+"s linear infinite"}),b.shadow&&h(d,l(e("#000","0 0 4px #000"),{top:"2px"})),h(a,h(d,e(b.color,"0 0 1px rgba(0,0,0,.1)")));return a},p.opacity=function(a,b,c){a.childNodes[b].style.opacity=c},function(){var a=l(g("group"),{behavior:"url(#default#VML)"}),b;if(!k(a,"transform")&&a.adj){for(b=4;b--;)i.addRule(["group","roundrect","fill","stroke"][b],"behavior:url(#default#VML)");p.lines=function(a,b){function k(a,d,i){h(f,h(l(e(),{rotation:360/b.lines*a+"deg",left:~~d}),h(l(g("roundrect",{arcsize:1}),{width:c,height:b.width,left:b.radius,top:-b.width>>1,filter:i}),g("fill",{color:b.color,opacity:b.opacity}),g("stroke",{opacity:0}))))}function e(){return l(g("group",{coordsize:d+" "+d,coordorigin:-c+" "+ -c}),{width:d,height:d})}var c=b.length+b.width,d=2*c,f=e(),i=~(b.length+b.radius+b.width)+"px",j;if(b.shadow)for(j=1;j<=b.lines;j++)k(j,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(j=1;j<=b.lines;j++)k(j);return h(l(a,{margin:i+" 0 0 "+i}),f)},p.opacity=function(a,b,c,d){d=d.shadow&&d.lines||0,a.firstChild.childNodes[b+d].firstChild.firstChild.opacity=c}}else f=k(a,"animation")}(),a.Spinner=o})(window,document);
(function(a,b){function d(a,d){var e=d.__amplify__?JSON.parse(d.__amplify__):{};c.addType(a,function(f,g,h){var i=g,j=(new Date).getTime(),k,l;if(!f){i={};for(f in e)k=d[f],l=k?JSON.parse(k):{expires:-1},l.expires&&l.expires<=j?(delete d[f],delete e[f]):i[f.replace(/^__amplify__/,"")]=l.data;d.__amplify__=JSON.stringify(e);return i}f="__amplify__"+f;if(g===b){if(e[f]){k=d[f],l=k?JSON.parse(k):{expires:-1};if(l.expires&&l.expires<=j)delete d[f],delete e[f];else return l.data}}else if(g===null)delete d[f],delete e[f];else{l=JSON.stringify({data:g,expires:h.expires?j+h.expires:null});try{d[f]=l,e[f]=!0}catch(m){c[a]();try{d[f]=l,e[f]=!0}catch(m){throw c.error()}}}d.__amplify__=JSON.stringify(e);return i})}JSON.stringify=JSON.stringify||JSON.encode,JSON.parse=JSON.parse||JSON.decode;var c=a.store=function(a,b,d,e){var e=c.type;d&&d.type&&d.type in c.types&&(e=d.type);return c.types[e](a,b,d||{})};c.types={},c.type=null,c.addType=function(a,b){c.type||(c.type=a),c.types[a]=b,c[a]=function(b,d,e){e=e||{},e.type=a;return c(b,d,e)}},c.error=function(){return"amplify.store quota exceeded"};for(var e in{localStorage:1,sessionStorage:1})try{window[e].getItem&&d(e,window[e])}catch(f){}window.globalStorage&&(d("globalStorage",window.globalStorage[window.location.hostname]),c.type==="sessionStorage"&&(c.type="globalStorage")),function(){var a=document.createElement("div"),d="amplify",e;a.style.display="none",document.getElementsByTagName("head")[0].appendChild(a),a.addBehavior&&(a.addBehavior("#default#userdata"),a.load(d),e=a.getAttribute(d)?JSON.parse(a.getAttribute(d)):{},c.addType("userData",function(f,g,h){var i=g,j=(new Date).getTime(),k,l,m;if(!f){i={};for(f in e)k=a.getAttribute(f),l=k?JSON.parse(k):{expires:-1},l.expires&&l.expires<=j?(a.removeAttribute(f),delete e[f]):i[f]=l.data;a.setAttribute(d,JSON.stringify(e)),a.save(d);return i}f=f.replace(/[^-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u37f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/g,"-");if(g===b){if(f in e){k=a.getAttribute(f),l=k?JSON.parse(k):{expires:-1};if(l.expires&&l.expires<=j)a.removeAttribute(f),delete e[f];else return l.data}}else g===null?(a.removeAttribute(f),delete e[f]):(m=a.getAttribute(f),l=JSON.stringify({data:g,expires:h.expires?j+h.expires:null}),a.setAttribute(f,l),e[f]=!0);a.setAttribute(d,JSON.stringify(e));try{a.save(d)}catch(n){m===null?(a.removeAttribute(f),delete e[f]):a.setAttribute(f,m),c.userData();try{a.setAttribute(f,l),e[f]=!0,a.save(d)}catch(n){m===null?(a.removeAttribute(f),delete e[f]):a.setAttribute(f,m);throw c.error()}}return i}))}(),d("memory",{})})(this.amplify=this.amplify||{});
(function(a,b){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){d(a).trigger(b)},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.amplify||!1,g=a.setTimeout,h=a.clearTimeout,i=a.setInterval,j=a.clearInterval,k=a.JSON,l=a.History=a.History||{},m=a.history;k.stringify=k.stringify||k.encode,k.parse=k.parse||k.decode;if(typeof l.init!="undefined")throw new Error("History.js Core has already been loaded...");l.init=function(){if(typeof l.Adapter=="undefined")return!1;typeof l.initCore!="undefined"&&l.initCore(),typeof l.initHtml4!="undefined"&&l.initHtml4();return!0},l.initCore=function(){if(typeof l.initCore.initialized!="undefined")return!1;l.initCore.initialized=!0,l.options=l.options||{},l.options.hashChangeInterval=l.options.hashChangeInterval||100,l.options.safariPollInterval=l.options.safariPollInterval||500,l.options.doubleCheckInterval=l.options.doubleCheckInterval||500,l.options.storeInterval=l.options.storeInterval||1e3,l.options.busyDelay=l.options.busyDelay||250,l.options.debug=l.options.debug||!1,l.options.initialTitle=l.options.initialTitle||d.title,l.intervalList=[],l.clearAllIntervals=function(){var a,b=l.intervalList;if(typeof b!="undefined"&&b!==null){for(a=0;a<b.length;a++)j(b[a]);l.intervalList=null}},l.Adapter.bind(a,"beforeunload",l.clearAllIntervals),l.Adapter.bind(a,"unload",l.clearAllIntervals),l.debug=function(){(l.options.debug||!1)&&l.log.apply(l,arguments)},l.log=function(){var a=typeof c!="undefined"&&typeof c.log!="undefined"&&typeof c.log.apply!="undefined",b=d.getElementById("log"),e,f,g;if(a){var 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])}else e="\n"+arguments[0]+"\n";for(f=1,g=arguments.length;f<g;++f){var i=arguments[f];if(typeof i=="object"&&typeof k!="undefined")try{i=k.stringify(i)}catch(j){}e+="\n"+i+"\n"}b?(b.value+=e+"\n-----\n",b.scrollTop=b.scrollHeight-b.clientHeight):a||alert(e);return!0},l.getInternetExplorerMajorVersion=function(){var a=l.getInternetExplorerMajorVersion.cached=typeof l.getInternetExplorerMajorVersion.cached!="undefined"?l.getInternetExplorerMajorVersion.cached:function(){var a=3,b=d.createElement("div"),c=b.getElementsByTagName("i");while((b.innerHTML="<!--[if gt IE "+ ++a+"]><i></i><![endif]-->")&&c[0]);return a>4?a:!1}();return a},l.isInternetExplorer=function(){var a=l.isInternetExplorer.cached=typeof l.isInternetExplorer.cached!="undefined"?l.isInternetExplorer.cached:Boolean(l.getInternetExplorerMajorVersion());return a},l.emulated={pushState:!Boolean(a.history&&a.history.pushState&&a.history.replaceState&&!/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i.test(e.userAgent)&&!/AppleWebKit\/5([0-2]|3[0-2])/i.test(e.userAgent)),hashChange:Boolean(!("onhashchange"in a||"onhashchange"in d)||l.isInternetExplorer()&&l.getInternetExplorerMajorVersion()<8)},l.enabled=!l.emulated.pushState,l.bugs={setHash:Boolean(!l.emulated.pushState&&e.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(e.userAgent)),safariPoll:Boolean(!l.emulated.pushState&&e.vendor==="Apple Computer, Inc."&&/AppleWebKit\/5([0-2]|3[0-3])/.test(e.userAgent)),ieDoubleCheck:Boolean(l.isInternetExplorer()&&l.getInternetExplorerMajorVersion()<8),hashEscape:Boolean(l.isInternetExplorer()&&l.getInternetExplorerMajorVersion()<7)},l.isEmptyObject=function(a){for(var b in a)return!1;return!0},l.cloneObject=function(a){var b,c;a?(b=k.stringify(a),c=k.parse(b)):c={};return c},l.getRootUrl=function(){var a=d.location.protocol+"//"+(d.location.hostname||d.location.host);if(d.location.port||!1)a+=":"+d.location.port;a+="/";return a},l.getBaseHref=function(){var a=d.getElementsByTagName("base"),b=null,c="";a.length===1&&(b=a[0],c=b.href.replace(/[^\/]+$/,"")),c=c.replace(/\/+$/,""),c&&(c+="/");return c},l.getBaseUrl=function(){var a=l.getBaseHref()||l.getBasePageUrl()||l.getRootUrl();return a},l.getPageUrl=function(){var a=l.getState(!1,!1),b=(a||{}).url||d.location.href,c=b.replace(/\/+$/,"").replace(/[^\/]+$/,function(a,b,c){return/\./.test(a)?a:a+"/"});return c},l.getBasePageUrl=function(){var a=d.location.href.replace(/[#\?].*/,"").replace(/[^\/]+$/,function(a,b,c){return/[^\/]$/.test(a)?"":a}).replace(/\/+$/,"")+"/";return a},l.getFullUrl=function(a,b){var c=a,d=a.substring(0,1);b=typeof b=="undefined"?!0:b,/[a-z]+\:\/\//.test(a)||(d==="/"?c=l.getRootUrl()+a.replace(/^\/+/,""):d==="#"?c=l.getPageUrl().replace(/#.*/,"")+a:d==="?"?c=l.getPageUrl().replace(/[\?#].*/,"")+a:b?c=l.getBaseUrl()+a.replace(/^(\.\/)+/,""):c=l.getBasePageUrl()+a.replace(/^(\.\/)+/,""));return c.replace(/\#$/,"")},l.getShortUrl=function(a){var b=a,c=l.getBaseUrl(),d=l.getRootUrl();l.emulated.pushState&&(b=b.replace(c,"")),b=b.replace(d,"/"),l.isTraditionalAnchor(b)&&(b="./"+b),b=b.replace(/^(\.\/)+/g,"./").replace(/\#$/,"");return b},l.store=f?f.store("History.store")||{}:{},l.store.idToState=l.store.idToState||{},l.store.urlToId=l.store.urlToId||{},l.store.stateToId=l.store.stateToId||{},l.idToState=l.idToState||{},l.stateToId=l.stateToId||{},l.urlToId=l.urlToId||{},l.storedStates=l.storedStates||[],l.savedStates=l.savedStates||[],l.getState=function(a,b){typeof a=="undefined"&&(a=!0),typeof b=="undefined"&&(b=!0);var c=l.getLastSavedState();!c&&b&&(c=l.createStateObject()),a&&(c=l.cloneObject(c),c.url=c.cleanUrl||c.url);return c},l.getIdByState=function(a){var b=l.extractId(a.url);if(!b){var c=l.getStateString(a);if(typeof l.stateToId[c]!="undefined")b=l.stateToId[c];else if(typeof l.store.stateToId[c]!="undefined")b=l.store.stateToId[c];else{for(;;){b=String(Math.floor(Math.random()*1e3));if(typeof l.idToState[b]=="undefined"&&typeof l.store.idToState[b]=="undefined")break}l.stateToId[c]=b,l.idToState[b]=a}}return b},l.normalizeState=function(a){if(!a||typeof a!="object")a={};if(typeof a.normalized!="undefined")return a;if(!a.data||typeof a.data!="object")a.data={};var b={};b.normalized=!0,b.title=a.title||"",b.url=l.getFullUrl(l.unescapeString(a.url||d.location.href)),b.hash=l.getShortUrl(b.url),b.data=l.cloneObject(a.data),b.id=l.getIdByState(b),b.cleanUrl=b.url.replace(/\??\&_suid.*/,""),b.url=b.cleanUrl;var c=!l.isEmptyObject(b.data);if(b.title||c)b.hash=l.getShortUrl(b.url).replace(/\??\&_suid.*/,""),/\?/.test(b.hash)||(b.hash+="?"),b.hash+="&_suid="+b.id;b.hashedUrl=l.getFullUrl(b.hash),(l.emulated.pushState||l.bugs.safariPoll)&&l.hasUrlDuplicate(b)&&(b.url=b.hashedUrl);return b},l.createStateObject=function(a,b,c){var d={data:a,title:b,url:c};d=l.normalizeState(d);return d},l.getStateById=function(a){a=String(a);var c=l.idToState[a]||l.store.idToState[a]||b;return c},l.getStateString=function(a){var b=l.normalizeState(a),c={data:b.data,title:a.title,url:a.url},d=k.stringify(c);return d},l.getStateId=function(a){var b=l.normalizeState(a),c=b.id;return c},l.getHashByState=function(a){var b,c=l.normalizeState(a);b=c.hash;return b},l.extractId=function(a){var b,c,d;c=/(.*)\&_suid=([0-9]+)$/.exec(a),d=c?c[1]||a:a,b=c?String(c[2]||""):"";return b||!1},l.isTraditionalAnchor=function(a){var b=!/[\/\?\.]/.test(a);return b},l.extractState=function(a,b){var c=null;b=b||!1;var d=l.extractId(a);d&&(c=l.getStateById(d));if(!c){var e=l.getFullUrl(a);d=l.getIdByUrl(e)||!1,d&&(c=l.getStateById(d)),!c&&b&&!l.isTraditionalAnchor(a)&&(c=l.createStateObject(null,null,e))}return c},l.getIdByUrl=function(a){var c=l.urlToId[a]||l.store.urlToId[a]||b;return c},l.getLastSavedState=function(){return l.savedStates[l.savedStates.length-1]||b},l.getLastStoredState=function(){return l.storedStates[l.storedStates.length-1]||b},l.hasUrlDuplicate=function(a){var b=!1,c=l.extractState(a.url);b=c&&c.id!==a.id;return b},l.storeState=function(a){l.urlToId[a.url]=a.id,l.storedStates.push(l.cloneObject(a));return a},l.isLastSavedState=function(a){var b=!1;if(l.savedStates.length){var c=a.id,d=l.getLastSavedState(),e=d.id;b=c===e}return b},l.saveState=function(a){if(l.isLastSavedState(a))return!1;l.savedStates.push(l.cloneObject(a));return!0},l.getStateByIndex=function(a){var b=null;typeof a=="undefined"?b=l.savedStates[l.savedStates.length-1]:a<0?b=l.savedStates[l.savedStates.length+a]:b=l.savedStates[a];return b},l.getHash=function(){var a=l.unescapeHash(d.location.hash);return a},l.unescapeString=function(b){var c=b,d;for(;;){d=a.unescape(c);if(d===c)break;c=d}return c},l.unescapeHash=function(a){var b=l.normalizeHash(a);b=l.unescapeString(b);return b},l.normalizeHash=function(a){var b=a.replace(/[^#]*#/,"").replace(/#.*/,"");return b},l.setHash=function(a,b){if(b!==!1&&l.busy()){l.pushQueue({scope:l,callback:l.setHash,args:arguments,queue:b});return!1}var c=l.escapeHash(a);l.busy(!0);var e=l.extractState(a,!0);if(e&&!l.emulated.pushState)l.pushState(e.data,e.title,e.url,!1);else if(d.location.hash!==c)if(l.bugs.setHash){var f=l.getPageUrl();l.pushState(null,null,f+"#"+c,!1)}else d.location.hash=c;return l},l.escapeHash=function(b){var c=l.normalizeHash(b);c=a.escape(c),l.bugs.hashEscape||(c=c.replace(/\%21/g,"!").replace(/\%26/g,"&").replace(/\%3D/g,"=").replace(/\%3F/g,"?"));return c},l.getHashByUrl=function(a){var b=String(a).replace(/([^#]*)#?([^#]*)#?(.*)/,"$2");b=l.unescapeHash(b);return b},l.setTitle=function(a){var b=a.title;if(!b){var c=l.getStateByIndex(0);c&&c.url===a.url&&(b=c.title||l.options.initialTitle)}try{d.getElementsByTagName("title")[0].innerHTML=b.replace("<","&lt;").replace(">","&gt;").replace(" & "," &amp; ")}catch(e){}d.title=b;return l},l.queues=[],l.busy=function(a){typeof a!="undefined"?l.busy.flag=a:typeof l.busy.flag=="undefined"&&(l.busy.flag=!1);if(!l.busy.flag){h(l.busy.timeout);var b=function(){if(!l.busy.flag)for(var a=l.queues.length-1;a>=0;--a){var c=l.queues[a];if(c.length===0)continue;var d=c.shift();l.fireQueueItem(d),l.busy.timeout=g(b,l.options.busyDelay)}};l.busy.timeout=g(b,l.options.busyDelay)}return l.busy.flag},l.fireQueueItem=function(a){return a.callback.apply(a.scope||l,a.args||[])},l.pushQueue=function(a){l.queues[a.queue||0]=l.queues[a.queue||0]||[],l.queues[a.queue||0].push(a);return l},l.queue=function(a,b){typeof a=="function"&&(a={callback:a}),typeof b!="undefined"&&(a.queue=b),l.busy()?l.pushQueue(a):l.fireQueueItem(a);return l},l.clearQueue=function(){l.busy.flag=!1,l.queues=[];return l},l.stateChanged=!1,l.doubleChecker=!1,l.doubleCheckComplete=function(){l.stateChanged=!0,l.doubleCheckClear();return l},l.doubleCheckClear=function(){l.doubleChecker&&(h(l.doubleChecker),l.doubleChecker=!1);return l},l.doubleCheck=function(a){l.stateChanged=!1,l.doubleCheckClear(),l.bugs.ieDoubleCheck&&(l.doubleChecker=g(function(){l.doubleCheckClear(),l.stateChanged||a();return!0},l.options.doubleCheckInterval));return l},l.safariStatePoll=function(){var b=l.extractState(d.location.href),c;if(!l.isLastSavedState(b))c=b;else return;c||(c=l.createStateObject()),l.Adapter.trigger(a,"popstate");return l},l.back=function(a){if(a!==!1&&l.busy()){l.pushQueue({scope:l,callback:l.back,args:arguments,queue:a});return!1}l.busy(!0),l.doubleCheck(function(){l.back(!1)}),m.go(-1);return!0},l.forward=function(a){if(a!==!1&&l.busy()){l.pushQueue({scope:l,callback:l.forward,args:arguments,queue:a});return!1}l.busy(!0),l.doubleCheck(function(){l.forward(!1)}),m.go(1);return!0},l.go=function(a,b){var c;if(a>0)for(c=1;c<=a;++c)l.forward(b);else{if(!(a<0))throw new Error("History.go: History.go requires a positive or negative integer passed.");for(c=-1;c>=a;--c)l.back(b)}return l},l.saveState(l.storeState(l.extractState(d.location.href,!0))),f&&(l.onUnload=function(){var a=f.store("History.store")||{},b;a.idToState=a.idToState||{},a.urlToId=a.urlToId||{},a.stateToId=a.stateToId||{};for(b in l.idToState){if(!l.idToState.hasOwnProperty(b))continue;a.idToState[b]=l.idToState[b]}for(b in l.urlToId){if(!l.urlToId.hasOwnProperty(b))continue;a.urlToId[b]=l.urlToId[b]}for(b in l.stateToId){if(!l.stateToId.hasOwnProperty(b))continue;a.stateToId[b]=l.stateToId[b]}l.store=a,f.store("History.store",a)},l.intervalList.push(i(l.onUnload,l.options.storeInterval)),l.Adapter.bind(a,"beforeunload",l.onUnload),l.Adapter.bind(a,"unload",l.onUnload));if(l.emulated.pushState){var n=function(){};l.pushState=l.pushState||n,l.replaceState=l.replaceState||n}else{l.onPopState=function(b){l.doubleCheckComplete();var c=l.getHash();if(c){var e=l.extractState(c||d.location.href,!0);e?l.replaceState(e.data,e.title,e.url,!1):(l.Adapter.trigger(a,"anchorchange"),l.busy(!1)),l.expectedStateId=!1;return!1}var f=!1;b=b||{},typeof b.state=="undefined"&&(typeof b.originalEvent!="undefined"&&typeof b.originalEvent.state!="undefined"?b.state=b.originalEvent.state||!1:typeof b.event!="undefined"&&typeof b.event.state!="undefined"&&(b.state=b.event.state||!1)),b.state=b.state||!1,b.state?f=l.getStateById(b.state):l.expectedStateId?f=l.getStateById(l.expectedStateId):f=l.extractState(d.location.href),f||(f=l.createStateObject(null,null,d.location.href)),l.expectedStateId=!1;if(l.isLastSavedState(f)){l.busy(!1);return!1}l.storeState(f),l.saveState(f),l.setTitle(f),l.Adapter.trigger(a,"statechange"),l.busy(!1);return!0},l.Adapter.bind(a,"popstate",l.onPopState),l.pushState=function(b,c,d,e){if(l.getHashByUrl(d)&&l.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(e!==!1&&l.busy()){l.pushQueue({scope:l,callback:l.pushState,args:arguments,queue:e});return!1}l.busy(!0);var f=l.createStateObject(b,c,d);l.isLastSavedState(f)?l.busy(!1):(l.storeState(f),l.expectedStateId=f.id,m.pushState(f.id,f.title,f.url),l.Adapter.trigger(a,"popstate"));return!0},l.replaceState=function(b,c,d,e){if(l.getHashByUrl(d)&&l.emulated.pushState)throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(e!==!1&&l.busy()){l.pushQueue({scope:l,callback:l.replaceState,args:arguments,queue:e});return!1}l.busy(!0);var f=l.createStateObject(b,c,d);l.isLastSavedState(f)?l.busy(!1):(l.storeState(f),l.expectedStateId=f.id,m.replaceState(f.id,f.title,f.url),l.Adapter.trigger(a,"popstate"));return!0},l.bugs.safariPoll&&l.intervalList.push(i(l.safariStatePoll,l.options.safariPollInterval));if(e.vendor==="Apple Computer, Inc."||(e.appCodeName||"")==="Mozilla")l.Adapter.bind(a,"hashchange",function(){l.Adapter.trigger(a,"popstate")}),l.getHash()&&l.Adapter.onDomLoad(function(){l.Adapter.trigger(a,"hashchange")})}},l.init()})(window);
(function(a,b){"use strict";var c=a.document,d=a.setTimeout||d,e=a.clearTimeout||e,f=a.setInterval||f,g=a.History=a.History||{};if(typeof g.initHtml4!="undefined")throw new Error("History.js HTML4 Support has already been loaded...");g.initHtml4=function(){if(typeof g.initHtml4.initialized!="undefined")return!1;g.initHtml4.initialized=!0,g.enabled=!0,g.savedHashes=[],g.isLastHash=function(a){var b=g.getHashByIndex(),c=a===b;return c},g.saveHash=function(a){if(g.isLastHash(a))return!1;g.savedHashes.push(a);return!0},g.getHashByIndex=function(a){var b=null;typeof a=="undefined"?b=g.savedHashes[g.savedHashes.length-1]:a<0?b=g.savedHashes[g.savedHashes.length+a]:b=g.savedHashes[a];return b},g.discardedHashes={},g.discardedStates={},g.discardState=function(a,b,c){var d=g.getHashByState(a),e={discardedState:a,backState:c,forwardState:b};g.discardedStates[d]=e;return!0},g.discardHash=function(a,b,c){var d={discardedHash:a,backState:c,forwardState:b};g.discardedHashes[a]=d;return!0},g.discardedState=function(a){var b=g.getHashByState(a),c=g.discardedStates[b]||!1;return c},g.discardedHash=function(a){var b=g.discardedHashes[a]||!1;return b},g.recycleState=function(a){var b=g.getHashByState(a);g.discardedState(a)&&delete g.discardedStates[b];return!0},g.emulated.hashChange&&(g.hashChangeInit=function(){g.checkerFunction=null;var b="";if(g.isInternetExplorer()){var d="historyjs-iframe",e=c.createElement("iframe");e.setAttribute("id",d),e.style.display="none",c.body.appendChild(e),e.contentWindow.document.open(),e.contentWindow.document.close();var h="",i=!1;g.checkerFunction=function(){if(i)return!1;i=!0;var c=g.getHash()||"",d=g.unescapeHash(e.contentWindow.document.location.hash)||"";c!==b?(b=c,d!==c&&(h=d=c,e.contentWindow.document.open(),e.contentWindow.document.close(),e.contentWindow.document.location.hash=g.escapeHash(c)),g.Adapter.trigger(a,"hashchange")):d!==h&&(h=d,g.setHash(d,!1)),i=!1;return!0}}else g.checkerFunction=function(){var c=g.getHash();c!==b&&(b=c,g.Adapter.trigger(a,"hashchange"));return!0};g.intervalList.push(f(g.checkerFunction,g.options.hashChangeInterval));return!0},g.Adapter.onDomLoad(g.hashChangeInit)),g.emulated.pushState&&(g.onHashChange=function(b){var d=b&&b.newURL||c.location.href,e=g.getHashByUrl(d),f=null,h=null,i=null;if(g.isLastHash(e)){g.busy(!1);return!1}g.doubleCheckComplete(),g.saveHash(e);if(e&&g.isTraditionalAnchor(e)){g.Adapter.trigger(a,"anchorchange"),g.busy(!1);return!1}f=g.extractState(g.getFullUrl(e||c.location.href,!1),!0);if(g.isLastSavedState(f)){g.busy(!1);return!1}h=g.getHashByState(f);var j=g.discardedState(f);if(j){g.getHashByIndex(-2)===g.getHashByState(j.forwardState)?g.back(!1):g.forward(!1);return!1}g.pushState(f.data,f.title,f.url,!1);return!0},g.Adapter.bind(a,"hashchange",g.onHashChange),g.pushState=function(b,d,e,f){if(g.getHashByUrl(e))throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(f!==!1&&g.busy()){g.pushQueue({scope:g,callback:g.pushState,args:arguments,queue:f});return!1}g.busy(!0);var h=g.createStateObject(b,d,e),i=g.getHashByState(h),j=g.getState(!1),k=g.getHashByState(j),l=g.getHash();g.storeState(h),g.expectedStateId=h.id,g.recycleState(h),g.setTitle(h);if(i===k){g.busy(!1);return!1}if(i!==l&&i!==g.getShortUrl(c.location.href)){g.setHash(i,!1);return!1}g.saveState(h),g.Adapter.trigger(a,"statechange"),g.busy(!1);return!0},g.replaceState=function(a,b,c,d){if(g.getHashByUrl(c))throw new Error("History.js does not support states with fragement-identifiers (hashes/anchors).");if(d!==!1&&g.busy()){g.pushQueue({scope:g,callback:g.replaceState,args:arguments,queue:d});return!1}g.busy(!0);var e=g.createStateObject(a,b,c),f=g.getState(!1),h=g.getStateByIndex(-2);g.discardState(f,e,h),g.pushState(e.data,e.title,e.url,!1);return!0},g.getHash()&&!g.emulated.hashChange&&g.Adapter.onDomLoad(function(){g.Adapter.trigger(a,"hashchange")}))},g.init()})(window);
/*!
 * jQuery UI 1.8.14
 *
 * 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( $, undefined ) {

// prevent duplicate loading
// this is only a problem because we proxy existing functions
// and we don't want to double proxy them
$.ui = $.ui || {};
if ( $.ui.version ) {
	return;
}

$.extend( $.ui, {
	version: "1.8.14",

	keyCode: {
		ALT: 18,
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		COMMAND: 91,
		COMMAND_LEFT: 91, // COMMAND
		COMMAND_RIGHT: 93,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		MENU: 93, // COMMAND_RIGHT
		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 // COMMAND
	}
});

// plugins
$.fn.extend({
	_focus: $.fn.focus,
	focus: function( delay, fn ) {
		return typeof delay === "number" ?
			this.each(function() {
				var elem = this;
				setTimeout(function() {
					$( elem ).focus();
					if ( fn ) {
						fn.call( elem );
					}
				}, delay );
			}) :
			this._focus.apply( this, arguments );
	},

	scrollParent: function() {
		var scrollParent;
		if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), position, value;
			while ( elem.length && elem[ 0 ] !== document ) {
				// Ignore z-index if position is set to a value where z-index is ignored by the browser
				// This makes behavior of this function consistent across browsers
				// WebKit always returns auto if the element is positioned
				position = elem.css( "position" );
				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
					// IE returns 0 when zIndex is not specified
					// other browsers return a string
					// we ignore the case of nested elements with an explicit value of 0
					// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
					value = parseInt( elem.css( "zIndex" ), 10 );
					if ( !isNaN( value ) && value !== 0 ) {
						return value;
					}
				}
				elem = elem.parent();
			}
		}

		return 0;
	},

	disableSelection: function() {
		return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
			".ui-disableSelection", function( event ) {
				event.preventDefault();
			});
	},

	enableSelection: function() {
		return this.unbind( ".ui-disableSelection" );
	}
});

$.each( [ "Width", "Height" ], function( i, name ) {
	var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
		type = name.toLowerCase(),
		orig = {
			innerWidth: $.fn.innerWidth,
			innerHeight: $.fn.innerHeight,
			outerWidth: $.fn.outerWidth,
			outerHeight: $.fn.outerHeight
		};

	function reduce( elem, size, border, margin ) {
		$.each( side, function() {
			size -= parseFloat( $.curCSS( elem, "padding" + this, true) ) || 0;
			if ( border ) {
				size -= parseFloat( $.curCSS( elem, "border" + this + "Width", true) ) || 0;
			}
			if ( margin ) {
				size -= parseFloat( $.curCSS( elem, "margin" + this, true) ) || 0;
			}
		});
		return size;
	}

	$.fn[ "inner" + name ] = function( size ) {
		if ( size === undefined ) {
			return orig[ "inner" + name ].call( this );
		}

		return this.each(function() {
			$( this ).css( type, reduce( this, size ) + "px" );
		});
	};

	$.fn[ "outer" + name] = function( size, margin ) {
		if ( typeof size !== "number" ) {
			return orig[ "outer" + name ].call( this, size );
		}

		return this.each(function() {
			$( this).css( type, reduce( this, size, true, margin ) + "px" );
		});
	};
});

// selectors
function focusable( element, isTabIndexNotNaN ) {
	var nodeName = element.nodeName.toLowerCase();
	if ( "area" === nodeName ) {
		var map = element.parentNode,
			mapName = map.name,
			img;
		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
			return false;
		}
		img = $( "img[usemap=#" + mapName + "]" )[0];
		return !!img && visible( img );
	}
	return ( /input|select|textarea|button|object/.test( nodeName )
		? !element.disabled
		: "a" == nodeName
			? element.href || isTabIndexNotNaN
			: isTabIndexNotNaN)
		// the element and all of its ancestors must be visible
		&& visible( element );
}

function visible( element ) {
	return !$( element ).parents().andSelf().filter(function() {
		return $.curCSS( this, "visibility" ) === "hidden" ||
			$.expr.filters.hidden( this );
	}).length;
}

$.extend( $.expr[ ":" ], {
	data: function( elem, i, match ) {
		return !!$.data( elem, match[ 3 ] );
	},

	focusable: function( element ) {
		return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
	},

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			isTabIndexNaN = isNaN( tabIndex );
		return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
	}
});

// support
$(function() {
	var body = document.body,
		div = body.appendChild( div = document.createElement( "div" ) );

	$.extend( div.style, {
		minHeight: "100px",
		height: "auto",
		padding: 0,
		borderWidth: 0
	});

	$.support.minHeight = div.offsetHeight === 100;
	$.support.selectstart = "onselectstart" in div;

	// set display to none to avoid a layout bug in IE
	// http://dev.jquery.com/ticket/4014
	body.removeChild( div ).style.display = "none";
});





// deprecated
$.extend( $.ui, {
	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function( module, option, set ) {
			var proto = $.ui[ module ].prototype;
			for ( var i in set ) {
				proto.plugins[ i ] = proto.plugins[ i ] || [];
				proto.plugins[ i ].push( [ option, set[ i ] ] );
			}
		},
		call: function( instance, name, args ) {
			var set = instance.plugins[ name ];
			if ( !set || !instance.element[ 0 ].parentNode ) {
				return;
			}
	
			for ( var i = 0; i < set.length; i++ ) {
				if ( instance.options[ set[ i ][ 0 ] ] ) {
					set[ i ][ 1 ].apply( instance.element, args );
				}
			}
		}
	},
	
	// will be deprecated when we switch to jQuery 1.4 - use jQuery.contains()
	contains: function( a, b ) {
		return document.compareDocumentPosition ?
			a.compareDocumentPosition( b ) & 16 :
			a !== b && a.contains( b );
	},
	
	// only used by resizable
	hasScroll: function( el, a ) {
	
		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ( $( el ).css( "overflow" ) === "hidden") {
			return false;
		}
	
		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;
	
		if ( el[ scroll ] > 0 ) {
			return true;
		}
	
		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	},
	
	// these are odd functions, fix the API or move into individual plugins
	isOverAxis: function( x, reference, size ) {
		//Determines when x coordinate is over "b" element axis
		return ( x > reference ) && ( x < ( reference + size ) );
	},
	isOver: function( y, x, top, left, height, width ) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
	}
});

})( jQuery );
;
/*!
 * jQuery UI Widget 1.8.14
 *
 * 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( $, undefined ) {

// jQuery 1.4+
if ( $.cleanData ) {
	var _cleanData = $.cleanData;
	$.cleanData = function( elems ) {
		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			$( elem ).triggerHandler( "remove" );
		}
		_cleanData( elems );
	};
} else {
	var _remove = $.fn.remove;
	$.fn.remove = function( selector, keepData ) {
		return this.each(function() {
			if ( !keepData ) {
				if ( !selector || $.filter( selector, [ this ] ).length ) {
					$( "*", this ).add( [ this ] ).each(function() {
						$( this ).triggerHandler( "remove" );
					});
				}
			}
			return _remove.call( $(this), selector, keepData );
		});
	};
}

$.widget = function( name, base, prototype ) {
	var namespace = name.split( "." )[ 0 ],
		fullName;
	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName ] = function( elem ) {
		return !!$.data( elem, name );
	};

	$[ namespace ] = $[ namespace ] || {};
	$[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without initializing for simple inheritance
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	var basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
//	$.each( basePrototype, function( key, val ) {
//		if ( $.isPlainObject(val) ) {
//			basePrototype[ key ] = $.extend( {}, val );
//		}
//	});
	basePrototype.options = $.extend( true, {}, basePrototype.options );
	$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
		namespace: namespace,
		widgetName: name,
		widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
		widgetBaseClass: fullName
	}, prototype );

	$.widget.bridge( name, $[ namespace ][ name ] );
};

$.widget.bridge = function( name, object ) {
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = Array.prototype.slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.extend.apply( null, [ true, options ].concat(args) ) :
			options;

		// prevent calls to internal methods
		if ( isMethodCall && options.charAt( 0 ) === "_" ) {
			return returnValue;
		}

		if ( isMethodCall ) {
			this.each(function() {
				var instance = $.data( this, name ),
					methodValue = instance && $.isFunction( instance[options] ) ?
						instance[ options ].apply( instance, args ) :
						instance;
				// TODO: add this back in 1.9 and use $.error() (see #5972)
//				if ( !instance ) {
//					throw "cannot call methods on " + name + " prior to initialization; " +
//						"attempted to call method '" + options + "'";
//				}
//				if ( !$.isFunction( instance[options] ) ) {
//					throw "no such method '" + options + "' for " + name + " widget instance";
//				}
//				var methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, name );
				if ( instance ) {
					instance.option( options || {} )._init();
				} else {
					$.data( this, name, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$.Widget = function( options, element ) {
	// allow instantiation without initializing for simple inheritance
	if ( arguments.length ) {
		this._createWidget( options, element );
	}
};

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	options: {
		disabled: false
	},
	_createWidget: function( options, element ) {
		// $.widget.bridge stores the plugin instance, but we do it anyway
		// so that it's stored even before the _create function runs
		$.data( element, this.widgetName, this );
		this.element = $( element );
		this.options = $.extend( true, {},
			this.options,
			this._getCreateOptions(),
			options );

		var self = this;
		this.element.bind( "remove." + this.widgetName, function() {
			self.destroy();
		});

		this._create();
		this._trigger( "create" );
		this._init();
	},
	_getCreateOptions: function() {
		return $.metadata && $.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( key, value ) {
		var options = key;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.extend( {}, this.options );
		}

		if  (typeof key === "string" ) {
			if ( value === undefined ) {
				return this.options[ key ];
			}
			options = {};
			options[ key ] = value;
		}

		this._setOptions( options );

		return this;
	},
	_setOptions: function( options ) {
		var self = this;
		$.each( options, function( key, value ) {
			self._setOption( key, value );
		});

		return this;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				[ value ? "addClass" : "removeClass"](
					this.widgetBaseClass + "-disabled" + " " +
					"ui-state-disabled" )
				.attr( "aria-disabled", value );
		}

		return this;
	},

	enable: function() {
		return this._setOption( "disabled", false );
	},
	disable: function() {
		return this._setOption( "disabled", true );
	},

	_trigger: function( type, event, data ) {
		var callback = this.options[ type ];

		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		data = data || {};

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if ( event.originalEvent ) {
			for ( var i = $.event.props.length, prop; i; ) {
				prop = $.event.props[ --i ];
				event[ prop ] = event.originalEvent[ prop ];
			}
		}

		this.element.trigger( event, data );

		return !( $.isFunction(callback) &&
			callback.call( this.element[0], event, data ) === false ||
			event.isDefaultPrevented() );
	}
};

})( jQuery );
;
/*!
 * jQuery UI Mouse 1.8.14
 *
 * 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( $, undefined ) {

var mouseHandled = false;
$(document).mousedown(function(e) {
	mouseHandled = false;
});

$.widget("ui.mouse", {
	options: {
		cancel: ':input,option',
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if (true === $.data(event.target, self.widgetName + '.preventClickEvent')) {
				    $.removeData(event.target, self.widgetName + '.preventClickEvent');
					event.stopImmediatePropagation();
					return false;
				}
			});

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		if(mouseHandled) {return};

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).closest(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if (true === $.data(event.target, this.widgetName + '.preventClickEvent')) {
			$.removeData(event.target, this.widgetName + '.preventClickEvent');
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		event.preventDefault();
		
		mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !(document.documentMode >= 9) && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;

			if (event.target == this._mouseDownEvent.target) {
			    $.data(event.target, this.widgetName + '.preventClickEvent', true);
			}

			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
});

})(jQuery);
;
/*
 * jQuery UI Slider 1.8.14
 *
 * 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/Slider
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

// number of pages in a slider
// (how many times can you page up/down to go through the whole range)
var numPages = 5;

$.widget( "ui.slider", $.ui.mouse, {

	widgetEventPrefix: "slide",

	options: {
		animate: false,
		distance: 0,
		max: 100,
		min: 0,
		orientation: "horizontal",
		range: false,
		step: 1,
		value: 0,
		values: null
	},

	_create: function() {
		var self = this,
			o = this.options,
			existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ),
			handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
			handleCount = ( o.values && o.values.length ) || 1,
			handles = [];

		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();

		this.element
			.addClass( "ui-slider" +
				" ui-slider-" + this.orientation +
				" ui-widget" +
				" ui-widget-content" +
				" ui-corner-all" +
				( o.disabled ? " ui-slider-disabled ui-disabled" : "" ) );

		this.range = $([]);

		if ( o.range ) {
			if ( o.range === true ) {
				if ( !o.values ) {
					o.values = [ this._valueMin(), this._valueMin() ];
				}
				if ( o.values.length && o.values.length !== 2 ) {
					o.values = [ o.values[0], o.values[0] ];
				}
			}

			this.range = $( "<div></div>" )
				.appendTo( this.element )
				.addClass( "ui-slider-range" +
				// note: this isn't the most fittingly semantic framework class for this element,
				// but worked best visually with a variety of themes
				" ui-widget-header" + 
				( ( o.range === "min" || o.range === "max" ) ? " ui-slider-range-" + o.range : "" ) );
		}

		for ( var i = existingHandles.length; i < handleCount; i += 1 ) {
			handles.push( handle );
		}

		this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( self.element ) );

		this.handle = this.handles.eq( 0 );

		this.handles.add( this.range ).filter( "a" )
			.click(function( event ) {
				event.preventDefault();
			})
			.hover(function() {
				if ( !o.disabled ) {
					$( this ).addClass( "ui-state-hover" );
				}
			}, function() {
				$( this ).removeClass( "ui-state-hover" );
			})
			.focus(function() {
				if ( !o.disabled ) {
					$( ".ui-slider .ui-state-focus" ).removeClass( "ui-state-focus" );
					$( this ).addClass( "ui-state-focus" );
				} else {
					$( this ).blur();
				}
			})
			.blur(function() {
				$( this ).removeClass( "ui-state-focus" );
			});

		this.handles.each(function( i ) {
			$( this ).data( "index.ui-slider-handle", i );
		});

		this.handles
			.keydown(function( event ) {
				var ret = true,
					index = $( this ).data( "index.ui-slider-handle" ),
					allowed,
					curVal,
					newVal,
					step;
	
				if ( self.options.disabled ) {
					return;
				}
	
				switch ( event.keyCode ) {
					case $.ui.keyCode.HOME:
					case $.ui.keyCode.END:
					case $.ui.keyCode.PAGE_UP:
					case $.ui.keyCode.PAGE_DOWN:
					case $.ui.keyCode.UP:
					case $.ui.keyCode.RIGHT:
					case $.ui.keyCode.DOWN:
					case $.ui.keyCode.LEFT:
						ret = false;
						if ( !self._keySliding ) {
							self._keySliding = true;
							$( this ).addClass( "ui-state-active" );
							allowed = self._start( event, index );
							if ( allowed === false ) {
								return;
							}
						}
						break;
				}
	
				step = self.options.step;
				if ( self.options.values && self.options.values.length ) {
					curVal = newVal = self.values( index );
				} else {
					curVal = newVal = self.value();
				}
	
				switch ( event.keyCode ) {
					case $.ui.keyCode.HOME:
						newVal = self._valueMin();
						break;
					case $.ui.keyCode.END:
						newVal = self._valueMax();
						break;
					case $.ui.keyCode.PAGE_UP:
						newVal = self._trimAlignValue( curVal + ( (self._valueMax() - self._valueMin()) / numPages ) );
						break;
					case $.ui.keyCode.PAGE_DOWN:
						newVal = self._trimAlignValue( curVal - ( (self._valueMax() - self._valueMin()) / numPages ) );
						break;
					case $.ui.keyCode.UP:
					case $.ui.keyCode.RIGHT:
						if ( curVal === self._valueMax() ) {
							return;
						}
						newVal = self._trimAlignValue( curVal + step );
						break;
					case $.ui.keyCode.DOWN:
					case $.ui.keyCode.LEFT:
						if ( curVal === self._valueMin() ) {
							return;
						}
						newVal = self._trimAlignValue( curVal - step );
						break;
				}
	
				self._slide( event, index, newVal );
	
				return ret;
	
			})
			.keyup(function( event ) {
				var index = $( this ).data( "index.ui-slider-handle" );
	
				if ( self._keySliding ) {
					self._keySliding = false;
					self._stop( event, index );
					self._change( event, index );
					$( this ).removeClass( "ui-state-active" );
				}
	
			});

		this._refreshValue();

		this._animateOff = false;
	},

	destroy: function() {
		this.handles.remove();
		this.range.remove();

		this.element
			.removeClass( "ui-slider" +
				" ui-slider-horizontal" +
				" ui-slider-vertical" +
				" ui-slider-disabled" +
				" ui-widget" +
				" ui-widget-content" +
				" ui-corner-all" )
			.removeData( "slider" )
			.unbind( ".slider" );

		this._mouseDestroy();

		return this;
	},

	_mouseCapture: function( event ) {
		var o = this.options,
			position,
			normValue,
			distance,
			closestHandle,
			self,
			index,
			allowed,
			offset,
			mouseOverHandle;

		if ( o.disabled ) {
			return false;
		}

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		position = { x: event.pageX, y: event.pageY };
		normValue = this._normValueFromMouse( position );
		distance = this._valueMax() - this._valueMin() + 1;
		self = this;
		this.handles.each(function( i ) {
			var thisDistance = Math.abs( normValue - self.values(i) );
			if ( distance > thisDistance ) {
				distance = thisDistance;
				closestHandle = $( this );
				index = i;
			}
		});

		// workaround for bug #3736 (if both handles of a range are at 0,
		// the first is always used as the one with least distance,
		// and moving it is obviously prevented by preventing negative ranges)
		if( o.range === true && this.values(1) === o.min ) {
			index += 1;
			closestHandle = $( this.handles[index] );
		}

		allowed = this._start( event, index );
		if ( allowed === false ) {
			return false;
		}
		this._mouseSliding = true;

		self._handleIndex = index;

		closestHandle
			.addClass( "ui-state-active" )
			.focus();
		
		offset = closestHandle.offset();
		mouseOverHandle = !$( event.target ).parents().andSelf().is( ".ui-slider-handle" );
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
			top: event.pageY - offset.top -
				( closestHandle.height() / 2 ) -
				( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
				( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
				( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
		};

		if ( !this.handles.hasClass( "ui-state-hover" ) ) {
			this._slide( event, index, normValue );
		}
		this._animateOff = true;
		return true;
	},

	_mouseStart: function( event ) {
		return true;
	},

	_mouseDrag: function( event ) {
		var position = { x: event.pageX, y: event.pageY },
			normValue = this._normValueFromMouse( position );
		
		this._slide( event, this._handleIndex, normValue );

		return false;
	},

	_mouseStop: function( event ) {
		this.handles.removeClass( "ui-state-active" );
		this._mouseSliding = false;

		this._stop( event, this._handleIndex );
		this._change( event, this._handleIndex );

		this._handleIndex = null;
		this._clickOffset = null;
		this._animateOff = false;

		return false;
	},
	
	_detectOrientation: function() {
		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
	},

	_normValueFromMouse: function( position ) {
		var pixelTotal,
			pixelMouse,
			percentMouse,
			valueTotal,
			valueMouse;

		if ( this.orientation === "horizontal" ) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
		}

		percentMouse = ( pixelMouse / pixelTotal );
		if ( percentMouse > 1 ) {
			percentMouse = 1;
		}
		if ( percentMouse < 0 ) {
			percentMouse = 0;
		}
		if ( this.orientation === "vertical" ) {
			percentMouse = 1 - percentMouse;
		}

		valueTotal = this._valueMax() - this._valueMin();
		valueMouse = this._valueMin() + percentMouse * valueTotal;

		return this._trimAlignValue( valueMouse );
	},

	_start: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}
		return this._trigger( "start", event, uiHash );
	},

	_slide: function( event, index, newVal ) {
		var otherVal,
			newValues,
			allowed;

		if ( this.options.values && this.options.values.length ) {
			otherVal = this.values( index ? 0 : 1 );

			if ( ( this.options.values.length === 2 && this.options.range === true ) && 
					( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
				) {
				newVal = otherVal;
			}

			if ( newVal !== this.values( index ) ) {
				newValues = this.values();
				newValues[ index ] = newVal;
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal,
					values: newValues
				} );
				otherVal = this.values( index ? 0 : 1 );
				if ( allowed !== false ) {
					this.values( index, newVal, true );
				}
			}
		} else {
			if ( newVal !== this.value() ) {
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal
				} );
				if ( allowed !== false ) {
					this.value( newVal );
				}
			}
		}
	},

	_stop: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}

		this._trigger( "stop", event, uiHash );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {
			var uiHash = {
				handle: this.handles[ index ],
				value: this.value()
			};
			if ( this.options.values && this.options.values.length ) {
				uiHash.value = this.values( index );
				uiHash.values = this.values();
			}

			this._trigger( "change", event, uiHash );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( $.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this.options.values && this.options.values.length ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( $.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		$.Widget.prototype._setOption.apply( this, arguments );

		switch ( key ) {
			case "disabled":
				if ( value ) {
					this.handles.filter( ".ui-state-focus" ).blur();
					this.handles.removeClass( "ui-state-hover" );
					this.handles.attr( "disabled", "disabled" );
					this.element.addClass( "ui-disabled" );
				} else {
					this.handles.removeAttr( "disabled" );
					this.element.removeClass( "ui-disabled" );
				}
				break;
			case "orientation":
				this._detectOrientation();
				this.element
					.removeClass( "ui-slider-horizontal ui-slider-vertical" )
					.addClass( "ui-slider-" + this.orientation );
				this._refreshValue();
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();
				for ( i = 0; i < valsLength; i += 1 ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
		}
	},

	//internal value getter
	// _value() returns value trimmed by min and max, aligned by step
	_value: function() {
		var val = this.options.value;
		val = this._trimAlignValue( val );

		return val;
	},

	//internal values getter
	// _values() returns array of values trimmed by min and max, aligned by step
	// _values( index ) returns single value trimmed by min and max, aligned by step
	_values: function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else {
			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i+= 1) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		}
	},
	
	// returns the step-aligned value that val is closest to, between (inclusive) min and max
	_trimAlignValue: function( val ) {
		if ( val <= this._valueMin() ) {
			return this._valueMin();
		}
		if ( val >= this._valueMax() ) {
			return this._valueMax();
		}
		var step = ( this.options.step > 0 ) ? this.options.step : 1,
			valModStep = (val - this._valueMin()) % step;
			alignValue = val - valModStep;

		if ( Math.abs(valModStep) * 2 >= step ) {
			alignValue += ( valModStep > 0 ) ? step : ( -step );
		}

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat( alignValue.toFixed(5) );
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.options.max;
	},
	
	_refreshValue: function() {
		var oRange = this.options.range,
			o = this.options,
			self = this,
			animate = ( !this._animateOff ) ? o.animate : false,
			valPercent,
			_set = {},
			lastValPercent,
			value,
			valueMin,
			valueMax;

		if ( this.options.values && this.options.values.length ) {
			this.handles.each(function( i, j ) {
				valPercent = ( self.values(i) - self._valueMin() ) / ( self._valueMax() - self._valueMin() ) * 100;
				_set[ self.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
				if ( self.options.range === true ) {
					if ( self.orientation === "horizontal" ) {
						if ( i === 0 ) {
							self.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
						}
						if ( i === 1 ) {
							self.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
						}
					} else {
						if ( i === 0 ) {
							self.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
						}
						if ( i === 1 ) {
							self.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
						}
					}
				}
				lastValPercent = valPercent;
			});
		} else {
			value = this.value();
			valueMin = this._valueMin();
			valueMax = this._valueMax();
			valPercent = ( valueMax !== valueMin ) ?
					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
					0;
			_set[ self.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );

			if ( oRange === "min" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
			}
			if ( oRange === "max" && this.orientation === "horizontal" ) {
				this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
			}
			if ( oRange === "min" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
			}
			if ( oRange === "max" && this.orientation === "vertical" ) {
				this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
			}
		}
	}

});

$.extend( $.ui.slider, {
	version: "1.8.14"
});

}(jQuery));
;
/*!
 * jQuery imagesLoaded plugin v1.0.4
 * http://github.com/desandro/imagesloaded
 *
 * MIT License. by Paul Irish et al.
 */

(function($, undefined) {

  // $('#my-container').imagesLoaded(myFunction)
  // or
  // $('img').imagesLoaded(myFunction)

  // execute a callback when all images have loaded.
  // needed because .load() doesn't work on cached images

  // callback function gets image collection as argument
  //  `this` is the container

  $.fn.imagesLoaded = function( callback ) {
    var $this = this,
        $images = $this.find('img').add( $this.filter('img') ),
        len = $images.length,
        blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

    function triggerCallback() {
      callback.call( $this, $images );
    }

    function imgLoaded( event ) {
      if ( --len <= 0 && event.target.src !== blank ){
        setTimeout( triggerCallback );
        $images.unbind( 'load error', imgLoaded );
      }
    }

    if ( !len ) {
      triggerCallback();
    }

    $images.bind( 'load error',  imgLoaded ).each( function() {
      // cached images don't fire load sometimes, so we reset src.
      if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
      }
    });

    return $this;
  };
})(jQuery);;

var Emphasis = {
    init: function() {
        this.config();

        this.pl = false; // Paragraph List
        this.p  = false; // Paragraph Anchor
        this.h  = false; // Highlighted paragraphs
        this.s  = false; // Highlighted sentences
        this.vu = false; // Are paragraph links visible or not
        this.kh = "|";

        this.addCSS();
        this.readHash();

		jQuery(document).keydown(function(ev) {
		  Emphasis.keydown(ev);
		});
    },

    config: function() {
    /*
        Eligible Paragraphs
        This uses some common markup for plain and simpel paragraphs - those that are not empty, no classes.
        We use PrototypeJS for its css selector awesomeness, but your needs might be simpler (getElementsByTagName('p') etc.)
    */	
		this.running           = true;
        this.paraSelctors      = jQuery("p");

    //  Class names
        this.classReady        = "emReady";
        this.classActive       = "emActive";
        this.classHighlight    = "emHighlight";
        this.classInfo         = "emInfo";
        this.classAnchor       = "emAnchor";
        this.classActiveAnchor = "emActiveAnchor";
    },

	goOverlay: function(keys, h) {
		jQuery("p.emReady").addClass("emPop");
		jQuery(document.body).append("<div id='emOverlay'></div>");
		
		jQuery('#emOverlay').click(function() {
		  jQuery('#emOverlay').fadeOut("fast",function() {
			    jQuery(this).remove();
          });
		});
	},

    addCSS: function() {
    /*  Inject the minimum styles rules required */
        var st = document.createElement('style');
        jQuery(st).html('p.' + this.classActive + ' span { background-color:#f2f4f5; } p span.' + this.classHighlight + ' { background-color:#fff0b3; } span.' + this.classInfo + ' { position:absolute; margin:-1px 0px 0px -8px; padding:0; font-size:10px; background-color: transparent !important} span.' + this.classInfo + ' a { text-decoration: none; } a.' + this.classAnchor + ' { color: darkBlue; font-family: Helvetica, Arial; font-size: 10px; } a.' + this.classActiveAnchor + ' { color: #000; font-size: 11px; }');
        document.getElementsByTagName("head")[0].appendChild(st);
    },

    readHash: function() {
    /*  Read and interpret the URL hash */
        var lh = decodeURI(location.hash);
        var p  = false, h = [], s = {}, k = [];

        if (lh.indexOf('[')<0 && lh.indexOf(']')<0) {
        /*  Version 1 Legacy support
            #p20h4s2,6,10,h6s5,1 -> p = 20, h = [ 4, 6 ], s = { "4": [ 2, 6, 10 ] , "6": [ 5, 1 ] }
        */
            var a, re = /[ph][0-9]+|s[0-9,]+|[0-9]/g;
            if (lh) {
                while ((a = re.exec(lh)) !== null) {
                    var f = a[0].substring(0, 1);
                    var r = a[0].substring(1);
                    if (f == 'p') {
                        p = parseInt(r);
                    } else if (f == 'h') {
                        h.push(parseInt(r));
                    } else {
                        a = r.split(',');
                        for (var i = 0; i < a.length; i++) {
                            a[i] = parseInt(a[i]);
                        }
                        s[h[h.length - 1]] = a;
                    }
                }
            }
        } else {
        /*  Version 2
            #h[tbsaoa,Sstaoo,2,4],p[FWaadw] -> p = "FWaadw", h = [ "tbsaoa", "Sstaoo" ], s = { "Sstaoo" : [ 2, 4 ] }
        */
            var findp = lh.match(/p\[([^[\]]*)\]/);
            var findh = lh.match(/h\[([^[\]]*)\]/);
            var undef, hi;

            p  = (findp && findp.length>0) ? findp[1] : false;
            hi = (findh && findh.length>0) ? findh[1] : false;

            if (hi) {

                hi = hi.match(/[a-zA-Z]+(,[0-9]+)*/g);
    
            	for (var i = 0; i < hi.length; i++) {
	
                    var a   = hi[i].split(',');
                    var key = a[0];

                    var pos = this.findKey(key)['index'];

                    if (pos!=undef) {
                        h.push(parseInt(pos)+1);
	                    k.push(key);

                        var b = a;
                        b.shift();

                        if (b.length>0) {
                            for (var j=1; j<b.length; j++) {
                                b[j] = parseInt(b[j]);
                            }
                        }
                        s[h[h.length - 1]] = b;
                    }
                }
            }
        }

        this.p = p; this.h = h; this.s = s;

        this.goAnchor(p);
        this.goHighlight(h, s);

		if (lh.indexOf('context')>0) {
        	this.goOverlay(k, h);
		}
    },

    keydown: function(e){
    /*  Look for double-shift keypress */
        var self = Emphasis;
        var kc   = e.keyCode;
        self.kh  = self.kh + kc + '|';
        if (self.kh.indexOf('|16|16|')>-1) {
            self.vu = (self.vu) ? false : true;
            self.paragraphInfo(self.vu);
        }
        setTimeout(function(){ self.kh = '|'; }, 500);
    },

    paragraphList: function() {
    /*  Build a list of Paragrphs, keys, and add meta-data to each Paragraph in DOM, saves list for later re-use */
        if (this.pl) return this.pl;
        var instance = this;
        var list = [];
        var keys = [];
        var c    = 0;
        var len  = this.paraSelctors.length;

        for (var p=0; p<len; p++) {
            var pr = this.paraSelctors[p];
            if ((pr.innerText || pr.textContent || "").length>0) {
                var k = instance.createKey(pr);
                list.push(pr);
                keys.push(k);
                pr.setAttribute("data-key", k); // Unique Key
                pr.setAttribute("data-num", c); // Order

				jQuery(pr).click(function(e) {
					instance.paragraphClick(e);
				});

                c++;
            }
        }

        this.pl = { list: list, keys: keys };
        return this.pl;
    },

    paragraphClick: function(e) {
    /*  Clicking a Paragrsph has consequences for Highlighting, selecting and changing active Anchor */

        if (!this.vu) { return; }

        var hasChanged = false;
        var pr = (e.currentTarget.nodeName=="P") ? e.currentTarget : false; // Paragraph
        var sp = (e.target.nodeName=="SPAN")     ? e.target        : false; // Span
        var an = (e.target.nodeName=="A")        ? e.target        : false; // Anchor

        if (an) {
        /*  Click an Anchor link */
            if (!jQuery(an).hasClass(this.classActiveAnchor)) {
                this.updateAnchor(an);
                hasChanged = true;
                e.preventDefault();
            }
        }

        if (!pr && !sp) {
            this.removeAllClasses("p", this.classActive);
            return;
        }

        if (jQuery(pr).hasClass(this.classReady)) {
            if (!jQuery(pr).hasClass(this.classActive) && (sp && !jQuery(sp).hasClass(this.classHighlight))) {
            //  If not current Active p tag, clear any others out there and make this the Active p tag
                this.removeAllClasses("p", this.classActive);
                jQuery(pr).addClass(this.classActive); // Mark as Active
            } else {
                if (!jQuery(pr).hasClass(this.classActive)) {
                    this.removeAllClasses("p", this.classActive);
                    jQuery(pr).addClass(this.classActive); // Mark as Active
                }

                if (sp) {
                    jQuery(sp).toggleClass(this.classHighlight);
                    hasChanged = true;
                }
            }
        } else {
        //  Add span tags to all Sentences within Paragraph and mark Paragraph as Ready
            var lines = this.getSentences(pr);
            var jLen  = lines.length;

            for (var j=0; j<jLen; j++) {
                lines[j] = "<span data-num='" + (j+1) + "'>" + this.rtrim(lines[j]) + "</span>";
            }

            var txt = lines.join('. ').replace(/__DOT__/g, ".").replace(/<\/span>\./g, ".<\/span>");
            var chr = txt.substring(txt.length-8).charCodeAt(0);
            if ("|8221|63|46|41|39|37|34|33|".indexOf(chr)==-1) { txt += "."; }

            jQuery(pr).html(txt);
            pr.setAttribute('data-sentences', jLen);

            this.removeAllClasses("p", this.classActive);
            jQuery(pr).addClass(this.classActive); // Mark as Active
            jQuery(pr).addClass(this.classReady);  // Mark as Ready
            hasChanged = true;
        }

        if (hasChanged) {
            this.updateURLHash();
        }
    },

    paragraphInfo: function(mode) {
    /*  Toggle anchor links next to Paragraphs */

        if (mode) {
            var hasSpan = (jQuery('span.' + this.classInfo)[0]) ? true : false;

            if (!hasSpan) {
                var pl  = this.paragraphList();
                var len = pl.list.length;
                for (var i=0; i<len; i++) {
                    var para = pl.list[i] || false;
                    if (para) {
                        var key        = pl.keys[i];
                        var isActive   = (key==this.p) ? (" " + this.classActiveAnchor) : "";
                        jQuery(para).html("<span class='" + this.classInfo + "'><a class='"+ this.classAnchor + isActive + "' href='#p[" + key + "]' data-key='" + key + "' title='Link to " + this.ordinal(i+1) + " paragraph'>&para;</a></span>" + jQuery(para).html());
                    }
                }
            }
        } else {
            var spans = jQuery('span.' + this.classInfo);
            var len = spans.length;
            for (var i=0; i<len; i++) {
                jQuery(spans[i]).remove();
            }
            this.removeAllClasses(this.classActive);
        }
    },

    updateAnchor: function(an) {
    /*  Make this A tag the one and only Anchor */
        this.p = jQuery(an).attr("data-key");
        this.removeAllClasses("a", this.classActiveAnchor);
        jQuery(an).addClass(this.classActiveAnchor);
    },

    updateURLHash: function() {
    /*  Scan the Paragraphs, note selections, highlights and update the URL with the new Hash */
        var h     = "h[";
        var paras = jQuery('p.emReady');
        var pLen  = paras.length;

        for (var p=0; p<pLen; p++) {
            var key = jQuery(paras[p]).attr("data-key");
            if (jQuery(paras[p]).hasClass(this.classHighlight)) {
                h += "," + key; // Highlight full paragraph
            } else {
                var spans = jQuery(paras[p]).find('span.' + this.classHighlight);
                var sLen  = spans.length;
                var nSent = jQuery(paras[p]).attr("data-sentences");

                if (sLen>0) { h += "," + key; }

                if (nSent!=sLen) {
                    for (var s=0; s<sLen; s++) {
                        h += "," + jQuery(spans[s]).attr("data-num");
                    }
                }
            }
        }

        var anchor    = ((this.p) ? "p[" + this.p + "]," : "");
        var hash      = (anchor + (h.replace("h[,", "h[") + "]")).replace(",h[]", "");
        location.hash = hash;
    },

    createKey: function(p) {
    /*  From a Paragraph, generate a Key */
        var key = "";
        var len = 6;
        var txt = (p.innerText || p.textContent || '').replace(/[^a-z\. ]+/gi, '');
        if (txt && txt.length>1) {

            var lines = this.getSentences(txt);
            if (lines.length>0) {
                var first = this.cleanArray(lines[0].replace(/[\s\s]+/gi, ' ').split(' ')).slice(0, (len/2));
                var last  = this.cleanArray(lines[lines.length-1].replace(/[\s\s]+/gi, ' ').split(' ')).slice(0, (len/2));
                var k     = first.concat(last);

                var max = (k.length>len) ? len : k.length;
                for (var i=0; i<max; i++) {
                    key += k[i].substring(0, 1);
                }
            }
        }
        return key;
    },

    findKey: function(key) {
    /*  From a list of Keys, locate the Key and corresponding Paragraph */
        var pl = this.paragraphList();
        var ln = pl.keys.length;
        var ix = false;
        var el = false;

        for (var i=0;i<ln;i++) {
            if (key==pl.keys[i]) { // Direct Match
                return { index: i, elm: pl.list[i] };
            } else { // Look for 1st closest Match
                if (!ix) {
                    var ls = this.lev(key.slice(0, 3), pl.keys[i].slice(0, 3));
                    var le = this.lev(key.slice(-3)  , pl.keys[i].slice(-3));
                    if ((ls+le)<3) {
                        ix = i;
                        el = pl.list[i];
                    }
                }
            }
        }
        return { index: ix, elm: el };
    },

    goAnchor: function(p) {
    /*  Move view to top of a given Paragraph */
        if (!p) return;
        var pg = (isNaN(p)) ? this.findKey(p)['elm'] : (this.paragraphList().list[p-1] || false);
        var instance = this;
        if (pg) {
            setTimeout(function(){

                //pg.scrollTo();
				jQuery(pg).animate({scrollTop:0}, 'slow');

            }, 500);
        }
    },

    goHighlight: function(h, s) {
    /*  Highlight a Paragraph, or specific Sentences within it */
        if (!h) return;
        var hLen = h.length;

        for (var i=0; i<hLen; i++) {
            var para = this.paragraphList().list[h[i]-1] || false;
            if (para) {
                var sntns = s[h[i].toString()] || false;
                var multi = !sntns || sntns.length==0; // Individual sentences, or whole paragraphy?
                var lines = this.getSentences(para);
                var jLen  = lines.length;

            /*  First pass. Add SPAN tags to all lines. */
                for (var j=0; j<jLen; j++) {
                    var k = (multi) ? j : sntns[j]-1;
                    lines[j] = "<span data-num='" + (j+1) + "'>" + lines[j] + "</span>";
                }

            /*  Second pass, update span to Highlight selected lines */
                for (var j=0; j<jLen; j++) {
                    var k    = (multi) ? j : sntns[j]-1;
                    var line = lines[k] || false;
                    if (line) {
                        lines[k] = lines[k].replace("<span", "<span class='" + this.classHighlight + "'");
                    }
                }

                para.setAttribute("data-sentences", jLen);
                jQuery(para).html(lines.join('. ').replace(/__DOT__/g, ".").replace(/<\/span>\./g, ".<\/span>"));
                jQuery(para).addClass('emReady'); /* Mark the paragraph as having SPANs */
            }
        }
    },

    getSentences: function(el) {
    /*  Break a Paragraph into Sentences, bearing in mind that the "." is not the definitive way to do so */
        var html    = (typeof el=="string") ? el : el.innerHTML;
        var mrsList = "Mr,Ms,Mrs,Miss,Msr,Dr,Gov,Pres,Sen,Prof,Gen,Rep,St,Messrs,Col,Sr,Jf,Ph,Sgt,Mgr,Fr,Rev,No,Jr,Snr";
        var topList = "A,B,C,D,E,F,G,H,I,J,K,L,M,m,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,etc,oz,cf,viz,sc,ca,Ave,St";
        var geoList = "Calif,Mass,Penn,AK,AL,AR,AS,AZ,CA,CO,CT,DC,DE,FL,FM,GA,GU,HI,IA,ID,IL,IN,KS,KY,LA,MA,MD,ME,MH,MI,MN,MO,MP,MS,MT,NC,ND,NE,NH,NJ,NM,NV,NY,OH,OK,OR,PA,PR,PW,RI,SC,SD,TN,TX,UT,VA,VI,VT,WA,WI,WV,WY,AE,AA,AP,NYC,GB,IRL,IE,UK,GB,FR";
        var numList = "0,1,2,3,4,5,6,7,8,9";
        var webList = "aero,asia,biz,cat,com,coop,edu,gov,info,int,jobs,mil,mobi,museum,name,net,org,pro,tel,travel,xxx";
        var extList = "www";
        var d       = "__DOT__";

        var list = (topList+","+geoList+","+numList+","+extList).split(",");
        var len  = list.length;
        for (var i=0;i<len;i++) {
            html = html.replace(new RegExp((" "+list[i]+"\\."), "g"), (" "+list[i]+d));
        }

        list = (mrsList+","+numList).split(",");
        len  = list.length;
        for (var i=0;i<len;i++) {
            html = html.replace(new RegExp((list[i]+"\\."), "g"), (list[i]+d));
        }

        list = (webList).split(",");
        len  = list.length;
        for (var i=0;i<len;i++) {
            html = html.replace(new RegExp(("\\."+list[i]), "g"), (d+list[i]));
        }

        var lines = this.cleanArray(html.split('. '));
        return lines;
    },

    ordinal: function(n) {
        var sfx = ["th","st","nd","rd"], val = n%100;
        return n + (sfx[(val-20)%10] || sfx[val] || sfx[0]);
    },

    lev: function(a, b) {
    /*  Get the Levenshtein distance - a measure of difference between two sequences */
        var m = a.length;
        var n = b.length;
        var r = []; r[0] = [];
        if (m < n) { var c = a; a = b; b = c; var o = m; m = n; n = o; }
        for (var c = 0; c < n+1; c++) { r[0][c] = c; }
        for (var i = 1; i < m+1; i++) {
            r[i] = [];
            r[i][0] = i;
            for (var j=1; j<n+1; j++) {
                r[i][j] = this.smallest(r[i-1][j]+1, r[i][j-1]+1, r[i-1][j-1]+((a.charAt(i-1)==b.charAt(j-1))? 0 : 1));
            }
        }
        return r[m][n];
    },

    smallest: function(x,y,z) {
    /*  Return smallest of two values */
        if (x < y && x < z) return x;
        if (y < x && y < z) return y;
        return z;
    },

    rtrim: function(txt) {
    /*  Trim whitespace from right of string */
        return txt.replace(/\s+$/, "");
    },

    cleanArray: function(a){
    /*  Remove empty items from an array */
        var n = [];
        for (var i = 0; i<a.length; i++){
            if (a[i] && a[i].replace(/ /g,'').length>0){ n.push(a[i]); }
        }
        return n;
    },

    removeAllClasses: function(tag, klass) {
    /*  Remove classes */
        if (!klass || !tag) return;
        var els = jQuery((tag + "." + klass));
        for (var i=0; i<els.length; i++){
            jQuery(els[i]).removeClass(klass);
        }
    }
};
;
(function() {
  window.GoogleChart = (function() {
    function GoogleChart(width, height) {
      this.width = width;
      this.height = height;
      this.encoded = [];
      this.data = [];
      this.chg = '';
      this.chf = '';
      this.chco = '';
      this.chdl = '';
      this.chxl = [];
      this.chxp = [];
    }
    GoogleChart.prototype.types = {
      'line': 'lc'
    };
    GoogleChart.prototype.base_url = 'http://chart.apis.google.com/chart?';
    GoogleChart.prototype.add_data = function(values) {
      return this.data.push(values);
    };
    GoogleChart.prototype.set_axis_labels = function(index, labels) {
      return this.chxl.push([index, labels]);
    };
    GoogleChart.prototype.set_axis_positions = function(index, positions) {
      return this.chxp.push([index, positions]);
    };
    GoogleChart.prototype.set_grid = function(x_step, y_step, dash_length, space_length, x_offset, y_offset) {
      return this.chg = x_step + ',' + y_step + ',' + dash_length + ',' + space_length + ',' + x_offset + ',' + y_offset;
    };
    GoogleChart.prototype.set_fill = function(fill_type, s, color) {
      return this.chf = fill_type + ',' + s + ',' + color;
    };
    GoogleChart.prototype.set_colors = function(colors) {
      return this.chco = colors.join(',');
    };
    GoogleChart.prototype.set_legend = function(legend) {
      return this.chdl = legend.join('|');
    };
    GoogleChart.prototype.chs = function() {
      return [this.width, this.height].join('x');
    };
    GoogleChart.prototype.cht = function() {
      return this.types['line'];
    };
    GoogleChart.prototype.chd = function() {
      var maxValue, values;
      maxValue = this.max(_(this.data).flatten());
      return this.encoding() + ((function() {
        var _i, _len, _ref, _results;
        _ref = this.data;
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          values = _ref[_i];
          _results.push(this.encode(values, maxValue));
        }
        return _results;
      }).call(this)).join(',');
    };
    GoogleChart.prototype.url = function() {
      var axis_labels, axis_positions, index, key, labels, pieces, positions, value, _i, _j, _len, _len2, _ref, _ref2;
      pieces = {
        'cht': this.cht(),
        'chs': this.chs(),
        'chd': this.chd(),
        'chg': this.chg,
        'chf': this.chf,
        'chco': this.chco,
        'chdlp': 't|l'
      };
      if (this.chdl !== '') {
        pieces['chdl'] = this.chdl;
      }
      if (this.chxl) {
        pieces['chxt'] = [];
        pieces['chxl'] = [];
        _ref = this.chxl;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          axis_labels = _ref[_i];
          index = axis_labels[0], labels = axis_labels[1];
          pieces['chxl'].push(_i + ':|' + labels.join('|'));
          pieces['chxt'].push(index);
        }
        pieces['chxl'] = pieces['chxl'].join('|');
        pieces['chxt'] = pieces['chxt'].join(',');
        if (this.chxp) {
          pieces['chxp'] = '';
          _ref2 = this.chxp;
          for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
            axis_positions = _ref2[_j];
            index = axis_positions[0], positions = axis_positions[1];
            index = {
              y: 0,
              x: 1
            }[index];
            pieces['chxp'] = index + ',' + positions.join(',');
          }
        }
      }
      return this.base_url + ((function() {
        var _results;
        _results = [];
        for (key in pieces) {
          value = pieces[key];
          _results.push("" + key + "=" + value);
        }
        return _results;
      })()).join('&');
    };
    GoogleChart.prototype.max = function(values) {
      return Math.max.apply(Math, values);
    };
    GoogleChart.prototype.encoding = function() {
      if (this.height > 100) {
        return 'e:';
      } else {
        return 's:';
      }
    };
    GoogleChart.prototype.encode = function(values, maxValue) {
      if (this.height > 100) {
        return this.extendedEncode(values, maxValue);
      } else {
        return this.simpleEncode(values, maxValue);
      }
    };
    GoogleChart.prototype.simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    GoogleChart.prototype.simpleEncode = function(values, maxValue) {
      var chartData, currentValue, val, _i, _len;
      chartData = [];
      for (_i = 0, _len = values.length; _i < _len; _i++) {
        currentValue = values[_i];
        if (!isNaN(currentValue && currentValue >= 0)) {
          val = Math.round((this.simpleEncoding.length - 1) * (currentValue / maxValue));
          chartData.push(this.simpleEncoding.charAt(val));
        } else {
          chartData.push('_');
        }
      }
      return chartData.join('');
    };
    GoogleChart.prototype.extendedMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.';
    GoogleChart.prototype.extendedEncode = function(values, maxValue) {
      var chartData, currentValue, mapLength, numericalVal, quotient, remainder, scaledVal, _i, _len;
      chartData = '';
      mapLength = this.extendedMap.length;
      for (_i = 0, _len = values.length; _i < _len; _i++) {
        currentValue = values[_i];
        numericalVal = new Number(currentValue);
        scaledVal = Math.floor(mapLength * mapLength * numericalVal / maxValue);
        if (scaledVal > (mapLength * mapLength) - 1) {
          chartData += '..';
        } else if (scaledVal < 0) {
          chartData += '__';
        } else {
          quotient = Math.floor(scaledVal / mapLength);
          remainder = scaledVal - mapLength * quotient;
          chartData += this.extendedMap.charAt(quotient) + this.extendedMap.charAt(remainder);
        }
      }
      return chartData;
    };
    return GoogleChart;
  })();
}).call(this);
;
(function() {
  /*
  CapitolWords
  main application class
  Requires: jQuery, jQuery ui slider, underscore
  */
  var $, currentMonth;
  var __indexOf = Array.prototype.indexOf || function(item) {
    for (var i = 0, l = this.length; i < l; i++) {
      if (this[i] === item) return i;
    }
    return -1;
  };
  $ = jQuery;
  /*
  jQuery.deparam
  reverses jQuery's param() method, converting a querystring back to an object
  */
  $.deparam = function(qs) {
    var params, pieces;
    params = {};
    if (!qs) {
      return params;
    }
    pieces = qs.split(/[&=]/);
    $.each(pieces, function(idx, val) {
      if (idx % 2) {
        return params[pieces[idx - 1]] = val;
      }
    });
    return params;
  };
  /*
  jQuery.cleanedValue
  decodes uri components and strips html tags
  */
  $.cleanedValue = function(str) {
    if (!str) {
      return '';
    }
    str = decodeURIComponent(str).replace(/\+/g, ' ');
    return $.trim($("<div>" + str + "</div>").text());
  };
  /*
  jQuery.sum
  returns the sum of an array
  */
  $.sum = function(arr) {
    var sum, val, _i, _len;
    sum = 0;
    for (_i = 0, _len = arr.length; _i < _len; _i++) {
      val = arr[_i];
      sum += val;
    }
    return sum;
  };
  currentMonth = function() {
    var d, pad;
    d = new Date();
    pad = d.getMonth() + 1 > 9 ? '' : '0';
    return "" + (d.getFullYear()) + pad + (d.getMonth() + 1);
  };
  window.CapitolWords = (function() {
    function CapitolWords() {}
    CapitolWords.prototype.cw = CapitolWords;
    CapitolWords.prototype.a = {};
    CapitolWords.prototype.b = {};
    CapitolWords.prototype.debug_progress = 0;
    CapitolWords.prototype.homepageDefaults = {
      'terma': 'Word or phrase',
      'termb': 'Word or phrase',
      'statea': '',
      'stateb': '',
      'partya': 'All',
      'partyb': 'All',
      'start': '199601',
      'end': currentMonth()
    };
    CapitolWords.prototype.itemsToCompare = [];
    CapitolWords.prototype.legislatorData = [];
    CapitolWords.prototype.minMonth = void 0;
    CapitolWords.prototype.maxMonth = void 0;
    CapitolWords.prototype.random_phrase_i = void 0;
    CapitolWords.prototype.smoothing = 0;
    CapitolWords.prototype.spinner = null;
    CapitolWords.prototype.year_values = [];
    CapitolWords.prototype.states = {
      "AL": "Alabama",
      "AK": "Alaska",
      "AZ": "Arizona",
      "AR": "Arkansas",
      "CA": "California",
      "CO": "Colorado",
      "CT": "Connecticut",
      "DE": "Delaware",
      "FL": "Florida",
      "GA": "Georgia",
      "HI": "Hawaii",
      "ID": "Idaho",
      "IL": "Illinois",
      "IN": "Indiana",
      "IA": "Iowa",
      "KS": "Kansas",
      "KY": "Kentucky",
      "LA": "Louisiana",
      "ME": "Maine",
      "MD": "Maryland",
      "MA": "Massachusetts",
      "MI": "Michigan",
      "MN": "Minnesota",
      "MS": "Mississippi",
      "MO": "Missouri",
      "MT": "Montana",
      "NE": "Nebraska",
      "NV": "Nevada",
      "NH": "New Hampshire",
      "NJ": "New Jersey",
      "NM": "New Mexico",
      "NY": "New York",
      "NC": "North Carolina",
      "ND": "North Dakota",
      "OH": "Ohio",
      "OK": "Oklahoma",
      "OR": "Oregon",
      "PA": "Pennsylvania",
      "RI": "Rhode Island",
      "SC": "South Carolina",
      "SD": "South Dakota",
      "TN": "Tennessee",
      "TX": "Texas",
      "UT": "Utah",
      "VT": "Vermont",
      "VA": "Virginia",
      "WA": "Washington",
      "WV": "West Virginia",
      "WI": "Wisconsin",
      "WY": "Wyoming",
      "DC": "District of Columbia",
      "AA": "Armed Forces Americas",
      "AE": "Armed Forces Europe",
      "AP": "Armed Forces Pacific",
      "AS": "American Samoa",
      "GU": "Guam",
      "MP": "Northern Mariana Islands",
      "PR": "Puerto Rico",
      "VI": "Virgin Islands"
    };
    CapitolWords.prototype.addLegislatorToChart = function(result, maxcount, div, callback) {
      var bioguide_id, pct, url;
      url = 'http://capitolwords.org/api/legislators.json';
      bioguide_id = result['legislator'];
      pct = (result['count'] / maxcount) * 100;
      return $.ajax({
        dataType: 'jsonp',
        url: url,
        async: false,
        data: {
          bioguide_id: bioguide_id,
          apikey: window.cwod_apikey
        },
        success: function(data) {
          data = data['results'];
          url = "/legislator/" + bioguide_id + "-" + data['slug'];
          cw.legislatorData.push({
            url: url,
            data: data,
            result: result,
            pct: pct
          });
          return callback();
        }
      });
    };
    CapitolWords.prototype.build_legend = function() {
      var legend, legendA, legendB, partyA, partyB, stateA, stateB, termA, termB, _ref;
      _ref = cw.phrases(), termA = _ref[0], termB = _ref[1];
      partyA = $('.partyA input:checked').eq(0).val();
      stateA = $('#stateA').val();
      legend = [];
      legendA = termA;
      if (termA && termA !== 'Word or phrase') {
        if (partyA && stateA) {
          legendA += " [" + partyA + "-" + stateA + "]";
        } else if (partyA) {
          legendA += " [" + partyA + "]";
        } else if (stateA) {
          legendA += " [" + stateA + "]";
        }
        legend.push(legendA);
      }
      partyB = $('.partyB input:checked').eq(0).val();
      stateB = $('#stateB').val();
      legendB = termB;
      if (termB && termB !== 'Word or phrase') {
        if (partyB && stateB) {
          legendB += " [" + partyB + "-" + stateB + "]";
        } else if (partyB) {
          legendB += " [" + partyB + "]";
        } else if (stateB) {
          legendB += " [" + stateB + "]";
        }
        legend.push(legendB);
      }
      return legend;
    };
    CapitolWords.prototype.build_legend_html = function() {
      var legend, partyA, partyB, stateA, stateB, template, termA, termB;
      legend = this.build_legend();
      termA = legend[0] && legend[0].split(' [')[0] || "(no term)";
      partyA = $.trim($('.partyA input:checked').eq(0).parent().text());
      if (partyA === 'All') {
        partyA = 'All Parties';
      }
      stateA = $('#stateA');
      stateA = stateA.val() && this.states[stateA.val()] || "All states";
      termB = legend[1] && legend[1].split(' [')[0] || "(no term)";
      partyB = $.trim($('.partyB input:checked').eq(0).parent().text());
      if (partyB === 'All') {
        partyB = 'All Parties';
      }
      stateB = $('#stateB');
      stateB = stateB.val() && this.states[stateB.val()] || "All states";
      template = "<div class=\"key\">\n    <span class=\"wordOne\">\n        <span class=\"color\"></span><a href=\"/term/" + termA + "\" class=\"wordOne\">" + termA + "</a>\n        <span class=\"filters\">[" + stateA + ", " + partyA + "]</span>\n    </span>\n    <span class=\"wordTwo\">\n        <span class=\"color\"></span><a href=\"/term/" + termB + "\" class=\"wordTwo\">" + termB + "</a>\n        <span class=\"filters\">[" + stateB + ", " + partyB + "]</span>\n    </span>\n</div>";
      return template;
    };
    CapitolWords.prototype.buildPartyGraph = function(minMonth, maxMonth, requestedUrls) {
      var colors, func, i, imgTag, imgUrl, labelPositions, params, parties, partyAPercentages, partyBPercentages, percentages, url, vals, x;
      if (minMonth && maxMonth) {
        func = function(v) {
          return v['month'] >= minMonth && v['month'] <= maxMonth;
        };
      } else {
        func = function() {
          return true;
        };
      }
      if (!requestedUrls) {
        requestedUrls = this.getDataUrlsForImage($('#partyTermChart'));
      }
      vals = [
        (function() {
          var _i, _len, _ref, _results;
          _ref = this.partyResults;
          _results = [];
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            x = _ref[_i];
            _results.push(_(x[1]).select(func));
          }
          return _results;
        }).call(this)
      ][0];
      labelPositions = this.buildXLabels(vals[0]);
      partyAPercentages = _(vals[0]).pluck('percentage');
      partyBPercentages = _(vals[1]).pluck('percentage');
      percentages = [partyAPercentages, partyBPercentages];
      parties = [
        (function() {
          var _i, _len, _ref, _results;
          _ref = this.partyResults;
          _results = [];
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            x = _ref[_i];
            _results.push(x[0]);
          }
          return _results;
        }).call(this)
      ];
      colors = {
        'D': '295e72',
        'R': 'bb3110'
      };
      params = {
        x_positions: labelPositions[0],
        x_label_positions: labelPositions[1],
        width: 565,
        height: 300,
        colors: [colors[this.partyResults[0][0]], colors[this.partyResults[1][0]]],
        legend: [this.partyResults[0][0], this.partyResults[1][0]]
      };
      imgUrl = this.showChart([partyAPercentages, partyBPercentages], params);
      imgTag = $("<img id=\"partyTermChart\"\nsrc=\"" + imgUrl + "\" />");
      if (typeof requestedUrls !== 'undefined') {
        for (i in requestedUrls) {
          url = requestedUrls[i];
          imgTag.attr('data-dataurl' + i, url);
        }
      }
      return $('#partyTimeline').html(imgTag);
    };
    CapitolWords.prototype.buildXLabels = function(values) {
      var labels, positions, year, years;
      years = _(_(values).pluck('month')).select(function(x) {
        return x.match(/01$/);
      });
      positions = [
        (function() {
          var _i, _len, _results;
          _results = [];
          for (_i = 0, _len = years.length; _i < _len; _i++) {
            year = years[_i];
            _results.push(Math.round((($.inArray(year, years)) / years.length) * 100));
          }
          return _results;
        })()
      ];
      labels = _(years).map(function(x) {
        return "1/" + (x.slice(2, 4));
      });
      return [labels, positions];
    };
    CapitolWords.prototype.customizeChart = function() {
      var party, state, url;
      party = $('#partySelect').val();
      state = $('#stateSelect').val();
      url = 'http://capitolwords.org/api/chart/timeline.json';
      return $.ajax({
        dataType: 'jsonp',
        url: url,
        data: {
          'party': party,
          'state': state,
          'phrase': $('#term').val(),
          'granularity': 'month',
          'percentages': 'true',
          'legend': 'false',
          'mincount': 0,
          'apikey': window.cwod_apikey
        },
        success: function(data) {
          var imgTag, imgUrl, results;
          results = data['results'];
          imgUrl = results['url'];
          imgTag = "<img src=\"" + imgUrl + "\"/>";
          return $('#customChart').attr('src', imgUrl);
        }
      });
    };
    CapitolWords.prototype.dateFromMonth = function(month) {
      var datePieces;
      datePieces = month.match(/(\d{4})(\d{2})/).slice(1, 3);
      datePieces.push('01');
      return datePieces.join('-');
    };
    CapitolWords.prototype.endDate = function() {
      var d;
      d = new Date();
      if (this.year_values[1]) {
        return "" + this.year_values[1] + "-12-31";
      } else {
        return "" + (d.getFullYear()) + "-12-31";
      }
    };
    CapitolWords.prototype.getCookie = function(name) {
      var cookie, cookieContent, cookieName, cookies, _i, _len, _ref;
      if (document.cookie && (document.cookie !== '')) {
        cookies = _(document.cookie.split(';')).map((function(x) {
          return $.trim(x);
        }));
        for (_i = 0, _len = cookies.length; _i < _len; _i++) {
          cookie = cookies[_i];
          _ref = cookie.split('=', 2), cookieName = _ref[0], cookieContent = _ref[1];
          if (cookieName === name) {
            return decodeURIComponent(cookieContent);
          }
        }
      }
    };
    CapitolWords.prototype.getCREntries = function(term) {
      var cw, data, url;
      url = 'http://capitolwords.org/api/text.json';
      cw = this;
      data = {
        'phrase': term,
        'bioguide_id': "['' TO *]",
        'start_date': cw.start_date,
        'end_date': cw.end_date,
        'sort': 'date desc,score desc',
        'apikey': window.cwod_apikey
      };
      return $.ajax({
        dataType: 'jsonp',
        url: url,
        data: data,
        success: function(data) {
          var entries, html, results, urls;
          results = data['results'];
          entries = [];
          urls = [];
          _(results).each(function(entry) {
            var _ref;
            if (entries.length >= 5) {
              return;
            }
            if (_ref = entry['origin_url'], __indexOf.call(urls, _ref) < 0) {
              urls.push(entry['origin_url']);
              return entries.push(entry);
            }
          });
          entries = cw.highlightEntries(entries, term);
          html = "";
          _(entries).each(function(entry, idx) {
            var cycle;
            cycle = idx % 2 ? 'odd' : 'even';
            return html += "<tr class=\"" + cycle + "\"><td colspan=\"2\">\n    <table>\n        <tbody>\n            <tr>\n                <td class=\"entTitle\"><a href=\"" + entry.capitolwords_url + "\">" + (cw.titleCase(entry.title)) + "</a></td>\n                <td class=\"entDate\">" + entry.date + "</td>\n            </tr>\n            <tr colspan=\"2\">\n                <td colspan=\"2\" class=\"legislators\">\n                <a href=\"/legislator/" + entry.bioguide_id + "\">" + entry.speaker_first + " " + entry.speaker_last + ", " + entry.speaker_party + "-" + entry.speaker_state + "</a>\n                </td>\n            </tr>\n            <tr colspan=\"2\">\n                <td colspan=\"2\" class=\"abstract\">\n                    " + entry.match + "\n                </td>\n            </tr>\n        </tbody>\n    </table>\n</td></tr>";
          });
          return $('#crEntries').html(html);
        }
      });
    };
    CapitolWords.prototype.getDataUrlsForImage = function(el) {
      var i, requestedUrls, url;
      requestedUrls = [];
      if ((url = $(el).attr('data-dataurl'))) {
        requestedUrls.push(url);
      } else {
        i = 0;
        while ((url = $(el).attr("data-dataurl" + i))) {
          requestedUrls.push(url);
          i++;
        }
      }
      return requestedUrls;
    };
    CapitolWords.prototype.getEmbedCode = function(container) {
      var fields, key, _i, _len, _ref;
      fields = {
        url: window.location.href,
        chart_color: $('#embedDark:checked').length ? 2 : 1,
        title: window.document.title.split(' | ')[0],
        img_src: '',
        by_party_img_src: '',
        overall_img_src: '',
        start_date: $.deparam(location.href.split('?')[1])['start'] || cw.minMonth || cw.homepageDefaults['start'],
        end_date: $.deparam(location.href.split('?')[1])['end'] || cw.maxMonth || cw.homepageDefaults['end'],
        apikey: window.cwod_apikey
      };
      $('#partyTimeline img').each(function() {
        fields['by_party_img_src'] = $('#partyTimeline img').attr('src');
        fields['overall_img_src'] = $('#overallTimeline img').attr('src');
        fields['chart_type'] = $('#partyTimeline img').is(':visible') ? 2 : 1;
        window.termDetailTerm && (fields['extra'] = {
          'term': termDetailTerm
        });
        return fields['extra'] = {
          by_party_dataurls: cw.getDataUrlsForImage($('#partyTimeline img').eq(0)),
          overall_dataurls: cw.getDataUrlsForImage($('#overallTimeline img').eq(0))
        };
      });
      $('#compareGraphic img#compareTimeline').each(function() {
        var terma, termb, _ref;
        fields['img_src'] = $(this).attr('src');
        fields['chart_type'] = 3;
        _ref = cw.phrases(), terma = _ref[0], termb = _ref[1];
        return fields['extra'] = {
          terma: terma,
          termb: termb,
          statea: $('#stateA').val(),
          stateb: $('#stateB').val(),
          partya: $('input[name=partya]').val(),
          partyb: $('input[name=partyb]').val(),
          dataurls: cw.getDataUrlsForImage($(this))
        };
      });
      _ref = ['img_src', 'by_party_img_src', 'overall_img_src'];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        key = _ref[_i];
        fields[key] = fields[key].replace(/chs=[\dx]+/, 'chs=570x200');
      }
      $.ajax({
        type: 'POST',
        url: '/embed/',
        data: fields,
        enctype: 'miltipart/form-data',
        success: function(url) {
          var full_url, script;
          full_url = "http://capitolwords.org" + url;
          script = "<script type=\"text/javascript\" src=\"" + full_url + "\"></script>";
          return container.find('textarea').val(script);
        }
      });
      return container.slideDown();
    };
    CapitolWords.prototype.getGraphData = function(term) {
      var cw, data, requestedUrl, url;
      data = {
        'phrase': term,
        'granularity': 'month',
        'percentages': 'true',
        'mincount': 0,
        'apikey': window.cwod_apikey
      };
      url = 'http://capitolwords.org/api/dates.json';
      cw = this;
      requestedUrl = "" + url + "?" + ($.param(data));
      return $.ajax({
        dataType: 'jsonp',
        url: url,
        data: data,
        success: function(data) {
          var counts, imgUrl, labelPositions, overallImgTag, percentages, results;
          results = data['results'];
          cw.results = results;
          counts = _(results).pluck('count');
          percentages = _(results).pluck('percentage');
          labelPositions = cw.buildXLabels(results);
          imgUrl = cw.showChart([percentages], {
            x_labels: labelPositions[0],
            x_label_positions: labelPositions[1],
            width: 565,
            height: 300,
            colors: ['E0B300']
          });
          overallImgTag = "<img id=\"termChart\"\nsrc=\"" + imgUrl + "\"\nalt=\"Timeline of occurrences of " + term + "\"\ndata-dataurl=\"" + requestedUrl + "\" />";
          $('#overallTimeline').html(overallImgTag);
          if (cw.minMonth && cw.maxMonth) {
            cw.limit(cw.minMonth, cw.maxMonth);
          }
          return $('#termChart, #partyTermChart').trigger('load.capitolwords');
        }
      });
    };
    CapitolWords.prototype.getLegislatorPopularity = function(term, div) {
      var cw, url;
      url = 'http://capitolwords.org/api/phrases/legislator.json';
      cw = this;
      return $.ajax({
        dataType: 'jsonp',
        url: url,
        data: {
          'phrase': term,
          'sort': 'count',
          'per_page': 10,
          'start_date': cw.start_date,
          'end_date': cw.end_date,
          'apikey': window.cwod_apikey
        },
        success: function(data) {
          var listItems, maxcount, render, renderWhenDone, result, results, _i, _len, _results;
          results = data['results'];
          maxcount = results[0]['count'];
          listItems = [];
          cw.legislatorData = [];
          render = function() {
            var done;
            listItems = [];
            cw.legislatorData.sort(function(a, b) {
              return b['pct'] - a['pct'];
            });
            done = [];
            _(cw.legislatorData).each(function(legislator) {
              var html, _ref;
              if (_ref = legislator.data.bioguide_id, __indexOf.call(done, _ref) >= 0) {
                return;
              }
              done.push(legislator.data.bioguide_id);
              html = "<li>\n    <span class=\"tagValue\" style=\"width:" + legislator['pct'] + "%\">\n        <span class=\"tagPercent\">" + legislator['pct'] + "%</span>\n        <span class=\"tagNumber\"></span>\n    </span>\n    <span class=\"barChartTitle\"><a href=\"" + legislator['url'] + "\">\n        " + legislator['data']['honorific'] + " " + legislator['data']['full_name'] + ", " + legislator['data']['party'] + "-" + legislator['data']['state'] + "\n    </a>\n    </span>\n    </li>";
              return listItems.push(html);
            });
            return div.html(listItems.join(''));
          };
          renderWhenDone = _(results.length).after(render);
          _results = [];
          for (_i = 0, _len = results.length; _i < _len; _i++) {
            result = results[_i];
            _results.push(cw.addLegislatorToChart(result, maxcount, div, renderWhenDone));
          }
          return _results;
        }
      });
    };
    CapitolWords.prototype.getPartyGraphData = function(term) {
      var cw, data, parties, partyData, render, renderWhenDone, requestedUrls, url;
      data = {
        'phrase': term,
        'granularity': 'month',
        'percentages': true,
        'mincount': 0
      };
      url = 'http://capitolwords.org/api/dates.json';
      cw = this;
      partyData = [];
      requestedUrls = [];
      render = function() {
        var chartData, legendItems;
        chartData = [];
        legendItems = [];
        cw.partyResults = [];
        _(partyData).each(function(partyResult) {
          return cw.partyResults.push(partyResult);
        });
        return cw.buildPartyGraph(cw.minMonth, cw.maxMonth, requestedUrls);
      };
      parties = ['D', 'R'];
      renderWhenDone = _(parties.length).after(render);
      return _(parties).each(function(party) {
        data = {
          'party': party,
          'phrase': term,
          'granularity': 'month',
          'percentages': true,
          'mincount': 0,
          'apikey': window.cwod_apikey
        };
        requestedUrls.push("" + url + "?" + ($.param(data)));
        return jQuery.ajax({
          dataType: 'jsonp',
          url: url,
          data: data,
          success: function(data) {
            var results;
            results = data['results'];
            partyData.push([party, results]);
            return renderWhenDone();
          }
        });
      });
    };
    CapitolWords.prototype.getPartyPieChart = function(term, div, width, height, callback) {
      var cw, url;
      if (_(width).isUndefined()) {
        width = '';
      }
      if (_(width).isUndefined()) {
        height = '';
      }
      url = 'http://capitolwords.org/api/chart/pie.json';
      cw = this;
      return $.ajax({
        dataType: 'jsonp',
        url: url,
        data: {
          'phrase': term,
          'entity_type': 'party',
          'width': width,
          'height': height,
          'start_date': cw.start_date,
          'end_date': cw.end_date,
          'apikey': window.cwod_apikey
        },
        success: function(data) {
          var imgUrl, results;
          results = data['results'];
          imgUrl = results['url'];
          return div.find('.default').fadeOut('slow', function() {
            return div.find('.realChart').attr('src', imgUrl).attr('alt', "Pie chart of occurrences of " + term + " by party").fadeIn('slow', function() {
              if (!_(callback).isUndefined()) {
                return callback(term, div);
              }
            });
          });
        }
      });
    };
    CapitolWords.prototype.getStatePopularity = function(term, div) {
      var cw, url;
      url = 'http://capitolwords.org/api/phrases/state.json';
      cw = this;
      return $.ajax({
        dataType: 'jsonp',
        url: url,
        data: {
          'phrase': term,
          'sort': 'count',
          'per_page': 10,
          'start_date': cw.start_date,
          'end_date': cw.end_date,
          'apikey': window.cwod_apikey
        },
        success: function(data) {
          var maxcount, results;
          div.html('');
          results = data['results'];
          maxcount = results[0]['count'];
          return _(results).each(function(result) {
            var abbrev, html, pct, state;
            abbrev = result['state'];
            state = abbrev;
            if (cw.states.hasOwnProperty(state)) {
              state = cw.states[state];
            }
            url = "/state/" + abbrev;
            pct = (result['count'] / maxcount) * 100;
            html = "<li>\n    <span class=\"tagValue\" style=\"width: " + pct + "%;\">\n        <span class=\"tagPercent\">" + pct + "%</span>\n        <span class=\"tagNumber\"></span>\n    </span>\n    <span class=\"barChartTitle\"><a href=\"" + url + "\">" + state + "</a></span>\n</li>";
            return div.append(html);
          });
        }
      });
    };
    CapitolWords.prototype.highlightEntries = function(entries, term) {
      var delim, entry_matches, regexp, term_parts;
      entry_matches = [];
      term_parts = term.split(/[\s\-]/);
      delim = '[\\s?!.,();:\'"\\-]+?';
      regexp = new RegExp(term_parts.join(delim), "ig");
      _(entries).each(function(entry) {
        var match;
        match = null;
        _(entry['speaking']).each(function(graf) {
          var matcher, versions_of_term;
          graf = graf.replace(/\n/, ' ');
          versions_of_term = _(graf.match(regexp)).uniq();
          if (!_(versions_of_term).isEmpty()) {
            matcher = new RegExp('(' + versions_of_term.join('|') + ')');
            match = graf.replace(matcher, function(a, b) {
              return "<em>" + b + "</em>";
            });
          }
        });
        entry['match'] = match;
        return entry_matches.push(entry);
      });
      return entry_matches;
    };
    CapitolWords.prototype.legislatorSearch = function(data) {
      var cw;
      cw = this;
      data = {
        chamber: data['chamber'] || $('#chamber').val(),
        party: data['party'] || $('#party').val(),
        congress: data['congress'] || $('#congress').val(),
        state: data['state'] || $('#state').val(),
        apikey: window.cwod_apikey
      };
      return $.ajax({
        dataType: 'jsonp',
        url: 'http://capitolwords.org/api/legislators.json',
        data: data,
        success: function(data) {
          return cw.populateLegislatorList(data['results']);
        }
      });
    };
    CapitolWords.prototype.limit = function(minMonth, maxMonth) {
      var aVals, bVals, func, imgUrl, labelPositions, labels, percentages, positions, vals;
      if (minMonth && maxMonth) {
        func = function(v) {
          return v['month'] >= minMonth && v['month'] <= maxMonth;
        };
      } else {
        func = function() {
          return true;
        };
      }
      if (typeof termDetailTerm !== 'undefined') {
        vals = _(this.results).select(func);
        percentages = _(vals).pluck('percentage');
        labelPositions = this.buildXLabels(vals);
        imgUrl = this.showChart([percentages], {
          x_labels: labelPositions[0],
          x_label_positions: labelPositions[1],
          width: 565,
          height: 300,
          colors: ['E0B300']
        });
        return $('#termChart').attr('src', imgUrl);
      } else {
        aVals = _(this.a['all']).select(func);
        bVals = _(this.b['all']).select(func);
        labelPositions = this.buildXLabels(aVals);
        labels = labelPositions[0];
        positions = labelPositions[1];
        return this.showChart([_(aVals).pluck('percentage'), _(bVals).pluck('percentage')], {
          x_labels: labels,
          x_label_positions: positions
        });
      }
    };
    CapitolWords.prototype.makeHomepageHistoryState = function(slid) {
      var cw, hash, hashParams, params, partyA, partyB, phraseA, phraseB, stateA, stateB, _ref;
      cw = this;
      stateA = $('#stateA').val() || cw.homepageDefaults['statea'];
      stateB = $('#stateB').val() || cw.homepageDefaults['stateb'];
      partyA = $('.partyA input:checked').eq(0).val() || cw.homepageDefaults['partya'];
      partyB = $('.partyB input:checked').eq(0).val() || cw.homepageDefaults['partyb'];
      _ref = this.phrases(), phraseA = _ref[0], phraseB = _ref[1];
      params = {
        "terma": phraseA,
        "termb": phraseB,
        "statea": stateA,
        "stateb": stateB,
        "partya": partyA,
        "partyb": partyB,
        "start": this.minMonth || cw.homepageDefaults['start'],
        "end": this.maxMonth || cw.homepageDefaults['end']
      };
      hashParams = {};
      _.each(params, function(v, k) {
        if (v !== cw.homepageDefaults[k] && v !== void 0) {
          return hashParams[k] = v;
        }
      });
      hash = $.param(hashParams);
      History.pushState({
        'slid': slid
      }, '', "?" + hash);
      return window._gaq && _gaq.push(["_trackPageView", "/?" + hash]);
    };
    CapitolWords.prototype.phrases = function() {
      var SAMPLE_PHRASES, params, phraseA, phraseB;
      params = $('#termSelect').serialize();
      phraseA = $('#terma').val();
      if (phraseA === 'Word or phrase') {
        phraseA = '';
      }
      phraseB = $('#termb').val();
      if (phraseB === 'Word or phrase') {
        phraseB = '';
      }
      if ((cw.random_phrase_i !== void 0) || (phraseA === '') && (phraseB === '') && (window.location.pathname.match(/(^\/?$|homepage\.html)/)) && (!(window.location.href.match(/[\?#]/)))) {
        SAMPLE_PHRASES = [['global warming', 'climate change'], ['iraq', 'afghanistan'], ['war', 'peace'], ['ozone', 'carbon dioxide'], ['bailout', 'big banks']];
        if (cw.random_phrase_i === void 0) {
          cw.random_phrase_i = Math.floor(Math.random() * SAMPLE_PHRASES.length);
        }
        return SAMPLE_PHRASES[cw.random_phrase_i];
      }
      return [phraseA, phraseB];
    };
    CapitolWords.prototype.populateLegislatorList = function(legislators) {
      var buildTable;
      buildTable = function() {
        var bioguides, n;
        $('table#legislatorList tbody').empty();
        bioguides = [];
        n = 0;
        _(legislators).each(function(legislator) {
          var klass, tr;
          if (!_(bioguides).include(legislator['bioguide_id'])) {
            bioguides.push(legislator['bioguide_id']);
            klass = n % 2 === 0 ? 'even' : 'odd';
            n++;
            tr = "<tr class=\"" + klass + "\">\n    <td>\n        <a href=\"/legislator/" + legislator['bioguide_id'] + "-" + legislator['slug'] + "\">\n        <img class=\"legislatorImage\" alt=\"legislator photo\" src=\"http://assets.sunlightfoundation.com/moc/40x50/" + legislator['bioguide_id'] + ".jpg\"/>\n        </a>\n    </td>\n    <td><a href=\"/legislator/" + legislator['bioguide_id'] + "-" + legislator['slug'] + "\">" + legislator['name'] + "</a></td>\n    <td>" + legislator['state'] + "</td>\n    <td>" + legislator['party'] + "</td>\n    <td>" + legislator['chamber'] + "</td>\n</tr>";
            return $('table#legislatorList tbody').append(tr);
          }
        });
        return $('table#legislatorList tbody').find('img').error(function() {
          return $(this).attr('src', 'http://assets.sunlightfoundation.com/capitol-words/media/img/cwod_default.png');
        }).end().imagesLoaded(function() {}).fadeIn('fast');
      };
      return $('table#legislatorList tbody').fadeOut('fast', buildTable);
    };
    CapitolWords.prototype.populateTermDetailPage = function(term) {
      term = unescape(term);
      this.getGraphData(term);
      this.getStatePopularity(term, jQuery('#stateBarChart'));
      this.getPartyPieChart(term, jQuery('#partyPieChart'));
      this.getLegislatorPopularity(term, jQuery('#legislatorBarChart'));
      if (_(this.partyResults).isUndefined()) {
        this.getPartyGraphData(term);
      }
      if (this.start_date && this.end_date) {
        return this.getCREntries(term);
      }
    };
    CapitolWords.prototype.readHomepageHistory = function(nosubmit) {
      var endYear, hash, param_id_map, params, startYear, state;
      cw.minMonth = cw.maxMonth = false;
      param_id_map = {
        'terma': '#terma',
        'termb': '#termb',
        'statea': '#stateA',
        'stateb': '#stateB'
      };
      state = History.getState();
      hash = state.hash.split('?')[1];
      params = $.deparam(hash);
      if (hash) {
        _(_.defaults(params, cw.homepageDefaults)).each(function(v, k) {
          var id;
          id = param_id_map[k];
          $("" + id).val($.cleanedValue(v));
          if (k === 'partya' && v) {
            return $("#partyA" + v).attr('checked', true);
          } else if (k === 'partyb' && v) {
            return $("#partyB" + v).attr('checked', true);
          } else if (k === 'start' && v !== cw.homepageDefaults[k]) {
            return cw.minMonth = v;
          } else if (k === 'end' && v !== cw.homepageDefaults[k]) {
            return cw.maxMonth = v;
          }
        });
        cw.minMonth = cw.minMonth || cw.homepageDefaults['start'];
        cw.maxMonth = cw.maxMonth || cw.homepageDefaults['end'];
        startYear = cw.minMonth.slice(0, 4);
        endYear = cw.maxMonth.slice(0, 4);
        $("#slider-range").slider("option", "values", [startYear, endYear]);
        cw.limit(cw.minMonth, cw.maxMonth);
        if (!nosubmit) {
          return cw.submitHomepageCompareForm(true);
        }
      }
    };
    CapitolWords.prototype.readLegislatorHistory = function() {
      var chamber, congress, data, hash, party, pieces, state;
      hash = History.getState().hash.split('?')[1];
      data = {
        congress: 112
      };
      $("#congress").val(112);
      if (hash) {
        pieces = hash.split('&');
        chamber = party = congress = state = void 0;
        _(pieces).each(function(piece) {
          var k, v, _ref;
          _ref = piece.split('='), k = _ref[0], v = _ref[1];
          $("#" + k).val(v);
          return data[k] = v;
        });
      }
      return this.legislatorSearch(data);
    };
    CapitolWords.prototype.readTermDetailPageHistory = function() {
      var endYear, hash, k, max, month, piece, pieces, startYear, v, x, _i, _len;
      this.minMonth = "199601";
      max = new Date();
      this.maxMonth = "" + (max.getFullYear());
      month = "" + (max.getMonth() + 1);
      this.maxMonth += month.length === 1 ? "0" + month : "" + month;
      if (typeof History.getState().hash === 'undefined') {
        return;
      }
      hash = History.getState().hash.split('?')[1];
      if (hash) {
        pieces = [
          (function() {
            var _i, _len, _ref, _results;
            _ref = hash.split('&');
            _results = [];
            for (_i = 0, _len = _ref.length; _i < _len; _i++) {
              x = _ref[_i];
              _results.push(x.split('='));
            }
            return _results;
          })()
        ][0];
        for (_i = 0, _len = pieces.length; _i < _len; _i++) {
          piece = pieces[_i];
          k = piece[0], v = piece[1];
          if (k === 'start') {
            this.minMonth = v;
            this.start_date = this.dateFromMonth(this.minMonth);
          } else if (k === 'end') {
            this.maxMonth = v;
            this.end_date = this.dateFromMonth(this.maxMonth);
          }
        }
      }
      if (this.minMonth || this.maxMonth) {
        startYear = this.minMonth.slice(0, 4);
        endYear = this.maxMonth.slice(0, 4);
        $("#slider-range").slider("values", [startYear, endYear]);
        return this.limit(this.minMonth, this.maxMonth);
      }
    };
    CapitolWords.prototype.sameOrigin = function(url) {
      var host, origin, protocol, sr_origin;
      host = document.location.host;
      protocol = document.location.protocol;
      sr_origin = "//" + host;
      origin = protocol + sr_origin;
      return (url === origin || url.slice(0, origin.length + 1) === origin + '/') || (url === sr_origin || url.slice(0, sr_origin.length + 1) === sr_origin + '/') || !(/^(\/\/|http:|https:).*/.test(url));
    };
    CapitolWords.prototype.showChart = function(data, params) {
      var chart, colors, cw, height, i, img, legend, max, maxValue, requestedUrls, url, values, width, x_label_positions, x_labels;
      x_labels = params.x_labels, x_label_positions = params.x_label_positions, width = params.width, height = params.height, colors = params.colors, legend = params.legend, requestedUrls = params.requestedUrls;
      width = width || 880;
      height = height || 340;
      chart = new GoogleChart(width, height);
      values = [];
      maxValue = 0;
      max = 0;
      cw = this;
      _(data).each(function(item) {
        values = item;
        maxValue = Math.round(_(values).max() * 10000) / 10000;
        if (maxValue > max) {
          max = Math.round(maxValue * 10000) / 10000;
        }
        return chart.add_data(values);
      });
      chart.set_grid(0, 50, 2, 5);
      chart.set_fill('bg', 's', '00000000');
      if (!colors) {
        colors = ['8E2844', 'A85B08', 'AF9703'];
      }
      if (!legend) {
        legend = this.build_legend();
      }
      if (!_(legend).isEmpty() && !location.pathname.match(/^\/?$/)) {
        chart.set_legend(legend);
      }
      chart.set_colors(colors.slice(0, legend.length));
      chart.set_axis_labels('y', ['', "" + max + "%"]);
      if (x_labels) {
        chart.set_axis_labels('x', x_labels);
      }
      if (x_label_positions) {
        chart.set_axis_positions('x', x_label_positions);
      }
      img = $('#chart img.realChart, #compareGraphic img#compareTimeline').attr('src', chart.url());
      if (typeof requestedUrls === 'object' && requestedUrls.length) {
        if (requestedUrls.length > 1) {
          for (i in requestedUrls) {
            url = requestedUrls[i];
            img.attr("data-dataurl" + i, url);
          }
        } else {
          img.attr('data-dataurl', requestedUrls[0]);
        }
      }
      img.fadeIn(500);
      img.trigger('load.capitolwords');
      if (cw.spinner) {
        cw.spinner.stop();
      }
      return chart.url();
    };
    CapitolWords.prototype.smooth = function(list, degree) {
      var frac, func, gauss, i, smoothed, weight, weightGauss, win, _i, _len, _ref;
      win = degree * 2 - 1;
      weight = _.range(0, win).map(function(x) {
        return 1.0;
      });
      weightGauss = [];
      _ref = _.range(0, win);
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        i = _ref[_i];
        i = i - degree + 1;
        frac = i / win;
        gauss = 1 / Math.exp((4 * frac) * (4 * frac));
        weightGauss.push(gauss);
      }
      weight = _(weightGauss).zip(weight).map(function(x) {
        return x[0] * x[1];
      });
      smoothed = _.range(0, (list.length + 1) - win).map(function(x) {
        return 0.0;
      });
      func = function(memo, num) {
        return memo + num;
      };
      return _(_.range(smoothed.length)).each(function(i) {
        return smoothed[i] = _(list.slice(i, i + win)).zip(weight).map(function(x) {
          return x[0] * x[1];
        }).reduce(func, 0) / _(weight).reduce(func, 0);
      });
    };
    CapitolWords.prototype.startDate = function() {
      if (this.year_values[0]) {
        return "" + this.year_values[0] + "-01-01";
      } else {
        return '1996-01-01';
      }
    };
    CapitolWords.prototype.submitHomepageCompareForm = function(skipState) {
      var breakdownUrl, breakdowna, breakdownaData, breakdownb, breakdownbData, cw, d, endDate, opts, phraseA, phraseB, querya, queryaData, queryb, querybData, requestedUrls, startDate, target, url, _ref;
      cw = this;
      opts = {
        lines: 12,
        length: 7,
        width: 4,
        radius: 10,
        color: '#000',
        speed: 1,
        trail: 100,
        shadow: true
      };
      target = document.getElementById('compareGraphic');
      cw.spinner && cw.spinner.stop && cw.spinner.stop();
      cw.spinner = new Spinner(opts).spin(target);
      url = 'http://capitolwords.org/api/dates.json';
      breakdownUrl = 'http://capitolwords.org/api/chart/pie.json';
      requestedUrls = [];
      _ref = cw.phrases(), phraseA = _ref[0], phraseB = _ref[1];
      d = new Date;
      startDate = cw.minMonth ? "" + (cw.minMonth.slice(0, 4)) + "-" + (cw.minMonth.slice(4, 6)) + "-01" : "1996-01-01";
      endDate = cw.maxMonth ? "" + (cw.maxMonth.slice(0, 4)) + "-12-31" : "" + (d.getFullYear()) + "-12-31";
      queryaData = {
        phrase: phraseA,
        state: $('#stateA').val() || '',
        party: $('.partyA input:checked').eq(0).val(),
        granularity: 'month',
        percentages: true,
        mincount: 0,
        apikey: window.cwod_apikey
      };
      requestedUrls.push("" + url + "?" + ($.param(queryaData)));
      querya = $.ajax({
        dataType: 'jsonp',
        url: url,
        data: queryaData,
        success: function(data) {
          var aResults;
          aResults = data['results'];
          cw.a['all'] = aResults;
          cw.a['counts'] = _(aResults).pluck('count');
          return cw.a['percentages'] = _(aResults).pluck('percentage');
        }
      });
      querybData = {
        phrase: phraseB,
        state: $('#stateB').val() || '',
        party: $('.partyB input:checked').eq(0).val(),
        granularity: 'month',
        percentages: true,
        mincount: 0,
        apikey: window.cwod_apikey
      };
      requestedUrls.push("" + url + "?" + ($.param(querybData)));
      queryb = $.ajax({
        dataType: 'jsonp',
        url: url,
        data: querybData,
        success: function(data) {
          var bResults;
          bResults = data['results'];
          cw.b['all'] = bResults;
          cw.b['counts'] = _(bResults).pluck('count');
          return cw.b['percentages'] = _(bResults).pluck('percentage');
        }
      });
      breakdownaData = {
        phrase: phraseA,
        output: 'data',
        entity_type: 'party',
        start_date: startDate,
        end_date: endDate,
        apikey: window.cwod_apikey
      };
      breakdowna = $.ajax({
        dataType: 'jsonp',
        url: breakdownUrl,
        data: breakdownaData,
        success: function(data) {
          return cw.a['breakdown'] = data.data;
        }
      });
      breakdownbData = {
        phrase: phraseB,
        output: 'data',
        entity_type: 'party',
        start_date: startDate,
        end_date: endDate,
        apikey: window.cwod_apikey
      };
      breakdownb = $.ajax({
        dataType: 'jsonp',
        url: breakdownUrl,
        data: breakdownbData,
        success: function(data) {
          return cw.b['breakdown'] = data.data;
        }
      });
      $.when(querya, queryb, breakdowna, breakdownb).done(function() {
        var labelPositions, labels, positions;
        labelPositions = cw.buildXLabels(cw.a['all']);
        labels = labelPositions[0];
        positions = labelPositions[1];
        cw.showChart([cw.a['percentages'], cw.b['percentages']], {
          x_labels: labels,
          x_label_positions: positions,
          requestedUrls: requestedUrls
        });
        if (cw.minMonth || cw.maxMonth) {
          return cw.limit(cw.minMonth, cw.maxMonth);
        }
      }).then(function() {
        var aTotal, bTotal, i, legend_html, party, _ref2, _ref3;
        if (cw.spinner) {
          cw.spinner.stop();
        }
        legend_html = cw.build_legend_html();
        $('#compareGraphic div.key span.wordOne span.legend-text').eq(0).html($(legend_html).find('span.wordOne').html());
        $('#compareGraphic div.key span.wordTwo span.legend-text').eq(0).html($(legend_html).find('span.wordTwo').html());
        aTotal = $.sum(cw.a.breakdown[1]);
        if (__indexOf.call(cw.a.breakdown[0], 'D') < 0) {
          $("#compareGraphic .key .wordOne .party-breakdown .D").animate({
            'width': 0
          });
          $("#compareGraphic .key .wordOne .party-breakdown-labels .D .percentage").html("0%");
        }
        if (__indexOf.call(cw.a.breakdown[0], 'R') < 0) {
          $("#compareGraphic .key .wordOne .party-breakdown .R").animate({
            'width': 0
          });
          $("#compareGraphic .key .wordOne .party-breakdown-labels .R .percentage").html("0%");
        }
        _ref2 = cw.a.breakdown[0];
        for (i in _ref2) {
          party = _ref2[i];
          $("#compareGraphic .key .wordOne .party-breakdown ." + party).animate({
            'width': "" + (((cw.a.breakdown[1][i] / aTotal) * 100).toFixed(0)) + "%"
          });
          $("#compareGraphic .key .wordOne .party-breakdown-labels ." + party + " .percentage").html("" + (((cw.a.breakdown[1][i] / aTotal) * 100).toFixed(0)) + "%");
        }
        bTotal = $.sum(cw.b.breakdown[1]);
        if (__indexOf.call(cw.b.breakdown[0], 'D') < 0) {
          $("#compareGraphic .key .wordTwo .party-breakdown .D").animate({
            'width': 0
          });
          $("#compareGraphic .key .wordTwo .party-breakdown-labels .D .percentage").html("0%");
        }
        if (__indexOf.call(cw.b.breakdown[0], 'R') < 0) {
          $("#compareGraphic .key .wordTwo .party-breakdown .R").animate({
            'width': 0
          });
          $("#compareGraphic .key .wordTwo .party-breakdown-labels .R .percentage").html("0%");
        }
        _ref3 = cw.b.breakdown[0];
        for (i in _ref3) {
          party = _ref3[i];
          $("#compareGraphic .key .wordTwo .party-breakdown ." + party).animate({
            'width': "" + ((cw.b.breakdown[1][i] / bTotal) * 100) + "%"
          });
          $("#compareGraphic .key .wordTwo .party-breakdown-labels ." + party + " .percentage").html("" + (((cw.b.breakdown[1][i] / bTotal) * 100).toFixed(0)) + "%");
        }
        return cw.random_phrase_i = void 0;
      });
      if (!skipState) {
        return this.makeHomepageHistoryState(true);
      }
    };
    CapitolWords.prototype.titleCase = function(s) {
      return s.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
      });
    };
    CapitolWords.prototype.trimGraph = function() {
      if (this.year_values.length === 2) {
        return true;
      } else {
        return false;
      }
    };
    return CapitolWords;
  })();
}).call(this);
;
(function() {
  /*
  Annotation class for Capitol Words sparklines
  
  Requires:
  - jQuery
  - underscore.js
  
  Usage: new Annotation($('img#myChart'), params)
  - el, {params}
  - el: a target image node, including a set of
       attrs data-datasrc(n) containing the data urls to be
       fetched for numbers of mentions, etc,
  - {params}: A JSON structure including:
      - template (required):
          A string of data to be interpolated with each sparkline's dataset
          and appended into the annotation box, 1 per dataset
      - heading (optional):
          A template-like string to optionally be applied before the first
          dataset's template is rendered; for example to create a date heading.
          will only have access to the first dataset when rendering
      - iterable (optional):
          A function to pre-process the ajax response for each incoming dataset.
          The default is to pass the data straight through
      - startDate (optional):
          A YYYYMM string representing the first month to display annotations for.
          The default is '199601'
      - endDate (optional):
          A YYYYMM string representing the last month to display annotations for.
          The default is the current month.
      - linkTo (optional):
          Bypasses the normal date-linking behavior, for embeds.
  
  Data-params:
  It is expected that `el` will include a Google Charts src attribute, as well as a
  data-dataurl attribute for each dataset to be displayed. The `src` attr is used to fetch
  a json representation of the chart, and `data-dataurl`s point to the Capitol Words API query
  the chart was built from. If more than one dataurl is present (i.e., 2 lines in a chart), they
  should be serialized as `data-dataurl0`, `data-dataurl1`, etc.
  
  A Note on templates:
  While the goal was to provide a syntax that would allow reuse of possibly pre-existing
  jQuery templates, only ${} is supported. Other $.template syntax features will NOT be interpolated.
  
  */
  var $;
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  $ = jQuery;
  $.deparam || ($.deparam = function(qs) {
    var params, pieces;
    params = {};
    if (!qs) {
      return params;
    }
    pieces = qs.split(/[&=]/);
    $.each(pieces, function(idx, val) {
      if (idx % 2) {
        return params[pieces[idx - 1]] = val;
      }
    });
    return params;
  });
  window.Annotation = (function() {
    var annotationEl, callstack, coords, coordsurl, datasets, dataurls, el, endDate, heading, iterable, lines, slices, startDate, template;
    el = null;
    annotationEl = null;
    callstack = [];
    coordsurl = null;
    coords = [];
    dataurls = [];
    datasets = [];
    endDate = null;
    heading = 'Annotations.js';
    iterable = function(data) {
      return data;
    };
    lines = [];
    slices = [];
    startDate = null;
    template = 'instantiate with new Annotation(el, {iterable, template, heading, startDate, endDate})';
    function Annotation(el, params) {
      var _ref;
      this.el = el;
      this.params = params;
      _ref = this.params, this.iterable = _ref.iterable, this.template = _ref.template, this.heading = _ref.heading, this.startDate = _ref.startDate, this.endDate = _ref.endDate, this.linkTo = _ref.linkTo;
      this.el = $(this.el);
      this.el.data('annotation', this);
      this.el.wrap('<a class="annotation-wrap" target="_top" href="#"></a>');
      if (this.linkTo) {
        this.el.parent().attr('href', this.linkTo);
      }
      this.el.parent().css('position', 'relative');
      this.annotationEl = $('<div class="annotation"><div class="inner-annotation"></div></div>').css('position', 'absolute').css('top', '50%').hide();
      this.el.after(this.annotationEl);
      this.refresh();
    }
    Annotation.prototype.applyTemplate = function(idx) {
      var dataset, html, i, varP, _ref;
      varP = /\$\{([^\}]+?)\}/gi;
      html = '';
      if (this.heading) {
        html += this.heading.replace(varP, __bind(function(match, varName) {
          var part, parts, value, _i, _len;
          try {
            value = this.datasets[0][idx];
          } catch (e) {
            return this.refresh();
          }
          parts = varName.split('.');
          for (_i = 0, _len = parts.length; _i < _len; _i++) {
            part = parts[_i];
            value = value[part];
          }
          return value.toString() || '';
        }, this));
      }
      _ref = this.datasets;
      for (i in _ref) {
        dataset = _ref[i];
        html += this.template.replace(varP, function(match, varName) {
          var part, parts, value, _i, _len;
          try {
            value = dataset[idx];
          } catch (e) {
            this.refresh();
          }
          parts = varName.split('.');
          for (_i = 0, _len = parts.length; _i < _len; _i++) {
            part = parts[_i];
            value = value[part];
          }
          if (varName === 'i') {
            return i;
          }
          if (typeof value === 'number' && (parseInt(value) !== value)) {
            value = value.toFixed(4);
          }
          return value.toString() || '';
        });
      }
      return html;
    };
    Annotation.prototype.bindMouse = function() {
      this.el.parent().bind('mouseenter.annotation', __bind(function(evt) {
        return this.annotationEl.show();
      }, this));
      this.el.parent().bind('mouseleave.annotation', __bind(function(evt) {
        return this.annotationEl.hide();
      }, this));
      return this.el.bind('mousemove.annotation', __bind(function(evt) {
        var date, month, step, x, year;
        x = evt.layerX || evt.offsetX;
        coords = this.point(evt);
        if (isNaN(coords[0])) {
          return this.annotationEl.hide();
        } else {
          step = this.step(x) + this.startOffset();
          this.annotationEl.show().stop().animate({
            'left': coords[0],
            'top': coords[1]
          }, 10).children('.inner-annotation').html(this.applyTemplate(step));
          date = this.datasets[0][step].month;
          year = date.slice(0, 4);
          month = date.slice(4, 6);
          if (!this.linkTo) {
            return this.el.parent().attr('href', "/date/" + year + "/" + month);
          }
        }
      }, this));
    };
    Annotation.prototype.destroy = function() {
      _(this.callstack).each(function(req) {
        return req.abort();
      });
      this.annotationEl.hide();
      this.el.unbind('.annotation');
      this.el.parent().unbind('.annotation');
      this.callstack = [];
      this.coordsurl = null;
      this.coords = [];
      this.dataurls = [];
      this.datasets = [];
      this.lines = [];
      this.slices = [];
      this._months = null;
      this._total = null;
      if (!(this.params['startDate'] || this.params['endDate'])) {
        this.startDate = null;
        return this.endDate = null;
      }
    };
    Annotation.prototype.getDataUrl = function(idx, url) {
      var dfd;
      dfd = $.Deferred();
      $.when(this.getJSONPVar(url)).done(__bind(function(data) {
        this.datasets[idx] = this.iterable(data);
        return dfd.resolve();
      }, this));
      return dfd.promise();
    };
    Annotation.prototype.getJSONPVar = function(url) {
      var req;
      req = $.ajax({
        url: url,
        dataType: 'jsonp',
        data: {
          'apikey': window.cwod_apikey
        }
      });
      this.callstack.push(req);
      return req;
    };
    Annotation.prototype.loadCoords = function() {
      var dfd;
      dfd = $.Deferred();
      $.when(this.getJSONPVar(this.coordsurl)).done(__bind(function(coords) {
        var flat, i, line, matches, obj, val, x, y, _i, _len, _ref;
        _ref = coords.chartshape;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          obj = _ref[_i];
          matches = obj.name.match(/line(\d+?)/);
          if (matches) {
            line = matches[1];
            this.coords[line] = [];
            flat = obj.coords.slice(0, obj.coords.length / 2);
            for (i in flat) {
              val = flat[i];
              if (i % 2) {
                x = flat[i - 1];
                y = flat[i];
                this.coords[line].push([x, y]);
              }
            }
          }
        }
        return dfd.resolve();
      }, this));
      return dfd.promise();
    };
    Annotation.prototype.loadData = function() {
      var dfd, idx, reqs, url;
      dfd = $.Deferred();
      reqs = [
        (function() {
          var _ref, _results;
          _ref = this.dataurls;
          _results = [];
          for (idx in _ref) {
            url = _ref[idx];
            _results.push(this.getDataUrl(idx, url));
          }
          return _results;
        }).call(this)
      ];
      $.when.apply($, reqs).done(function() {
        return dfd.resolve();
      });
      return dfd.promise();
    };
    Annotation.prototype.point = function(evt) {
      var coordset, overlap, pair, step, x, y, ys;
      x = evt.layerX || evt.offsetX;
      step = this.step(x);
      pair = [NaN, NaN];
      if ((0 <= step && step < this.coords[0].length)) {
        ys = [
          (function() {
            var _i, _len, _ref, _results;
            _ref = this.coords;
            _results = [];
            for (_i = 0, _len = _ref.length; _i < _len; _i++) {
              coordset = _ref[_i];
              _results.push(coordset[step].slice()[1]);
            }
            return _results;
          }).call(this)
        ][0];
        y = _.min(ys);
        x = this.coords[0][step][0];
        pair = [x, y];
        if (pair[0] + this.annotationEl.outerWidth() > this.el.width()) {
          pair[0] -= this.annotationEl.outerWidth();
          this.annotationEl.addClass('flipped');
        } else {
          this.annotationEl.removeClass('flipped');
        }
        if ((overlap = pair[1] - this.annotationEl.height() / 2) < 0) {
          pair[1] += overlap * -1;
        } else if ((overlap = pair[1] + this.annotationEl.height() / 2) > this.el.height()) {
          pair[1] -= overlap - this.el.height();
        }
      }
      return pair;
    };
    Annotation.prototype.refresh = function() {
      var d, i, qparams, qs, url;
      this.destroy();
      if (!this.startDate && !this.endDate) {
        qs = window.location.href.split('?')[1];
        qparams = $.deparam(qs);
        try {
          this.startDate = qparams['start'];
        } catch (_e) {}
        try {
          this.endDate = qparams['end'];
        } catch (_e) {}
        if (!this.startDate) {
          this.startDate = '199601';
        }
        if (!this.endDate) {
          d = new Date();
          this.endDate = "" + (d.getFullYear()) + "12";
        }
      }
      if ((url = this.el.attr('data-dataurl'))) {
        this.dataurls.push(url);
      } else {
        i = 0;
        while ((url = this.el.attr("data-dataurl" + i))) {
          this.dataurls.push(url);
          i += 1;
        }
      }
      this.coordsurl = "" + (this.el.attr('src')) + "&chof=json";
      return $.when(this.loadCoords(), this.loadData()).done(__bind(function() {
        return this.bindMouse();
      }, this));
    };
    Annotation.prototype.step = function(x) {
      var max, min, range, stepsize;
      try {
        this._total || (this._total = this.coords[0].length);
        min = this.coords[0][0][0];
        max = this.coords[0][this._total - 1][0];
        range = max - min;
        stepsize = range / this._total;
        return Math.floor((x - min) / stepsize);
      } catch (e) {
        return this.refresh();
      }
    };
    Annotation.prototype.startOffset = function() {
      var offset;
      this._months || (this._months = _.pluck(this.datasets[0], 'month'));
      offset = _.indexOf(this._months, this.startDate, true);
      if (offset === -1) {
        offset = 0;
      }
      return offset;
    };
    return Annotation;
  })();
}).call(this);
;
(function() {
  var $, History, cw;
  $ = jQuery;
  /*
  Create a global CW instance within this closure
  */
  cw = new window.CapitolWords;
  window.cw = cw;
  History = window.History;
  /*
  Add csrf token to ajax POSTs
  */
  $(document).ajaxSend(function(event, xhr, settings) {
    if ((settings.type === 'POST') && cw.sameOrigin(settings.url)) {
      return xhr.setRequestHeader("X-CSRFToken", cw.getCookie('csrftoken'));
    }
  });
  /*
  Handle special routes
  */
  History.Adapter.bind(window, 'statechange', function() {
    if (window.location.pathname.match(/^\/legislator\/?$/)) {
      return cw.readLegislatorHistory();
    } else if (window.location.pathname.match(/^\/term\/.+\/?$/)) {
      cw.readTermDetailPageHistory();
      return cw.populateTermDetailPage(termDetailTerm);
    } else if (window.location.pathname.match(/^\/?$/)) {
      return cw.readHomepageHistory();
    }
  });
  $(window).trigger('statechange');
  /*
  DomReady Handler
  */
  $(document).ready(function() {
    var area, d, endYear, startYear;
    if (typeof termDetailTerm !== 'undefined') {
      cw.readTermDetailPageHistory();
      cw.populateTermDetailPage(termDetailTerm);
    }
    $('img').error(function() {
      return $(this).attr('src', 'http://assets.sunlightfoundation.com/capitol-words/media/img/cwod_default.png');
    });
    $('#toggleSearchCompare').click(function(e) {
      e.preventDefault();
      return $('.toggleSearchCompare').slideToggle('fast', 'swing');
    });
    $('#compareTermBtn').live('click', function(e) {
      var word;
      e.preventDefault();
      word = $(this).find('em').text();
      $('#terma').val(word);
      return $('#toggleSearchCompare').trigger('click');
    });
    $('.ngramMenu span').bind('click', function(x) {
      var classToShow;
      classToShow = $(this).attr('class');
      $('.ngramMenu span').removeAttr('id');
      $(this).attr('id', 'selected');
      return $('.barChart:visible').eq(0).hide(0, function() {
        return $("ol#" + classToShow).show(0);
      });
    });
    $('#timelineToggle input').bind('click', function() {
      var selected, selectedId, timelines;
      selectedId = $('input[name=toggle]:checked', '#timelineToggle').attr('id');
      timelines = [['party', $('#partyTimeline')], ['overall', $('#overallTimeline')]];
      selected = {
        'overallTimelineSelect': 'overall',
        'partyTimelineSelect': 'party'
      }[selectedId];
      return _(timelines).each(function(timeline) {
        var name, obj;
        name = timeline[0];
        obj = timeline[1];
        if (name === selected) {
          return obj.show().imagesLoaded(function() {
            return $(this).find('img').load();
          });
        } else {
          return obj.hide();
        }
      });
    });
    $('#partySelect, #stateSelect').change(function() {
      return cw.customizeChart();
    });
    $('.compareSubmit').bind('click', function(e) {
      if (window.location.pathname.match(/^\/?$/)) {
        e.preventDefault();
        return cw.submitHomepageCompareForm();
      } else {
        return true;
      }
    });
    $('#termSelect input').bind('keyup', function(e) {
      if (e.keyCode === 13) {
        return $('.compareSubmit').trigger('click');
      }
    });
    $('#termSelect input[type=text]').bind('focus', function() {
      if ($(this).val() === 'Word or phrase') {
        return $(this).val('');
      }
    });
    $('#termSelect input[type=text]').bind('blur', function() {
      if ($(this).val() === '') {
        return $(this).val('Word or phrase');
      }
    });
    $('#searchFilterButton').bind('click', function() {
      var hash, pieces;
      pieces = [];
      $('#searchFilter select').each(function(select) {
        var id, val;
        id = $(this).attr('id');
        val = $(this).val();
        return pieces.push("" + id + "=" + val);
      });
      hash = pieces.join('&');
      History.pushState({}, '', "/legislator/?" + hash);
      window._gaq && _gaq.push(["_trackPageView", "/legislator/?" + hash]);
      return cw.legislatorSearch({});
    });
    $('#signUp').find('input[type=text]').bind('focus', function() {
      var el;
      el = $(this);
      try {
        return el.parent().find('label[for=' + el.attr('id') + ']').eq(0).addClass('hidden');
      } catch (_e) {}
    }).bind('blur', function() {
      var el;
      el = $(this);
      if (!el.val()) {
        try {
          return el.parent().find('label[for=' + el.attr('id') + ']').eq(0).removeClass('hidden');
        } catch (_e) {}
      }
    });
    if (!_($('#slider-range')).isEmpty()) {
      d = new Date();
      if (cw.minMonth && cw.maxMonth) {
        startYear = cw.minMonth.slice(0, 4);
        endYear = cw.maxMonth.slice(0, 4);
      } else {
        startYear = 1996;
        endYear = d.getFullYear();
      }
      $('#slider-range').slider({
        range: true,
        min: 1996,
        max: d.getFullYear(),
        values: [startYear, endYear],
        slide: function(event, ui) {
          return $('#years').val("" + ui.values[0] + "-" + ui.values[1]);
        },
        stop: function(event, ui) {
          cw.minMonth = "" + ui.values[0] + "01";
          cw.maxMonth = "" + ui.values[1] + "12";
          if (!_(_(cw.a).keys()).isEmpty() || !_(_(cw.b).keys()).isEmpty()) {
            cw.limit(cw.minMonth, cw.maxMonth);
          } else if (typeof termDetailTerm !== 'undefined') {
            cw.limit(cw.minMonth, cw.maxMonth);
            cw.buildPartyGraph(cw.minMonth, cw.maxMonth);
            cw.start_date = cw.dateFromMonth(cw.minMonth);
            cw.end_date = cw.dateFromMonth(cw.maxMonth);
            cw.populateTermDetailPage(termDetailTerm);
          }
          return cw.makeHomepageHistoryState(true);
        }
      });
    }
    $('.advanced').bind('click', function() {
      var t;
      t = $(this);
      return $('ul.wordFilter').slideToggle('fast', 'swing', function() {
        if ($(this).is(':visible')) {
          return t.addClass('expanded');
        } else {
          return t.removeClass('expanded');
        }
      });
    });
    $('#embed a').bind('click', function(e) {
      var t;
      e.preventDefault();
      t = $('.embedContainer');
      if (t.is(':visible')) {
        return t.slideUp();
      } else {
        return cw.getEmbedCode(t);
      }
    });
    $('#customizeEmbed input').change(function() {
      return cw.getEmbedCode($('.embedContainer'));
    });
    $('#compareGraphic img#compareTimeline, #overallTimeline img, #partyTimeline img').live('load.capitolwords', function() {
      var existingAnnotation, heading, iterable, template;
      existingAnnotation = $(this).data('annotation');
      if (existingAnnotation) {
        return existingAnnotation.refresh();
      } else {
        heading = '<p class="meta">${verboseMonth}</p>';
        template = '<p class="data"><span class="color-${i}"></span> ${count} ${noun} (${percentage}%)</p>';
        iterable = function(data) {
          data = data.results;
          $.each(data, function(i, obj) {
            var m, mos, o, y;
            o = obj.month;
            y = o.substr(0, 4);
            m = parseInt(o.substr(4, 2), 10);
            mos = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
            data[i].verboseMonth = "" + mos[m] + " " + y;
            return obj.noun = obj.count === 1 ? 'mention' : 'mentions';
          });
          return data;
        };
        return new Annotation(this, {
          iterable: iterable,
          heading: heading,
          template: template
        });
      }
    });
    $('#compareGraphic img#compareTimeline, #overallTimeline img, #partyTimeline img').each(function() {
      if (!$(this).parent().hasClass('annotation-wrap')) {
        return $(this).trigger('load.capitolwords');
      }
    });
    (area = $('#rtColumn, .crContent')) && area.length && area.imagesLoaded(function() {
      return $(this).find('img').load();
    });
    if ((window.location.pathname.match(/(^\/?$|homepage\.html)/)) && (!(window.location.href.match(/\?/)))) {
      return cw.submitHomepageCompareForm();
    }
  });
}).call(this);
;

