var EpisodeFlipper = {
	target: null,
	postsId: 0,
	usersId: 0,
	datestamp: 0,
	posts: [],
	windowPostion: 0,
	prevWindowPosition: 0,
	prevLength: 0,
	reachedTop: false,
	reachedBottom: false,
	listH : 0,
	dir: 0,
	fragments: "",

	bumperCheck: function() {
		
		if (this.posts.length%2) {
			var limiter = 0;
		} else {
			var limiter = 1;
		}
			
	
		if (this.reachedTop && this.windowPosition <= limiter) {
			$("#EpisodeTopBumper").slideDown("fast");
		} else {
			$("#EpisodeTopBumper").slideUp("fast");
		}
		
		if (this.reachedBottom && this.windowPosition == this.posts.length-2) {
			$("#EpisodeBottomBumper").slideDown("fast");		
		} else {
			$("#EpisodeBottomBumper").slideUp("fast");
		}
	},

	correctThumb: function(t) {
		if (t) { return t; } else {
			return("/skin/mercury/images/episode_default_thumb.gif");
		}
	},

	findWindowPosition: function() {
		for(var i=0; i<this.posts.length; i++) {
			if (this.posts[i].postsId == this.postsId) {
				this.windowPosition = i;
				return i;
			}
		}

		return 0;
	},

	getDuration : function (s) {
		return(Math.floor(s/60) + ":" + this.pad(s%60));
	},

	getTitle : function(t) {
		if (t.length > 40) {
			return(t.substring(0, 40) + "..")
		} else {
			return(t);
		}
	},
	

	hideProgress: function() {
		$("#EpisodeFlipperLoading").fadeOut();
	},

	initialize: function(target,postsId,usersId,datestamp) {
		this.target = target;
		this.postsId = postsId;
		this.usersId = usersId;
		this.datestamp = datestamp;
		var self = this;
		this.load(postsId,datestamp,0,function() { 
			self.findWindowPosition(); 
			self.setFragments();
			self.render(); 
			self.bumperCheck();
		});
	},

	load: function(postsId,datestamp,direction,callback) {
		this.showProgress();

		if (typeof(callback) == "function") {
			this.loadCallback = callback;
		}

		// TODO FIXME Doesn't allow for concurrent requests.
		this.loadDatestamp = datestamp;
		this.loadPostsId = postsId;
		this.loadDirection = direction;
		this.prevLength = this.posts.length;
		
		//$.getScript("/posts/?surrounding_datestamp=" + datestamp + "&user=" + this.usersId + "&skin=json&version=2&callback=EpisodeFlipper.loaded");
		$.ajax({
			url:"/posts/?surrounding_datestamp=" + datestamp + "&user=" + this.usersId + "&nsfw=dc&hidden=0&skin=json&version=2&callback=EpisodeFlipper.loaded",
			cache:true,
			dataType:"script"
		});
	},

	loaded: function(posts) {
		
		// If we're loading previous, then add the posts before current to the beginning
		if (this.loadDirection < 0) {
			if (posts.length < 6) {
				this.reachedTop = true;
			}

			while (posts.length && posts[posts.length-1].postsId != this.loadPostsId) {
				posts.pop();
			}

			if (posts.length) {
				posts.pop();
				posts = posts.reverse();
			
				for (var i=0; i< posts.length; i++) {
					this.windowPosition++;
					this.posts.unshift(posts[i]);
				}

			}
		}
		// If we're loading next, then add the posts after the current to the end
		else if (this.loadDirection > 0) {
			if (posts.length < 6) {
				this.reachedBottom = true;
			}

			while (posts.length && posts[0].postsId != this.loadPostsId) {
				posts.shift();
			}

			if (posts.length) {
				posts.shift();
				for (var i=0; i<posts.length; i++) {
					this.posts.push(posts[i]);
				}
			}
		}
		// Otherwise we're loading the whole thing
		else {
			if (posts.length == 1) {
				$("#ep_flip_next").fadeOut();
				$("#ep_flip_prev").fadeOut();
				this.resizeForSingle();
				
			} else if (posts.length < 4) {
				if (posts.length == 2) {
					$("#ep_flip_next").fadeOut();
					$("#ep_flip_prev").fadeOut();
				}
				this.reachedTop = true;
				this.reachedBottom = true;
			}

			this.posts = posts;
		}

		// Handle callback
		if (this.loadCallback) {
			this.loadCallback();
			delete this.loadCallback;
		}

		this.prevWindowPosition = this.windowPosition;
		this.prevLength = this.posts.length;


		// TODO FIXME This won't allow for concurrent requests
		delete this.loadDatestamp;
		delete this.loadPostsId;
		delete this.loadDirection;

		this.hideProgress();
	},

	older: function() {
	
		this.dir = 1;

		this.prevWindowPosition = this.windowPosition;
		this.prevLength = this.posts.length;

				
		if (this.windowPosition < this.posts.length - 2) {
	
			this.windowPosition++;
			
			if (this.windowPosition < this.posts.length - 2) {
				this.windowPosition++;
			}

			if (!this.reachedBottom && this.windowPosition == this.posts.length - 2) {
				var post = this.posts[this.posts.length-1];
				var self = this;
				this.load(post.postsId,post.datestampUnixtime,1,function() { self.render(); });
			}
			else {
				this.render();
			}
		}

		this.bumperCheck();
	},
	
	pad : function(n) {
		if (n < 10) { return ("0" + n); } else { return n; }
	},

	newer: function() {

		this.dir = -1;

		this.prevWindowPosition = this.windowPosition;
		this.prevLength = this.posts.length;

	
		if (this.windowPosition >= 0) {
				
			if (this.windowPosition > 0) {
				this.windowPosition--;
				if (this.windowPosition > 0) {
					this.windowPosition--;
				}
			}
			
			if (!this.reachedTop && this.windowPosition <= 1) {
				var post = this.posts[0];
				var self = this;
				this.load(post.postsId,post.datestampUnixtime,-1,function() { self.render(); });
			}
			else {
				this.render();
			}
		} 
		
		this.bumperCheck();
	},
	
	render: function() {

		this.hideProgress();
		var html = "";
		
		
		for (var i=0; i<this.windowPosition; i++) {
			var post = this.posts[i];
			if (post) {
				var postThumb = this.correctThumb(post.thumbnail120Url);
				var duration = post.media && post.media.duration ? this.getDuration(post.media.duration) : this.getDuration(0);
				html += "<div class='EpisodeItem' id=" + post.datestampUnixtime +"><a href='" + post.url + this.fragments +"'><img width='80' height='60' src=" + postThumb + "></a><a href='" + post.url + this.fragments + "' class='FC_EP_Title'>" + this.getTitle(post.title) + "</a><img src='/skin/mercury/images/clock.gif'> " + duration + "<div class='clear'></div></div>";
			}
			
		}
		for (var i=this.windowPosition; i<=this.windowPosition+1; i++) {
			var post = this.posts[i];
			if (post) {
				var postThumb = this.correctThumb(post.thumbnail120Url);
				var duration = post.media && post.media.duration ? this.getDuration(post.media.duration) : this.getDuration(0);
				var specialClass = "";
				if (this.datestamp == post.datestampUnixtime) {
					specialClass =" CurrentlyPlaying";
				}
				html += "<div class='EpisodeItem"+ specialClass +"' id=" + post.datestampUnixtime +"><a href='" + post.url + this.fragments +"'><img width='80' height='60' src=" + postThumb + "></a><a href='" + post.url + this.fragments + "' class='FC_EP_Title'>" + this.getTitle(post.title) + "</a><img src='/skin/mercury/images/clock.gif'> " + duration + "<div class='clear'></div></div>";
			}
		}
		for (var i=this.windowPosition+2; i<this.posts.length; i++) {
			var post = this.posts[i];
			if (post) {
				var postThumb = this.correctThumb(post.thumbnail120Url);
				var duration = post.media && post.media.duration ? this.getDuration(post.media.duration) : this.getDuration(0);
				html += "<div class='EpisodeItem' id=" + post.datestampUnixtime +"><a href='" + post.url + this.fragments +"'><img width='80' height='60' src=" + postThumb + "></a><a href='" + post.url + this.fragments + "' class='FC_EP_Title'>" + this.getTitle(post.title) + "</a><img src='/skin/mercury/images/clock.gif'> " + duration + "<div class='clear'></div></div>";
			}
		}
		

		this.target.innerHTML = html;	
		this.repositionEpisodes();
		
		$("#EpisodeBottomBumper").dequeue();
		$("#EpisodeTopBumper").dequeue();		
	},
	
	repositionEpisodes: function() {
		
		
		if (this.windowPosition > 0) {
			if (this.windowPosition == this.posts.length-1) {
				this.windowPosition--;
			}
		}

		var toggledItem = $("#" + this.posts[this.prevWindowPosition].datestampUnixtime);
		var tlHeight = $(toggledItem).height() + 22;
		$(this.target).css("margin-top", (0-((this.prevWindowPosition) * tlHeight)));
		var moveTo = (0-(this.windowPosition * tlHeight));
			
		$(this.target).animate({
			marginTop: moveTo
		}, 350);
	},
	
	resizeForSingle: function() {
		$(this.target).height(80);
		$("#EpisodeFlipperWrapper").height(93);
		$("#EpisodeItemHolderWrapper").height(93);		
	},

	setFragments: function(){
		var url = new Url(window.location.href);
		var fileType = url.getQueryParam("file_type");
		if (fileType != null) {
			this.fragments = "?file_type=" + fileType;	
		}
	},

	showProgress: function() {
		$("#EpisodeFlipperLoading").fadeIn();
	}
};

