$(document).ready(loadFeed);

function loadFeed()
{
	rewriteAnchors();
// abs path to the proxy script 
//	$.get("http://www.quietless.com/kitchen/wp-content/themes/quietless/twitter/buffer.php", onFeedReceived);
	$.get("http://www.quietless.com/kitchen/wp-content/themes/quietless/twitter/proxy.php?count=3", onFeedReceived);
}

var t = setTimeout('nofeed()', 2000);
function nofeed(){		
	$('#twitter').html('<ul><li>Sorry, Feed Currently Unavailable</li></ul>');		
}

function onFeedReceived(feed)
{
// create an array to contain the returned status //	
	var f = feed.getElementsByTagName('status');

	$('#twitter').text('');	
	$('#twitter').html('<ul>');	
// iterate over the array converting each status into a <li>	
	for (var i=0; i < f.length; i++) 
	{
	// get the actual tweet text //	
		var tweet = getXMLNodeValue(f[i], 'text');
		time = parseDate(getXMLNodeValue(f[i], 'created_at'));
		
	// match links //	
		var link = /http:\/\/[^\s]*/;
	// find urls in the tweet //	
		var l = tweet.match(link);
	// wrap urls in anchor tags //	
		var str = tweet;
		if (l) str = tweet.replace(l[0], "<a href='"+l[0]+"'>"+l[0]+"</a>");
	// dump onscreen //	
		$('#twitter').append("<li><div class='date'>"+ time + "</div><div class='tweet'>" + str + '</div></li>');
	};
	$('#twitter').append('</ul>');	
// if twitter dies display an error //	
	if ($('#twitter').text()!='') clearTimeout(t);		
}

function parseDate($stamp)
{
// time stamp arrives as Tue Apr 07 22:52:51 +0000 2009		
// convert to local string and remove seconds and year //		
	var date = new Date(Date.parse($stamp)).toLocaleString().substr(0, 16);
	var hour = date.substr(-5, 2); 
	var ampm = hour<12 ? ' AM' : ' PM';
	if (hour>12) hour-= 12;
	if (hour==0) hour = 12;
	return date.substr(0, 11)+' • ' + hour + date.substr(13) + ampm;
}

function getXMLNodeValue($node, $name)
{
	var n = $node.getElementsByTagName($name);
	return n[0].childNodes[0].nodeValue;
}

function rewriteAnchors()
{
    $('a[href^="http://"]').filter(function()
	{
    	return this.hostname && this.hostname !== location.hostname; })
        .addClass("external")
        .attr({ title: "Link will open in new window" })
        .click( function() {
            window.open(this.href);
            return false;
	});	
}