var View = {};
View.Find = {};

View.Jcrop = {
	coords: {
		x: 0,
		y: 0,
		w: 500
	}	
};

View.Basic = Backbone.View.extend({
	initialize: function(options) {
		if(options && options.template) {
			this.template = templates.get(options.template).compiled;
		}
		if(this.init) {this.init(options);}
	}
});

View.Autobind = Backbone.View.extend({
	initialize: function(options) {
		if(options && options.template) {
			this.template = templates.get(options.template).compiled;
		}
		if(this.init) {this.init(options);}
		if(this.model||this.collection)(this.model||this.collection).bind('all', this.render, this);
	}
});

View.Entity = Backbone.View.extend({
	initialize: function(options) {
		this.entity = this.model;
		if(options && options.template) {
			this.template = templates.get(options.template).compiled;
		}
		if(this.init) {this.init(options);}
		if(this.entity) {
			this.entity.bind('change:commentCount', this.changeCommentCount, this);
			this.entity.bind('change:likeCount', this.changeLikeCount, this);
			this.entity.bind('change:likedByMe', this.changeLikedByMe, this);
		}
	},
	changeCommentCount: function() {
		$(this.el).find('.bb-comment-count').text(this.entity.get('commentCount'));
	},
	changeLikeCount: function() {
		$(this.el).find('.bb-like-count').text(this.entity.get('likeCount'));
	},
	changeLikedByMe: function() {
		$(this.el).find('.bb-toggle-like').text(this.entity.get('likedByMe') ? 'Unlike': 'Like');
	},
	toggleLike: function(event) {
		if(account.isSignedIn()) {
			this.entity.toggleLike();
		} else {
			$('[data-controls-modal="js-account-signup-form"]').click();
		}
	},
	toggleComments: function(event, show) {
		var $container = $(this.el).find('.bb-comment-container');
		if(!this.comments) {
			this.comments = new Collection.Entity([], {url: '/json/entities/'+this.entity.id+'/comments'});
			this.commentsView = new View.Comments({collection: this.comments, entity: this.entity}); 
			var that = this;
			this.comments.fetch({
				success: function(comments) {
					$container.html(that.commentsView.render().el);
					that.entity.set({'commentCount': comments.length});
				}
			});			
		}
		if(show || $container.css('display') == 'none') {
			this.entity.showComments = true;
			$container.show('fast');
		} else {
			this.entity.showComments = false;
			$container.hide();	
		}
	},
	viewLikes: function() {
	},
	destroy: function(event) {
		if(event) event.stopImmediatePropagation();
		if(confirm('Are you sure you want to delete this?')) {
			this.entity.destroy();
		}
	}
});

View.Album = View.Entity.extend({
	events: {
		'click .bb-delete': 'destroy',
		'click': 'delve'
	},
	tagName: 'li',
	render: function() {
		$(this.el).addClass('toolhelper').attr('title', this.model.get('name'));
		$(this.el).html(templates.get('album').compiled({album: this.model.toJSON()}));
		return this;
	},
	destroy: function(event) {
		if(confirm('Are you sure you want to delete this album?')) {
			this.model.destroy();
		}
		event.stopImmediatePropagation();
	},
	delve: function() {
		Backbone.history.navigate('/entities/'+entity.id+'/albums/'+this.model.id, true);
	}
});

//TODO: Convert into a View
function autocomplete(el, dictionary, template, callback) {
	$(el).autocomplete({
		source: function(request, response) {
			$.getJSON('/json/autocomplete',
				{
					query: request.term,
					dictionaryId: dictionary
				},
				function(data) {
					$.each(data, function(index, element) {
						element.label = element.name;
					});
					response(data);
				}
			);
		},
		minLength: 2,
		select: function(event, ui) {
			callback(event, ui);
		},
		open: function() {
		},
		close: function() {
		}
	}).data( "autocomplete" )._renderItem = function(ul, item) {
		return $("<li></li>")
		.data("item.autocomplete", item)
		.append(templates.get(template).compiled({item: item}))
		.appendTo(ul);
	};
}

