var MW = {
	pjaxContainer: '#main',
	pjaxScroll: '#main',
	fadeSpeed: 450,
	scrollSpeed: 400
}

;(function($){
	
	$.fn.smartFade = function(speed, level ) {
		level = level || 1
		speed = speed || 'normal'
		if ( Modernizr.csstransitions ) {
			return this.toggleClass("faded")
		}
		return this.fadeTo(speed, level)
	}
	
	var html = $("html")
	
	// OS detection
	$.each(['Mac','Win','Linux'], function(i, val){
		if ( navigator.platform.match(val) )
			html.addClass( val.toLowerCase() )
	})

	// Platform Detection
	$.each(['msie','mozilla','webkit'], function(i, val) {
		if ( $.browser[val] )
			html.addClass(val)
	})
	
	// iOS detection
	if ( navigator.userAgent.match(/iP(hone|od|ad)/i) ) {
		html.addClass("ios")
		$.support.isiOS = true
	}
	else {
		$.support.isiOS = false
	}
	
	// easing
	$.extend($.easing,{easeInExpo:function(x,t,b,c,d){return(t==0)?b:c*Math.pow(2,10*(t/d-1))+b;},easeOutExpo:function(x,t,b,c,d){return(t==d)?b+c:c*(-Math.pow(2,-10*t/d)+1)+b;},easeInOutExpo:function(x,t,b,c,d){if(t==0)return b;if(t==d)return b+c;if((t/=d/2)<1)return c/2*Math.pow(2,10*(t-1))+b;return c/2*(-Math.pow(2,-10*--t)+2)+b;}})
	
})(jQuery);

/*!
 * jQuery Fancy Letter Plugin v1.1
 *
 * Date: Sun Feb 06 20:51:59 2011 EST
 * Requires: jQuery v1.2.6+
 *
 * Copyright 2011, Karl Swedberg
 * Dual licensed under the MIT and GPL licenses (just like jQuery):
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Contributor: Matt Wiebe (::first-letter spec semi-conformance)
 *
 *
*/
;(function(g){g.fn.fancyletter=function(m){function k(a,d,b){return['<span class="',b.punctuationClass," ",b.ltrClassPrefix+b["punctuation"+a][d],'">',d,"</span>"].join("")}function l(a,d){var b=a.firstChild,e="",f={};if(!a)return f;for(;a.childNodes.length;)a=a.firstChild;e=a.nodeValue&&a.nodeValue.replace(/^\s\s*/,"")||"";if(e===""&&b&&b.nextSibling)return l(b.nextSibling,d);else{b=e;for(var i=f="",c=0,h=b.charAt(c),j={};h in d.punctuationLeft;){c++;f+=k("Left",h,d);h=b.charAt(c)}j.pl=f;j.firstChar=
h;c++;for(h=b.charAt(c);h in d.punctuationRight;){c++;i+=k("Right",h,d);h=b.charAt(c)}j.pr=i;j.slicePoint=c;f=j;f.node=a;f.val=e;return f}}this.each(function(){var a,d,b,e,f=this;a=g(this);var i=g.extend({},g.fn.fancyletter.defaults,m||{},g.metadata?a.metadata():g.meta?a.data():{}),c=RegExp(i.characters);e=l(f,i);if(e.firstChar){a=e.val;f=e.node;d=e.firstChar;b=d.toLowerCase();if(c.test(d)){c=g("<span></span>");f.nodeValue=a.slice(e.slicePoint);c.html(e.pl+d+e.pr);c.addClass(i.commonClass+" "+i.ltrClassPrefix+
b);c.prependTo(this)}}});return this};g.fn.fancyletter.defaults={commonClass:"fancy-letter",ltrClassPrefix:"ltr-",characters:"[a-zA-Z0-9]",groupPunctuation:true,punctuationClass:"punct",punctuationLeft:{'"':"dquo","'":"squo","\u201c":"ldquo","\u2018":"lsquo","\u00ab":"laquo","\u2039":"lsaquo","(":"lparen"},punctuationRight:{'"':"dquo","'":"squo","\u201d":"rdquo","\u2019":"rsquo","\u00bb":"raquo","\u203a":"rsaquo",")":"rparen"}}})(jQuery)

