function load_and_track_ga() {
	var account_id = 'UA-8727341-1';
	var host = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	var src = host + 'google-analytics.com/ga.js';
	$.getScript(src, function() {
		if (typeof _gat != undefined) {
			pageTracker = _gat._getTracker(account_id);
			pageTracker._trackPageview();
		} else {
			throw "_gat is undefined";
		}
	});
}
  
function getHashPart(link){
	if (!link) {
		hash=window.location.hash;
	} else {
		hash=link.substr(link.lastIndexOf('#'));
	}
	array=hash.substr(1).split('/');
	if ($('.multipartwrapper').length) {//Multipart exists
		return array[0];
	} else { //Only Works Cited Possible, no part
		return false;
	}
}
function getHashWork(link){	
	//If the works cited is on a multipart document, the id MUST be in the form #part/author
	if (!link) {
		hash=window.location.hash;
	} else {
		hash=link.substr(link.lastIndexOf('#'));
	}
	return hash.replace('\/','\\\/');
}
function clearHashWork() {
	hash=window.location.hash;
	if (hash) {
		array=hash.substr(1).split('/');
		window.location.hash=array[0];
	}
}
function animateParts(i,time) {
	if (!i) {i=0};
	if (undefined===time) {time=400};
	$('ol.multipart > li').css('height','auto');
	if (time>0) {
		$('ol.multipart').stop().animate({marginLeft:-(100*i)+'%'},time,'swing',function(){
			$('ol.multipart > li:not(:eq('+i+'))').css('height','0px');	
		});
	} else {
		$('ol.multipart').css('marginLeft',-(100*i)+'%');
		$('ol.multipart > li:not(:eq('+i+'))').css('height','0px');	
	}
}
function relTime(time) {
	var delta = new Date().getTime()/1000 - time.getTime()/1000;
	if (delta < 60) {
		return 'less than a minute ago';
	} else if (delta < 120) {
		return 'about a minute ago';
	} else if (delta < (45 * 60)) {
		return Math.floor(delta / 60) + ' minutes ago';
	} else if (delta < (90 * 60)) {
		return 'about an hour ago';
	} else if (delta < (24 * 60 * 60)) {
		return 'about ' + Math.floor(delta / 3600) + ' hours ago';
	} else if (delta < (48 * 60 * 60)) {
		return '1 day ago';
	} else {
		return Math.floor(delta / 86400) + ' days ago';
	}
}

//Linking to works cited entries in multiparts sucks royally in Safari and a little bit it some other browsers.
//Here, I remove the links from the url.  It's a bad solution, but I have no better ideas yet
clearHashWork();

