var Blogger = (function() {
    var fetchPosts = function() {
        $.ajax({
            type: 'GET',
            url: '/blog/posts',
            dataType: 'json',
            success : function(posts) {
                displayPosts(posts);
            },
            error : function(xhr, type) {
                console.log("Error fetching blog posts");
            }
        });
    };

    var displayPosts = function(posts) {
        posts['disp'] = dispPost;
        posts.disp(0, $('#blogpost1'));
        posts.disp(1, $('#blogpost2'));
        // activate social buttons
        activateSocial();
    };


    var dispPost = function (i, sel) {
        var post = this[i];
        var article = $(sel);

        var title = $('<h1></h1>');
        title.text(post.title);

        article.append(title);

        var body = $('<p></p>');
        var content = post.content.split("<a name='more'></a>")[0];
        content += '<a name="more" href="' + post.link + '#more">Read more >></a>' +
            '<br/><br/><g:plusone href="' + post.link + '"></g:plusone>' +
            '<a href="https://twitter.com/share" class="twitter-share-button" data-url="' + post.link + '" data-text="' + post.title + '" data-via="ugtug" data-lang="en">Tweet</a>';
        body.html(content);
        article.append(body);

        article.removeClass('loading');
    };

    var activateSocial = function() {
        // G+1
        gapi.plusone.go();
        // TWTTR
        !function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (!d.getElementById(id)) {
                js = d.createElement(s);
                js.id = id;
                js.src = "//platform.twitter.com/widgets.js";
                fjs.parentNode.insertBefore(js, fjs);
            }
        }(document, "script", "twitter-wjs");
    };

    return {
        fetch: fetchPosts
    }
})();
