var Router = {};

Router.App = Backbone.Router.extend({
	routes : {
		"" 				: "home",
		"/stream" 		: "stream",
		"/groups" 		: "groups",
		"/settings" 	: "settings",
		"/search" 		: "search",
		"/releases"		: "releases",
		"/messages"		: "messages",
		"/members"		: "findMembers",
		"/pets"			: "findPets",
		"/notifications": "notifications",
		
		// ////////////////////////
		// Owner
		// ////////////////////////
		"/entities/:entityId/albums/:albumId" 	: "album",
		"/entities/:entityId/blog" 				: "blog",
		"/entities/:entityId/photos" 			: "photos",
		"/entities/:entityId/pets" 				: "pets",
		"/entities/:entityId/followers" 		: "followers",
		"/entities/:entityId/following" 		: "following",
		"/entities/:entityId/wall" 				: "wall",
		"/entities/:entityId/posts/:postId"		: "post"
	},
	accountFilter : function(callback, title) {
		if (account.isSignedIn()) {
			$('#topbar').show();
			window.entity = account.owner;
			$('#stage').html(new View.PetOrOwner({buttons: [], model: entity, title: title}).render().el);
			callback();
		}
	},
	entityFilter : function(entityId, callback, title, buttons) {
		new Model.Entity({id: entityId}).fetch({
			success: function(entity) {
				$('#topbar').show();
				window.entity = entity;
				$('#stage').html(new View.PetOrOwner({buttons: buttons, model: entity, title: title}).render().el);
				callback(entity);
			}
		});
	},
	releases: function() {
		$('#stage').html(new View.Releases({}).render().el);
	},
	home : function() {
		$('#topbar').hide();
		if(account.isSignedIn()) {
			this.stream();
		} else {
			$('#stage').html(new View.FrontPage({}).render().el);
		}
	},
	findMembers: function() {
		$('#topbar').show();
		$('#stage').html(new View.Find.Owners({collection: window.members}).render().el);
	},
	findPets: function() {
		$('#topbar').show();
		$('#stage').html(new View.Find.Pets({collection: window.pets}).render().el);
	},
	messages: function() {
		this.accountFilter(function() {
			
		}, 'Messages');
	},
	notifications: function() {
		this.accountFilter(function() {
			new Collection.Entity([], {url: '/json/notifications'}).fetch({
				success: function(notifications) {
					$('#spotlight').html(new View.Notifications({collection: notifications}).render().el);
				}
			});
		}, 'Notifications');
	},
	stream : function() {
		this.accountFilter(function() {
			new Collection.Entity([], {url: '/json/stream'}).fetch({
				success: function(stream) {
					$('#spotlight').html(new View.Stream({collection: stream}).render().el);
				}
			});
		}, 'Home');
	},
	settings : function() {
		this.accountFilter(function() {
			$('#spotlight').html(new View.Settings({}).render().el);
		}, 'Settings');
	},
	search : function() {

	},
	wall : function(entityId) {
		this.entityFilter(entityId, function(entity) {
			new Collection.Entity([],{url: '/json/entities/'+entityId+'/statusUpdates'}).fetch({
				success: function(posts) {
					$('#spotlight').html(new View.Wall({model: entity, collection: posts}).render().el);
				}
			});
		}, 'Wall');
	},
	
	album : function(entityId, albumId) {
		this.entityFilter(entityId, function() {
			new Model.Entity({id: albumId}).fetch({
				success: function(album) {						
					new Collection.Entity([],{url : '/json/entities/'+albumId+'/images'}).fetch({
						success: function(images) {
							var view = new View.ImageCollection({collection : images, album: album});
							$('#spotlight').html(view.render().el);
							if(account.isCurrentOwner()) {
								releaseTheSWF(album.id, view);
							}
						}
					});
					$('#title').html('<a href="#/entities/'+entityId+'/photos">Photos</a> &gt; ' + album.get('name'));
					$('.bb-photos').addClass('active');
				}
			});
		}, '', [{jsClass: 'js-add-photos-form', label: 'Add Photos'}]);
	},
	
	blog : function(entityId) {
		this.entityFilter(entityId, function() {
			new Collection.Entity([],{url: '/json/entities/'+entityId+'/blogPosts'}).fetch({
				success: function(posts) {
					$('#spotlight').html(new View.PostCollection({collection : posts}).render().el);
				}
			});
		}, 'Blog', [{jsClass: 'js-add-entry-form', label: 'Add Entry'}]);
	},
	post: function(entityId, postId) {
		this.entityFilter(entityId, function() {
			new Model.Entity({id: postId}).fetch({
				success: function(post) {
					var type = post.get('type');
					if(type == 'ALBUM') {
						$('#spotlight').html(new View.Album({model: post}).render().el);
					} else if(type == 'IMAGE') {
						$('#spotlight').html(new View.ImageCollection({collection: new Collection.Entity([post])}).render().el);
					} else if(type == 'BLOG') {
						$('#spotlight').html(new View.Post({model: post}).render().el);
					} else if(type == 'STATUS_UPDATE') {
						$('#spotlight').html(new View.Post({model: post}).render().el);
					}
				}
			});
		}, '');
	},
	photos : function(entityId) {
		this.entityFilter(entityId, function() {
			new Collection.Entity([],{url: '/json/entities/'+entityId+'/albums'}).fetch({
				success: function(albums) {
					var view = new View.Photos({collection: albums});
					$('#spotlight').html(view.render().el);
					if(account.isCurrentOwner()) {
						releaseTheSWF(albums.getByAttribute('name', 'Unassigned').id, view);
					}
				}
			});
		}, 'Photos', [{jsClass: 'js-add-album-form', label: 'Add Album'}]);
	},
	
	pets : function(entityId) {
		this.entityFilter(entityId, function() {
			new Collection.Entity([], {url: '/json/entities/' + entityId + '/pets'}).fetch({
				success : function(pets, response) {
					$('#spotlight').html(new View.Pets({collection : pets}).render().el);
				}
			});
		}, 'Pets',  [{jsClass: 'js-add-pet-form', label: 'Add Pet'}]);
	},
	
	followers : function(entityId) {
		this.entityFilter(entityId, function() {
			new Collection.Entity([], {url: '/json/entities/' + entityId + '/followers'}).fetch({
				success : function(followers, response) {
					$('#spotlight').html(new View.Followers({collection : followers}).render().el);
				}
			});
		}, 'Followers');
	},
	
	following : function(entityId) {
		this.entityFilter(entityId, function() {
			new Collection.Entity([], {url: '/json/entities/' + entityId + '/following'}).fetch({
				success : function(following, response) {
					$('#spotlight').html(new View.Following({collection : following}).render().el);
				}
			});
		}, 'Following');
	},
	
	addAlbum: function(response) {
		$('#js-add-album-form').modal('hide');
		Backbone.history.navigate('/entities/'+entity.id+'/albums/'+response.id, true);
	},
	
	addPet: function(response) {
		$('#js-add-pet-form').modal('hide');
		Backbone.history.navigate('/entities/'+response.id+'/wall', true);
	},
	
	addPost: function(response) {
		$('#js-add-entry-form').modal('hide');
		Backbone.history.reload();
	},
	
	signin: function(response) {
		account.load({
			success: function() {
				$('#js-account-signin-form').modal('hide');
				Backbone.history.navigate('/stream', true);
			}
		}, new Model.Entity(response.owner));
	},
	
	signup: function(response) {
		account.load({
			success: function() {
				$('#js-account-signup-form').modal('hide');
				Backbone.history.navigate('/entities/'+account.owner.id+'/wall', true);
			}
		}, new Model.Entity(response.owner));
	},
	
	signout: function() {
		account.signout();
	},
	
	facebookConnect: function(options) {
		account.facebookConnect({
			success: function() {
				Backbone.history.navigate('/stream', true);
			}
		});
	}
});