View.Carousel = View.Basic.extend({
	className: 'carousel modal',
	init: function() {
		this.views = new Collection.Entity();
	},
	render : function() {
		$('.carousel').remove();
		$('#bb-modal').html($(this.el).html(templates.get('carousel').compiled({})));
		$(this.el).modal({show: true, backdrop: true});
		this.model.collection.forEach(function(model) {
			$('#carousel-backstage').append(new View.Carousel.Image({model: model}).render().el);
		}, this);
		this.model.trigger('selected');
		return this;
	}
});

View.Carousel.Image = View.Entity.extend({
	init: function() {
		this.model.bind('selected', this.selected, this);
	},
	events: {
		'click .bb-toggle-like' : 'toggleLike',
		'click .bb-toggle-comments' : 'toggleComments',
		'click .bb-view-likes' : 'viewLikes',
		'click .bb-delete' : 'destroy',
		'click .next': 'next',
		'click .prev': 'prev'
	},
	render: function() {
		$(this.el).html(templates.get('carousel-image').compiled({image: this.model.toJSON()}));
		if(this.model.showComments) {
			this.toggleComments(undefined, true);
		}
		return this;
	},
	selected: function() {
		$('#carousel-backstage').append($('#carousel-stage').children());
		$("#carousel-stage").html(this.el);
	},
	next: function() {
		this.model.next().trigger('selected');
	},
	prev: function() {
		this.model.prev().trigger('selected');
	}
});

View.Comments = View.Basic.extend({
	initialize: function() {
		this.collection.bind('add', this.addComment, this);
	},
	events: {
		'keypress .bb-comment' : 'comment',
		'focus .bb-comment' : 'focusComment'
	},
	render : function() {
		$(this.el).empty();
		$(this.el).html(templates.get('comments').compiled({}));
		var tbody = $(this.el).find('tbody');
		_.each(this.collection.models, function(comment) {
			$(tbody).prepend(new View.Comment({model: comment, entity: this.options.entity}).render().el);
		}, this);
		return this;
	},
	addComment: function() {
		$(this.el).find('tbody').append(new View.Comment({model: this.collection.last(), entity: this.options.entity}).render().el);
	},
	comment: function(event) {
	    if(event.keyCode == 13) {
	    	if(account.isSignedIn()) {
	    		var that = this;
	    		new Model.Entity({comment: $(this.el).find('.bb-comment').val()}, {collection: this.collection}).save({}, {
					success: function(comment) {
						that.options.entity.fetch({
							success: function() {
								if(that.options.entity.get('commentCount') == that.collection.length + 1) {
									that.collection.add(comment);									
								} else {
									that.collection.fetch({
										success: function() {
											that.render();
										}
									});
								}
							}
						});
						$(that.el).find('.bb-comment').val('');
					}
				});
	    	} else {
	    		$('[data-controls-modal="js-account-signup-form"]').click();
	    	}
	    }
	},
	focusComment: function() {
		$(this.el).find('.bb-comment').val('');
	}
});

View.Comment = View.Autobind.extend({
	events: {
		'click .bb-toggle-comment-like' : 'toggleLike',
		'click .bb-delete-comment' : 'destroy'
	},
	className: 'comment',
	tagName: 'tr',
	render : function() {
		$(this.el).html(templates.get('comment').compiled({comment: this.model.toJSON()}));
		return this;
	},
	toggleLike: function(event) {
		event.stopImmediatePropagation();
		if(account.isSignedIn()) {
			this.model.toggleLike();
		} else {
			$('[data-controls-modal="js-account-signup-form"]').click();
		}
	},
	destroy: function() {
		if(confirm('Are you sure you want to delete this comment?')) {
			var that = this;
			this.model.destroy({
				success: function() {
					if(that.options && that.options.entity)	that.options.entity.fetch();
					$(that.el).remove();
				}
			});
		}
	}
});

