var player = null;

var Browser = { 
	isChrome: (navigator.userAgent.indexOf('Chrome') > -1),
	isFirefox: Prototype.Browser.Gecko,
	supportsVideo: (!!document.createElement('video').canPlayType)
};

var Util = {
	getRelativePosition: function(x, relativeElement) {
	    return Math.max(0, Math.min(1, (x - this.findPosX(relativeElement)) / relativeElement.offsetWidth));
	},
	getMouseX: function(e) {
		if (e.pageX) { 
			return e.pageX;		 
		}
		else if (e.clientX) { // IE
			return e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
		}
		else {
			return null;
		}
	},
	// Get an element's x offset on the page
	findPosX: function(element) {
	    var curleft = element.offsetLeft;
	    
		while(element = element.offsetParent) {
			curleft += element.offsetLeft;
		}
	    
	    return curleft;
	},
	blockTextSelection: function() {
		document.body.focus();
		document.onselectstart = function () { return false; };
	},
	unblockTextSelection: function() {
		document.onselectstart = function () { return true; };
	}
};

var Plugin = Class.create({
	initialize: function(name) {		
		this.name = name; // silverlight, flash, ...
		
		this.version = {
			text: '',
			major: -1,
			minor: -1
		}
		
		this.setVersion();
		
		this.isInstalled = this.version.major > -1;
	},
	setVersion: function() {
		if(window.ActiveXObject) {
			this.setActiveXVersion();
		}
		else {					
			this.setNavigatorVersion();
		}
	},
	getNavigatorPlugin: function() {		
		try {
			if(this.name == 'flash') {
				return navigator.plugins['Shockwave Flash'];
			}
		}
		catch(e) { }
		
		return null;
	},
	getActiveXObject: function() {
		try {
			if(this.name == 'flash') {
				return new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
			}
    	}
    	catch(e) { }
        
        return null;
	},
	setActiveXVersion: function() {
		try {
			var activeXObject = this.getActiveXObject();
				
			if(activeXObject) {
				if(this.name == 'flash') {
					var versionText = activeXObject.GetVariable('$version');
					
					var versionArray = versionText.split(',');
	               
	   				this.version.text =	versionText;
	        		this.version.major = parseInt(versionArray[0].split(' ')[1], 10);
	        		this.version.minor = parseInt(versionArray[1], 10);
	        	}
			}
		}
		catch(e) { }
    },
    setNavigatorVersion: function() {
    	try {
	    	var navigatorPlugin = this.getNavigatorPlugin();
				
			if (navigatorPlugin) { 				
				var versionText = navigatorPlugin.description;
					
		    	this.version.text = versionText;
		    	
		    	if(versionText.startsWith('Shockwave')) {
		        	var descParts = versionText.split(/ +/);
		        	var majorMinor = descParts[2].split(/\./);
		        	var revisionText = descParts[3];
		        	        	
		            this.version.major = parseInt(majorMinor[0], 10);
		        	this.version.minor = parseInt(majorMinor[1], 10);
		        }
		        else {
		        	var versionParts = versionText.split('.');
		        	
		        	this.version.major = parseInt(versionParts[0], 10);
		        	this.version.minor = parseInt(versionParts[1], 10);
		        }
			}
		}
		catch(e) { }
    }
});

