var Homepage = new Class({
	videos: null,
	videoStarttimes: null,
	playing: {},
	
	initialize: function(videos, videoStarttimes) {
		this.videos = videos;
		this.videoStarttimes = videoStarttimes;
		(Browser.Engine.trident ? $(document.body) : window).addEvent("mousemove", this.onMousemove.create({bind:this}));
		this.showTimes.periodical(500, this);
	},
	
	showTimes: function() {
		var date = new Date();
		this.videoStarttimes.each(function(videoStarttime, index) {
			var starttime = this.currentStarttime(videoStarttime);
			var secondsLeft = videoStarttime.duration - starttime;
			var minutesLeft = Utils.getMinutes(secondsLeft * 1000);
			var timeRemainingEl = $("timeRemaining" + (index+1));
			if (secondsLeft > 0) {
				timeRemainingEl.set(
					"text", 
					"(nog " + (minutesLeft >= 1 ? minutesLeft : "< 1") + " min!)"
				);
			} else {
				timeRemainingEl.set(
						"text", 
						"(afgelopen)"
					);
			}
		}, this);
	},
	
	currentStarttime: function(starttime) {
		return parseInt(((new Date() - starttime.date) / 1000) + starttime.sec);
	},
	
	onMousemove: function(evt) {		
		var id = this.getVideoId(evt.target);		
		if (id !== null) {
			var currentVideo = this.videos[id-1];		
			var currentState = currentVideo.currentState;
			if (currentState == "Paused" || currentState == "Closed") {
				if (!$defined(this.playing[id-1])) {
					this.playing[id-1] = true;
					var starttime = this.currentStarttime(this.videoStarttimes[id-1]);
					
					var videoEl = $("video" + id);
					if (videoEl.hasClass("loaded")) {
						this.videos[id-1].play();
					} else {
						this.videos[id-1].start({sec:starttime});
						videoEl.addClass("loaded");
					}
				}
			}
		} 
		for (var i=0, len=this.videos.length; i<len ;i++) {			
			if (id !== null && id == (i+1))				
				continue;
			
			
			if (this.videos[i].currentState != "Paused" && this.videos[i].currentState != "Closed") {
				this.videos[i].pause();
				delete this.playing[i];				
			}
		}
	},

	getId: function(videoEl) {
		return videoEl.id.substring("video".length);
	},
	
	getVideoId: function(node) {
		return node && node.parentNode && $(node.parentNode).hasClass && $(node.parentNode).hasClass("video") ? 
				this.getId($(node.parentNode)) : null;
	}
});