(function ($) {
    var scrollY; $.fn.readTweet = function (options) {
        var settings = { 'search': 'from:twitter', 'user': 0, 'width': 0, 'tweets': 20, 'speed': 20 };
        return this.each(function () {
            if (options) {
                $.extend(settings, options);
            }
            $(this).html('<div class="rtwrapper"><div class="rtstage"><div class="rtfadeleft"></div><div class="rtfaderight"></div><div class="rtscroller"></div></div></div>');
            readTweet = $(this).children('.rtwrapper');
            rtScroller = readTweet.children().children('.rtscroller');
            if (settings['width']) {
                readTweet.width(settings['width']);
            }
            readTweet.children('.rtstage').width(readTweet.width());
            readTweet.children('.rtstage').children('.rtfaderight').css('marginLeft', readTweet.children('.rtstage').width() - readTweet.children('.rtstage').children('.rtfaderight').width());
            totalWidth = 0;
            var url = 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' + settings['user'] + '&count=' + settings['tweets'] + '&callback=?';
            $.getJSON(url, function (data) {
                $.each(data, function (i, item) {
                    twitterUrl = 'http://twitter.com/' + item.user.screen_name;
                    message = item['text'].replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
                    message = message.replace(/(^|\s)@(\w+)/g, "$1<a href='http://www.twitter.com/$2' target='_blank'>@$2</a>");
                    message = message.replace(/(^|\s)#(\w+)/g, "$1<a href='http://search.twitter.com/search?q=%23$2' target='_blank'>#$2</a>");
                    htmlCode = '<div class="rttweet"><div class="rtavatar"><a href="' + twitterUrl + '" target="_blank"><img src="' + item.user.profile_image_url + '"/></a></div><div class="rtinfo"><div class="rttop"><div class="rtname"><a href="' + twitterUrl + '" target="_blank">' + item.user.screen_name + '</a></div><div class="rtdate">' + Format.RelativeTime(item.created_at) + '</div></div><div class="rtmessage">' + message + '</div></div></div>';
                    rtScroller.append(htmlCode);
                    rttop = rtScroller.children(':last').children().children('.rttop');
                    rttop.width(rttop.children('.rtname').outerWidth(true) + rttop.children('.rtdate').outerWidth(true) + 10);
                    totalWidth += rtScroller.children(':last').width();
                })
                rtScroller.hide();
                rtScroller.width(totalWidth);
                speed = (41 - settings['speed']) * 100;
                rtScroller.css('marginLeft', 100);
                scrollY = 100;
                rtScroller.fadeIn(500);
                rtScroller.rtScroll();
                rtScroller.hover(function () {
                    rtScroller.rtPause(1);
                }, function () {
                    rtScroller.rtPause(0);
                });
            });
        })
    };
    var Format = {
        ParseDate: function (dateStr) {
            return Date.parse(dateStr.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
        },
        RelativeTime: function (dateTimeValue) {
            var parsedDate = Format.ParseDate(dateTimeValue);
            var relativeTo = (arguments.length > 1) ? arguments[1] : new Date();
            var difference = parseInt((relativeTo.getTime() - parsedDate) / 1000);
            var postMessage = "";
            if (difference < 5)
                postMessage = "neste momento"
            else
                if (difference <= 1.5 * 60)
                    postMessage = "h&#225; um minuto"
                else
                    if (difference < 3600)
                        postMessage = "h&#225; " + Math.round(difference / 60) + " minutos"
                    else
                        if (difference <= 1.5 * 3600)
                            postMessage = "h&#225; uma hora"
                        else
                            if (difference < 23.5 * 3600)
                                postMessage = "h&#225; " + Math.round(difference / 3600) + " horas"
                            else
                                if (difference < 1.5 * 24 * 3600)
                                    postMessage = "h&#225; um dia"
                                else
                                    if (difference > 1.5 * 24 * 3600)
                                        postMessage = "h&#225; " + Math.round(difference / 3600 / 24) + " dias";
            return "Postado " + postMessage;
        }
    }
    $.fn.rtScroll = function () {
        scrollY -= 100; rtScroller = $(this);
        rtScroller.animate({ marginLeft: scrollY }, speed, 'linear', function () { $(this).rtOverflow(); });
    }
    $.fn.rtOverflow = function () {
        rtScroller = $(this);
        rtTarget = $(this).children(':first');
        if (-scrollY > rtTarget.width()) {
            scrollY += rtTarget.width();
            rtScroller.css('marginLeft', scrollY);
            rtScroller.append('<div class="rttweet">' + $(this).children(':first').html() + '</div>');
            rtTarget.remove();
        }
        $(this).rtScroll();
    }
    $.fn.rtPause = function (mouseOver) {
        if (mouseOver == '1') {
            rtScroller = $(this);
            rtScroller.stop();
            scrollY = parseInt(rtScroller.css('marginLeft'));
        }
        else {
            rtScroller.rtScroll();
        }
    }
})(jQuery);

