﻿var timer = null, last = null;
function processTweets(tweets) {
    function show(el) { el.fadeIn("slow", function() { show(el.next("div")); }); }
    var host = $("#tweet");
    function addTweet(tweet, host) {
        host.append("<div></div>"); var el = host.children("div:last"); el.hide();
        el.html(tweet.t.replace(/https?:[^\s]+/gi, "<a href=\"$&\" target=\"_blank\">$&</a>").
            replace(/@([a-z0-9_]+)/gi, "<a href=\"http://twitter.com/$1\" target=\"twitter\">$&</a>"));
        el.append("<br/>"); el.append("<span></span>"); el.children("span").text(tweet.d); return el;}
    function showNext(tweet) { show(addTweet(tweet, host)); }
    if ( last != null ) {
        last += 1; if (last >= tweets.length) last = 0;
        var el = host.children("div:first"); el.fadeTo("slow", 0.01, function() { el.hide("slow", function() { el.remove(); showNext(tweets[last]); }); });
    }
    else {
        last = Math.min(2, tweets.length - 1);
        for (var i = 0; i <= last; i++) { addTweet(tweets[i], host); }
        host.animate({ "height": "+=190px" }, "slow", function() { show(host.children("div:first")); });
        if (timer!=null) { ; } else { timer = window.setInterval(function() { processTweets(tweets); }, 10000); }
    }
}
function getTweets() {
    if ("$" in window) {
        $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", async: true,
            dataType: "json", url: "Tweets.asmx/GetTweet", data: "{}",
            dataFilter: function(data) { var R = /(<.*?>)/g; data = data.replace(R, ""); return data; },
            success: function(d) { if (timer) { window.clearInterval(timer); timer = null; } if (last != null) { last = -1; }; processTweets(d); }, fail: function(s) { ; }
        });
        // window.setInterval(getTweets, 30000);
    }
    else {
        var t = window.setTimeout(function() { window.clearTimeout(t); getTweets(); }, 1000);
    }
}; getTweets();

