//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2009 Aaron Newton <http://clientcide.com/>, Valerio Proietti <http://mad4milk.net> & the MooTools team <http://mootools.net/developers>, MIT Style License.
//TwitterGitter - David Walsh http://davidwalsh.name/
//tangerine smash, Andrew Gleave (c) 2009
MooTools.More={version:"1.2.2.2"};var Log=new Class({log:function(){Log.logger.call(this,arguments);}});Log.logged=[];Log.logger=function(){if(window.console&&console.log){console.log.apply(console,arguments);
}else{Log.logged.push(arguments);}};Element.implement({measure:function(e){var g=function(h){return !!(!h||h.offsetHeight||h.offsetWidth);};if(g(this)){return e.apply(this);
}var d=this.getParent(),b=[],f=[];while(!g(d)&&d!=document.body){b.push(d.expose());d=d.getParent();}var c=this.expose();var a=e.apply(this);c();b.each(function(h){h();
});return a;},expose:function(){if(this.getStyle("display")!="none"){return $empty;}var a=this.getStyles("display","position","visibility");return this.setStyles({display:"block",position:"absolute",visibility:"hidden"}).setStyles.pass(a,this);
},getDimensions:function(a){a=$merge({computeSize:false},a);var d={};var c=function(f,e){return(e.computeSize)?f.getComputedSize(e):f.getSize();};if(this.getStyle("display")=="none"){d=this.measure(function(){return c(this,a);
});}else{try{d=c(this,a);}catch(b){}}return $chk(d.x)?$extend(d,{width:d.x,height:d.y}):$extend(d,{x:d.width,y:d.height});},getComputedSize:function(a){a=$merge({styles:["padding","border"],plains:{height:["top","bottom"],width:["left","right"]},mode:"both"},a);
var c={width:0,height:0};switch(a.mode){case"vertical":delete c.width;delete a.plains.width;break;case"horizontal":delete c.height;delete a.plains.height;
break;}var b=[];$each(a.plains,function(g,f){g.each(function(h){a.styles.each(function(i){b.push((i=="border")?i+"-"+h+"-width":i+"-"+h);});});});var e={};
b.each(function(f){e[f]=this.getComputedStyle(f);},this);var d=[];$each(a.plains,function(g,f){var h=f.capitalize();c["total"+h]=0;c["computed"+h]=0;g.each(function(i){c["computed"+i.capitalize()]=0;
b.each(function(k,j){if(k.test(i)){e[k]=e[k].toInt()||0;c["total"+h]=c["total"+h]+e[k];c["computed"+i.capitalize()]=c["computed"+i.capitalize()]+e[k];}if(k.test(i)&&f!=k&&(k.test("border")||k.test("padding"))&&!d.contains(k)){d.push(k);
c["computed"+h]=c["computed"+h]-e[k];}});});});["Width","Height"].each(function(g){var f=g.toLowerCase();if(!$chk(c[f])){return;}c[f]=c[f]+this["offset"+g]+c["computed"+g];
c["total"+g]=c[f]+c["total"+g];delete c["computed"+g];},this);return $extend(e,c);}});Element.implement({isDisplayed:function(){return this.getStyle("display")!="none";
},toggle:function(){return this[this.isDisplayed()?"hide":"show"]();},hide:function(){var b;try{if("none"!=this.getStyle("display")){b=this.getStyle("display");
}}catch(a){}return this.store("originalDisplay",b||"block").setStyle("display","none");},show:function(a){return this.setStyle("display",a||this.retrieve("originalDisplay")||"block");
},swapClass:function(a,b){return this.removeClass(a).addClass(b);}});Fx.Elements=new Class({Extends:Fx.CSS,initialize:function(b,a){this.elements=this.subject=$$(b);
this.parent(a);},compute:function(g,h,j){var c={};for(var d in g){var a=g[d],e=h[d],f=c[d]={};for(var b in a){f[b]=this.parent(a[b],e[b],j);}}return c;
},set:function(b){for(var c in b){var a=b[c];for(var d in a){this.render(this.elements[c],d,a[d],this.options.unit);}}return this;},start:function(c){if(!this.check(c)){return this;
}var h={},j={};for(var d in c){var f=c[d],a=h[d]={},g=j[d]={};for(var b in f){var e=this.prepare(this.elements[d],b,f[b]);a[b]=e.from;g[b]=e.to;}}return this.parent(h,j);
}});Fx.Reveal=new Class({Extends:Fx.Morph,options:{styles:["padding","border","margin"],transitionOpacity:!Browser.Engine.trident4,mode:"vertical",display:"block",hideInputs:Browser.Engine.trident?"select, input, textarea, object, embed":false},dissolve:function(){try{if(!this.hiding&&!this.showing){if(this.element.getStyle("display")!="none"){this.hiding=true;
this.showing=false;this.hidden=true;var d=this.element.getComputedSize({styles:this.options.styles,mode:this.options.mode});var g=(this.element.style.height===""||this.element.style.height=="auto");
this.element.setStyle("display","block");if(this.options.transitionOpacity){d.opacity=1;}var b={};$each(d,function(h,e){b[e]=[h,0];},this);var f=this.element.getStyle("overflow");
this.element.setStyle("overflow","hidden");var a=this.options.hideInputs?this.element.getElements(this.options.hideInputs):null;this.$chain.unshift(function(){if(this.hidden){this.hiding=false;
$each(d,function(h,e){d[e]=h;},this);this.element.setStyles($merge({display:"none",overflow:f},d));if(g){if(["vertical","both"].contains(this.options.mode)){this.element.style.height="";
}if(["width","both"].contains(this.options.mode)){this.element.style.width="";}}if(a){a.setStyle("visibility","visible");}}this.fireEvent("hide",this.element);
this.callChain();}.bind(this));if(a){a.setStyle("visibility","hidden");}this.start(b);}else{this.callChain.delay(10,this);this.fireEvent("complete",this.element);
this.fireEvent("hide",this.element);}}else{if(this.options.link=="chain"){this.chain(this.dissolve.bind(this));}else{if(this.options.link=="cancel"&&!this.hiding){this.cancel();
this.dissolve();}}}}catch(c){this.hiding=false;this.element.setStyle("display","none");this.callChain.delay(10,this);this.fireEvent("complete",this.element);
this.fireEvent("hide",this.element);}return this;},reveal:function(){try{if(!this.showing&&!this.hiding){if(this.element.getStyle("display")=="none"||this.element.getStyle("visiblity")=="hidden"||this.element.getStyle("opacity")==0){this.showing=true;
this.hiding=false;this.hidden=false;var g,d;this.element.measure(function(){g=(this.element.style.height===""||this.element.style.height=="auto");d=this.element.getComputedSize({styles:this.options.styles,mode:this.options.mode});
}.bind(this));$each(d,function(h,e){d[e]=h;});if($chk(this.options.heightOverride)){d.height=this.options.heightOverride.toInt();}if($chk(this.options.widthOverride)){d.width=this.options.widthOverride.toInt();
}if(this.options.transitionOpacity){this.element.setStyle("opacity",0);d.opacity=1;}var b={height:0,display:this.options.display};$each(d,function(h,e){b[e]=0;
});var f=this.element.getStyle("overflow");this.element.setStyles($merge(b,{overflow:"hidden"}));var a=this.options.hideInputs?this.element.getElements(this.options.hideInputs):null;
if(a){a.setStyle("visibility","hidden");}this.start(d);this.$chain.unshift(function(){this.element.setStyle("overflow",f);if(!this.options.heightOverride&&g){if(["vertical","both"].contains(this.options.mode)){this.element.style.height="";
}if(["width","both"].contains(this.options.mode)){this.element.style.width="";}}if(!this.hidden){this.showing=false;}if(a){a.setStyle("visibility","visible");
}this.callChain();this.fireEvent("show",this.element);}.bind(this));}else{this.callChain();this.fireEvent("complete",this.element);this.fireEvent("show",this.element);
}}else{if(this.options.link=="chain"){this.chain(this.reveal.bind(this));}else{if(this.options.link=="cancel"&&!this.showing){this.cancel();this.reveal();
}}}}catch(c){this.element.setStyles({display:this.options.display,visiblity:"visible",opacity:1});this.showing=false;this.callChain.delay(10,this);this.fireEvent("complete",this.element);
this.fireEvent("show",this.element);}return this;},toggle:function(){if(this.element.getStyle("display")=="none"||this.element.getStyle("visiblity")=="hidden"||this.element.getStyle("opacity")==0){this.reveal();
}else{this.dissolve();}return this;}});Element.Properties.reveal={set:function(a){var b=this.retrieve("reveal");if(b){b.cancel();}return this.eliminate("reveal").store("reveal:options",$extend({link:"cancel"},a));
},get:function(a){if(a||!this.retrieve("reveal")){if(a||!this.retrieve("reveal:options")){this.set("reveal",a);}this.store("reveal",new Fx.Reveal(this,this.retrieve("reveal:options")));
}return this.retrieve("reveal");}};Element.Properties.dissolve=Element.Properties.reveal;Element.implement({reveal:function(a){this.get("reveal",a).reveal();
return this;},dissolve:function(a){this.get("reveal",a).dissolve();return this;},nix:function(){var a=Array.link(arguments,{destroy:Boolean.type,options:Object.type});
this.get("reveal",a.options).dissolve().chain(function(){this[a.destroy?"destroy":"dispose"]();}.bind(this));return this;},wink:function(){var b=Array.link(arguments,{duration:Number.type,options:Object.type});
var a=this.get("reveal",b.options);a.reveal().chain(function(){(function(){a.dissolve();}).delay(b.duration||2000);});}});var Drag=new Class({Implements:[Events,Options],options:{snap:6,unit:"px",grid:false,style:true,limit:false,handle:false,invert:false,preventDefault:false,modifiers:{x:"left",y:"top"}},initialize:function(){var b=Array.link(arguments,{options:Object.type,element:$defined});
this.element=$(b.element);this.document=this.element.getDocument();this.setOptions(b.options||{});var a=$type(this.options.handle);this.handles=((a=="array"||a=="collection")?$$(this.options.handle):$(this.options.handle))||this.element;
this.mouse={now:{},pos:{}};this.value={start:{},now:{}};this.selection=(Browser.Engine.trident)?"selectstart":"mousedown";this.bound={start:this.start.bind(this),check:this.check.bind(this),drag:this.drag.bind(this),stop:this.stop.bind(this),cancel:this.cancel.bind(this),eventStop:$lambda(false)};
this.attach();},attach:function(){this.handles.addEvent("mousedown",this.bound.start);return this;},detach:function(){this.handles.removeEvent("mousedown",this.bound.start);
return this;},start:function(c){if(this.options.preventDefault){c.preventDefault();}this.mouse.start=c.page;this.fireEvent("beforeStart",this.element);
var a=this.options.limit;this.limit={x:[],y:[]};for(var d in this.options.modifiers){if(!this.options.modifiers[d]){continue;}if(this.options.style){this.value.now[d]=this.element.getStyle(this.options.modifiers[d]).toInt();
}else{this.value.now[d]=this.element[this.options.modifiers[d]];}if(this.options.invert){this.value.now[d]*=-1;}this.mouse.pos[d]=c.page[d]-this.value.now[d];
if(a&&a[d]){for(var b=2;b--;b){if($chk(a[d][b])){this.limit[d][b]=$lambda(a[d][b])();}}}}if($type(this.options.grid)=="number"){this.options.grid={x:this.options.grid,y:this.options.grid};
}this.document.addEvents({mousemove:this.bound.check,mouseup:this.bound.cancel});this.document.addEvent(this.selection,this.bound.eventStop);},check:function(a){if(this.options.preventDefault){a.preventDefault();
}var b=Math.round(Math.sqrt(Math.pow(a.page.x-this.mouse.start.x,2)+Math.pow(a.page.y-this.mouse.start.y,2)));if(b>this.options.snap){this.cancel();this.document.addEvents({mousemove:this.bound.drag,mouseup:this.bound.stop});
this.fireEvent("start",[this.element,a]).fireEvent("snap",this.element);}},drag:function(a){if(this.options.preventDefault){a.preventDefault();}this.mouse.now=a.page;
for(var b in this.options.modifiers){if(!this.options.modifiers[b]){continue;}this.value.now[b]=this.mouse.now[b]-this.mouse.pos[b];if(this.options.invert){this.value.now[b]*=-1;
}if(this.options.limit&&this.limit[b]){if($chk(this.limit[b][1])&&(this.value.now[b]>this.limit[b][1])){this.value.now[b]=this.limit[b][1];}else{if($chk(this.limit[b][0])&&(this.value.now[b]<this.limit[b][0])){this.value.now[b]=this.limit[b][0];
}}}if(this.options.grid[b]){this.value.now[b]-=((this.value.now[b]-this.limit[b][0])%this.options.grid[b]);}if(this.options.style){this.element.setStyle(this.options.modifiers[b],this.value.now[b]+this.options.unit);
}else{this.element[this.options.modifiers[b]]=this.value.now[b];}}this.fireEvent("drag",[this.element,a]);},cancel:function(a){this.document.removeEvent("mousemove",this.bound.check);
this.document.removeEvent("mouseup",this.bound.cancel);if(a){this.document.removeEvent(this.selection,this.bound.eventStop);this.fireEvent("cancel",this.element);
}},stop:function(a){this.document.removeEvent(this.selection,this.bound.eventStop);this.document.removeEvent("mousemove",this.bound.drag);this.document.removeEvent("mouseup",this.bound.stop);
if(a){this.fireEvent("complete",[this.element,a]);}}});Element.implement({makeResizable:function(a){var b=new Drag(this,$merge({modifiers:{x:"width",y:"height"}},a));
this.store("resizer",b);return b.addEvent("drag",function(){this.fireEvent("resize",b);}.bind(this));}});Drag.Move=new Class({Extends:Drag,options:{droppables:[],container:false,precalculate:false,includeMargins:true,checkDroppables:true},initialize:function(c,b){this.parent(c,b);
this.droppables=$$(this.options.droppables);this.container=$(this.options.container);if(this.container&&$type(this.container)!="element"){this.container=$(this.container.getDocument().body);
}var a=this.element.getStyle("position");if(a=="static"){a="absolute";}if([this.element.getStyle("left"),this.element.getStyle("top")].contains("auto")){this.element.position(this.element.getPosition(this.element.offsetParent));
}this.element.setStyle("position",a);this.addEvent("start",this.checkDroppables,true);this.overed=null;},start:function(f){if(this.container){var b=this.container.getCoordinates(this.element.getOffsetParent()),c={},e={};
["top","right","bottom","left"].each(function(g){c[g]=this.container.getStyle("border-"+g).toInt();e[g]=this.element.getStyle("margin-"+g).toInt();},this);
var d=this.element.offsetWidth+e.left+e.right;var a=this.element.offsetHeight+e.top+e.bottom;if(this.options.includeMargins){$each(e,function(h,g){e[g]=0;
});}if(this.container==this.element.getOffsetParent()){this.options.limit={x:[0-e.left,b.right-c.left-c.right-d+e.right],y:[0-e.top,b.bottom-c.top-c.bottom-a+e.bottom]};
}else{this.options.limit={x:[b.left+c.left-e.left,b.right-c.right-d+e.right],y:[b.top+c.top-e.top,b.bottom-c.bottom-a+e.bottom]};}}if(this.options.precalculate){this.positions=this.droppables.map(function(g){return g.getCoordinates();
});}this.parent(f);},checkAgainst:function(c,b){c=(this.positions)?this.positions[b]:c.getCoordinates();var a=this.mouse.now;return(a.x>c.left&&a.x<c.right&&a.y<c.bottom&&a.y>c.top);
},checkDroppables:function(){var a=this.droppables.filter(this.checkAgainst,this).getLast();if(this.overed!=a){if(this.overed){this.fireEvent("leave",[this.element,this.overed]);
}if(a){this.fireEvent("enter",[this.element,a]);}this.overed=a;}},drag:function(a){this.parent(a);if(this.options.checkDroppables&&this.droppables.length){this.checkDroppables();
}},stop:function(a){this.checkDroppables();this.fireEvent("drop",[this.element,this.overed,a]);this.overed=null;return this.parent(a);}});Element.implement({makeDraggable:function(a){var b=new Drag.Move(this,a);
this.store("dragger",b);return b;}});var Sortables=new Class({Implements:[Events,Options],options:{snap:4,opacity:1,clone:false,revert:false,handle:false,constrain:false},initialize:function(a,b){this.setOptions(b);
this.elements=[];this.lists=[];this.idle=true;this.addLists($$($(a)||a));if(!this.options.clone){this.options.revert=false;}if(this.options.revert){this.effect=new Fx.Morph(null,$merge({duration:250,link:"cancel"},this.options.revert));
}},attach:function(){this.addLists(this.lists);return this;},detach:function(){this.lists=this.removeLists(this.lists);return this;},addItems:function(){Array.flatten(arguments).each(function(a){this.elements.push(a);
var b=a.retrieve("sortables:start",this.start.bindWithEvent(this,a));(this.options.handle?a.getElement(this.options.handle)||a:a).addEvent("mousedown",b);
},this);return this;},addLists:function(){Array.flatten(arguments).each(function(a){this.lists.push(a);this.addItems(a.getChildren());},this);return this;
},removeItems:function(){return $$(Array.flatten(arguments).map(function(a){this.elements.erase(a);var b=a.retrieve("sortables:start");(this.options.handle?a.getElement(this.options.handle)||a:a).removeEvent("mousedown",b);
return a;},this));},removeLists:function(){return $$(Array.flatten(arguments).map(function(a){this.lists.erase(a);this.removeItems(a.getChildren());return a;
},this));},getClone:function(b,a){if(!this.options.clone){return new Element("div").inject(document.body);}if($type(this.options.clone)=="function"){return this.options.clone.call(this,b,a,this.list);
}return a.clone(true).setStyles({margin:"0px",position:"absolute",visibility:"hidden",width:a.getStyle("width")}).inject(this.list).position(a.getPosition(a.getOffsetParent()));
},getDroppables:function(){var a=this.list.getChildren();if(!this.options.constrain){a=this.lists.concat(a).erase(this.list);}return a.erase(this.clone).erase(this.element);
},insert:function(c,b){var a="inside";if(this.lists.contains(b)){this.list=b;this.drag.droppables=this.getDroppables();}else{a=this.element.getAllPrevious().contains(b)?"before":"after";
}this.element.inject(b,a);this.fireEvent("sort",[this.element,this.clone]);},start:function(b,a){if(!this.idle){return;}this.idle=false;this.element=a;
this.opacity=a.get("opacity");this.list=a.getParent();this.clone=this.getClone(b,a);this.drag=new Drag.Move(this.clone,{snap:this.options.snap,container:this.options.constrain&&this.element.getParent(),droppables:this.getDroppables(),onSnap:function(){b.stop();
this.clone.setStyle("visibility","visible");this.element.set("opacity",this.options.opacity||0);this.fireEvent("start",[this.element,this.clone]);}.bind(this),onEnter:this.insert.bind(this),onCancel:this.reset.bind(this),onComplete:this.end.bind(this)});
this.clone.inject(this.element,"before");this.drag.start(b);},end:function(){this.drag.detach();this.element.set("opacity",this.opacity);if(this.effect){var a=this.element.getStyles("width","height");
var b=this.clone.computePosition(this.element.getPosition(this.clone.offsetParent));this.effect.element=this.clone;this.effect.start({top:b.top,left:b.left,width:a.width,height:a.height,opacity:0.25}).chain(this.reset.bind(this));
}else{this.reset();}},reset:function(){this.idle=true;this.clone.destroy();this.fireEvent("complete",this.element);},serialize:function(){var c=Array.link(arguments,{modifier:Function.type,index:$defined});
var b=this.lists.map(function(d){return d.getChildren().map(c.modifier||function(e){return e.get("id");},this);},this);var a=c.index;if(this.lists.length==1){a=0;
}return $chk(a)&&a>=0&&a<this.lists.length?b[a]:b;}});Request.JSONP=new Class({Implements:[Chain,Events,Options,Log],options:{url:"",data:{},retries:0,timeout:0,link:"ignore",callbackKey:"callback",injectScript:document.head},initialize:function(a){this.setOptions(a);
this.running=false;this.requests=0;this.triesRemaining=[];},check:function(){if(!this.running){return true;}switch(this.options.link){case"cancel":this.cancel();
return true;case"chain":this.chain(this.caller.bind(this,arguments));return false;}return false;},send:function(c){if(!$chk(arguments[1])&&!this.check(c)){return this;
}var e=$type(c),a=this.options,b=$chk(arguments[1])?arguments[1]:this.requests++;if(e=="string"||e=="element"){c={data:c};}c=$extend({data:a.data,url:a.url},c);
if(!$chk(this.triesRemaining[b])){this.triesRemaining[b]=this.options.retries;}var d=this.triesRemaining[b];(function(){var f=this.getScript(c);this.log("JSONP retrieving script with url: "+f.get("src"));
this.fireEvent("request",f);this.running=true;(function(){if(d){this.triesRemaining[b]=d-1;if(f){f.destroy();this.request(c,b);this.fireEvent("retry",this.triesRemaining[b]);
}}else{if(f&&this.options.timeout){f.destroy();this.cancel();this.fireEvent("failure");}}}).delay(this.options.timeout,this);}).delay(Browser.Engine.trident?50:0,this);
return this;},cancel:function(){if(!this.running){return this;}this.running=false;this.fireEvent("cancel");return this;},getScript:function(c){var b=Request.JSONP.counter,d;
Request.JSONP.counter++;switch($type(c.data)){case"element":d=$(c.data).toQueryString();break;case"object":case"hash":d=Hash.toQueryString(c.data);}var e=c.url+(c.url.test("\\?")?"&":"?")+(c.callbackKey||this.options.callbackKey)+"=Request.JSONP.request_map.request_"+b+(d?"&"+d:"");
if(e.length>2083){this.log("JSONP "+e+" will fail in Internet Explorer, which enforces a 2083 bytes length limit on URIs");}var a=new Element("script",{type:"text/javascript",src:e});
Request.JSONP.request_map["request_"+b]=function(f){this.success(f,a);}.bind(this);return a.inject(this.options.injectScript);},success:function(b,a){if(a){a.destroy();
}this.running=false;this.log("JSONP successfully retrieved: ",b);this.fireEvent("complete",[b]).fireEvent("success",[b]).callChain();}});Request.JSONP.counter=0;
Request.JSONP.request_map={};