View.FollowButton = View.Autobind.extend({
	render: function() {
		if(account.isFollowing(entity.id)) {
			$(this.el).html('<a class="btn primary pull-right bb-unfollow">Stop Following</a>');
		} else {
			$(this.el).html('<a class="btn primary pull-right bb-follow">Follow</a>');
		}
		return this;
	}
});

View.FrontPage = View.Autobind.extend({
	events: {
		'click .bb-facebook-connect': 'facebookConnect'
	},
	render : function() {
		$(this.el).html(templates.get('frontpage').compiled({}));
		return this;
	},
	facebookConnect: function() {
		 account.facebookConnect({
			 success: function() {
				 Backbone.history.navigate('/stream', true);
			 }
		 });
	}
});

View.Image = View.Entity.extend({
	events: {
		'click': 'carousel',
		'click .ui-icon-person' : 'makeProfileImage',
		'click .ui-icon-trash' : 'destroy'
	},
	tagName: 'li',
	render: function() {
		$(this.el).addClass('toolhelper').attr('title', this.model.get('caption'));
		$(this.el).html(templates.get('image').compiled({image: this.model.toJSON()}));
		return this;
	},
	carousel: function() {
		new View.Carousel({model: this.model}).render();
	},
	makeProfileImage: function(event) {
		event.stopImmediatePropagation();
		new View.ProfileImageChangeImageCrop({el: $('#bb-modal'), model: this.model}).render();
		$('#bb-modal').modal({show: true, backdrop: true});
	}
});

View.ImageCollection = View.Autobind.extend({
	tagName: 'ul',
	render : function() {
		$(this.el).addClass('media-grid');
		$(this.el).empty();
		_.each(this.collection.models, function(image) {
			$(this.el).append(new View.Image({model: image}).render().el);
		}, this);
		return this;
	},
	addImage: function(albumId, imageId) {
		this.collection.fetch();
	},
});

View.ImageGroup = View.Entity.extend({
	init: function() {
		this.entity = new Model.Entity(this.model.get('album'));
	},
	events: {
		'click .bb-toggle-like' : 'toggleLike',
		'click .bb-toggle-comments' : 'toggleComments',
		'click .bb-view-likes' : 'viewLikes',
		'click .bb-delete' : 'destroy',
		'click ul li': 'click'
	},
	render: function() {
		$(this.el).html(templates.get('image-group').compiled({post: this.model.toJSON()}));
		_.each(this.model.get('latestImages'), function(image, index) {
			$(this.el).find('ul.small').append(new View.ImageGroup.Image({model: new Backbone.Model({id: image})}).render().el);
		}, this);
		return this;
	},
	click: function() {
		Backbone.history.navigate('/entities/'+this.model.get('contributedTo')+'/albums/'+this.model.get('albumId'), true);
	}
});

View.ImageGroup.Image = View.Basic.extend({
	tagName: 'li',
	render: function() {
		$(this.el).html(templates.get('image-group-image').compiled({image: this.model.toJSON()}));
		return this;
	}
});