var MediaPlayers = {
	instances: new Hash(),
	
	get: function(el) {
		var element = $(el);
		
		return this.instances.get(element.id);
	},
	setup: function() {		
		var base = this;
		
		var i = 0;
		
		var playerEls = $$('.mediaPlayer');
		
		playerEls.each(function(playerEl) {
			
			var layout = playerEl.getLayout();
			
			var options = { 
				width: layout.get('width'), 
				height: layout.get('height')
			};
		
			var mediaPlayer;

			var errorTitle = playerEl.down('.unsupportedGuts h3');
			var errorDescription = playerEl.down('.unsupportedGuts h4');
			
			if(Browser.supportsVideo && (document.createElement('video').canPlayType('video/mp4') || document.createElement('video').canPlayType('video/webm'))) {
				mediaPlayer = new HtmlMediaPlayer(playerEl, options);
			}
			else
			{
				var flash = new Plugin('flash');
				
				if(flash.isInstalled) {
					if(flash.version.major >= 10) { // Flash 10.0+
						mediaPlayer = new FlashMediaPlayer(playerEl, options);
					}
					else { // Flash is out of date
						playerEl.addClassName('unsupported');
						
						errorTitle.update('You need to upgrade Flash to play this video.');
						errorDescription.update('<a href="http://get.adobe.com/flashplayer/">Download the latest Adobe Flash plugin.</a>/');
					}
				}
				else { // No plugin
					playerEl.addClassName('unsupported');
					
					errorTitle.update('You need Adobe Flash to play this video.');
					errorDescription.update('Download Adobe Flash <a href="http://get.adobe.com/flashplayer/">here</a>.');
				}
			}
			
			if(mediaPlayer) {
				mediaPlayer.index = i;
				
				base.instances.set(mediaPlayer.element.id, mediaPlayer);
			
				player = mediaPlayer;
					
				i++;

			}
							
			try { window.addEventListener('unload', MediaPlayers.cleanup, false); }
			catch(e) { }

		});
	},
	cleanup: function() {
		try { player.pluginEl.remove(); }
		catch(e) { }
	}
};

var MediaSource = Class.create({
	initialize: function(url, type) {	
		this.url = url;
		this.type = type;
		
		this.canPlay = (Browser.supportsVideo && document.createElement('video').canPlayType(this.type));
	}
});

