function loadTweets(count, username, $outputelem)
{
	$.ajax({
		url: 'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=0&screen_name='+username+'&count='+count,
		cache: true,
		dataType: 'jsonp',
		success : function(data, status, jqXHR)
		{
			var output = '';

			$.each(data, function(index, tweet){
				output +=	'<div class="tweet">'+
								'<p class="tweetmsg">'+linkify_entities(tweet)+'</p>'+
								'<p class="tweetmore">'+
									'<a href="http://www.twitter.com/'+username+'/status/'+tweet.id_str+'" target="_blank">tweetet '+timeago(tweet.created_at)+'</a>'+
									'<a href="http://twitter.com/intent/tweet?in_reply_to='+tweet.id_str+'" target="_blank">reply</a>'+
									'<a href="http://twitter.com/intent/retweet?tweet_id='+tweet.id_str+'" target="_blank">retweet</a>'+
									'<a href="http://twitter.com/intent/favorite?tweet_id='+tweet.id_str+'" target="_blank" class="last">favorite</a>'+
								'</p>'+
							'</div>';
			});
			var $output = $(output);
			$output.last('.tweet').addClass('last');
			$outputelem.html($output);
		}
	});
}

function timeago(date)
{
	var output = date;
	var strings = {
		"year" 		: ['1 year ago', '%d years ago'],
		"month" 	: ['1 month ago', '%d months ago'],
		"day" 		: ['1 day ago', '%d days ago'],
		"hour" 		: ['1 hour ago', '%d hours ago'],
		"minute" 	: ['1 minute ago', '%d minutes ago'],
		"second" 	: ['now', '%d secons ago']
	};

	var currentTime = new Date();
	var tweetDate = createDateFromTwitter(date);
	var time = Math.round((currentTime.getTime() - tweetDate.getTime())/1000);

	if (time < 1)
	{
		return strings.second[0];
	}

	var seconds_year = 12 * 30 * 24 * 60 * 60;
	var seconds_month = 30 * 24 * 60 * 60;
	var seconds_day = 24 * 60 * 60;
	var seconds_hour = 60 * 60;
	var seconds_minute = 60;
	var seconds_second = 60;
	var seconds = {
		'year' 		: seconds_year,
		'month'		: seconds_month,
		'day'		: seconds_day,
		'hour'		: seconds_hour,
		'minute'	: seconds_minute,
		'second'	: seconds_second
	};

	$.each(seconds, function(container, seconds)
	{
		var diff = parseInt(time) / parseInt(seconds);
		var rounded = Math.round(diff);
		if(rounded > 0)
		{
			output = (rounded == 1) ? strings[container][0] : strings[container][1].replace('%d', rounded);
			return false;
		}
	});

	return output;
}

function createDateFromTwitter(datestring)
{
	var months = {
		"Jan": 0,
		"Feb": 1,
		"Mar": 2,
		"Apr": 3,
		"May": 4,
		"Jun": 5,
		"Jul": 6,
		"Aug": 7,
		"Sep": 8,
		"Oct": 0,
		"Nov": 10,
		"Dec": 11
	}

	// For example "Mon Nov 14 12:46:36 +0000 2011"
	var date_arr = datestring.split(' ');
	var time = date_arr[3].split(':');
	var now = new Date();
	var timezone = -now.getTimezoneOffset()/60;
	
	var year = date_arr[5];
	var month = months[date_arr[1]];
	var day = date_arr[2];
	var hours = parseInt(time[0])+parseInt(timezone);
	var minutes = time[1];
	var seconds = time[2];

	var date = new Date(year, month, day, hours, minutes, seconds, 0);

	return date;
}

function escapeHTML(text)
{
    return $('<div/>').text(text).html()
}

function linkify_entities(tweet)
{
    if (!(tweet.entities))
	{
        return escapeHTML(tweet.text);
    }

    // This is very naive, should find a better way to parse this
    var index_map = {}

    $.each(tweet.entities.urls, function(i,entry)
	{
        index_map[entry.indices[0]] = [entry.indices[1], function(text) {return "<a href='"+escapeHTML(entry.url)+"'>"+escapeHTML(text)+"</a>";}];
    });

    $.each(tweet.entities.hashtags, function(i,entry)
	{
        index_map[entry.indices[0]] = [entry.indices[1], function(text) {return "<a href='http://twitter.com/search?q="+escape("#"+entry.text)+"'>"+escapeHTML(text)+"</a>";}];
    });

    $.each(tweet.entities.user_mentions, function(i,entry)
	{
        index_map[entry.indices[0]] = [entry.indices[1], function(text) {return "<a title='"+escapeHTML(entry.name)+"' href='http://twitter.com/"+escapeHTML(entry.screen_name)+"'>"+escapeHTML(text)+"</a>";}];
    });

    var result = "";
    var last_i = 0;
    var i = 0;

    // iterate through the string looking for matches in the index_map
    for (i=0; i < tweet.text.length; ++i)
	{
        var ind = index_map[i];
        if(ind)
		{
            var end = ind[0];
            var func = ind[1];
            if (i > last_i)
			{
                result += escapeHTML(tweet.text.substring(last_i, i));
            }
            result += func(tweet.text.substring(i, end));
            i = end - 1;
            last_i = end;
        }
    }

    if (i > last_i)
	{
        result += escapeHTML(tweet.text.substring(last_i, i));
    }

    return result;
}