//tangerine smash, Andrew Gleave (c) 2009
var TimelineNav = new Class({
    Implements:[Options],
    options: {
        sigma: 3.0,
        scale: 800.0,
        transition: Fx.Transitions.Quad.easeOut,
        duration: 250,
        spanOffset: {x: 15, y: null},
        selector: 'li[class!=marker]',
        highlightOnShow: true
    },
    initialize: function(target, options) {
        if(!$(target)) return;
        this.setOptions(options);
        this.target = $(target);
        this.items = this.target.getElements(this.options.selector);
        this.fx = new Fx.Elements(this.items, {wait: false, duration: this.options.duration, transition: this.options.transition});
        this.gaussian = this.buildGaussian();
        this.gaussianMid = this.gaussian.length / 2;
        this.target.set('reveal', {duration: 180, mode: 'vertical', transition: Fx.Transitions.Sine.easeIn})
        this.attach();
    },
    attach: function() {
        if(!this.items.length) return;
        if(!this.options.spanOffset.y)
            this.options.spanOffset.y = (this.items[0].getStyle('margin-bottom').toInt() + this.items[0].getStyle('height').toInt());
        var defaultWidth = this.items[0].getStyle('width').toInt() || 8;
        this.items.each(function(item, i) {
            item.addEvent('mouseenter', function(e) {
                var o = {};
                var currentIndex = this.items.indexOf(item);
                o[i] = {'width': [item.getStyle('width').toInt(), this.gaussian[this.gaussianMid]]};
                item.getElement('span').setStyles({
                        'display': 'block',
                        'left': this.gaussian[this.gaussianMid] + this.options.spanOffset.x,
                        'top': this.options.spanOffset.y * currentIndex + (this.items.length - (this.items.length/currentIndex))
                });
                if(this.options.highlightOnShow) item.getElement('a').addClass('highlight');
                this.items.each(function(other, j) {
                    if(i != j) {
                        var p = this.gaussian[this.gaussianMid - currentIndex + j];
                        if(p < defaultWidth) p = defaultWidth;
                        o[j] = {'width': [other.getStyle('width').toInt(), p]};
                        other.getElement('span').setStyle('display', 'none');
                        other.getElement('a').removeClass('highlight');
                    }
                }.bind(this));
                this.fx.start(o);
            }.bind(this));
        }.bind(this));
        this.target.addEvent('mouseleave', function(e) {
            var o = {};
            this.items.each(function(item, i) {
                o[i] = {'width': [item.getStyle('width').toInt(), defaultWidth]};
                item.getElement('span').setStyle('display', 'none');
                if(this.options.highlightOnShow) item.getElement('a').removeClass('highlight');
            }.bind(this));
            this.fx.start(o);
        }.bind(this));
    },
    hide: function() {
        this.target.get('reveal').dissolve();
        return false;
    },
    show: function() {
        this.target.reveal();
        if(this.options.highlightOnShow) {
            var found = false;
            this.items.each(function(el) {
                if(window.location.pathname == el.getElement('a').get('href')) {
                    el.fireEvent('mouseenter');
                    found = true;
                    return;
                }
            });
            if(!found) this.items[0].fireEvent('mouseenter');
        }
        return false;
    },
    toggle: function() {
        return this.target.getStyle('display') == 'none' ? this.show() : this.hide();
    },
    buildGaussian: function() {
        var sqrtTwoPi = Math.sqrt(2 * Math.PI);
        var g = Array();
        function gaussian(x, sigma, mu, scale) { return (scale / (sigma * sqrtTwoPi)) * Math.pow(Math.E, (-Math.pow(x - mu, 2) / (2 * Math.pow(sigma, 2)))); }
        for(var i = 0; i < this.items.length * 2; i++)
            g.push(Math.ceil(gaussian(i, this.options.sigma, this.items.length, this.options.scale)));
        return g;
    }
});


