function displayTweets(data) {
    var el;
    var tweets = document.getElementById('tweets');
    tweets.innerHTML = '';
    for (d in data.results) {
        el = document.createElement('li');
        tweets.appendChild(el);
        el.innerHTML = '<a href="http://twitter.com/' + data.results[d].from_user + '"><img src="' + data.results[d].profile_image_url + '" alt="' + data.results[d].from_user + '"/></a><p><img src="/img/bubble.png" alt="Speech Bubble"/>' + linkify(data.results[d].text) + '<span class="time"> ' + friendlyTime(data.results[d].created_at) + '</span></p>';
    }
    var el = document.createElement('li');
    el.innerHTML = '<a href="http://twitter.com/search?q=%23antietam+OR+antietam">View more updates&nbsp;&raquo;</a>';
    tweets.appendChild(el);
}
function refreshTwitter() {
    var el = document.getElementById('jsonp');
    if (el) {
        document.body.removeChild(el);
    }
    el = document.createElement('script');
    el.id='jsonp';
    el.type='text/javascript';
    el.src='http://search.twitter.com/search.json?callback=displayTweets&q=%23antietam+OR+antietam&result_type=recent&rpp=4';
    document.body.appendChild(el);
}
function linkify(input) {
    var regexps = [
        { 'prepend': '', 'regexp': /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/g, 'replace': '$&' },
        { 'prepend': 'http://twitter.com/', 'regexp': /@([a-zA-Z0-9_]+)/g, 'replace': '$1' },
        { 'prepend': 'http://twitter.com/search?q=%23', 'regexp': /#([a-zA_Z0-9_]+)/g, 'replace': '$1' }
    ];

    for (r in regexps) {
        input = input.replace(regexps[r].regexp, '<a href="' + regexps[r].prepend + regexps[r].replace +'">$&</a>');
    }
    return input;
}
function friendlyTime(timeString) {
    var now = new Date;
    var then = new Date(timeString);
    var offset = now.getTime() - then.getTime();
    var output = 'a long time';
    offset = Math.round(offset / 60000);
    if (offset == 0) { output = 'less than a minute'; }
    else if (offset < 60) { output = Math.round(offset) + ' minute' + (offset == 1 ? '' : 's'); }
    else if (offset < 1440) { output = 'about ' + Math.round(offset / 60) + ' hour' + (offset < 120 ? '' : 's'); }
    else if (offset < 44640) { output = 'about ' + Math.round(offset / 1440) + ' day' + (offset < 2880 ? '' : 's'); }
    else { output = 'about ' + Math.round(offset / 44640) + ' month' + (offset < 89280 ? '' : 's'); }
    return output + ' ago';
}
jQuery(document).ready(function () {
    refreshTwitter();
    setInterval(refreshTwitter, 60 * 1000);
});

