relatedVidLinks = {
	containerHeight: 0,
	totalVideosHeight: 0,
	videos: [],
	activeVideoIndex: 0,
	speed: 500,
	scroll: function(dir) {
		var newVideoIndex, oldVideoIndex;
		newVideoIndex = oldVideoIndex = this.activeVideoIndex;
		if (dir == 'up' && oldVideoIndex > 0) {
			newVideoIndex = oldVideoIndex - 1;
		} else if (dir == 'down' && oldVideoIndex < (this.videos.length -1)) {
			newVideoIndex = oldVideoIndex + 1;
		}
		
		this.scrollToVideo(newVideoIndex);
		this.activeVideoIndex = newVideoIndex;
		if (this.activeVideoIndex == 0) {
			$('#relatedVideos .up').css('background-position','0 -100px');
			$('#relatedVideos .down').css('background-position','0 0');
		} else if (this.activeVideoIndex == (this.videos.length -1)) {
			$('#relatedVideos .up').css('background-position','0 0');
			$('#relatedVideos .down').css('background-position','0 -100px');
		} else {
			$('#relatedVideos .scroll').css('background-position','0 0');
		}
	},
	scrollToVideo: function(i) {
//		alert(this.videos[i].top+'px');
		$('#relatedVideos div.wrapper').animate({
			top: '-' + this.videos[i].top
		},this.speed);
	},
	init: function() {
		this.containerHeight = $('#relatedVideos').height();
		var c = this;
		$('#relatedVideos div.video').each(function(p) {
			var height = $(this).outerHeight(true);
			c.videos.push({'height': height,'top': c.totalVideosHeight, 'bottom': (c.totalVideosHeight + height)});
			c.totalVideosHeight = c.totalVideosHeight + height;
			var link = $(this).find('a').attr('href');
			$(this).click(function() {
				window.location.href = link;
			});
			if ($(this).hasClass('active')) {
				c.activeVideoIndex = p;
			}
		});
		if (this.containerHeight < this.totalVideosHeight) {
			$('#relatedVideos').css('height',this.containerHeight+'px').wrapInner('<div class="wrapper"></div>').prepend('<div class="scroll up"><a href="#">Scroll Up</a></div>').append('<div class="scroll down"><a href="#">Scroll Down</a></div>');
//			for (var i=0; i<this.videos.length; i++) {
//				alert('height: ' + this.videos[i].height + ', top: ' + this.videos[i].top);
//			}
			this.scroll(this.activeVideoIndex);
			$('#relatedVideos .up a').click(function(e) {
				e.preventDefault();
				c.scroll('up');
			});
			$('#relatedVideos .down a').click(function(e) {
				e.preventDefault();
				c.scroll('down');
			});
		}
	}
}

$(document).ready(function() {
	relatedVidLinks.init();
});