$(document).ready(function() {


	load_and_track_ga();
	
	//Formats Code Blocks to have line numbers and stuff
	$.each($('code'),function() {
		$(this).addClass('formatted');
		var lines=$(this).html().split('\n');	
		var code=$(this);
		$(this).empty();	
		$(this).append('<ol>');
		$.each(lines,function(i,n) {
			$(code).children('ol').append('<li><span class="line">'+(i+1)+'</span> '+(n)+'</li>');
		});
		$(this).append('</ol>');
	});
	
	
//Formats "schedules" for classes and such
	$('table.schedule').each(function(i){
		var newdiv=$('<div class="schedule"></div>').insertAfter(this);
		$(this).find('tr:gt(0)').each(function(j){
			$(this).addClass('schedule'+i+'-'+j);
			var start=$(this).find('span[data-time="start"]').text();
			start=parseInt(start.split(':')[0])+parseInt(start.split(':')[1])/60;
			start=(start<8)?start+12-8:start-8;
			var end=$(this).find('span[data-time="end"]').text();
			end=parseInt(end.split(':')[0])+parseInt(end.split(':')[1])/60;
			end=(end<8)?end+12-8:end-8;

			var dates=$(this).find('td:eq(3)').text().split('');
			$.each(dates,function(k){
				$('<div style="width:'+((end-start)*30)+'px;left:'+start*30+'px;" class="'+dates[k]+' schedule'+i+'-'+j+'">&nbsp; '+'</div>').appendTo(newdiv)
					.mouseover(function(){
						$('.schedule'+i+'-'+j).addClass('selected');
					}).mouseout(function(){
						$('.schedule'+i+'-'+j).removeClass('selected');
					})
			});
			$(this).mouseover(function(){
				$('.schedule'+i+'-'+j).addClass('selected');
			});
			$(this).mouseout(function(){
				$('.schedule'+i+'-'+j).removeClass('selected');
			});
		});
		$(newdiv).append('<span class="M">Mon</span><span class="T">Tues</span><span class="W">Wed</span><span class="R">Thurs</span><span class="F">Fri</span>');
		$([8,9,10,11,12,1,2,3,4,5,6,7,8]).each(function(l){
			$(newdiv).append('<span class="label" style="left:'+(l*30)+'px;">'+(this)+'</span>');
		});
	});
	//BLK Name Switcher
		$('aside.BLK').each(function(){
			$(this).html('<span class="BLK">Brittany</span>\'s names can be confusing. Which one are you used to? <ul><li>Brittany</li> <li>Lynn</li></ul>');
			$(this).find('li').click(function(){
				var name=$(this).text();
				$('span.BLK').text(name);
			});
		});
	
	
	//Eportfolio Only Stuff
	if ($('body').hasClass('eportfolio')) {
		//Handles the switching between multiple parts on the page
		var totalItems=$('.multipartwrapper nav li').length;
		$('ol.multipart').css('width',(100*totalItems)+'%');
		$('ol.multipart > li').css('width',(100/totalItems)+'%');
		
		$('.multipartwrapper nav li').length;
	
		$('.multipartwrapper nav li').each(function(i){
			//Changes ids on all articles to prevent scrolling
				$('ol.multipart > li:eq('+i+') article').removeAttr('id');
				$('ol.multipart > li:eq('+i+')').removeAttr('id');
			//Sets each article's container to float, bringing them all to the same height
				$('ol.multipart > li:eq('+i+')').css('float','left');
			//For page loading
				if (getHashPart(window.location.hash)==(getHashPart($('.multipartwrapper nav li:eq('+i+') a').attr('href'))) || (!getHashPart() && i==0)) {
					$(this).addClass('selected');
					animateParts(i,0);
				}
			var link=$('.multipartwrapper nav li:eq('+i+') a');		
			link.click(function(e){
				e.preventDefault();
				$('.workscited .selected').removeClass('selected');
				window.location.hash=getHashPart(link.attr('href'));
				$('.multipartwrapper nav li').removeClass('selected')
				$(this).parent().addClass('selected');
				animateParts(i);
			});
		});
	
		//Workscited integration
		if (getHashWork()) {
			$('.workscited '+getHashWork()).addClass('selected');
		};
		$('a.citation').click(function(){
			$('.workscited .selected').removeClass('selected');
			$('.workscited '+getHashWork($(this).attr('href'))).addClass('selected');
		});
	};
	
	//Twatter Integration
	if ($('body').hasClass('blog')||$('body').hasClass('aboutme')) {
		$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=williamflake&count=10&callback=?',function(tweets){
			var section=$('<section class="tweets"><h1>Recent Tweets</h1><h2 class="more"><a href="http://twitter.com/WilliamFlake">More</a></h2></section>').hide().appendTo('#tools');
			var list=$('<ol></ol>').appendTo(section);
			var i=1;
			$.each(tweets,function(){
				if (i==5){return false};
				var text = this.text;
				if(text.substring(0,1)!='@') {
text=text.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/g,'<a href="$1">$1</a>');
					text=text.replace(/@([a-zA-Z0-9_]{1,15})/g,'<a href="http://twitter.com/$1">@$1</a>');
					var date = new Date(this.created_at);
					//2009-02-17T05:00-07:00
					var year=date.getUTCFullYear();
					var month=(date.getUTCMonth()<10)?'0'+date.getUTCMonth():date.getUTCMonth();
					var day=(date.getUTCDate()<10)?'0'+date.getUTCDate():date.getUTCDate();
					var hour=(date.getUTCHours()<10)?'0'+date.getUTCHours():date.getUTCHours();
					var minute=(date.getUTCMinutes()<10)?'0'+date.getUTCMinutes():date.getUTCMinutes();
					var second=(date.getUTCSeconds()<10)?'0'+date.getUTCSeconds():date.getUTCSeconds();
					$('<li>'+(text)+' <time datetime="'+year+'-'+month+'-'+day+'T'+hour+':'+minute+':'+second+'Z">'+relTime(date)+'</time></li>').appendTo(list);
					i++;
				};
			});
			$(section).fadeIn(500);
		});
		
	}	
});






