(function(Post){
	
	// Dependencies

	// Shorthands

	// Model
	Post.Model = Backbone.Model.extend({
		initialize: function() {
			this.posts = new Post.Collection();

			this.bind("change", function() {
				this.posts.clearCache();
			});
		},
	});

	// Collection
	Post.Collection = Backbone.Collection.extend({
		model: Post.Model,
		// url: '/posts',
		cache: null,
		url: '/wp/api/get_recent_posts',
		parse: function(response) {
			return response.posts;
		},

		get: function() {
			if(this.cache == null){
				this.cache = this.fetch({
					success: function() {
						
					},
					error: function(collection, response) {
						console.error('message', "error loading posts");
						console.log('collection', collection);
						console.log('response', response);
					}
				});
				//console.log('not cached');
				return this.cache;
			} else {
				//console.log('cached');
				return this.cache;
			}
		},

		clearCache: function() {
			this.cache = null;
		}
	});

	// Views
	Post.Views.Single = Backbone.View.extend({
		tagName: 'article',
		initialize: function() {
			_.bindAll(this, 'render');
			this.model.bind('change', this.render);

			this.template = _.template($('#post-template').html());
		},

		render: function() {
			var renderedContent = this.template(this.model.toJSON());
			$(this.el).html(renderedContent);
			return this;
		}
	});
		
	Post.Views.Archive = Backbone.View.extend({
		tagName: 'section',
		id: 'archive',
		initialize: function() {
			_.bindAll(this, 'render');
			this.template = _.template($('#list-template').html());

			this.collection.bind('reset', this.render);
			this.render();
		}, 

		render: function() {
			var $posts,
				collection = this.collection;

			$(this.el).html(this.template({}));
			$posts = $(this.el);
			collection.each(function(post) {
				var view = new Post.Views.Single({
					model: post,
					collection: collection
				});
				$posts.append(view.render().el);
			});
			return this;
		},
	});
		
})(App.module("post"));
