jQuery(function($) {
	var opml = 'http://electricpulp.com/pulpsters.xml';
	
	// Semanticize Tweets
	var parseTwitter = function(text) {
		return text.replace(/^([^:]*: )/, ''). // remove handle
			replace(/((?:https?:\/\/)(?:[^\s]*))/i, '<a href="$1">$1</a>'). // link to links
			replace(/@([A-Za-z0-9_]*)/, '@<a class="handle" href="http://twitter.com/$1">$1</a>'); // link to handles
	}
	
	// For each Pulpster...
	$('#team .vcard').hover(function() {
		var that = $(this).addClass("hover");
		
		// If this Pulpster's sites ain't loaded...
		if (that.find('.sites').length < 1) {
			if (that.find('.ohai').length < 1) {
				that.wrapInner('<div class="ohai"></div>');
			}
			
			// Containers for sites info
			that.append(
				$('<div class="sites sites-loading"></div>').append(
					$('<div class="header"></div>').append(that.find('.ohai').contents().clone())
				).append('<ul class="navigation"></ul><ul class="content"></ul>')
			);
			
			// Contents
			// $.getJSON('http://pipes.yahoo.com/pipes/pipe.run?_id=2ace9a4de496407c53e87608898030d3&name='+this.id+'&opml='+escape(opml)+'&_render=json&_callback=?', function(json) {
			$.getJSON('/pulpsters/'+this.id.toLowerCase()+'.json', function(json) {
				// BRILLIANT!
				$.each(json.value.items, function() {
					if (this.author.toLowerCase() == 'twitter') this.description = parseTwitter(this.description);
					
					var id = that.attr('id')+'-'+this.author.replace(/[^A-Za-z0-9]*/, '-').toLowerCase();
					that.find('ul.navigation').append('<li><a href="#'+id+'">'+this.author+'</a></li>').find('a').click(function() {
						that.find('ul.navigation li').removeClass('here');
						that.find('ul.content li').hide();
						$(this).parent().addClass('here');
						$($(this).attr('href').replace(/[^#]*/, '')).show();
						return false;
					});
					that.find('ul.content').append('<li id="'+id+'"><div class="content">'+this.description+'</div><p class="gtfo"><a href="'+this.link+'">Go There</a></p></li>');
				});
				
				// Load the first tab
				that.find('ul.navigation li:first a').trigger('click').end().find('.sites').removeClass('sites-loading');
			});
		}
		
		// Slide sites up
		that.find('.sites').show();
		that.find('.sites img.photo').animate({
			width: '75px',
			height: '75px'
		}, 100);
	}, function() {
		var that = $(this).removeClass('hover');
		
		setTimeout(function() {
			if (that.hasClass('hover')) return false;
			
			that.find('.sites img.photo').animate({
				width: '300px',
				height: '300px'
			}, {
				// Phwoar
				complete: function() { that.find('.sites').hide() },
				duration: 80
			});
		}, 420); // I would
	});
});
