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-_]+/g, function (t) {
        var tag = t.replace("#", "%23")
        return t.link("http://search.twitter.com/search?q=" + tag);
    });
};

function PadDigits(n, totalDigits)
    {
        n = n.toString();
        var pd = '';
        if (totalDigits > n.length)
        {
            for (i=0; i < (totalDigits-n.length); i++)
            {
                pd += '0';
            }
        }
        return pd + n.toString();
    }

function fetch_tweets(elem,firstcall) {
    elem = $(elem);
    input = elem.attr('title');
    lang = elem.attr('lang');

    

    var count = 0;
    var rpp;
    var divstr;

    if (input != window.twitterwall['text-' + input]) {
        window.twitterwall['last_id' + input] = 0;
        window.twitterwall['text-' + input] = input;
        window.twitterwall['count-' + input] = 12;
    }

    if (window.twitterwall['count-' + input] > 10) {
        window.twitterwall['count-' + input] = 0;
    }

    if( firstcall == 1 ){
        rpp = 15;
    }else{
        rpp = 50;
    }

    var url = "http://search.twitter.com/search.json?lang=all&q=%23" + input + "&rpp=" + rpp + "&since_id=" + window.twitterwall['last_id' + input] + "&callback=?";

    var search = $('.tweets:first').attr('title');

    $.getJSON(url, function (json) {

        if( firstcall == 1 ){

            var count_url = "twittercount.php?search=" + input;

            $.get( count_url
                        , null,
                          function(data){
                            window.twitterwall['mycount-' + input] = ( parseInt( data ) - rpp );
                            $('#twcountercontent').html( window.twitterwall['mycount-' + input] );
                            document.title = '(' + window.twitterwall['mycount-' + input] + ') GreenAction Twitterwall';
                          });

        }

        $(json.results).reverse().each(function () {
            if ( $('#' + this.id, elem).length == 0  && this.text !== undefined ) {

                count++;

                window.twitterwall['count-' + input]++;

                

                var thedate = new Date(Date.parse(this.created_at));
                var thedatestr = PadDigits( thedate.getHours() , 2 ) + ':' + PadDigits( thedate.getMinutes() , 2 );
                window.twitterwall['last_id' + input] = this.id;

                //if( firstcall == 1 ){
                //    divstr = '<li id="' + this.id + '" style="height: 58px"><div><img width="48" height="48" src="' + this.profile_image_url + '" alt="" /><p>' + this.text.linkify().linkuser().linktag() + '<br /><a href="http://twitter.com/' + this.from_user + '">' + this.from_user + '</a> &middot; <span><a href="#">' + thedatestr + '</a></span></p></div></li>'

                //}else{
                    divstr = '<li id="' + this.id + '" style="display:none; height: 58px" class="hiddentweet"><div style="display:none;"><img width="48" height="48" src="' + this.profile_image_url + '" alt="" /><p>' + this.text.linkify().linkuser().linktag() + '<br /><a href="http://twitter.com/' + this.from_user + '">' + this.from_user + '</a> &middot; <span><a href="#">' + thedatestr + '</a></span></p></div></li>'

                //}

                tweetsCount( this.id , search );
                

                elem.find('ul').prepend(divstr);

            }
        });

        input = escape(input);

        setTimeout(function () {
                fetch_tweets(elem,0)
            },
            7000);
    });

    return (false);

}

function tweetsInOut(){


    $('.hiddentweet:last').each( function(){

        $(this).removeClass('hiddentweet').addClass('showtweet').slideDown( 900 , function(){
            
            $(this).find('div').fadeIn('slow');
            window.twitterwall['mycount-' + input]++;
            $('#twcountercontent').html( window.twitterwall['mycount-' + input] );
            document.title = '(' + window.twitterwall['mycount-' + input] + ') GreenAction Twitterwall';


        },'easeInOutCirc' );

        var count = 0;

        $('.showtweet').each(
            function(){
                count++;
                if( count > 15 ){
                    $(this).remove();
                }
            }
        );

    });

    setTimeout(function () {
          tweetsInOut()
    },1200);


}

function tweetsCount( tid , search ){

    var count_url = "twittercount.php?type=getcount&id="
                                            + $.md5( tid + ' ' + search )
                                            + "&tid=" + tid
                                            + "&search=" + search;

    $.get( count_url, null);
    

}

$(document).ready(function () {
    tweetsInOut();
    window.twitterwall = {};
    $('.tweets').each(function (e) {
        rrp = 50;
        fetch_tweets(this , 1 );
        
    });
});