View.PetOrOwner = View.Autobind.extend({
	init: function(options) {
		this.buttons = options.buttons;
		this.title = options.title;
	},
	events : {
		'click .bb-follow' : 'follow',
		'click .bb-unfollow' : 'unfollow',
		'click .bb-wall' : 'wall',
		'click .bb-blog' : 'blog',
		'click .bb-photos' : 'photos',
		'click .bb-pets' : 'pets',
		'click .bb-followers' : 'followers',
		'click .bb-following' : 'following',
		'click .bb-update-profile-image': 'updateProfileImage'
	},
	title : '',
	render : function() {
		if(this.model) {
			if(this.model.get('type') == 'PET') {
				$(this.el).html(templates.get('pet').compiled({pet : this.model.toJSON(), title : this.title, buttons : this.buttons}));		
			} else {
				$(this.el).html(templates.get('owner').compiled({owner : this.model.toJSON(), title : this.title, buttons : this.buttons}));	
			}
			$(this.el).find('.bb-'+_.last(document.location.hash.split('/'))).addClass('active');
			if(account.isSignedIn() && !account.isCurrentOwner()) {
				new View.FollowButton({el: $(this.el).find('.bb-button-panel'), collection: account.following}).render();
			}
			$(this.el).find('.bb-spotlight-members').html(new View.Spotlight.Entities({collection: window.members}).render().el);
			$(this.el).find('.bb-spotlight-pets').html(new View.Spotlight.Entities({collection: window.pets}).render().el);
		}
		return this;
	},
	follow: function() {
		account.follow(this.model.id, {
			success: function() {
				account.following.fetch({
					success: function() {
						//Backbone.history.reload();
					}
				});
			}
		});
	},
	unfollow: function() {
		account.unfollow(this.model.id, {
			success: function() {
				account.following.fetch({
					success: function() {
						//Backbone.history.reload();
					}
				});
			}
		});
	},
	wall: function() {
		Backbone.history.navigate('/entities/'+this.model.id+'/wall', true);
	},
	blog: function() {
		Backbone.history.navigate('/entities/'+this.model.id+'/blog', true);
	},
	photos: function() {
		Backbone.history.navigate('/entities/'+this.model.id+'/photos', true);
	},
	pets: function() {
		Backbone.history.navigate('/entities/'+this.model.id+'/pets', true);
	},
	followers: function() {
		Backbone.history.navigate('/entities/'+this.model.id+'/followers', true);
	},
	following: function() {
		Backbone.history.navigate('/entities/'+this.model.id+'/following', true);
	},
	updateProfileImage: function() {
		new Collection.Entity([],{url: '/json/entities/'+entity.id+'/albums'}).fetch({success: function(albums) {
			new View.ProfileImageChangeAlbumCollection({el: $('#bb-modal'), collection: albums}).render();
			$('#bb-modal').modal({show: true, backdrop: true});
		}});
	}
});

View.Find.Owners = View.Basic.extend({
	className: 'round row row2 tmargin10',
	render: function() {
		$(this.el).html(templates.get('find-owners').compiled({}));
		var $tbody = $(this.el).find('tbody');
		_.each(this.collection.models, function(owner) {
			if(owner.get('type') == 'OWNER') {
				$tbody.append(new View.Find.Owner({model: owner}).render().el);
			}
		}, this);
		$(this.el).find('table').tablesorter({
			sortList : [ [ 1, 0 ] ]
		});
		return this;
	}
});

View.Find.Owner = View.Basic.extend({
	events: {
		'click': 'click'
	},
	tagName: 'tr',
	render: function() {
		$(this.el).html(templates.get('find-owner').compiled({owner: this.model.toJSON()}));		
		return this;
	},
	click: function() {
		Backbone.history.navigate('/entities/'+this.model.id+'/wall', true);
	}
});

View.Find.Pets = View.Basic.extend({
	className: 'round row row2 tmargin10',
	render: function() {
		$(this.el).html(templates.get('find-pets').compiled({}));
		var $tbody = $(this.el).find('tbody');
		_.each(this.collection.models, function(owner) {
			if(owner.get('type') == 'PET') {
				$tbody.append(new View.Find.Pet({model: owner}).render().el);
			}
		}, this);
		$(this.el).find('table').tablesorter({
			sortList : [ [ 1, 0 ] ]
		});
		return this;
	}
});

View.Find.Pet = View.Basic.extend({
	events: {
		'click': 'click'
	},
	tagName: 'tr',
	render: function() {
		$(this.el).html(templates.get('find-pet').compiled({pet: this.model.toJSON()}));		
		return this;
	},
	click: function() {
		Backbone.history.navigate('/entities/'+this.model.id+'/wall', true);
	}
});

View.Followers = View.Autobind.extend({
	init: function() {
		this.collection.bind('all', this.render, this);
		if(account.following) account.following.bind('all', this.fetch, this);
	},
	fetch: function() {
		this.collection.fetch();
	},
	render : function() {
		var $tbody = $(this.el).html(templates.get('owner-followers').compiled({followers : this.collection.toJSON()})).find('tbody');
		if (this.collection.models && this.collection.models.length > 0) {
			_.each(this.collection.models, function(owner) {
				$tbody.append(new View.Follower({model: owner}).render().el);
			}, this);
			$(this.el).find('table').tablesorter({
				sortList : [ [ 1, 0 ] ]
			});
		}
		return this;
	}
});