var MediaPlayer = Class.create({
	initialize: function(element, options) {	
		var base = this;
		
		this.movieName = 'player_1';
		this.autoPlay = true;
		this.jsReady = false;	
		this.state = 'uninitialized';
		this.videoReady = false;
		
		/*
		 * Used to store any cached Flash commands
		 */
		this.cache = {
			url: null,
			volume: null,
			seek: null,
			playState: null
		};
				
		this.isReady = false;
		this.isPlaying = false;
		this.duration = 0;
		this.currentTime = 0;

		this.element = element;
		this.video = this.element.down('video');
		this.playOverlay = this.element.down('.playOverlay');
		this.posterEl = this.element.down('.poster');
		
		this.mediaSrc = this.video.src;
		
		this.sources = [];
		
		this.video.select('source').each(function(sourceEl) {			
			base.sources.push(new MediaSource(sourceEl.src, sourceEl.type));
		});
		
		if(!this.mediaSrc && this.sources.length > 0) {
			this.mediaSrc = this.sources[0].url;
		}
		
		if(!this.element.id) {
			this.element.identify();
		}
		
		this.options = {
			defaultVolume: 0.80, // Will be overridden by localStorage volume if available,
			width: 768,
			height: 432
		};

		if(options && typeof options == 'object') {
			Object.extend(this.options, options);
		}
		
		this.width = this.options.width;
		this.height = this.options.height;
		
		this.supportsFullscreen = !Browser.isChrome && typeof(this.video.webkitSupportsFullscreen) !== 'undefined';
					
		this.controller = new MediaController(this);
	
		this.element.on('mouseover', 	Util.blockTextSelection);
		this.element.on('mouseout', 	Util.unblockTextSelection);
		
		this.element.on(Browser.isFirefox ? 'click' : 'mouseup', this.onClick.bind(this));

		this.element.on('mousemove', 	this.onMouseMove.bind(this));		// Show the controller on mouse move
		this.element.on('mouseout', 	this.onMouseOut.bind(this));		// Hide the controller on mouse out
		
		document.on('keydown', this.onKeyDown.bind(this)); 				// Watch key down events

		this.setup();
	},
	
	setSources: function(sources) {
		this.sources = sources;			
	},
		
	onClick: function(e) {		
		var c = e.findElement('.controller');
		
		if(!c) {			
			this.togglePlay();
		}
		else {
			// .controller
		}
	},
	onMouseMove: function(e) {
		this.controller.show();
    
		if(this.mouseMoveTimeout) {
			clearInterval(this.mouseMoveTimeout);
		}
    	
    	if(this.isPlaying) {
			this.mouseMoveTimeout = setTimeout(function() {         		
				this.controller.hide(); }.bind(this), 4000
			);
		}
	},
	onMouseOut: function(e) {				
		Event.stop(e);
		
		if(!this.isPlaying) { 
			return;
		}
		
		var controllerEl = this.controller.element;
			
		// Prevent flicker by making sure mouse hasn't left the video    
    	var parent = e.relatedTarget;

		while (parent && parent !== this.video && parent !== controllerEl) {
			parent = parent.parentNode;
		}
    
		if (parent !== this.video && parent !== controllerEl) {
			this.controller.hide();
		}
	},
	play: function(e) {
		if(e) {
			Event.stop(e);
		}
				
		this.isPlaying = true;
  		
  	this.element.removeClassName('paused');
  	
  	this.element.addClassName('played');
  	this.element.addClassName('playing');
  		
    this.controller.playControlEl.className = 'playControl pauseButton';
    	
    this.controller.show();

		this._play();
	},
	pause: function() {		
		this.element.removeClassName('waiting');
		
		this._pause();
		
		this.isPlaying = false;
		
		this.element.removeClassName('playing');
		
		this.element.addClassName('paused');
		
    	this.controller.playControlEl.className = 'playControl playButton';
    	
    	this.controller.show();
	},
	seek: function(time) {
		this.element.addClassName('seeking');
		
		this._seek(time);
	},
	setVolume: function(volume) {
		var vol = parseFloat(volume);
		
		this.controller.volumeControl.setVolume(vol);
		
		localStorage.volume = vol;
		
		// Call the internal implementation
		this._setVolume(vol);
	},
	setDefaultVolume: function() {
		var volume = localStorage.volume || this.options.defaultVolume;
		
		// Set to stored volume OR 85%
		this.setVolume(volume);
	},
	
	setPosterSrc: function(src) {		
		this.posterEl.style.backgroundImage = 'url("' + src + '")';
	},
	reset: function() {
		this.isPlaying = false;
		
		var base = this;
		
		var states = ['played', 'playing', 'seeking', 'paused', 'waiting'];
		
		states.each(function(state) {
			base.element.removeClassName(state);
		});
				
		this.controller.reset();
	},
	
	toggleFullscreen: function() {
		if(this.video.webkitSupportsFullscreen) { 
			
			this.video.webkitEnterFullScreen(); 
		}
	},
	togglePlay: function() {		
		if(this.isPlaying) {
			this.pause();
		}
		else {
			this.play();
		}
	},
	onWaiting: function() {		
		this.element.addClassName('waiting');
	},
	onSeeking: function(e) {
  		this.element.addClassName('waiting');
  		this.element.addClassName('seeking');
  		
  		this.isSeeking = true;
	},
	onSeeked: function() {
		this.element.removeClassName('waiting');
  		this.element.removeClassName('seeking');
  		
  		this.isSeeking = false;
	},
	onLoadProgress: function(progress) {
		if(progress) {	
			this.controller.scrubber.setLoadProgress(progress);		
		}		
	},
	onCurrentTimeChange: function(time) {
		this.currentTime = time;
		
		this.controller.scrubber.setCurrentTime(time);
		
		this.element.removeClassName('waiting');
	},
	onFullscreen: function() {
		this.element.addClassName('fullscreen');		
	},
	onKeyDown: function(e) {
		if(this.isFullscreen) {
			if (e.keyCode == 27) { // ESCAPE KEY
				this.fullscreenOff();
			}
		}
		
		var allowSpace = this.element.up().hasClassName('outer');
		
		if(allowSpace && e.keyCode == 32) { // Space
			Event.stop(e);
			
			this.togglePlay();
		}
	},
	fullscreenOn: function() {
		this.isFullscreen = true;
		
		if(this.video.webkitSupportsFullscreen) { 
			
			this.video.webkitEnterFullScreen(); 
 
 			return;
		}
	},
	fullscreenOff: function() {
    	this.isFullscreen = false;
    	
		// HACK (Webkit manages its own off state)
		if(this.video.webkitSupportsFullscreen) {			
			return;
		}	
	}
});

