/*
 * Author:  Tayfun Sen
 * URL:     http://blog.tayfunsen.com
 *
 */
// Pass jQuery object so that the dollar doesn't collide with other libraries.
// See: http://docs.jquery.com/Plugins/Authoring#Getting_Started
(function($) {
    // Because IE < 9 does not support Date.now()
    var now = (new Date()).getTime();

    $(document).ready(stylePage);

    function stylePage() {
        prettyDates();
        insertArchives();

        $(".tweet").tweet({
            username: "tayfunsen",
            join_text: "auto",
            avatar_size: 32,
            count: 6,
            retweeets: false,
            auto_join_text_default: "", 
            auto_join_text_ed: "",
            auto_join_text_ing: "",
            auto_join_text_reply: "",
            auto_join_text_url: "",
            loading_text: "loading tweets..."
        });
    }

    function insertArchives() {
        $.get('/archive.html', function(data) {
            document.getElementById('archive-widget').innerHTML = data;
            openCurrentArchives();
            $('#archive').click(makeInteractiveArchives);
        });
    }

    function openCurrentArchives() {
        var firstYear = $($('#archive li')[0]);
        firstYear.addClass('current');
        var firstMonth = $(firstYear.find('ul li')[0]);
        firstMonth.addClass('current');
    }

    function makeInteractiveArchives(event) {
        var target = $(event.target);
        var targetParent = target.parent();
        if (!target.is('a') || target.is('.archive-link')) { return; }
        targetParent.toggleClass('current');
    }

    function prettyDates() {
        var postDateArr = $("time.postdate");
        $.each(postDateArr, function(index, el) {
            el = $(el);
            var postDate = new Date(el.attr('datetime'));
            var elapsedDays = Math.floor((now - postDate) / 86400000);
            var elapsedDaysStr = beforePosted(elapsedDays);
            el.text(elapsedDaysStr);
        });
    }

    function beforePosted(days) {
        if (days == 0) {
            return "today";
        } else if (days == 1) {
            return "yesterday";
        } else if (days < 30) {
            return days + " days ago";
        } else if (days < 365) {
            var months = Math.floor(days / 30);
            return (months > 1? months + " months" : "a month") + " ago";
        } else {
            var years = Math.floor(days / 365);
            return (years > 1? years + " years" : "a year") + " ago";
        }
    }
})(jQuery);