View.Follower = View.Autobind.extend({
	events: {
		'click': 'click'
	},
	tagName: 'tr',
	render: function() {
		$(this.el).html(templates.get('owner-follower').compiled({owner: this.model.toJSON()}));
		return this;
	},
	click: function() {
		document.location.hash = '/entities/'+this.model.id+'/wall';
	}
});

View.Following = View.Autobind.extend({
	render : function() {
		$(this.el).html(templates.get('owner-following').compiled({
			following : this.collection.toJSON()
		}));
		if (this.collection.models && this.collection.models.length > 0) {
			var $tbody = $(this.el).html(templates.get('owner-following').compiled({followers : this.collection.toJSON()})).find('tbody');
			if(this.collection.models && this.collection.models.length > 0) {
				_.each(this.collection.models, function(owner) {
					$tbody.append(new View.Follower({model: owner}).render().el);
				}, this);
				$(this.el).find('table').tablesorter({
					sortList : [ [ 1, 0 ] ]
				});
			}
		}
		return this;
	}
});

View.Footer = View.Autobind.extend({
	render : function() {
		$(this.el).html(templates.get('footer').compiled({}));
		return this;
	}
});

View.Notification = View.Basic.extend({
	tagName: 'tr',
	render: function() {
		$(this.el).html(templates.get(this.getTemplateName()).compiled({notification: this.model.toJSON()}));
		return this;
	},
	getTemplateName: function() {
		var notificationType = this.model.get('notificationType');
		if(notificationType == 'LIKE') {
			return 'like-notification';
		} else if(notificationType == 'COMMENT') {
			return 'comment-notification';
		} else if(notificationType == 'NEW_FOLLOWER') {
			return 'new-follower-notification';
		} else if(notificationType == 'POST') {
			return 'post-notification';
		}
	}
});

View.Notifications = View.Basic.extend({
	tagName: 'table',
	render: function() {
		_.each(this.collection.models, function(notification) {
			$(this.el).append(new View.Notification({model: notification}).render().el);
		}, this);
		return this;
	}
});

View.Pets = View.Autobind.extend({
	render : function() {
		var $tbody = $(this.el).html(templates.get('owner-pets').compiled({})).find('tbody');
		_.each(this.collection.models, function(pet) {
			$tbody.append(new View.Pet({model: pet}).render().el);
		}, this);
		if(this.collection.models && this.collection.models.length > 0) {
			$('table#pets-table').tablesorter({
				sortList : [ [ 1, 0 ] ]
			});
		}
		return this;
	}
});

View.Pet = View.Autobind.extend({
	events: {
		'click .bb-delete': 'destroy',
		'click': 'click'
	},
	tagName: 'tr',
	render: function() {
		$(this.el).html(templates.get('owner-pet').compiled({pet: this.model.toJSON()}));
		return this;
	},
	click: function() {
		Backbone.history.navigate('/entities/'+this.model.id+'/wall', true);
	},
	destroy: function(event) {
		event.stopImmediatePropagation();
		if(confirm('Are you sure you want to delete '+this.model.get('displayName')+'?')) {
			this.model.destroy();
		}
	}
});

View.Photos = View.Basic.extend({
	render : function() {
		$(this.el).html(templates.get('photos').compiled({albumCount: this.collection.length}));
		if(this.collection.length > 1) {
			var $albums = $(this.el).find('.bb-albums ul');
			_.each(this.collection.models, function(album) {
				if(album.get('name') != 'Unassigned' && (account.isCurrentOwner() || album.get('imageCount') > 0)) {
					$albums.append(new View.Album({model: album}).render().el);
				}
			}, this);
		}
		var unassigned = this.collection.getByAttribute('name', 'Unassigned');
		var that = this;
		new Collection.Entity([],{url : '/json/entities/'+unassigned.id+'/images'}).fetch({
			success: function(images) {
				var view = new View.ImageCollection({collection : images, album: unassigned});
				$(that.el).find('.bb-images').append(view.render().el);
			}
		});
		return this;
	},
	addImage: function(albumId, imageId) {
		this.collection.fetch();
	}
});