function debug(message) {
	// $('debug').insert( message + '<br />' );
}

var FlashMediaPlayer = Class.create(MediaPlayer, {
	setup: function() {		
	
		this.video.hide(); // Hide the native video element
				
		this.pluginPlaceholder = this.element.down('.fallback');
	
		this.movieName = 'player_1';
											
		var objectHtml = this.getPluginHTML();
		
		this.pluginPlaceholder.update(objectHtml);
		
		this.pluginEl = document.getElementById(this.movieName);
	},
	getPluginHTML: function () {		
		this.autoPlay = false;
		
		var vars = {
			url: this.mediaSrc,
			backgroundColor: '0x000000',
			width: this.options.width,
			height: this.options.height,
			autoPlay: this.autoPlay,
			playerRef: 'player'
		};
						
		var windowMode = 'opaque';
		var pluginSrc = 'http://s.cmcdn.net/scripts/player/2011-02-01.swf';
		
		if(Prototype.Browser.IE) {
			pluginSrc += '?' + new Date().getTime();
		}
		
		debug(pluginSrc);
		
		return [
			'<object',
				' id="', this.movieName, '"',
				' name="', this.movieName, '"',
				' type="application/x-shockwave-flash"',
				' data="', pluginSrc, '"',
				' width="', this.options.width, '"', 
				' height="', this.options.height, '"',
			'>',
			
				'<param name="wmode" value="opaque" />',
				'<param name="movie" value="', pluginSrc, '" />',
				'<param name="quality" value="high" />',
				'<param name="menu" value="false" />',
				'<param name="allowScriptAccess" value="always" />',
				'<param name="flashvars" value="' + Object.toQueryString(vars) + '" />',
			'</object>'
		].join("");
	},
	callFlash: function(functionName, argument) {	
		try {
			(argument != null) ? this.pluginEl[functionName](argument) :  this.pluginEl[functionName]();
		}
		catch (ex) {
			debug("Exception calling flash function '" + functionName + "': " + ex.message);
		}
	},
	callback: function (functionName, argument) {
		if (this[functionName] != null) {
			try {
				argument != null ? this[functionName](argument) :  this[functionName]();
			}
			catch (ex) {
				debug("Exception calling player function '" + functionName + "': " + ex.message);
			}
		}
	},
	
	reload: function() {					
		this.loadUrl(this.sources[0].url);
	},	

	loadUrl: function(url) {
		this.reset();
		
		if (this.jsReady) { 
			this.callFlash('_loadUrl', url);
		}
		else {
			this.cache.url = url;
		}
		
		return this;
	},
	
	_play: function() {
		if (this.jsReady && this.videoReady) {
			this.callFlash('_play');
		}
			
		else this.cache.playState = 'play';
		return this;
	},
	_pause: function() {
		if ( this.jsReady && this.videoReady ) {
			this.callFlash('_pause');
		}
		else {
			this.cache.playState = 'pause';
		} 
		
		return this;
	},
	_setVolume: function(level) {
		if (this.jsReady) {
			this.callFlash('_setVolume', level);
		}
		else { 
			this.cache.volume = level;
		}
		
		return this;
	},
	_seek: function(time)  {
		if (this.jsReady && this.videoReady) {
			this.callFlash('_seek', time);
		}
		else this.cache.seek = time;
		return this;
	},
		
	onDebug: function( message ) {
		debug('onDebug: ' + message);
	},
	
	onJsReady: function() {
		debug('onJsReady: set cached URL & volume, if they exist');
		
		this.jsReady = true;
		
		// load cached url if exists
		if (this.cache.url != null) {
			this.loadUrl( this.cache.url );
			this.cache.url = null;
		}
		// set cached volume if exists
		if (this.cache.volume != null) {
			this.setVolume(this.cache.volume);
			this.cache.volume = null;
		}
		else {
			this.setDefaultVolume();
		}
		
		var base = this;
		
		this.element.fire('player:ready', { id: 1, instance: base });
	},
	
	onPlayerStateChange: function(state) {
		debug('onPlayerStateChange: ' + state);
		
		this.state = state;
		var prevReady = this.videoReady;
		if (state == 'playing' || state == 'paused') { 
			this.videoReady = true;
		}
		else if ( state == 'ready' && this.autoPlay == false ) { 
			this.videoReady = true;
		}
		else {
			this.videoReady = false;
		}
		
		if (!prevReady && this.videoReady) {
			debug('Initialized & ready for commands, so do any cached commands');
			
			// set cached seek if exists
			if (this.cache.seek != null) {
				this.seek( this.cache.seek );
				this.cache.seek = null;
			}
			
			// set cached playState if exists
			if (this.cache.playState != null) {
				this[ this.cache.playState ]();
				this.cache.playState = null;
			}
		}
	},
	_onLoadProgress: function(percent) {
		// debug('onLoadProgress: ' + percent);
		// $('loadPrct').update(percent);
		
		//this.onLoadProgress(progress);
	},
	onMediaError: function( error ) {
		var errStr =	'<br /> - errorID: '	+ error.errorID +	
						'<br /> - message: '	+ error.message +
						'<br /> - detail: ' 	+ error.detail;
						
		debug('onMediaError: ' + errStr);
	}, 
	onComplete: function() {
		debug('onComplete');
	},
	onDurationChange: function(time) {
		debug('onDurationChange: ' + time);
		
		this.duration = time;
	},
	onVolumeChange: function( level ) {
		debug('onVolumeChange: ' + level);
		
		// $('volVal').value = level;
	},
	
	onBufferingChange: function(isBuffering) {
		debug('onBufferingChange: ' + isBuffering);

		if(isBuffering) {
			this.onWaiting();
		}
		else {
			this.element.removeClassName('waiting');
		}
	 }
});

