var Model = {};

Model.Iterator = Backbone.Model.extend({
	next: function() {
		return this.collection ? this.collection.next(this) : this;
	},
	prev: function() {
		return this.collection ? this.collection.prev(this) : this;
	}
});

Model.Entity = Model.Iterator.extend({
	urlRoot: '/json/entities',
	showComments: false,
	url: function() {
		if(this.id) return this.urlRoot+'/'+this.id;
		if(this.collection && this.collection.url) return this.collection.url;
		return this.urlRoot;
	},
	toggleLike: function() {
		if(this.get('likedByMe')) {
			var that = this;
			$.ajax({
				type: 'DELETE',
				url: '/json/entities/'+this.id+'/likes',
				success: function() {
					that.fetch();
				}
			});
		} else {
			var that = this;
			$.ajax({
				type: 'POST',
				url: '/json/entities/'+this.id+'/likes',
				success: function() {
					that.fetch();
				}
			});
		}
	},
});

Model.Account = Backbone.Model.extend({
	owner: undefined,
	groups: undefined,
	isSignedIn: function() {
		if(this.owner) {
			return true;
		}
		return false;
	},
	isCurrentOwner: function() {
		if(account.isSignedIn() && (entity.id == this.owner.id || this.isOwner(entity))) {
			return true;
		}
		return false;
	},
	isOwner: function(entity) {
		if(entity.get('type') == 'PET' && _.indexOf(entity.get('ownerIds'), this.owner.id) > -1) {
			return true;
		}
		return false;
	},
	isFollowing: function(ownerId) {
		if(account.following && account.following.get(ownerId)) {
			return true;
		}
		return false;
	},
	canManage: function(entity) {
		if(this.isSignedIn() && entity) {
			if(entity instanceof Backbone.Model) {
				// TODO: handle this
			} else {
				if((entity.contributor && (entity.contributor == this.owner.id)) 
						|| (entity.contributedTo && entity.contributedTo == this.owner.id)) {
					return true;
				}
			}
		}
		return false;
	},
	follow: function(entityId, options) {
		$.ajax({
			url: '/json/entities/'+entityId+'/followers',
			type: 'POST',
			error: function() {
				if(options && options.error) {
					options.error();
				}
			},
			success: function() {
				account.loadFollowing(options);
				window.members.fetch();
			}
		});
	},
	getContributedTo: function(entity) {
		if(window.entity.get('type') == 'PET') {
			if(window.entity.attributes.ownerIds.indexOf(entity.contributor) > -1) {
				return entity.contributedTo;
			} else {
				return entity.contributor;
			}
		} else if(entity.contributedTo == window.entity.id) {
			return entity.contributor;
		}
		return entity.contributedTo;
	},
	getContributedToName: function(entity) {
		if(window.entity.get('type') == 'PET') {
			if(window.entity.attributes.ownerIds.indexOf(entity.contributor) > -1) {
				return entity.contributedToName;
			} else {
				return entity.contributorName;
			}
		} else if(entity.contributedTo == window.entity.id) {
			return entity.contributorName;
		}
		return entity.contributedToName;
	},
	unfollow: function(entityId, options) {
		$.ajax({
			url: '/json/entities/'+entityId+'/followers',
			type: 'DELETE',
			error: function() {
				if(options && options.error) {
					options.error();
				}
			},
			success: function() {
				account.loadFollowing(options);
				window.members.fetch();
			}
		});
	},
	loadFollowing: function(options) {
		new Collection.Entity([], {url: '/json/entities/'+account.owner.id+'/following'}).fetch({
			success: function(following) {
				account.following = following;
				account.trigger('change');
				if(options && options.success) {
					options.success();
				}
			}
		});
	},
	facebookConnect: function(options) {
		FB.login(function(response) {
			 if (response.authResponse) {
				 FB.api('/me', function(response) {
					 account.load({
						 success: function() {
							 if(options && options.success) {options.success();}
						 }
					 });
				 });
			 } else {
			 }
		 }, {scope: 'email'});
	},
	load: function(options, owner) {
		if(owner) {
			account.setOwner(owner, options);
		} else {
			FB.getLoginStatus(function(response) {
				var accessToken = '';
				var userId = '';
				if (response.status === 'connected') {
					userId = response.authResponse.userID;
					accessToken = response.authResponse.accessToken;
				} else if (response.status === 'not_authorized') {
				} else {
				}
				$.ajax({
					  url: '/json/account',
					  data: {
						  fbAccessToken: accessToken,
						  fbUserId: userId
					  },
					  dataType: 'json',
					  error: function(response) {
						  if(options.error) {options.error();};  
					  },
					  success: function(response) {
						  account.setOwner(new Model.Entity(response.owner), options);
					  }
				});
			});
		}
	},
	setOwner: function(owner, options) {
		account.owner = owner;
		this.loadFollowing(options);
	},
	signout: function() {
		FB.logout(function(response) {
			$.getJSON("/json/signout", function(response) {
				account.owner = undefined;
				if(account.following) {
					account.following.reset();
				}
				account.trigger('change');
			});
		});
	}
});

Model.Template = Backbone.Model.extend({
	initialize: function() {
		this.compiled = _.template(this.get('html'));
	}
});

Model.NotificationCount = Backbone.Model.extend({
	url: '/json/notifications/count',
	init: function() {
		window.notificationCount = this;
	},
	start: function() {
		setInterval(this.poll, 30000);
	},
	poll: function() {
		window.notificationCount.fetch();
	}
});