var KwickNav = new Class({
    Implements:[Options],
    options: {
        minWidth: 50,
        fullWidth: 150,
        transition: Fx.Transitions.Quad.easeOut,
        duration: 150,
        selector: 'li[class!=disabled]',
        removeTitles: true
    },
    initialize: function(target, options) {
        if(!$(target)) return;
        this.setOptions(options);
        this.target = $(target);
        this.items = this.target.getElements(this.options.selector);
        this.fx = new Fx.Elements(this.items, {wait: false, duration: this.options.duration, transition: this.options.transition});
        this.attach();
    },
    attach: function() {
        if(!this.items.length) return;
        var defaultWidth = this.items[0].getStyle('width').toInt();
        this.items.each(function(item, i) {
            item.addEvent('mouseenter', function(e) {
                var o = {};
                o[i] = {'width': [item.getStyle('width').toInt(), this.options.fullWidth]};
                item.getElement('span').setStyle('display', 'block');
                this.items.each(function(other, j) {
                    if(i != j) {
                        var w = other.getStyle('width').toInt();
                        if(w != this.options.minWidth)
                            o[j] = {width: [w, this.options.minWidth]};
                        other.getElement('span').setStyle('display', 'none');
                    }
                }.bind(this));
                this.fx.start(o);
            }.bind(this));
            item.addEvent('mouseleave', function() {item.getElement('span').setStyle('display', 'none');});
            item.getElement('span').setStyle('display', 'none');
            if(this.options.removeTitles) item.getElement('a').set('title', '');
        }.bind(this));
        this.target.addEvent('mouseleave', function() {
            var o = {};
            this.items.each(function(item, i) {
                o[i] = {width: [item.getStyle('width').toInt(), this.options.minWidth]};
                item.getElement('span').setStyle('display', 'none');
            }.bind(this));
            this.fx.start(o);
        }.bind(this));
    }
});

