/**
 * A Single Page Blog
 */

/*global _ $ Backbone $$site_url */

_.templateSettings = {
    interpolate: /\{{2,3}(.+?)\}{2,3}/g
};

(function(){


    // Post Model
    // ----------

    // Our basic **Post** model has `id`, `title`, `date`, `categories`, and `content` attributes.
    this.Post = Backbone.Model.extend({

        // If you don't provide a post, one will be provided for you.
        EMPTY: "oh, my god, this shouldn't happen...",

        // Ensure that each post created has `content`.
        initialize: function() {
            if (!this.get("content")) {
                this.set({"content": this.EMPTY});
            }
        }

    });


    // Post Collection
    // ---------------

    // The collection of posts is backed by *localStorage* or a remote server.
    this.PostList = Backbone.Collection.extend({

        // Reference to this collection's model.
        model: Post,

        // Save all of the posts under the `"post"` namespace.
        //localCache: new Store("post")

        sync: function(method, model, success, error) {
            success($$posts);
        },

        parse: function(resp) {
            return _.map(resp, function(data) {
                var str = data.split('`');

                return {
                    site: $$site_url,
                    title: str[0],
                    author: 'xthsky',
                    date: str[1],
                    category: str[2],
                    content: str[3],
                    url: str[4].slice(1)
                };
            });
        }

    });


    // Post Item View
    // --------------

    // The DOM element for a post...
    this.PostView = Backbone.View.extend({

        tagName: 'section',

        className: 'post',

        // Cache the template function for a single item.
        template: _.template($('#post-template').html()),

        // The DOM events specific to an item.
        events: {
            "click .entry-title"   : "more"
        },

        // The TodoView listens for changes to its model, re-rendering. Since there's
        // a one-to-one correspondence between a **Post** and a **PostView** in this
        // app, we set a direct reference on the model for convenience.
        initialize: function(mode) {
            _.bindAll(this, 'render', 'close');
            this.model.bind('change', this.render);
            this.model.view = this;

            _.log('PostView initialized');
        },

        // Re-render the contents of the post item.
        render: function() {
            var a = this.template(this.model.toJSON());
            $(this.el).html(this.template(this.model.toJSON()));

            return this;
        },

        // More this view from the DOM.
        more: function() {
        }

    });


    this.HomeView = Backbone.View.extend({

        el: document.getElementById('content'),

        initialize: function() {

            this.clear();
            this.addAll();
        },

        // Add a single post item to the list by creating a view for it, and
        // appending its element to the `<ul>`.
        addOne: function(post) {
            var view = new PostView({model: post});
            $(this.el).append(view.render().el);
        },

        // Add all items in the **Posts** collection at once.
        addAll: function() {
            Posts.each(this.addOne, this);
        },

        clear: function() {
            $(this.el).empty();
        }
    });

    // The Application
    // ---------------
    this.App = Backbone.Controller.extend({

        routes: {
            "":         "home",
            "about":    "about"
        },

        initialize: function() {

            _.bindAll(this, 'post', 'debug');
            this.route(/^(\d{4}\/\d{2}\/.+)$/, "post", this.post);
            this.route(/^(.*?)\?debug$/, "debug", this.debug);

            // grab datas.
            Posts.fetch();

            // some help methods.
            _.log = function (msg) {};
        },

        home: function() {

            this.contentView = new HomeView();
        },

        post: function() {
            $('#content').html('post');
        },

        about: function() {
            $('#content').html('逐步更新中');
        },

        debug: function(url) {
            _.log = function (msg) {
                var node = $('#underscore-log');

                if(node.length === 0) {
                    node = $('<div id="underscore-log"><h2>console</h2></div>');
                    $('body').append(node);
                }

                node.append('<p>'+msg+'</p>');
            };
        }

    });

}).call(this);

// Initialize the application once the DOM is ready, using `jQuery.ready`:
$(document).ready(function() {

    // Create our global collection of **Posts**.
    window.Posts = new PostList;

    // Finally, we kick things off by creating the **App**.
    window.app = new App();

    Backbone.history.start();
});