var HtmlMediaPlayer = Class.create(MediaPlayer, {
	setup: function() {		
		this.video.on('loadeddata', 	this.onLoadedData.bind(this));
		this.video.on('loadedmetadata', this.onLoadedMetadata.bind(this));
		
		/* this.video.on('play', 		this.onPlay.bind(this)); */
		/* this.video.on('pause', 		this.onPause.bind(this)); */
		
		this.video.on('ended', 			this.onEnded.bind(this));
		
		this.video.on('durationchange', this.onDurationChange.bind(this));
		this.video.on('timeupdate', 	this.onTimeUpdate.bind(this));
		this.video.on('volumechange', 	this.onVolumeChange.bind(this));
		
		this.video.on('error', 			this.onError.bind(this));
		this.video.on('seeking', 		this.onSeeking.bind(this));
		this.video.on('seeked', 		this.onSeeked.bind(this));
		this.video.on('waiting', 		this.onWaiting.bind(this));
		
		this.video.controls = false; 		// Hide the default browser controls
		
		this.setDefaultVolume();			// Set the default volume
		
		this.bufferMonitor = new MediaBufferMonitor(this);
		
		this.isReady = true;
		this.errorCount = 0;
			
		this.element.fire('player:ready', { id: 1 });
	},
	_play: function() {		
		this.video.play();
		
		this.bufferMonitor.start();
	},
	_pause: function() {
		this.video.pause();
		
		if(this.video.controls) {
     		this.video.controls = false; 
     	}
		
		this.bufferMonitor.stop();
	},
	_seek: function(time) {
		this.onSeeking();
		
		this.video.currentTime = time; // In seconds
	},
	_setVolume: function(newVol){
    	this.video.volume = parseFloat(newVol);
	},
	reload: function() {
		var base = this;
		
		this.errorCount = 0;
		
		this.video.pause();
				
		this.video.select('source').each(function(sourceEl) {
			sourceEl.remove();
		});
		
		this.sources.each(function(source) { 
			base.video.insert({ bottom: new Element('source', { src: source.url, type: source.type }) });
		});
		
		this.reset();
		
		this.video.load();
	},	

	onEnded: function(e) {
		this.video.pause();
	},	
	onDurationChange: function(e) {			
		this.duration = this.video.duration;
	},
	onTimeUpdate: function(e) {		
	
		if(this.video.controls) {
       		this.video.controls = false; 
       	}

		this.onCurrentTimeChange(this.video.currentTime);
	},
	onVolumeChange: function(e) {
		// this.video.volume
	},
	onError: function(e) {
		this.errorCount++;
		
		var base = this;
		
		var error = e.target.error;
		
		/*		
		switch (error.code) {
			case error.MEDIA_ERR_ABORTED:			// Client abortion
			case error.MEDIA_ERR_NETWORK:			// Mid-way network error
			case error.MEDIA_ERR_DECODE:			// Decoding error
			case error.MEDIA_ERR_SRC_NOT_SUPPORTED:	// Network or format error
				break;
			default:								// Unknown error
			  	break;
		}
		*/
   		
		if(error && error.code == 4 && this.errorCount < 3) {		
			setTimeout(function() {
				base.video.load();
			}, 4000);
		}		
	},
	onLoadedData: function(e) {
		// Called when ready to play @ current position
	},
	onLoadedMetadata: function(e) {		
		this.duration = this.video.duration;
	},
	/* -------- HELPERS ---- */
	canPlayType: function(type) {
	    var canPlay = this.video.canPlayType(type);
	    	
	 	if(canPlay == "probably" || canPlay == "maybe") {
	  		return true;
	   	}	
	}
});

