var timer;
var twitterUrl = "http://search.twitter.com/search.json";
var searchtype = "?q=%23" //Hash tag
var keyword = "sibos"; //This is the search string
var numberOfResultsReturned = 3; //This is the number of tweets to display
var timerDelay = inSeconds(10); //Set timer. Can be set inSeconds(addSeconds)
var url = twitterUrlBuilder(twitterUrl, searchtype, keyword, numberOfResultsReturned);


$(function(document) {
    $('#loading').append('<img src="/externalevents/assets/spinner.gif" /> Loading');
   
    $('.twitStream').each(function() {
        fetch_tweets(true);  
    });
});

function twitterUrlBuilder(mainUrl, b, c, d) {
    return mainUrl + b + c + "&rpp=" + d + "&callback=?";
};

function inSeconds(val) {
    return val * 1000;
};

function createTimer() {
    timer =
        setTimeout(function() {
        $('#loading').show();
        $('#loading').append('<img src="/externalevents/assets/spinner.gif" /> Updating');
            fetch_tweets(false);
        }, timerDelay);
};

function clearLoading() {
    $('#loading').fadeOut("fast", function() {
        $('#loading').empty();
    });
};

function clearTweets() {
    $('#loading').empty();
};

function clearSpecific(id) {
    $('.twitStream').empty();
};

function buildNewTweet(content, id) {
    $('#' + id).prepend(content);
};

function moveTweetsDown(id) {
    $('#' + id).show("slide", { direction: "up" }, 1000);
};

function generateRandomDivId() {
    return Math.floor(Math.random() * 1000000000000000);  
};

function fetch_tweets(isFirst) {

    elem = $('.twitStream');

    var randomNum = generateRandomDivId();

    $('.twitStream').prepend("<div id=" + randomNum + " style='displayed:none;'></div>");

    $.getJSON(url,
    function(data) {
        clearLoading();
        url = twitterUrlBuilder(twitterUrl, "", data.refresh_url, numberOfResultsReturned);

        $(data.results).each(function() {

            var tTime = new Date(Date.parse(this.created_at));
            var cTime = new Date();
            var sinceMin = Math.round((cTime - tTime) / 60000);
            if (sinceMin == 0) {
                var sinceSec = Math.round((cTime - tTime) / 1000);
                if (sinceSec < 10)
                    var since = 'less than 10 seconds ago';
                else if (sinceSec < 20)
                    var since = 'less than 20 seconds ago';
                else
                    var since = 'half a minute ago';
            }
            else if (sinceMin == 1) {
                var sinceSec = Math.round((cTime - tTime) / 1000);
                if (sinceSec == 30)
                    var since = 'half a minute ago';
                else if (sinceSec < 60)
                    var since = 'less than a minute ago';
                else
                    var since = '1 minute ago';
            }
            else if (sinceMin < 45)
                var since = sinceMin + ' minutes ago';
            else if (sinceMin > 44 && sinceMin < 60)
                var since = 'about 1 hour ago';
            else if (sinceMin < 1440) {
                var sinceHr = Math.round(sinceMin / 60);
                if (sinceHr == 1)
                    var since = 'about 1 hour ago';
                else
                    var since = 'about ' + sinceHr + ' hours ago';
            }
            else if (sinceMin > 1439 && sinceMin < 2880)
                var since = '1 day ago';
            else {
                var sinceDay = Math.round(sinceMin / 1440);
                var since = sinceDay + ' days ago';
            }
            var isDisplay = "block";
            if (isFirst == true) {
                isDisplay = "block";
            }

            var tweet = '<div class="tweet" id="' + this.id + '" style="display:' + isDisplay + '"><div class="tweet-left"><a target="_blank" href="http://twitter.com/'
            + this.from_user
            + '"><img width="48" height="48" alt="'
            + this.from_user
            + ' on Twitter" src="'
            + this.profile_image_url
            + '" /></a></div><div class="tweet-right"><div class="text">'
            + '<div class="name"><a target="_blank" href="http://twitter.com/'
            + this.from_user
            + '">'
            + this.from_user
            + '</a></div>'
            + this.text
            + '<br />'
            + since
            + '<br />'
            + '</div></div><br style="clear: both;" /></div>';

            if (isFirst == true) {
                elem.append(tweet);
            }
            else {
                buildNewTweet(tweet, randomNum);
            }
        });
        moveTweetsDown(randomNum);
    });
    createTimer();
    return (false);
}