View.Post = View.Entity.extend({
	events: {
		'click .bb-toggle-like' : 'toggleLike',
		'click .bb-toggle-comments' : 'toggleComments',
		'click .bb-view-likes' : 'viewLikes',
		'click .bb-delete' : 'destroy'
	},
	destroy: function() {
		if(confirm('Are you sure you want to delete this entry?')) {
			var that = this;
			this.model.destroy({
				success: function() {
					$(that.el).remove();
				}
			});
		}
	},
	tagName: 'div',
	render : function() {
		var template = this.getTemplate();
		if(template) $(this.el).html(template.compiled({post: this.model.toJSON()}));
		if(this.model.showComments) {
			this.toggleComments(undefined, true);
		}
		FB.XFBML.parse(this.el);
		return this;
	},
	getTemplate: function() {
		if(this.model.get('type') == 'BLOG') {
			return templates.get('blog');
		} else if(this.model.get('type') == 'STATUS_UPDATE') {
			return templates.get('status');
		}
		return undefined;
	}
});

View.PostCollection = View.Basic.extend({
	initialize: function() {
		this.collection.bind('add', this.addPost, this);
	},
	render : function() {
		$(this.el).empty();
		var that = this;
		_.each(this.collection.models, function(post) {
			$(that.el).append(new View.Post({model: post}).render().el);
		});
		return this;
	},
	addPost: function() {
		$(this.el).prepend(new View.Post({model: this.collection.first()}).render().el);
	}
});

View.ProfileImageChangeAlbumCollection = View.Autobind.extend({
	render: function() {
		var $ul = $(this.el).html(templates.get('profile-image-change-album-collection').compiled()).find('ul');
		_.each(this.collection.models, function(album) {
			$ul.append(new View.ProfileImageChangeAlbum({model: album}).render().el);
		}, this);
		return this;
	}
});

View.ProfileImageChangeAlbum = View.Autobind.extend({
	events: {
		'click': 'click'
	},
	tagName: 'li',
	render: function() {
		$(this.el).html(templates.get('profile-image-change-album').compiled({album: this.model.toJSON()}));
		return this;
	},
	click: function() {
		new Collection.Entity([],{url: '/json/entities/'+this.model.id+'/images'}).fetch({success: function(images) {
			new View.ProfileImageChangeImageCollection({el: $('#bb-modal'), collection: images}).render();
		}});
	}
});

View.ProfileImageChangeImage = View.Autobind.extend({
	events: {
		'click': 'click'
	},
	tagName: 'li',
	render: function() {
		$(this.el).html(templates.get('profile-image-change-image').compiled({image: this.model.toJSON()}));
		return this;
	},
	click: function() {
		new View.ProfileImageChangeImageCrop({el: $('#bb-modal'), model: this.model}).render();
	}
});

View.ProfileImageChangeImageCollection = View.Autobind.extend({
	render: function() {
		var $ul = $(this.el).html(templates.get('profile-image-change-image-collection').compiled()).find('ul');
		_.each(this.collection.models, function(image) {
			$ul.append(new View.ProfileImageChangeImage({model: image}).render().el);
		}, this);
		return this;
	}
});

