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).replace(/href/,'target="_blank" href');
    });
};
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).replace(/href/,'target="_blank" href');
    });
};
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).replace(/href/,'target="_blank" href');
    });
};
function relative_time(parsed_date) {
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	//delta = delta - (relative_to.getTimezoneOffset() * 60);
	if (delta < 60) return 'less than a minute ago';
	else if(delta < 120) return 'about a minute ago';
	else if(delta < (45*60)) return (parseInt(delta / 60)).toString() + ' minutes ago';
	else if(delta < (90*60)) return 'about an hour ago';
	else if(delta < (24*60*60)) {
		h = (parseInt(delta / 3600)).toString()
		if(h == 1) return 'about ' + h + ' hour ago';
		else return 'about ' + h + ' hours ago';
	} else if(delta < (48*60*60)) return '1 day ago';
	else return (parseInt(delta / 86400)).toString() + ' days ago';
}

function fetch_tweets(elem) {
    elem = $(elem);
    input = elem.attr('title');
    lang = elem.attr('lang');
    if (input != window.monitter['text-' + input]) {
        window.monitter['last_id' + input] = 0;
        window.monitter['text-' + input] = input;
        window.monitter['count-' + input] = 12;;
    }
    if (window.monitter['count-' + input] > 10) {
        window.monitter['count-' + input] = 0;
    }
    var url = "http://search.twitter.com/search.json?q=" + input + "&lang=" + lang + "&rpp=" + rrp + "&since_id=" + window.monitter['last_id' + input] + "&callback=?";
    $.getJSON(url,
    function(json) {
        $('div.tweet:gt(' + window.monitter['limit'] + ')', elem).each(function() {
            $(this).fadeOut('slow')
        });

        $(json.results).reverse().each(function() {
            if ($('#tw' + this.id, elem).length == 0) {
                window.monitter['count-' + input]++;
                var thedatestr = relative_time(new Date(Date.parse(this.created_at)))
//alert(thedatestr+' '+this.created_at);
                var divstr = '<div id="tw' + this.id + '" class="tweet"><img width="73" height="73" src="' + this.profile_image_url.replace('_normal', '_bigger') + '" ><p class="text">' + this.text.replace(/^@shortyawards/, '').linkify().linkuser().linktag() + '&nbsp;<br /><span class="user_time">Posted by <a href="http://twitter.com/' + this.from_user + '" target="_blank">' + this.from_user + '</a>&nbsp;<b title="' + this.created_at + '">' + thedatestr + '</b></span></p></div>';
                window.monitter['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('slow');
            }
        });
	$("b").each(function() { 
		$(this).html(relative_time(new Date(Date.parse($(this).attr('title')))));
        });

        input = escape(input);
        rrp = 1;
        setTimeout(function() {
            fetch_tweets(elem)
        },
        60000);
    });
    return (false);
}
$(document).ready(function() {
    window.monitter = {};
    $('.monitter').each(function(e) {
        rrp = 50;
        fetch_tweets(this);
    });
});