/**
 * jQuery.LocalScroll & jQuery.scrollTo
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 */
;(function(c){var a=c.scrollTo=function(f,e,d){c(window).scrollTo(f,e,d);};a.defaults={axis:"xy",duration:parseFloat(c.fn.jquery)>=1.3?0:1};a.window=function(d){return c(window).scrollable();};c.fn.scrollable=function(){return this.map(function(){var e=this,d=!e.nodeName||c.inArray(e.nodeName.toLowerCase(),["iframe","#document","html","body"])!=-1;if(!d){return e;}var f=(e.contentWindow||e).document||e.ownerDocument||e;return c.browser.safari||f.compatMode=="BackCompat"?f.body:f.documentElement;});};c.fn.scrollTo=function(f,e,d){if(typeof e=="object"){d=e;e=0;}if(typeof d=="function"){d={onAfter:d};}if(f=="max"){f=9000000000;}d=c.extend({},a.defaults,d);e=e||d.speed||d.duration;d.queue=d.queue&&d.axis.length>1;if(d.queue){e/=2;}d.offset=b(d.offset);d.over=b(d.over);return this.scrollable().each(function(){var m=this,k=c(m),l=f,j,h={},n=k.is("html,body");switch(typeof l){case"number":case"string":if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(l)){l=b(l);break;}l=c(l,this);case"object":if(l.is||l.style){j=(l=c(l)).offset();}}c.each(d.axis.split(""),function(r,s){var t=s=="x"?"Left":"Top",u=t.toLowerCase(),q="scroll"+t,o=m[q],p=s=="x"?"Width":"Height";if(j){h[q]=j[u]+(n?0:o-k.offset()[u]);if(d.margin){h[q]-=parseInt(l.css("margin"+t),10)||0;h[q]-=parseInt(l.css("border"+t+"Width"),10)||0;}h[q]+=d.offset[u]||0;if(d.over[u]){h[q]+=l[p.toLowerCase()]()*d.over[u];}}else{h[q]=l[u];}if(/^\d+$/.test(h[q])){h[q]=h[q]<=0?0:Math.min(h[q],g(p));}if(!r&&d.queue){if(o!=h[q]){i(d.onAfterFirst);}delete h[q];}});i(d.onAfter);function i(o){k.animate(h,e,d.easing,o&&function(){o.call(this,f,d);});}function g(s){var p="scroll"+s;if(!n){return m[p];}var r="client"+s,q=m.ownerDocument.documentElement,o=m.ownerDocument.body;return Math.max(q[p],o[p])-Math.min(q[r],o[r]);}}).end();};function b(d){return typeof d=="object"?d:{top:d,left:d};}})(jQuery);(function(d){var b=location.href.replace(/#.*/,"");var c=d.localScroll=function(e){d("body").localScroll(e);};c.defaults={duration:1000,axis:"y",event:"click",stop:true,target:window,reset:true};c.hash=function(e){if(location.hash){e=d.extend({},c.defaults,e);e.hash=false;if(e.reset){var f=e.duration;delete e.duration;d(e.target).scrollTo(0,e);e.duration=f;}a(0,location,e);}};d.fn.localScroll=function(f){f=d.extend({},c.defaults,f);return f.lazy?this.bind(f.event,function(h){var g=d([h.target,h.target.parentNode]).filter(e)[0];if(g){a(h,g,f);}}):this.find("a,area").filter(e).bind(f.event,function(g){a(g,this,f);}).end().end();function e(){return !!this.href&&!!this.hash&&this.href.replace(this.hash,"")==b&&(!f.filter||d(this).is(f.filter));}};function a(l,j,h){var m=j.hash.slice(1),i=document.getElementById(m)||document.getElementsByName(m)[0];if(!i){return;}if(l){l.preventDefault();}var g=d(h.target);if(h.lock&&g.is(":animated")||h.onBefore&&h.onBefore.call(h,l,i,g)===false){return;}if(h.stop){g.stop(true);}if(h.hash){var f=i.id==m?"id":"name",k=d("<a> </a>").attr(f,m).css({position:"absolute",top:d(window).scrollTop(),left:d(window).scrollLeft()});i[f]="";d("body").prepend(k);location=j.hash;k.remove();i[f]=m;}g.scrollTo(i,h).trigger("notify.serialScroll",[i]);}})(jQuery);

// jquery.pjax.js
// copyright chris wanstrath
// https://github.com/defunkt/jquery-pjax
;(function(c){c.fn.pjax=function(d,e){if(e){e.container=d;}else{e=c.isPlainObject(d)?d:{container:d};}if(e.container&&typeof e.container!=="string"){throw"pjax container must be a string selector!";return false;}return this.live("click",function(f){if(f.which>1||f.metaKey){return true;}var g={url:this.href,container:c(this).attr("data-pjax"),clickedElement:c(this),fragment:null};c.pjax(c.extend({},g,e));f.preventDefault();});};c.pjax=function(d){var h=c(d.container),g=d.success||c.noop;delete d.success;if(typeof d.container!=="string"){throw"pjax container must be a string selector!";}var e={timeout:650,push:true,replace:false,data:{_pjax:true},type:"GET",dataType:"html",beforeSend:function(i){h.trigger("start.pjax");i.setRequestHeader("X-PJAX","true");},error:function(){window.location=d.url;},complete:function(){h.trigger("end.pjax");},success:function(l){if(d.fragment){var o=c(l).find(d.fragment);if(o.length){l=o.children();}else{return window.location=d.url;}}else{if(!c.trim(l)||/<html/i.test(l)){return window.location=d.url;}}h.html(l);var i=document.title,n=c.trim(h.find("title").remove().text());if(n){document.title=n;}var k={pjax:d.container,fragment:d.fragment,timeout:d.timeout};var j=c.param(d.data);if(j!="_pjax=true"){k.url=d.url+(/\?/.test(d.url)?"&":"?")+j;}if(d.replace){window.history.replaceState(k,document.title,d.url);}else{if(d.push){if(!c.pjax.active){window.history.replaceState(c.extend({},k,{url:null}),i);c.pjax.active=true;}window.history.pushState(k,document.title,d.url);}}if((d.replace||d.push)&&window._gaq){_gaq.push(["_trackPageview"]);}var m=window.location.hash.toString();if(m!==""){window.location.href=m;}g.apply(this,arguments);}};d=c.extend(true,{},e,d);if(c.isFunction(d.url)){d.url=d.url();}var f=c.pjax.xhr;if(f&&f.readyState<4){f.onreadystatechange=c.noop;f.abort();}c.pjax.xhr=c.ajax(d);c(document).trigger("pjax",c.pjax.xhr,d);return c.pjax.xhr;};var b=("state" in window.history),a=location.href;c(window).bind("popstate",function(f){var e=!b&&location.href==a;b=true;if(e){return;}var g=f.state;if(g&&g.pjax){var d=g.pjax;if(c(d+"").length){c.pjax({url:g.url||location.href,fragment:g.fragment,container:d,push:false,timeout:g.timeout});}else{window.location=location.href;}}});if(c.inArray("state",c.event.props)<0){c.event.props.push("state");}c.support.pjax=Boolean(window.history&&window.history.pushState&&window.history.replaceState&&!((/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent)||(/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent)));if(!c.support.pjax){c.pjax=function(d){window.location=c.isFunction(d.url)?d.url():d.url;};c.fn.pjax=function(){return this;};}})(jQuery)

/* 
* FitVids 1.0
*
* Copyright 2011, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com
* Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - http://sam.zoy.org/wtfpl/
*
* Date: Thu Sept 01 18:00:00 2011 -0500
*/
;(function(a){a.fn.fitVids=function(b){var c={customSelector:null};var e=document.createElement("div"),d=document.getElementsByTagName("base")[0]||document.getElementsByTagName("script")[0];e.className="fit-vids-style";e.innerHTML="&shy;<style> .fluid-width-video-wrapper { width: 100%; position: relative;padding: 0; }.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed { position: absolute;top: 0;left: 0; width: 100%; height: 100%; }</style>";d.parentNode.insertBefore(e,d);if(b){a.extend(c,b);}return this.each(function(){var f=["iframe[src^='http://player.vimeo.com']","iframe[src^='http://www.youtube.com']","iframe[src^='http://www.kickstarter.com']","object","embed"];if(c.customSelector){f.push(c.customSelector);}var g=a(this).find(f.join(","));g.each(function(){var j=a(this);if(this.tagName.toLowerCase()=="embed"&&j.parent("object").length||j.parent(".fluid-width-video-wrapper").length){return;}var h=this.tagName.toLowerCase()=="object"?j.attr("height"):j.height(),i=h/j.width();j.wrap('<div class="fluid-width-video-wrapper" />').parent(".fluid-width-video-wrapper").css("padding-top",(i*100)+"%");j.removeAttr("height").removeAttr("width");});});};})(jQuery);

jQuery(document).ready(function($) {
	
	//$("h1").click(function() { $("body").toggleClass("baseline");});
		
	function postNiceties() {
		/* 
		Safari sucks ass at first-letter (font doesn't work)
		Firefox also sucks: box model is broken.
		Let's normalize with span magic.
		*/
		var firstP = $(".entry > p:first-child")
		firstP.fancyletter({commonClass:"first-letter"})
		// fancyletter will put our letter before an initial image
		firstP.each(function(index) {
			$(this).find(".first-letter + img").prependTo(this)
			$(this).find(".first-letter + a:has(img)").prependTo(this)
		});

		// let's add a hook for links that contain images
		$(".entry a:has(img)").addClass("image-link")
		// videos respond and stuff
		$(".entry").fitVids()
	}
	postNiceties()

	// Pretty Scrolling
	$.scrollTo.defaults.easing = 'easeInOutExpo'
	$.localScroll.defaults.duration = MW.scrollSpeed
	$.localScroll.defaults.hash = true
	$.localScroll()

	function dopjax() {
		$(".entry-title > a, a.more, #nav-below a, #site-title, #colophon nav a").pjax(MW.pjaxContainer, {fragment: MW.pjaxContainer, timeout: 2500, success: function(data, textStatus, jqXHR) {
			if ( this.clickedElement.attr("id") === "site-title" ) {
				MW.pjaxScroll = false
			}
			if ( typeof Hyphenator !== 'undefined' ) {
				Hyphenator.run();
			}
		}});

		var main = $("#main")
		main.bind('start.pjax', function(ev) {
			main.smartFade(MW.fadeSpeed, .333)
		});
		main.bind('end.pjax',   function(ev) {
			main.smartFade(MW.fadeSpeed, 1)
			if ( MW.pjaxScroll ) {
				$(window).scrollTo(MW.pjaxScroll, $.localScroll.defaults.duration)
			}
			MW.pjaxScroll = MW.pjaxContainer
			postNiceties()
		})

		$(document).bind("pjax", function(pjaxxhr, options){
			options.success(function(data, textStatus, jqXHR){
				var rawTitle = data.match(/<title>(.*)<\/title>/, data).pop(),
					title = $("<div />").html(rawTitle).text(),
					bodyClass = data.match(/<body class=["'](.*)["']>/, data).pop()

				if ( title ) {
					document.title = title
				}
				if ( bodyClass ) {
					$("body").attr("class", bodyClass)
				}
			})
		})
	}
	
	if ( ! $.support.isiOS ) {
		dopjax();
	}
	
	
})