View.ProfileImageChangeImageCrop = View.Autobind.extend({
	init: function() {
		View.Jcrop.coords = {
			x: 0,
			y: 0,
			w: 500
		};
	},
	events: {
		'click .bb-save': 'save'
	},
	render: function() {
		$('#bb-jcrop-hidden').attr('src', 'http://petzibit-images.s3.amazonaws.com/'+this.model.id+'.jpg');
		$(this.el).html(templates.get('profile-image-change-image-crop').compiled({image: this.model.toJSON()}));
		$(this.el).find('#jcrop-target').Jcrop({aspectRatio: 1, onChange: this.onChange, onSelect: this.onChange});
		return this;
	},
	save: function() {
		var scale = $('#bb-jcrop-hidden').width() / $(this.el).find('#jcrop-target').width();
			
		$.ajax({
			url: '/json/image/profile/create',
			data: {
				entityId: entity.id,
				imageId: this.model.id,
				x: Math.round(scale * View.Jcrop.coords.x),
				y: Math.round(scale * View.Jcrop.coords.y),
				size: Math.round(View.Jcrop.coords.w * scale)
			},
			success: function() {
				window.location.reload();
			}
		});
	},
	onChange: function(coords) {
		View.Jcrop.coords = coords;
	}
});

View.Releases = View.Autobind.extend({
	className: 'round row row2 tmargin10',
	render: function() {
		$(this.el).html(templates.get('releases').compiled({}));
		var that = this;
		new Collection.Entity([], {url: '/html/releases.html'}).fetch({
			error: function(releases) {
				$(this.el).append('<div>Unable to load release data.</div>');
			},
			success: function(releases) {
				_.each(releases.models, function(release) {
					$(this.el).append(new View.Release({model: release}).render().el);
				}, that);
			}
		});
		return this;
	}
});

View.Release = View.Autobind.extend({
	className: 'span14',
	render: function() {
		$(this.el).html(templates.get('release').compiled({release: this.model.toJSON()}));
		return this;
	}
});

View.Settings = View.Autobind.extend({
	events: {
		'click .bb-profile-image-selection': 'profileImageSelection'
	},
	render : function() {
		$(this.el).html(templates.get('settings').compiled({}));
		return this;
	},
	profileImageSelection: function() {
		new Collection.Entity([],{url: '/json/entities/'+account.owner.id+'/albums'}).fetch({success: function(albums) {
			new View.ProfileImageChangeAlbumCollection({el: $('#bb-modal'), collection: albums}).render();
			$('#bb-modal').modal({show: true, backdrop: true});
		}});
	}
});

View.Stream = View.Basic.extend({
	render : function() {
		if(this.collection.length == 0) {
			$(this.el).append(templates.get('empty-stream').compiled({}));
		} else {
			$(this.el).empty();
			var that = this;
			_.each(this.collection.models, function(entity) {
				if(entity.get('type') == 'IMAGE_GROUP') {
					$(that.el).append(new View.ImageGroup({model: entity}).render().el);
				} else {
					$(that.el).append(new View.Post({model: entity}).render().el);
				}
			});
		}
		return this;
	}
});


View.Notification.Count = View.Basic.extend({
	tagName: 'li',
	init: function() {
		this.model.bind('change:count', this.render, this);
	},
	render: function() {
		$(this.el).html(templates.get('notification-count').compiled({count: this.model.get('count')}));
		if(Backbone.history.getFragment() == '/notifications') {
			Backbone.history.reload();
		}
		return this;
	}
});

View.TopBar = View.Autobind.extend({
	events : {
		'click .bb-signout': 'signout',
		'click .bb-facebook-connect': 'facebookConnect'
	},
	render : function() {
		$(this.el).html(templates.get('topbar').compiled({}));
		autocomplete($(this.el).find('#search-query'), 'ENTITY_NAME', 'autocomplete-owner', function(event, ui) {
			 $(this.el).find('#search-query').val('');
			app.navigate('/entities/'+ui.item.id+'/wall', true);
		});
		if(!this.rendered) {
			this.rendered = true;
		} else {
			Backbone.history.reload();
		}
		var that = this;
		if(!window.notificationCount) window.notificationCount = new Model.NotificationCount();
		window.notificationCount.start();
		window.notificationCount.fetch({
			success: function() {
				$(that.el).find('.bb-home').append(new View.Notification.Count({model: window.notificationCount}).render().el);
			}
		});
		return this;
	},
	signout : function() {
		app.signout();
	},
	facebookConnect: function() {
		 account.facebookConnect();
	}
});

