﻿function initTweets(elementId, searchPhrase, maxCount, refreshTimeout) {
    loadTweets(elementId, searchPhrase, maxCount)
    setInterval(function() { loadTweets(elementId, searchPhrase, maxCount); }, refreshTimeout);
}

function loadTweets(elementId, searchPhrase, maxCount) {
    var lastTweetId = $("#" + elementId + " .tweet:first").attr("ID");

    var url = "http://search.twitter.com/search.json?q=" + URLEncode(searchPhrase) + "&result_type=recent";
    if (lastTweetId) {
        lastTweetId = lastTweetId.replace("tweet", "");
        url += "&since_id=" + lastTweetId;
    } else {
        url += "&rpp=" + maxCount;
    }
    url += "&callback=?";

    $.getJSON(url, function(json) {
        var results = '';
        $(json.results).each(function() {
            if (this.id == undefined) return;
            results += "<li class='tweet' id='tweet" + this.id + "'><a href='http://twitter.com/" + this.from_user + "' class='imageLink'>" +
			           "<img alt='" + this.from_user + " on Twitter' src='" + this.profile_image_url + "' /></a>" +
			           "<span class='content'><a href='http://twitter.com/" + this.from_user + "' class='textLink'>" + this.from_user + "</a> " +
			           linkify(this.text) +
			           "<span class='time'>" + relativeTime(this.created_at) + " via " + htmlDecode(this.source) + "</span></span></li>";
        });
        $("#" + elementId).prepend(results);

        $("#" + elementId + " .tweet:gt(" + (maxCount - 1) + ")").remove();
    });
}

function htmlDecode(text) {
    return $('<div/>').html(text).text()
}

function htmlEncode(text) {
    return $('<div/>').text(text).html()
}

function linkify(text) {
    // modified from TwitterGitter by David Walsh (davidwalsh.name)
    // courtesy of Jeremy Parrish (rrish.org)
    return text.replace(/(https?:\/\/[\w\-:;?&=+.%#\/]+)/gi, '<a href="$1">$1</a>')
               .replace(/(^|\W)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>')
               .replace(/(^|\W)#(\w+)/g, '$1#<a href="http://search.twitter.com/search?q=%23$2">$2</a>');
}

function URLEncode(clearString) {
    // From http://cass-hacks.com/articles/code/js_url_encode_decode/
    var output = '';
    var x = 0;
    clearString = clearString.toString();
    var regex = /(^[a-zA-Z0-9_.]*)/;
    while (x < clearString.length) {
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != '') {
            output += match[1];
            x += match[1].length;
        } else {
            if (clearString[x] == ' ')
                output += '+';
            else {
                var charCode = clearString.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
            }
            x++;
        }
    }
    return output;
}

function relativeTime(pastTime) {
    var origStamp = Date.parse(pastTime);
    var cDate = new Date();
    var currentStamp = cDate.getTime();

    var difference = parseInt((currentStamp - origStamp) / 1000);

    if (difference < 0) return false;

    if (difference <= 5) return "Just now";
    if (difference <= 20) return "Just Seconds ago";
    if (difference <= 60) return "A minute ago";
    if (difference < 3600) return parseInt(difference / 60) + " minutes ago";
    if (difference <= 1.5 * 3600) return "One hour ago";
    if (difference < 23.5 * 3600) return Math.round(difference / 3600) + " hours ago";
    if (difference < 1.5 * 24 * 3600) return "One day ago";

    var days = difference / (1.5 * 24 * 3600);

    if (days <= 10) {
        return Math.round(days) + " days ago";
    }
    else {
        var dateArr = pastTime.split(' ');


        var t = dateArr[4].split(":");
        var time_format = "";
        if (parseInt(t[0]) > 12) {
            var a = parseInt(t) - 12
            time_format = dateArr[2] + " " + dateArr[1] + " " + a + ":" + t[1] + " PM";
        }
        else {
            var first = "";
            if (t[0].substring(0, 1) == "0") {
                first = t[0].substring(1, 2);
            }
            else {
                first = t[0];
            }

            time_format = dateArr[2] + " " + dateArr[1] + " " + first + ":" + t[1] + " AM";
        }

        return time_format;
    }

}
