﻿(function ()
{
    if (typeof jQuery === 'undefined')
    {
        setTimeout(arguments.callee, 100);
        return;
    }

    $ = jQuery;

    // Konstante
    var container = $("#TweetContainer");
    var currPage = 1;
    var pageSize = 2;
    var fadeTimeout = 250;
    var maxPage = 5;
    var interval = null;

    $(document).ready(function ()
    {
        $.ajax(
        {
            url: 'http://api.twitter.com/1/statuses/user_timeline.json?user_id=187935359',
            dataType: 'jsonp',
            success: createTweets
        });
    });

    function createTweets(data)
    {
        function getParsedDate(dateStr)
        {
            function padleft(val, ch, num)
            {
                var re = new RegExp(".{" + num + "}$");
                var pad = "";
                if (!ch) ch = " ";
                do
                {
                    pad += ch;
                } while (pad.length < num);
                return re.exec(pad + val)[0];
            }

            var created = new Date(dateStr.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/, "$1 $2 $4 $3 UTC"));

            var days = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
            var months = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];

            var text = '{0}, {1}. {2} {3} um {4}:{5}:{6}';
            text = text.replace('{0}', days[created.getDay()]);
            text = text.replace('{1}', padleft(created.getDate(), '0', 2));
            text = text.replace('{2}', months[created.getMonth()]);
            text = text.replace('{3}', created.getFullYear());
            text = text.replace('{4}', padleft(created.getHours(), '0', 2));
            text = text.replace('{5}', padleft(created.getMinutes(), '0', 2));
            text = text.replace('{6}', padleft(created.getSeconds(), '0', 2));

            return text;
        }

        for (var i = 0, l = Math.min(data.length, 10); i < l; i++)
        {
            var text = data[i].text;

            text = text.replace(/(https?:\/\/\S*)/g, '<a target="_blank" href="$1">$1</a>&nbsp;');
            text = text.replace(/#([a-zA-Z]*)/g, '<a href="https://twitter.com/search?q=%23$1" target="_blank">#$1</a>'); // #hash
            text = text.replace(/@([\w]*)/ig, '<a target="_blank" href="https://twitter.com/$1">@$1</a>'); // @Username
            text += '<div class="PublishDate">' + getParsedDate(data[i].created_at) + '</div>';
            var className = "Tweet invisible";
            $('<div class="' + className + '">' + text + '</div>').appendTo(container);
        }

        showPage(1);
    }

    function showPage(page)
    {
        $("#TweetsPaging a").each(function ()
        {
            var thisPage = parseInt($(this).text());
            if (thisPage == page) $(this).addClass("Active");
            else $(this).removeClass("Active");
        });

        var toShow = [], toHide = [];

        container.find(".Tweet").each(function (i)
        {
            if (parseInt(i / pageSize) == currPage - 1) toHide.push($(this));
            if (parseInt(i / pageSize) == page - 1) toShow.push($(this));
        });

        for (var i = 0; i < pageSize; i++)
        {
            (function (i)
            {
                if (toHide[i]) toHide[i].fadeOut(fadeTimeout, function () { if (toShow[i]) toShow[i].fadeIn(fadeTimeout); });
                else if (toShow[i]) toShow[i].fadeIn(fadeTimeout);
            })(i);
        }

        startLoopAnim();

        currPage = page;
    }

    function startLoopAnim()
    {
        stopLoopAnim();
        interval = setInterval(function () { var page = currPage + 1; if (page > maxPage) page = 1; showPage(page); }, 5000);
    }

    function stopLoopAnim()
    {
        if (interval) clearInterval(interval);
    }

    $("#TweetsPaging a").click(function (e)
    {
        $("#TweetsPaging a").removeClass("Active");
        $(this).addClass("Active");

        showPage(parseInt($(this).text()));
        return false;
    });

    container.mouseover(function () { stopLoopAnim(); });
    container.mouseout(function () { startLoopAnim(); });

})();
