﻿var lastID = '';
var tweetsTimeOut;
var n = 6;
var toShow = 6;

function getTweets(id) {
    $.ajax({
        type: "POST",
        url: "/ajax.asmx/GetTweets",
        data: "{'id':'" + id + "','n':'" + n + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $.eachDelay(eval(msg.d), function (count, item) {

                addTweet(item);
                //console.log(item.TweetScreenName);

            }, 300);
        },
        error: function () {
            $("#tweets ul").append("<li>Error returning tweets</li>");
        }
    });
    n = 3; // set back to get only 3 at a time after initially filling up with all 6
}

var itemCount = 0;

function addTweet(item) {

    if ($("#tweets ul li").length == toShow) {
        $("#tweets ul li:last").remove();
    }

    var html;
    html += "<li>";
    html += "<span class='tweet'>" + replaceURLWithHTMLLinks(item.TweetText) + "</span>";
    html += "<br/><span class='author'><a href='http://twitter.com/" + item.TweetScreenName + "' target='_blank'>" + item.TweetScreenName + "</a></span>";
    html += "<br/><span class='date'>" + $.timeago(item.TweetCreated) + "</span>";
    html += "</li>";

    $(html).hide().prependTo("#tweets ul").fadeIn(300);
    lastID = item.TweetID;
}

function pollTweets() {
    getTweets(lastID);
}

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    text = text.replace(exp, "<a href='$1' target='_blank'>$1</a>");
    text = text.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
		var username = u.replace("@","")
		return "<a href='http://twitter.com/" + username + "' target='_blank'>" + u + "</a>";
});
    text = text.replace(/[#]+[A-Za-z0-9-_]+/g, function (t) {
        var tag = t.replace("#", "%23")
        return "<a href='http://search.twitter.com/search?q=" + tag + "' target='_blank'>" + t + "</a>";
    });
    return text;
}

//$(function () {

//poll();
    pollTweets();
    setInterval("pollTweets();", 20000);

    //    $("#stop").click(function () {
    //        clearTimeout(timeOut);
    //        return false;
    //    });

    //    $("#start").click(function () {
    //        poll();
    //        return false;
    //    });

//});