var MediaBufferMonitor = Class.create({
	initialize: function(player) {
		this.player = player;
		this.video = this.player.video;
	},
	start: function() {
		if(this.video.buffered) {
			this.monitor = setInterval(this._check.bind(this), 33);
		}
	},
	stop: function() {
		if(this.monitor) {
			clearInterval(this.monitor);
		}
	},
	_check: function() {	
		var buffered = this.video.buffered; // An array of time ranges
		        		
		if (buffered.length >= 1) {
  
			var loadProgress = buffered.end(0) / this.video.duration;
  
  			this.player.onLoadProgress(loadProgress);
    		
			if (loadProgress == 1) {
				this.stop();
			}
		}	
	}
});

var MediaController = Class.create({
	initialize: function(player) {
		this.player = player;
		
		this.element = this.player.element.down('.controller');
		
		this.isHidden = true;
			
		this.scrubberEl = this.element.down('.scrubber');
		this.playControlEl = this.element.down('.playControl');
		this.volumeControlEl = this.element.down('.volumeControl');
		this.fullscreenControlEl = this.element.down('.fullscreenControl');
		
		this.scrubber = new Scrubber(
			/*element*/ this.scrubberEl,
			/*controller*/ this
		);
    	
    	this.volumeControl = new VolumeControl(
    		/*element*/ this.volumeControlEl,
    		/*controller*/ this
    	)
    	
    	if(!this.player.supportsFullscreen) {
    		this.fullscreenControlEl.hide();
    	}
    	
    	this.playControlEl.on('click', this.onPlayControlClick.bind(this));
    	this.fullscreenControlEl.on('click', this.onFullscreenControlClick.bind(this));
   		
   		this.width = this.player.width;
   		
   		// this.element.style.width = '800px';
 
   		this.scrubber.setup();
	},
	reset: function() {
		this.scrubber.reset();
	},
	show: function() {
		this.element.show();
		
		this.isHidden = false;
	},
	hide: function() {
		var base = this;
		
		this.element.hide();
    	
    	this.isHidden = true;
	},
	onPlayControlClick: function(e) {		
		Event.stop(e);
		
		this.player.togglePlay();   
	},
	onFullscreenControlClick: function(e) {
		Event.stop(e);
		
		this.player.toggleFullscreen();
	}
});