View.Wall = View.Autobind.extend({
	events: {
		'keypress .bb-status-update' : 'statusUpdate'
	},
	render : function() {
		$(this.el).html(templates.get('wall').compiled({}));
		new View.PostCollection({el : $(this.el).find('.content'), collection : this.collection}).render();
		return this;
	},
	statusUpdate: function(event) {
		if (event.keyCode == 13) {			
			event.stopImmediatePropagation();
			var that = this;
			new Model.Entity({content: $(this.el).find('.bb-status-update').val()}, {collection: this.collection}).save({}, {
				success: function(post) {
					that.collection.add([post], {at: 0});
				}
			});
			$('.bb-status-update').val('');
		}
	}
});

View.SignIn = View.Autobind.extend({
	events: {
		'click .bb-facebook-connect': 'facebookConnect'
	},
	render: function() {
		return this;
	},
	facebookConnect: function() {
		$(this.el).modal('hide');
		account.facebookConnect();
	}
});

View.SignUp = View.Autobind.extend({
	events: {
		'click .bb-facebook-connect': 'facebookConnect'
	},
	render: function() {
		return this;
	},
	facebookConnect: function() {
		$(this.el).modal('hide');
		account.facebookConnect();
	}
});

View.AddPet = View.Autobind.extend({
	events: {
		'change [name=species-type]': 'changeSpeciesType',
		'select [name=species-type]': 'changeSpeciesType'
	},
	render: function() {
		return this;
	},
	classificationNameToIdMap: {
		'Dog': '694343358224588800',
		'Cat': '694343358225113088',
		'Rabbit': '694343358225637376',
		'Horse': '694343358226161664',
		'Guinea Pig': '694343358226685952',
		'Hamster': '694343358227210240'
	},
	changeSpeciesType: function() {
		var speciesType = $(this.el).find('[name=species-type]');
		var classification = $(this.el).find('[name=classification]');
		var classificationDiv = classification.parents('.js-validate');
		var breeds = $(this.el).find('[name=breeds]');
		var breedsDiv = breeds.parents('.js-validate');
		var traits = $(this.el).find('[name=traits]');
		var traitsDiv = traits.parents('.js-validate');
		if(speciesType.val() == 'Other') {
			breeds.val('');
			classification.val('');
			traits.val('');
			breedsDiv.hide();
			classificationDiv.show();
			traitsDiv.show();
		} else if (speciesType.val() != '') {
			breeds.val('');
			classification.val(speciesType.val());
			traits.val('');
			breedsDiv.show();
			autocomplete(breeds, 'BREEDS_'+this.classificationNameToIdMap[speciesType.val()], 'autocomplete-breed', function(event, ui) {
				breeds.val(ui.item.name);
			});
			classificationDiv.hide();
			traitsDiv.show();
		} else {
			breeds.val('');
			classification.val('');
			traits.val('');
			breedsDiv.hide();
			classificationDiv.hide();
			traitsDiv.hide();
		}
	}
});

View.Spotlight = {};

View.Spotlight.Entities = View.Autobind.extend({
	tagName: 'ul',
	className: 'media-grid',
	render: function() {
		$(this.el).empty();
		var that = this;
		var count = 0;
		this.collection.each(function(entity) {
			if(!account.isSignedIn() || (entity.id != account.owner.id && !account.isFollowing(entity) && !account.isOwner(entity))) {
				if(count < 6) {					
					$(that.el).append(new View.Spotlight.Entities.Entity({model: entity}).render().el);
					count++;
				}
			}
		}, this);
		return this;
	}
});

View.Spotlight.Entities.Entity = View.Basic.extend({
	events: {
		'click': 'click'
	},
	tagName: 'li',
	render: function() {
		$(this.el).html('<a data-content="'+this.model.get('displayName')+'" data-placement="below" rel="popover" data-original-title=""><img class="thumbnail-mini" src="http://petzibit-crop.s3.amazonaws.com/'+this.model.id+'.jpg"/></a>');
		return this;
	},
	click: function() {
		Backbone.history.navigate('/entities/'+this.model.id+'/wall', true);
	}
});
