$.ajax({
	url: "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&exclude_replies=true&count=50&screen_name=art_dick",
	    dataType: "jsonp",
	    jsonpCallback: "loadTwitterStream"
	    });


function loadTwitterStream(json) 
{
    for(i in json)
	{
	    $('#tweets').append( buildTweet(json[i]) );
	}
}

function buildTweet(tweet)
{
    var content = tweet['text'];

    indexOffsets = [];
    for(i in tweet['entities']['urls'])
	{
	    var link = '<a href="' + tweet['entities']['urls'][i]['expanded_url'] + '">'+tweet['entities']['urls'][i]['display_url'] + '</a>';
	    content = replaceContent(content, link, tweet['entities']['urls'][i]['indices']);
	}

    for(i in tweet['entities']['hashtags'])
	{
	    var tag = '#'+tweet['entities']['hashtags'][i]['text'];
	    var link = '<a href="http://twitter.com/search?q='+encodeURIComponent(tag)+'" target="_blank">'+tag+'</a>';
	    content = replaceContent(content, link, tweet['entities']['hashtags'][i]['indices']);
	}

    for(i in tweet['entities']['user_mentions'])
	{
	    var mention = '@'+tweet['entities']['user_mentions'][i]['screen_name'];
	    var link = '<a href="http://twitter.com/'+tweet['entities']['user_mentions'][i]['screen_name']+'/" target="_blank">'+mention+'</a>';
	    content = replaceContent(content, link, tweet['entities']['user_mentions'][i]['indices']);
	}

    var v = tweet['created_at'].split(' ');
    var time = new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
    var timezone = zeroPad(Math.floor(Math.abs(time.getTimezoneOffset()/60))) + zeroPad(Math.abs(time.getTimezoneOffset()%60));
    if(time.getTimezoneOffset() < 0)
	timezone = '+' + timezone;
    else if(time.getTimezoneOffset() > 0)
	timezone = '-' + timezone;
    else if(time.getTimezoneOffset() == 0)
	timezone  = 'Z';
    else
	timezone = '';

    var time_link = '<a href="http://twitter.com/' + tweet['user']['screen_name'] +'/status/' + tweet['id_str'] + '">' + time.getFullYear() + '-' + zeroPad(time.getMonth()+1) + '-' + zeroPad(time.getDate()) + ' ' + zeroPad(time.getHours()) + ':' + zeroPad(time.getMinutes()) + timezone + '</a>';

    return '<div class="tweet"><p class="text">' + content + ' <span class="time">' + time_link + '</span></p></div>';
}

function replaceContent(content, newString, indices)
{
    var oldLen = indices[1] - indices[0];
    var replaceLen = newString.length;
    var nextIndex = indices[0];
    
    for(i in indexOffsets)
	{
	    if(indexOffsets[i][0] < nextIndex)
		nextIndex = nextIndex + indexOffsets[i][1];
	}

    window.indexOffsets.push( [nextIndex, (replaceLen - oldLen)] );

    return content.substr(0, nextIndex) + newString + content.substr(nextIndex+oldLen);
}

function zeroPad(number)
{
    if(number < 10)
	return '0'+number;
    return number;
}