// DurationBar, LoadBar, PlayBar
var Bar = Class.create({
	initialize: function(element) {
		this.element = element;
	},
	reset: function() {
		this.setProgress(0);
	},
	setProgress: function(percent) {
		this.element.style.width = (percent * 100) + '%';
	}
});

var Scrubber = Class.create({
	initialize: function(element, controller) {
		this.element = element;
		this.controller = controller;
			
		this.player = this.controller.player;
		
		this.scrubberBarEl = this.element.down('.scrubberBar');
		
		this.loadBar = new Bar(this.scrubberBarEl.down('.loadBar'));
		this.playBar = new Bar(this.scrubberBarEl.down('.playBar'));
		
		this.scrubberBarEl.on('mousedown', this.onMouseDown.bind(this));
		this.scrubberBarEl.on('mouseup', this.onMouseUp.bind(this));
	},
	setup: function() {				
		var barWidth = this.controller.width - 96;
		
		// HACK
		if(this.controller.width == 800) {
			barWidth -= 30;
		}
		
		if(this.controller.player.supportsFullscreen) {
			barWidth -= 40;
		}
		
		if(barWidth > 0) {
			// Stretch the bar to the remaining control width
	    	this.element.style.width = barWidth + 'px';
	    	
	   		// Add 20 pixels of padding to the right
	    	this.scrubberBarEl.style.width = (barWidth - 20) + 'px';
	    }
	},
	reset: function() {
		 this.playBar.reset();
		 this.loadBar.reset();
	},	
	setLoadProgress: function(percent) {
		this.loadBar.setProgress(percent);
	},
	setPlayProgressWithEvent: function(e) {	
		if(!e) { return; }
		
		var progress = Util.getRelativePosition(Util.getMouseX(e), this.scrubberBarEl);
	
		var seconds = progress * this.player.duration;
	
		this.player.seek(seconds);
   	   
 		this.playBar.setProgress(progress);
  	},
  	setCurrentTime: function(time) {
		if(!this.player.duration) {
			return;
		}
		
		var playPercent = (time / this.player.duration);
		   
		this.playBar.setProgress(playPercent);
	},
	onMouseDown: function(e) {
		Event.stop(e);
		
		if (!this.player.isPlaying) {
			this.videoWasPlaying = false;
		} 
		else {
			this.videoWasPlaying = true;
		  
			this.player.pause();
		}
		
		var body = document.documentElement;
		
		body.onmouseup = function(e) {		  
			body.onmousemove = null;
			body.onmouseup = null;
		  	
			if (this.videoWasPlaying) {
				this.player.play();
			}
		}.bind(this);
		
		body.onmousemove = function(e) {
			this.setPlayProgressWithEvent(e);
		}.bind(this);
	},
	onMouseUp: function(e) {		
		this.setPlayProgressWithEvent(e);
	}
});

var VolumeControl = Class.create({
	initialize: function(element, controller) {
		this.element = element;	// .volumeControl
		this.controller = controller;
		this.player = this.controller.player;
		
		this.barsUl = this.element.down();
		
		// Observe drag events on the volume control
   	this.element.on('mousedown', this.onMouseDown.bind(this));
   	this.element.on('mouseup', this.onMouseUp.bind(this));
	},
	onMouseDown: function(e) {
		Event.stop(e);
		
		document.onmousemove = function(e) {
			this.setVolumeWithEvent(e);
		}.bind(this);
		
		document.onmouseup = function() {
			document.onmousemove = null;
			document.onmouseup = null;
		}.bind(this);
	},
	onMouseUp: function(e){
		this.setVolumeWithEvent(e);
	},
	setVolume: function(volume) {
	    var volNum = Math.ceil(volume * 6);
	    
		for(var i=0; i<6; i++) {
			var barEl = this.barsUl.children[i];
			
	        barEl.className = (i < volNum) ? "on" : "off";
		}
	},
	setVolumeWithEvent: function(e) {	
		if(!e) { return; }
			
    var newVol = Util.getRelativePosition(Util.getMouseX(e), this.element);
    	
    this.player.setVolume(newVol);
	}
});