$(document).ready(function() {	
	window.templates = new Collection.Template();
	templates.fetch({
		success: function() {
			window.fbAsyncInit = function() {
				FB.init({
					appId : '268348959861956', 								// App ID
					channelUrl : 'channel.html', 	// Channel File
					status : true, 											// check login status
					cookie : true, 											// enable cookies to allow the server to access the session
					xfbml : true											// parse XFBML
				});
				
				account.load({
					error: function() {
						this.start();
					},
					success: function() {
						this.start();
					},
					start: function() {
						
						// Add reload capabilities to Backbone.history
						Backbone.history.reload = function() {
							this.loadUrl(document.location.hash.replace('#', ''));
						};
						
						// Wrap loadUrl to record activity in GA
						Backbone.history.oldLoadUrl = Backbone.history.loadUrl;
						Backbone.history.loadUrl = function(fragmentOverride) {
							// Track stuff
							_gaq.push(['_trackPageview',location.pathname + location.search  + location.hash]);
							// Scroll browser to the top left
							window.scrollTo(0, 0);
							return Backbone.history.oldLoadUrl(fragmentOverride);
						};

						$(document).on('mouseover', '.toolhelper', function(event) {
							$(this).find('.toolbox').show();
						});
						$(document).on('mouseleave', '.toolhelper', function(event) {
							$(this).find('.toolbox').hide();
						});					
						
						$('#topbar').html(new View.TopBar({model: account}).render().el);
						new View.Footer({el: $('#footer')}).render();
						
						
						if(!Backbone.history.start()) {
							app.navigate('/', true);
						}
					}
				});
			};

			window.account = new Model.Account();	
			window.entity = new Model.Entity();
			window.app = new Router.App();
			
			window.members = new Collection.Entity([],{url: '/json/owners'});
			window.members.fetch();
			window.pets = new Collection.Entity([],{url: '/json/pets'});
			window.pets.fetch();
			
			$('#backstage').append(templates.get('add-album-form').get('html'));
			$('#backstage').append(templates.get('add-photos-form').get('html'));
			$('#backstage').append(templates.get('add-entry-form').get('html'));
			$('#backstage').append(templates.get('add-pet-form').get('html'));
			$('#backstage').append(templates.get('signin-form').get('html'));
			$('#backstage').append(templates.get('signup-form').get('html'));
			
			$('#js-add-entry-form').form(function() {return '/json/entities/'+entity.id+'/blogPosts';}, {title: null, body: null}, {success: app.addPost}, app);
			$('#js-add-pet-form').form(function() {return '/json/entities/'+account.owner.id+'/pets';}, {displayName: null, 'species-type': null, breeds: null, about: null, traits: null, classification: null}, {success: app.addPet}, app);
			$('#js-add-album-form').form(function() {return '/json/entities/'+entity.id+'/albums';}, {name: null, caption: null}, {json: true, success: app.addAlbum}, app);
			$('#js-account-signin-form').form('/json/signin', {email : null, password : null}, {success: app.signin});
			$('#js-account-signup-form').form('/json/signup', {name : null, email : null, password : null, confirmPassword : null}, {success: app.signup});
			
			new View.SignIn({el: $('#js-account-signin-form')});
			new View.SignUp({el: $('#js-account-signin-form')});
			new View.AddPet({el: $('#js-add-pet-form')});
			
			$('#js-add-photos-form').bind('show', function () {
				$(this).find('.modal-body tbody').empty();
				$('#uploaded-photos-table').hide();
			});
			
			(function(d, s, id) {
			  var js, fjs = d.getElementsByTagName(s)[0];
			  if (d.getElementById(id)) return;
			  js = d.createElement(s); js.id = id;
			  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=268348959861956";
			  fjs.parentNode.insertBefore(js, fjs);
			}(document, 'script', 'facebook-jssdk'));
			
			$().popover({live: true});
		}
	});
});

