(function( $ ){
    $.fn.mTwitter = function ( opcoes ) {

        var parametros = {
            avatar : true,
            profileLink: true,
            titulo: "Meus twittes",
            altura: 500,
            largura: 250
        };

        var imagem = null;
        $(this).addClass("mTwitter");
        $(this).html('');
        $(this).css({width : parametros.largura, height : parametros.altura});

        $(this).append("<div id='topo'></div>");
        $(this).append("<div id='lista'></div>");
        $(this).append("<div id='rodape'></div>");

        return this.each(function(){
            //faz o merge entre as opções enviadas e os parametros
            if(opcoes){
                $.extend(parametros, opcoes)
            }

            var $lista = $("#lista", this);
            var $topo = $("#topo", this);
            var $rodape = $("#rodape", this);


            
            $lista.html("<img id='loading' src='mTwitter/imagens/loading.gif' />");
            $lista.height(50);

            //executa a consulta ao twitter
            $.getJSON("http://twitter.com/status/user_timeline/" + parametros.usuario + ".json?count=" + parametros.quantidade + "&callback=?",
            function(data){
                $lista.html('');
                $lista.hide();
                $lista.height(parametros.altura - $topo.height() - $rodape.height());
                $.each(data, function(i, post) {
                    $lista.append("<div class='tweet'><span class='txt'>"+formatTwitString(post.text) + "</span>\n\
<span class='time'>" + relativeTime(post.created_at)+"</span></div>");

                    if (!imagem) imagem = post.user.profile_image_url;
                });
                
                (parametros.avatar && imagem)?$topo.append("<img id='avatar' src='" + imagem + "'/>") : $topo.append("<img id='avatar' src='mTwitter/imagens/at-twitter.png'/>");
                
                $lista.slideDown('slow', function(){
                    $lista.jScrollPane({verticalDragMinHeight: 10,
                                        verticalDragMaxHeight: 10
                    });
                });
                

                
                
            });

            $topo.append("<span id='titulo'>" + parametros.titulo + "</span>");
            

            (parametros.profileLink)?$rodape.append("<a href='http://twitter.com/" + parametros.usuario + "' >" + parametros.usuario + "</a>"):$rodape.append(paremetros.usuario);


           
            
            
            
        });

    }


})( jQuery );

function formatTwitString(str){
    // This function formats the tweet body text

    str=' '+str;

    str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
    // The tweets arrive as plain text, so we replace all the textual URLs with hyperlinks

    str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
    // Replace the mentions

    str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
    // Replace the hashtags

    return str;
}

function relativeTime(pastTime){
    // Generate a JavaScript relative time for the tweets

    var origStamp = Date.parse(pastTime);
    var curDate = new Date();
    var currentStamp = curDate.getTime();
    var difference = parseInt((currentStamp - origStamp)/1000);

    if(difference < 0) return false;

    if(difference <= 5)          return "Ainda agora";
    if(difference <= 20)         return "Há segundos";
    if(difference <= 60)         return "Há um minuto";
    if(difference < 3600)        return "Há " + parseInt(difference/60)+" minutos";
    if(difference <= 1.5*3600)   return "Há uma hora";
    if(difference < 23.5*3600)   return "Há " + Math.round(difference/3600)+" horas";
    if(difference < 1.5*24*3600) return "Há um dia";

    // If the tweet is older than a day, show an absolute date/time value;

    var dateArr = pastTime.split(' ');

    return dateArr[4].replace(/\:\d+$/,'')+' '+dateArr[2]+' '+dateArr[1]+
    (dateArr[3]!=curDate.getFullYear()?' '+dateArr[3]:'');
}
