﻿var userName = 'westfieldhealth';
var count = 2;

$(document).ready(function() {
    getTweets(userName, count);
});

function getTweets(userName, count) {
    $.getJSON(
					    'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' + userName + '&count=' + count + '&callback=?',
					    {},
					    showTweets,
					    'jsonp'
				    );
}

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, "<a href='$1'>$1</a>");
}

function showTweets(tweets) {
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var str = '<div>';
    //str += '<h2>Tweets from ' + userName + '</h2>';//
    var i = 0;
    $.each(tweets, function(index, value) {
        if (i == count) return;
        var dt = new Date(value.created_at);
        str += '<div class="tweet"><p>';
        str += replaceURLWithHTMLLinks(value.text);
        str += '</p>';
        str += '<p>';
        //str += '<a href=\'http://twitter.com/' + userName + '\'>' + dt.getDate() + ' ' + months[dt.getMonth()] + ' ' + dt.getFullYear() + '</a>';
        str += '</p></div>';
        if (i == 0) {
            str += '<div class="tweetbottoml"></div>';
        }
        else {
            str += '<div class="tweetbottomr"></div>';
        }
        i++;
    });
    str += '</div>';
    $('#tweets').html(str);
}
