jQuery.fn.reverse = Array.prototype.reverse;
String.prototype.linkify = function()
 {
    return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g,
    function(m)
    {
        return m.link(m);
    });
};
String.prototype.linkuser = function()
 {
    return this.replace(/[@]+[A-Za-z0-9-_]+/g,
    function(u)
    {
        var username = u.replace("@", "")
        return u.link("http://twitter.com/" + username);
    });
};
String.prototype.linktag = function()
 {
    return this.replace(/[#]+[A-Za-z0-9-_]+/,
    function(t)
    {
        var tag = t.replace("#", "%23")
        return t.link("http://search.twitter.com/search?q="+tag);
    });
};
function fetchA(node) {
   for(var i=0; i<node.childNodes.length; i++) {
    var child = node.childNodes[i];
    if(child.href) {
     child.target = "_blank";
    }
    fetchA(child);
   }
  }
function fetch_tweets(elem)
 {
    elem = $(elem);
    input = elem.attr('title');
    lang = elem.attr('lang');
    if (input != window.twitterwidget['text-' + input])
    {
        window.twitterwidget['last_id' + input] = 0;
        window.twitterwidget['text-' + input] = input;
        window.twitterwidget['count-' + input] = 12;;
    }
    var url = "http://search.twitter.com/search.json?q=" + input + "&lang=" + lang + "&rpp=" + rrp + "&since_id=" + window.twitterwidget['last_id' + input] + "&callback=?";
    $.getJSON(url,
    function(json)
    {
        $('div.tweet:gt(' + window.twitterwidget['limit'] + ')', elem).each(function() {
            $(this).fadeOut('slow')
        });
        $(json.results).reverse().each(function()
        {
            if ($('#tw' + this.id, elem).length == 0)
            {
                window.twitterwidget['count-' + input]++;
                var thedate = new Date(Date.parse(this.created_at));
                var thedatestr = thedate.getHours() + ':' + thedate.getMinutes();
                var divstr = '<div id="tw' + this.id + '" class="tweet"><p style="margin-top: 0;">' + this.text.linkify().linkuser().linktag() + '</p></div>';
                window.twitterwidget['last_id' + input] = this.id;
                elem.prepend(divstr);
                $('#tw' + this.id, elem).hide();
                $('#tw' + this.id + ' img', elem).hide();
                $('#tw' + this.id + ' img', elem).fadeIn(4000);
                $('#tw' + this.id, elem).fadeIn(800);
				
				fetchA(document.getElementById("tw" + this.id));
            }
        });
        input = escape(input);
        rrp = 1;
        setTimeout(function() {
            fetch_tweets(elem)
        },
        10000);
    });
    return (false);
}
$(document).ready(function() {
    window.twitterwidget = {};
    $('.twitterwidget').each(function(e) {
        rrp = 1;
        fetch_tweets(this);
    });
});