﻿function objTweet(strText, strTime, strAuthor, strID) {
    this.strText = strText;
    this.strTime = strTime;
    this.strAuthor = strAuthor;
    this.strID = strID;
    // Methods
    this.mtdReplaceText = mtdReplaceText;
    this.mtdReturnTime = mtdReturnTime;
    this.mtdWriteHTML = mtdWriteHTML;
}

function mtdReplaceText() {
    this.strText = this.strText.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function (strURL) {
        return "<a href=\"" + strURL + "\">" + strURL + "</a>";
    }).replace(/\B@([_a-z0-9]+)/ig, function (strReply) {
        return strReply.charAt(0) + "<a href=\"http://twitter.com/" + strReply.substring(1) + "\">" + strReply.substring(1) + "</a>";
    });
}

function mtdReturnTime() {
    var arrValues = this.strTime.split(" ");
    var dteTime = Date.parse(arrValues[1] + " " + arrValues[2] + ", " + arrValues[5] + " " + arrValues[3]);
    var dteNow = (arguments.length > 1) ? arguments[1] : new Date();
    var intMinutes = parseInt((dteNow.getTime() - dteTime) / 1000);
    intMinutes = intMinutes + (dteNow.getTimezoneOffset() * 60);
    if (intMinutes < 60) {
        return "less than a minute ago";
    }
    else if (intMinutes < 120) {
        return "about a minute ago";
    }
    else if (intMinutes < (60 * 60)) {
        return (parseInt(intMinutes / 60)).toString() + " minutes ago";
    }
    else if (intMinutes < (120 * 60)) {
        return "about an hour ago";
    }
    else if (intMinutes < (24 * 60 * 60)) {
        return "about " + (parseInt(intMinutes / 3600)).toString() + " hours ago";
    }
    else if (intMinutes < (48 * 60 * 60)) {
        return "1 day ago";
    }
    else {
        return (parseInt(intMinutes / 86400)).toString() + " days ago";
    }
}

function mtdWriteHTML() {
    this.mtdReplaceText();
    var strOutput = "<p>" + this.strText + "</p>";
    strOutput += "<span><strong>" + this.mtdReturnTime() + " by</strong> <a href=\"http://twitter.com/" + this.strAuthor + "\">@" + this.strAuthor + "</a></span>";
    return strOutput;
}

function ftnTwitterCallback(arrRawTweets) {
    var arrTweets = new Array();
    for (a = 0; a < arrRawTweets.length; a++) {
        arrTweets[a] = new objTweet(arrRawTweets[a].text, arrRawTweets[a].created_at, arrRawTweets[a].user.screen_name, arrRawTweets[a].user.id_str);
    }
    if (arrTweets.length > 0) {
        var intCount = 0;
        $(".Tweet").each(function () {
            if (intCount == 0) {
                $(this).html("<h2>Tweet</h2>" + arrTweets[intCount].mtdWriteHTML());
            }
            else if (arrTweets.length > 1) {
                $(this).html(arrTweets[intCount].mtdWriteHTML());
            }
            intCount++;
        });
    }
}

$.getScript("http://twitter.com/statuses/user_timeline/" + strTwitterUsername + ".json?callback=ftnTwitterCallback&count=3");