//TwitterGitter - David Walsh http://davidwalsh.name/
var TwitterGitter = new Class({
    Implements: [Options, Events],
    options: {
        count: 2,
        sinceID: 1,
        link: true,
        onRequest: $empty,
        onComplete: $empty
    },
    initialize: function(username, options) {
        this.setOptions(options);
        this.username = username;
    },
    retrieve: function() {
        new Request.JSONP({
            url: 'http://twitter.com/statuses/user_timeline/{username}.json'.substitute({username: this.username}),
            data: {
                count: this.options.count,
                since_id: this.options.sinceID
            },
            onRequest: this.fireEvent('request'),
            onComplete: function(data) {
                if(this.options.link) {
                    data.each(function(tweet) { tweet.text = this.linkify(tweet.text); },this);
                }
                this.fireEvent('complete', [data, data[0].user]);
            }.bind(this)
        }).send();
        return this;
    },
    linkify: function(text) {
        return text.replace(/(https?:\/\/\S+)/gi,'<a href="$1">$1</a>').replace(/(^|\s)@(\w+)/g,'$1<a href="http://twitter.com/$2">@$2</a>').replace(/(^|\s)#(\w+)/g,'$1#<a href="http://search.twitter.com/search?q=%23$2">$2</a>');
    }
});

BackTextFactory = new Class({
    initialize: function(form, elements) {
        this.form = $(form);
        this.elements = $H(elements);
        this.attach();
    },
    attach: function() {
        this.form.addEvent('submit', this.reset.bind(this));
        this.elements.each(function(v, k) {
            k = $(k);
            k.addEvents({
                'focus': function() {
                    if (k.hasClass('back_text')) {
                        k.removeClass('back_text');
                        k.value = '';
                    }
                },
                'blur': function() {
                    if (k.value == '' || k.value == v) {
                        k.value = v;
                        k.addClass('back_text');
                    }
                }
            });
            k.fireEvent('blur');
        });
    },
    reset: function() {
        this.elements.each(function(v, k) {
            k = $(k);
            if(k.value == v) k.value = '';
        });
    }
})


SimpleAjaxForm  = new Class({
    Implements: [Options, Events],
    options: {
        duration: 500,
        messageText: 'Your message has been sent',
        hideShowTrigger: null
    },
    initialize: function(form, options) {
        this.setOptions(options);
        this.form = $(form);
        this.form.addEvent('submit', this.sendMessage.bind(this));
    },
    sendMessage: function(e) {
        var form = this.form;
        var options = this.options;
        if(form.retrieve('back_text')) form.retrieve('back_text').reset();
        form.get('send',  {'method': 'post', onComplete: function(res) {
            if(this.status == 204) {
                form.setStyle('display', 'none');
                var info = new Element('h3', {'html': options.messageText, 'styles': {'opacity': 0}, 'class': 'result_info'});
                info.inject(form, 'after');
                info.get('tween', {property: 'opacity', duration: options.duration}).start(1);
                form.nix();
                if(options.hideShowTrigger) options.hideShowTrigger.removeEvents('click');
            }
            else {
                form.getElements('strong.error').each(function(elm) {elm.destroy()});
                $H(JSON.decode(res).errors).each(function(v, k) {
                     new Element('strong', {'class' : 'error', 'html': v[0].replace('.', '')}).inject($('id_' + k), 'after');
                });
                form.getElements('input, textarea').each(function(el){el.fireEvent('blur')});
            }
        }
        }).send();
        return false;
    }
});


window.addEvent('domready', function() {
    var classList = $(document.body).get('class').split(' ');
    if(classList.contains('tweets')) {
        if($defined($('tweets'))) {
            $('tweets').addEvent('click', function(e) {
                if(!$defined($('col_b'))) {
                    $(document.body).toggleClass('indicator');
                    new TwitterGitter('andrewgleave', {
                        count: 3,
                        onComplete: function(tweets, user) {
                            var container = new Element('ol', {'id': 'tweet_container'});
                            new Element('div', {'id': 'col_b'}).adopt(container).inject($('col_a'), 'after');
                            tweets.each(function(tweet, i) {
                                var el = new Element('li', {'html': '<h3>{creation_date}</h3><p>{body}</p>'.substitute({'creation_date': tweet.created_at.substring(0, tweet.created_at.lastIndexOf(':')), 'body': tweet.text})});
                                container.adopt(el);
                                el.fade('hide');
                                el.fade('in');
                            });
                            container.adopt(new Element('li', {'html': '<p><a href="http://twitter.com/andrewgleave/">Follow me on Twitter...</a></p>'}));
                            $(document.body).toggleClass('indicator');
                        }.bind(this)
                    }).retrieve();
                }
                return false;
            });
        }
    }
    if(classList.contains('timeline')) {
        $('archive').addEvent('click', function(e) {
            if(Browser.Engine.trident || e.shift)return true;
            if(!$defined($('timeline'))) {
                $(document.body).toggleClass('indicator');
                new Request({
                    url: $('archive').get('href'),
                    method: 'get',
                    onComplete: function(resp) {
                        new Element('div', {html: resp}).getElement('div').inject($('content'), 'top');
                        new TimelineNav($('timeline'), {spanOffset: {x: 75, y: 10}}).show();
                        $(document.body).toggleClass('indicator');
                   }
                }).send();
            }
            return false;
        });
    }
    if(classList.contains('contact')) {
        new SimpleAjaxForm($('contact_form'), {messageText: 'Thanks, your message has been received.'});
        $$('#puzzle li a').addEvent('click', function() {return false;});
        var puzzle = new Sortables('puzzle', {
            revert: {duration: 100, transition: Fx.Transitions.Quad.easeInOut},
            constrain: true,
            clone: true,
            opacity: 0.5,
            onComplete: function() {$('id_image_order').set('value', this.serialize());}
        });
        $('id_image_order').set('value', puzzle.serialize());
        $('contact_form').store('back_text', new BackTextFactory($('contact_form'), {
            'id_name': 'Your name',
            'id_email': 'Your email address',
            'id_message': 'What\'s your question?'
        }));
    }
    if(classList.contains('kwick'))
        new KwickNav($('main_nav'), {minWidth: 32, fullWidth: 120});
    if(classList.contains('comment')) {
        new SimpleAjaxForm($('comment_form'), {messageText: 'Thanks, your comment has been submitted', hideShowTrigger: $('comment_form')});
        $('comment_form').set('reveal', {duration: 180, mode: 'vertical', transition: Fx.Transitions.Sine.easeInOut}).dissolve();
        $('show_comment').addEvent('click', function() {$('comment_form').get('reveal').toggle();return false;});
        $('comment_form').store('back_text', new BackTextFactory($('comment_form'), {
            'id_name': 'Your name',
            'id_url': 'Your site URL',
            'id_comment': 'Your comment'
        }));
    }
    $$('pre').addEvent('click', function() {this.toggleClass('expand')});
    $$('a.back_history').addEvent('click', function() {window.history.back();});
});