


var EmbedVideoPlayer = new Class({
	Extends: EmbedVideo,
	
	options: {
		screen:"a.screen",
		controls:{
				play:".playButton",
				pause:".pauseButton",
				pausePlayToggle:".pausePlayToggle",
				scrubbar:".scrubBar",
				volumebar:".volumeBar",
				volumeArea:".volume-container",
				timeArea:".time",
				counter:".counter",
				captionArea:".captionArea",
				captionsToggle:".captionsToggle",
				lengthIndicator:".lengthIndicator"
				
			},
		continuousScrub:true,
		timeCheckInterval:250,
		trimTimeDisplay:true,
		defaultVolume:50,
		initialDuration:"",
		captions:false,
		captionPath:"",
		frontLoadCaptions:false,
		hideCntlWithPoster:true
	},
		
	captions:false,
	
	formattedDuration:false, //stores formatted string of current video duration, or false
	
	initialize:function(element, options){
		
		//fail if no element is defined
		if(!element) return false;
		
		//player uses own controls, set video controller to false
		options.controller=false;
		
		
		//set player element
		this.videoPlayerElem = element;
		
		//set new options
		this.setOptions(options);
		
		//flash must always be non-continuous scrubbing 
		if(this.options.plugin=="flash"){
			this.options.continuousScrub=false;
		}
		
		//get the player's screen element
		var screenElement = element.getElement(this.options.screen);
		
		//set caption file from class property if not set in options
		var captionProp = this.getPropValue("captions",screenElement);
		if($type(captionProp) =="string" & !options.captions){
			this.options.captions = captionProp + ".xml";
		}
		
		//set initial duration from class property if not set in options
		var initDurationProp = this.getPropValue("initialDuration",screenElement);
		
		if($type(captionProp) =="string" & !options.captions){
			this.options.initialDuration = initDurationProp;
		}
		
		//fire parent code: embed video 
		this.parent(screenElement, options);
		
		
		
		//choose the correct player class for chosen plugin, add player specific options
		switch(this.options.plugin){
			
			case "quicktime":
				this.playerClass = QTPlayer;
				this.playerClassOptions = {maxVolume:255};
				break;
			case "flash":
				this.playerClass = FlashPlayer;
				this.playerClassOptions = {maxVolume:1};
				break;
			case "wmv":
				this.playerClass = WMVPlayer;
				this.playerClassOptions = {maxVolume:100};
				break;
		}
		
		
		//synchronously load captions at initialization, if option set
		if (this.options.frontLoadCaptions) {
			this.loadCaptions(false);
		}
		
		
		//set initial formatted time for movie, shown before loading actual movie
		this.setFormattedDuration(this.options.initialDuration);
		
		
		//add the play pause toggle control and deactivate it until play
		this.controls.pausePlayToggle = new PlayerControl("pausePlayToggle", element.getElement(this.options.controls.pausePlayToggle), {
			toggleOn:function(controlElem){
				
				this.play();
			}.bind(this),
				
			toggleOff:function(controlElem){
				
				this.pause();
				
			}.bind(this),
			
			onOffChange:function(isOn,controlElem){
				
				if(isOn){
					controlElem.addClass("playing");
					controlElem.removeClass("paused");
				}else{
					controlElem.addClass("paused");
					controlElem.removeClass("playing");
				}
			},
			
			activeStyles: {},
			inactiveStyles: {}
		});
		this.controls.pausePlayToggle.activate();
		this.controls.pausePlayToggle.setOnState(false);
		
		//initialize volume bar
		this.initVolumeBar();
		
		//initialize scubbar
		this.initScrubBar.bind(this)();
		
		
		//add end poster event
		this.addEventAction('ended',function(){
	
				this.clearScrubInterval();
				
				if (this.options.restartAtEnd) {
					this.drawposter(this.movieElem);
				}
				else {
					//create a new end poster
					var ending = new EndPoster(this.options.posterElement)
					
					var doDraw = function(){
						//draw end poster
						var newPoster = this.drawposter(this.movieElem, ending);
						
						//make poster have screen id
						$(newPoster).set('id', this.options.movieid);
					}.bind(this);
					
					doDraw.delay(700);
				}
				
				this.player = null;
				
				//this.controls.pause.deactivate();
				this.controls.pausePlayToggle.setOnState(false);
				this.controls.scrubbar.deactivate();
					
			}.bind(this));
		
		//handle controls on play event
		this.addEventAction('play',function(){
				
				this.controls.pausePlayToggle.setOnState(true);
				
		}.bind(this));
		
		//handle controls on pause event
		this.addEventAction('pause',function(){
	
				this.controls.pausePlayToggle.setOnState(false);
				
		}.bind(this));
		
		
		
		
		//add time area to controls
		this.controls.timeArea = new PlayerControl("time", element.getElement(this.options.controls.timeArea), {
			activeStyles: {},
			inactiveStyles: {}
		});
		
		//add count timer to controls
		this.controls.counter = new PlayerControl("counter", element.getElement(this.options.controls.counter), {
			activeStyles: {},
			inactiveStyles: {}
		});
		
		//add length / duration indicator to controls
		this.controls.lengthIndicator = new PlayerControl("lengthIndicator", element.getElement(this.options.controls.lengthIndicator), {
			activeStyles: {},
			inactiveStyles: {}
		});
		
		//add the captions area control and deactivate it until play
		this.controls.captionArea = new PlayerControl("captionArea", element.getElement(this.options.controls.captionArea), {
			activeStyles: {},
			inactiveStyles: {}
		});

		this.controls.captionArea.deactivate();
		
		
		//add the toggle caption area control and deactivate until embed
		this.controls.captionsToggle = new PlayerControl("captionsToggle", element.getElement(this.options.controls.captionsToggle), {
			click: this.toggleCaptions.bind(this),
			activeStyles: {},
			inactiveStyles: {}
		});
		this.controls.captionsToggle.activate();
		
		
		//hide controls and just show poster when setting on
		if(this.options.hideCntlWithPoster){
			
			for(control in this.controls ){

				this.controls[control].hide();
			}
			
		}
		
		
	},
	
	
	
	controls:{
		
		scrubbar:$lambda(false),
		volumebar:$lambda(false)
		
	},
	
	embedPlayer:function(controls){
		
		//stop action if video player element does not exist
		if(!this.videoPlayerElem) return false;
		
		
		this.embed();
		//this.controls.play.activate();
		
		
	},
	
	loadCaptions:function(byAsynchRequest){
		
		if (this.options.plugin == "none") {
			return false; //don't load captions when no plugin
		}
		
		
		this.controls.captionArea.control.set('html','loading captions...'); 
		
		if($type(this.options.captions)=="string"){
			
			//load captions from external xml file in DFXP TT caption format
			
			if (this.options.captionPath != "") {
			
				var xmlpath = this.options.captionPath + this.options.captions;
			
			}else {
				
				var xmlpath = this.options.captions;
				
			}
			
			var req = new Request({
			    method: 'get',
				async:byAsynchRequest,
			    url: xmlpath,
			    onRequest: function() { }.bind(this),
			
			    // the response is passed to the callback as the first parameter
			    onComplete: function(response) { 
			    		
						
						//convert XML text to traversable DOM object
						var captionXML = parseXml(response);
						
						//convert HTML to JSON text equivalent
						var captionJSONText = xml2json(captionXML, " ");
						
						//convert JSON text to JSON object
						var captionJSON = JSON.decode(captionJSONText);
						
						this.captions = new Captions(captionJSON);
						
						//clear caption text
						this.controls.captionArea.control.set('html','');
						
			     }.bind(this)
			
				}).send();

		}else if($type(this.options.captions)=="object"){
			
			//load captions from JSON object passed to player
			
			
			this.captions = new Captions(captionJSON);
			
			//clear caption text
			this.controls.captionArea.control.set('html','');
		}
	},
	
	endDraw:function(){
		//function happens after javascript draws plugin code
		
		//don't load scrubbar when no plugin
		if (this.options.plugin == "none") {
			return false; 
		}
		
		//check for player being loaded, enable scrub bar
		this.loadInterval = setInterval(function(){ 
								
            				    if (this.playerExists()) {
            				    	
									var duration = this.player.getDuration();
									
									if (duration > 0) {
										this.initScrubBar.bind(this)();
										clearInterval(this.loadInterval);
									}
								}
            					
            					}.bind(this), 1000);
	},
	
	
	setScrubInterval:function(millsec){
		
		//don't load interval when no plugin
		if (this.options.plugin == "none") {
			return false; 
		}
		
		this.scrubInterval = setInterval(function(){ 
								var curTime=0;
								if(this.player)
            				    	curTime = this.getTime();
									
									var counttime = this.videoPlayerElem.getElement(this.options.controls.counter)
									if (counttime) {
										//set timer value
										counttime.set('text', this.getFormattedTime());
									}
									if (this.captions && this.controls.captionArea.active) {
										this.videoPlayerElem.getElement(this.options.controls.captionArea).set('html', this.captions.get(curTime))
									}
									
									if (!this.controls.scrubbar.isChanging) {//don't change while being dragged
										this.controls.scrubbar.set(curTime, true);
									}
            						
									
									if($(this.controls.scrubbar.element)){
										var scrubHandle = this.controls.scrubbar.element.getElement('.knob');
  										var scrubProgress = this.controls.scrubbar.element.getElement('.progress');
										scrubProgress.setStyle('width',scrubHandle.getStyle('left'));
									}
            					}.bind(this), millsec);
	},
	
	clearScrubInterval:function(){
		
		clearInterval(this.scrubInterval);
		this.scrubInterval=null;
	},
	
	initVolumeBar:function(){
		
			//get DOM element for video player's volume bar
			var el = this.videoPlayerElem.getElement(this.options.controls.volumebar);
			
			//set volume min and max for player
			var minVolume = 0;
			var maxVolume = 100;
			
			// Create the new slider instance
			this.controls.volumebar = new VideoSlider("vbar",el, el.getElement('.knob'), {
				
				range: [minVolume,maxVolume],
				steps:maxVolume-minVolume,
				
				onChange: function(value){
					
					this.setVolume(value);
				}.bind(this)

			});
			
			//init start volume to default
			this.controls.volumebar.set(this.options.defaultVolume);
			
			//activate control
			this.controls.volumebar.activate();
			
			//add volume area to controls
			this.controls.volumeArea = new PlayerControl("volumeArea", this.videoPlayerElem.getElement(this.options.controls.volumeArea), {
			activeStyles: {},
			inactiveStyles: {}
		});
			
			
	},
	
	initScrubBar:function(){
		// Slider
		
		 var el = this.videoPlayerElem.getElement(this.options.controls.scrubbar);
		
		//if(this.playerExists()){
			
			
			this.setScrubInterval(this.options.timeCheckInterval);
								
			//get duration
			var duration = this.getDuration();
		
			
			var scrubHandle = el.getElement('.knob');
			
			var scrubProgress = el.getElement('.progress');
			
			// Create the new slider instance
			this.controls.scrubbar = new VideoSlider("scrub",el, scrubHandle, {
				
				range: [0,duration],
				steps:duration,
				
				onChange: function(value){
					this.clearScrubInterval();
					if (this.options.continuousScrub) {
						
						this.setTime(value);
					}else{
						this.controls.scrubbar.isChanging = true;
					}
					scrubProgress.setStyle('width',scrubHandle.getStyle('left'));
				}.bind(this),
				
				onComplete:function(value){
					if (!this.options.continuousScrub) {
						
						this.setTime(value);
						this.controls.scrubbar.isChanging =false;
					}
					
					this.setScrubInterval(this.options.timeCheckInterval);
				}.bind(this)
			});
			
			this.controls.scrubbar.activate();
		//}
	},
	
	initPlayer:function(){
		
		//cancel init if a plugin does not exist
		if(this.options.plugin=="none"){
		
			return false;
		}
		
		var playerObj=false;
		
		var embedObj = document.getElementById(this.options.movieid);
		
		if(embedObj.tagName.toUpperCase()!="OBJECT"){
			if ($(embedObj).get('tag') == "iframe") {
			
				playerObj = embedObj.contentWindow.document[this.options.movieid];
			}
		}else {
			
			if(document[this.options.movieid]){
				playerObj = document[this.options.movieid];
			}
			
		}
		
		
		if (playerObj) {
			
			this.player = new this.playerClass(playerObj,this.playerClassOptions);
			
			
			this.setVolume(this.volume);
			
			var curMovDur = this.player.getFormattedDuration();
			if(curMovDur == "00:00" && this.options.initialDuration!=""){
				curMovDur = this.options.initialDuration;
				
			}
			
			this.setFormattedDuration(curMovDur);

			
			if(this.options.hideCntlWithPoster){
				
				//show all controls upon init
				for(control in this.controls ){
					this.controls[control].show();
				}
				
			}
			
			return true;
		}
		else {
			
			return false;
		}
		
		
		
		
	},
	
	toggleCaptions:function(e){
		
		if (this.controls.captionArea.active) {
			this.controls.captionArea.deactivate();
		}
		else {
			
			if(!this.captions){
				this.loadCaptions(true);//load captions asynchronously
			}
			this.controls.captionArea.activate();
		}
		
		if (e) {//stop any click event from propagating
			e = new Event(e).stop();
		}
	},
	
	playerExists:function(){
		if(this.player){
			return true;
		}else{
			
			return this.initPlayer();
		}
	},
	

	
	playNew:function(url,options){
		
		
		//assign new url to player
		this.options.path = url;
		
		//update url with proper extension
		this.updatePathExt();
		
		//load captions
		if (options.captions) {
				this.loadCaptions(false);
		}
		
		//update options
		this.setOptions(options);
		
			
		if (this.player) {
			
			//play new path in existing player
			this.player.changeMovie(this.options.path);
			
		}else{
			
			//play with new path
			this.play();
		}
	},
	
	play:function(e){
		
		if (this.playerExists()) {
			this.player.play();
			
		}else{
			
			if(this.options.plugin=="none"){
				//deactivate some controls when plugin does not exist
				this.controls.captionsToggle.deactivate();
				this.controls.captionArea.deactivate();
				this.controls.volumebar.deactivate();
			}
			
			
			
			this.draw();//draw the plugin code
			
		}
		
		
		if (e) {//stop any click event from propagating
			e = new Event(e).stop();
		}
		
		
	},
	
	pause:function(e){
			
		if(this.playerExists())
			this.player.pause();
			
		if (e) {//stop any click event from propagating
			e = new Event(e).stop();
		}
	},
	
	stop:function(e){
			
		if(this.playerExists())
			this.player.stop();
		this.player.getDuration();
		
		if (e) {//stop any click event from propagating
			e = new Event(e).stop();
		}
	},
	
	
	setVolume:function(volume){
		this.volume = volume;
		if(this.player)
			this.player.setVolume(this.volume);
	},
	
	getVolume:function(){
			return this.volume;
		
	},
	
	getTime:function(){
		if(this.player){
			return this.player.getTime();
		}else{
			return 0;
		}
	},
	
	getDuration:function(){
		if(this.player){
			var duration = this.player.getDuration();
			if(!this.formattedDuration){
				//set formatted duration for remembering duration
				this.setFormattedDuration(this.player.getFormattedDuration());
			}
			return duration;
		}else{
			return 0;
		}
		
	},
	
	getFormattedDuration:function(){
		var formattedDur ="00:00";
		
		if(this.formattedDuration){
			formattedDur = this.formattedDuration;
		}else if(this.player){
			
			var curMovDur = this.player.getFormattedDuration();
			if(curMovDur == "00:00" && this.options.initialDuration!=""){
				curMovDur = this.options.initialDuration;
				
			}
			
			this.setFormattedDuration(curMovDur);
			
			formattedDur= this.formattedDuration;
			
		}
		
		return this.trimTime(formattedDur);
		
	},
	
	getFormattedTime:function(){
		var time ="00:00";
		if(this.player){
			time = this.player.getFormattedTime();
		}
		
		return this.trimTime(time);
	},
	
	trimTime:function(formattedTime){
		
		if($type(formattedTime)!="string") return "";
		
		if(!this.options.trimTimeDisplay) return formattedTime;
		
		
		for(var x=0;x<formattedTime.length;x++){
			if(formattedTime.substring(x,x+1)!="0"){
				
				break;
			}
		}
		if((formattedTime.length-x) < 4) x=x-1;//always have at least 0:00
		
	 	return formattedTime.substring(x,formattedTime.length);
	},
	
	setTime:function(time){
		if (this.player) {
			this.player.setTime(time);
		}
	},
	
	setFormattedDuration:function(value){
		
		this.formattedDuration = this.trimTime(value);		
		
		//set the length indicator
		var lengthIndicator = this.videoPlayerElem.getElement(this.options.controls.lengthIndicator);
		if(lengthIndicator){
			lengthIndicator.set('text',value);
		}
	}
	
	
});
	
var VideoPlayer = new Class({
	Implements: Options,

	//default options
	options: {
		maxVolume:100,
		minVolume:0
	},
	
	initialize:function(playObj,options){
		this.playObj = playObj;
		this.playControls = this.playObj;
		
		this.setOptions(options);
		this.timescale = 1;//default to 1:1 ratio for player time scale
	},
	
	play:function(){
		this.playControls.Play();
	},
	
	pause:function(){
		this.playControls.Pause();
	},
	
	stop:function(){
		this.playControls.Stop();
	},
	
	changeMovie:function(url){
		
		this.playControls.SetURL(url);
	},
	
	getFormattedTime:function() {  
		
		var timeMillisecs = this.getTime();
		
		return this.formatTime(timeMillisecs);
	} ,
   
   getFormattedDuration:function() {  
		
		var durMillisecs = this.getDuration();
		
		return this.formatTime(durMillisecs);
 	},
	
   formatTime:function(millisecs){
   		
		if($type(millisecs) !="number"){
			return "00:00";
		}
		
		var s = millisecs/1000;
		var m = s/60;
		var h = m/60;
		
		var hh = Math.floor(h);
		var mm = Math.floor((m - hh*60));
		var ss = Math.floor(s - mm*60);
		
		if(hh/10<1){
			hh = "0" + hh;
		}
		if(mm/10<1){
			mm = "0" + mm;
		}
		if(ss/10<1){
			ss = "0" + ss;
		}
		
		var formatted ="";
		
		if(hh=="00"){
			var formatted = mm + ":" + ss;
		}else{
			var formatted = hh +":" + mm + ":" + ss;
		}
		
		return formatted;
   },
   
  	
	
	getDuration:function(){
		//always returns time in milliseconds
		return this.playControls.GetDuration() / this.timescale * 1000;
	},
	
	getTime:function(){
		//always returns time in milliseconds
		return this.playControls.GetTime() / this.timescale * 1000;
	},
	
	setTime:function(time){
		
		//convert time back to time scale from milliseconds
		time = time/1000 * this.timescale
		
		//set time in player
		this.playControls.SetTime(time)
	},
	
	getVolume:function(){
		
		//get currently set player volume
		var volume = this.playControls.GetVolume();
		
		//player volume must be converted to a 0-100 range
		var convertedVolume = volume/this.options.maxVolume * 100;
		
		
		return convertedVolume;
		
	},
	
	setVolume:function(volume){
		
		//passed volume is within a 0-100 range, convert to video player range
		var convertedVolume = volume * this.options.maxVolume/100;
		
		//set player's volume to correct volume
		this.playControls.SetVolume(convertedVolume);
	}
	
});

var QTPlayer = new Class({
	Extends: VideoPlayer,
	
	initialize:function(playObj,options){
		this.parent(playObj,options);
		this.timescale = this.playObj.GetTimeScale();
	},
	
	//over ride player pause for unique quicktime function
	pause:function(){
		this.playControls.Stop();
	},
	
	//over ride player stop for unique quicktime function
	stop:function(){
		this.playControls.Stop();
		this.playControls.Rewind();//go back to beginning
	},
	
	changeMovie:function(url){
		
		this.playControls.SetResetPropertiesOnReload(false);
		this.playControls.SetURL(url);
		
	}
});

var FlashPlayer = new Class({
	
	Extends: VideoPlayer,
	
	play:function(){
		this.playControls.PlayMe();
	}
	
});

var WMVPlayer = new Class({
	
	initialize:function(playObj){
		this.playObj = playObj;
		
		//play controls may be accessed in one object or subobject for wmp
		if(playObj.controls){
			this.playControls = playObj.controls;
		}else{
			this.playControls = playObj;
		}
	},
	
	getDuration:function(){
		if (this.playObj.currentMedia) {
			return this.playObj.currentMedia.Duration / this.timescale * 1000;
		}else{
			return this.playObj.Duration / this.timescale * 1000;
		}
	}
});

/*
var WMVPlayer = new Class({
	
	initialize:function(playObj){
		this.playObj = playObj;
	},
	
	play:function(){
		if (this.playObj.controls) {
			this.playObj.controls.Play();
		}else{
			this.playObj.Play();
		}
	},
	
	pause:function(){
		if (this.playObj.controls) {
			this.playObj.controls.Pause();
		}else{
			this.playObj.Pause();
		}
	},
	
	stop:function(){
		if (this.playObj.controls) {
			this.playObj.controls.Stop();
		}else{
			this.playObj.Stop();
		}
	},
	
	getDuration:function(){
		if (this.playObj.currentMedia) {
			return this.toMilliSecs(this.playObj.currentMedia.Duration);
		}else{
			return this.toMilliSecs(this.playObj.Duration);
		}
	},
	
	getTime:function(){
		if (this.playObj.controls) {
			return this.toMilliSecs(this.playObj.controls.CurrentPosition);
		}else{
			return this.toMilliSecs(this.playObj.CurrentPosition);
		}
	},
	setTime:function(time){
		if (this.playObj.controls) {
			this.playObj.controls.currentPosition = this.toSecs(time);
		}else{
			this.playObj.currentPosition = this.toSecs(time);
		}
		
	},
	toMilliSecs:function (secs){
    	return parseInt(secs*1000);
  	},
	toSecs:function(ms){
    	return ms/1000;
  	}
});
*/


var Captions = new Class({
	Implements: Options,

	//default options
	options: {
		maxVolume:100,
		minVolume:0
	},
	
	initialize:function(jsonCaptions,options){
		
		var captions = jsonCaptions.tt.body.div.p;
		
		//convert caption times to millisecs
		var numCaptions = captions.length;
		for(var x=0; x<numCaptions;x++){
			
			if(captions[x]["@begin"]){
				captions[x]["@begin"] = this.capTimeToMillisec(captions[x]["@begin"]);
			}
			if (captions[x]["@dur"]) {
				captions[x]["@dur"] = this.capTimeToMillisec(captions[x]["@dur"]);
			}
			if (captions[x]["@end"]) {
				captions[x]["@end"] = this.capTimeToMillisec(captions[x]["@end"]);
			}
		}
		
		//function to use in sorting captions in JSON object to correct time order
		var compare = function(a,b){
			
			if(a["@begin"]>b["@begin"]){
				return 1; //a is greater than b
			}else if(a["@begin"]==b["@begin"]){
				return 0; //a is equal to b
			}else{
				return -1;//as is less than b
			}
			
		};
		//sort captions by begin time
		captions.sort(compare);
		
		this.transcript = captions;
		
	},
	
	capTimeToMillisec:function(capTime){
		
		var timeArr = capTime.split(':');
		
		var hours = timeArr[0].toFloat();
		var minutes = timeArr[1].toFloat();
		var seconds = timeArr[2].toFloat();
		
		var millisecsHours = hours * 60 * 60 * 1000;
		var millisecsMinutes = minutes * 60 * 1000;
		var millisecsSeconds = seconds * 1000;
		
		var totalMillisecs = (millisecsHours + millisecsMinutes + millisecsSeconds).toInt();
		
		return totalMillisecs;
	},
	
	findCapIndex:function(start,end,curTime){
		
		if(end<0){
			return -1;//end is invalid, should not be processed
		}
		
		//binary search alg to find correct transcript item for current time given
		if(start>end){
			
			if (this.transcript[end]["@end"]) {
				var capEnd = this.transcript[end]["@end"];
			}
			else {
				var capEnd = this.transcript[end]["@begin"] + this.transcript[end]["@dur"];
			}
			 
			if (curTime < capEnd) {
				return end;
			}else{
				return -1;
			}
		}else{
			
			var midVal = Math.ceil((start + end)/2);
			var prevMidVal = midVal==0 ? 0 : midVal-1;
			
			
			
			if(curTime <= this.transcript[midVal]["@begin"] && curTime >this.transcript[prevMidVal]["@begin"]){
				
				//define order of importance of caption end point
				
				//priority 1: caption's end will always be before or the same as the next caption's beginning
				//priority 2: the caption will disappear at the designated end point, regardless of duration
				//priority 3: caption will end after its designated duration
				
				if (this.transcript[prevMidVal]["@end"]) {
					var capEnd = this.transcript[prevMidVal]["@end"];
				}else if(this.transcript[prevMidVal]["@dur"]){
					var capEnd = this.transcript[prevMidVal]["@begin"] + this.transcript[prevMidVal]["@dur"];
				}else{
					var capEnd = this.transcript[midVal]["@begin"]
				}
				
				if (curTime <= capEnd) {
					
					return prevMidVal;//return caption index
				}else{
					return -1;//remove caption, but add no new caption
				}
			}else if(curTime < this.transcript[midVal]["@begin"]){
				return this.findCapIndex(start,midVal-1,curTime);
				
			}else{
				
				return this.findCapIndex(midVal+1,end,curTime);
				
			}
		}
	},
	
	get:function(curTime){
		var start = 0;
		var end = this.transcript.length-1;
		
		var curIndex = this.findCapIndex(start,end,curTime);
		
		if (curIndex != -1) {
			if (this.transcript[curIndex]) {
				return this.transcript[curIndex]["#text"];
			}
		}else{
			return "";
		}
	}

});


//class for making end poster, pulling from existing html on page
var EndPoster = new Class({

	Extends: Poster,
	initialize:function(posterElement){
	
		var posterShell = $(posterElement).clone(false);
		var posterHtml = $(posterElement).get('html');
		$(posterShell).set('html',posterHtml);
		this.posterElem =posterShell;
	},
	postOver: function(){
		
		return this.posterElem;
	}
});

//class for making chapter poster
var ChapterPoster = new Class({

	Extends: Poster,
	initialize:function(options,video){
		this.parent(options);
		this.addChapter("previous","Previous Chapter",function(){
			//video.playNew({poster:"",autoplay:true,path:"the_last_enemy_1.1.s.mov"});
			video.playNew("the_last_enemy_1.1.s.mov");
		}.bind(video));
		
		this.addChapter("current","Current Chapter",function(){
			video.playNew({poster:"",autoplay:true});
		}.bind(video));
		
		this.addChapter("next","Next Chapter",function(){
			//video.playNew({poster:"",autoplay:true,path:"the_last_enemy_1.3.s.mov"});
			video.playNew("the_last_enemy_1.3.s.mov");
		}.bind(video));
		
	},
	
	postOver:function(elemToPoster){
		
		this.posterElem = new Element("div",{
				id:this.options.movieid							
		});
		
		$(this.posterElem).setStyle('background-color','#000');
		$(this.posterElem).setStyle('height',this.options.height + "px");
		$(this.posterElem).setStyle('width',this.options.width + "px");
		
		
		var chapter1 = new Element("div",{
							
		});
		
		
		$(chapter1).setStyle('background-color','#fff');
		$(chapter1).setStyle('height',50 + "px");
		$(chapter1).setStyle('width',50 + "px");
		$(chapter1).setStyle('position',"absolute");
		$(chapter1).setStyle('top',"80px");
		$(chapter1).setStyle('font-size',"13px");
		$(chapter1).setStyle('font-weight',"bold");
		$(chapter1).setStyle('color',"#fff");
		
		var chapter2 = $(chapter1).clone();//.cloneEvents(chapter1);
		var chapter3 = $(chapter1).clone();//.cloneEvents(chapter1);
		
		//position left corners
		$(chapter1).setStyle('left',"480px");
		$(chapter2).setStyle('left',"560px");
		$(chapter3).setStyle('left',"640px");
	
		//add grow event to each chapter
		$(chapter1).addEvent('mouseover',function(){
			this.set('morph', {duration: 'short'});
			this.morph({height: 100, width: 100,left:455,top:55,fontSize:"16px"});
			
		});
		$(chapter1).addEvent('mouseout',function(){
			this.set('morph', {duration: 'short'});
			this.morph({height: 50, width: 50,left:480,top:80,fontSize:"13px"});
			
		});
		
		$(chapter2).addEvent('mouseover',function(){
			this.set('morph', {duration: 'short'});
			this.morph({height: 100, width: 100,left:535,top:55,fontSize:"16px"});
		});
		$(chapter2).addEvent('mouseout',function(){
			this.set('morph', {duration: 'short'});
			this.morph({height: 50, width: 50,left:560,top:80,fontSize:"13px"});
		});
		
		$(chapter3).addEvent('mouseover',function(){
			this.set('morph', {duration: 'short'});
			this.morph({height: 100, width: 100,left:615,top:55,fontSize:"16px"});
		});
		
		$(chapter3).addEvent('mouseout',function(){
			this.set('morph', {duration: 'short'});
			this.morph({height: 50, width: 50,left:640,top:80,fontSize:"13px"});
		});
		
		
		//add chapter images
		var chapter1Img = new Element("img",{
				src:"chap1.png",
				border:0,
				height:"100%",
				width:"100%"
		});
		$(chapter1Img).inject(chapter1);
		
		var chapter2Img = new Element("img",{
				src:"chap2.png",
				border:0,
				height:"100%",
				width:"100%"
		});
		$(chapter2Img).inject(chapter2);
		
		var chapter3Img = new Element("img",{
				src:"chap3.png",
				border:0,
				height:"100%",
				width:"100%"
		});
		$(chapter3Img).inject(chapter3);
		
		
		//add Chapter Titles
		var chapter1Title = new Element("p",
					{
						html:"Chapter&nbsp;1"
					}
		);
		$(chapter1Title).setStyle('text-align',"center");
		$(chapter1Title).setStyle('margin',"-50px");
		$(chapter1Title).setStyle('position',"relative");
		$(chapter1Title).setStyle('top',"20px");
		$(chapter1Title).inject(chapter1);
		
		var chapter2Title = new Element("p",
					{
						html:"Chapter&nbsp;2"
					}
		);
		$(chapter2Title).setStyle('text-align',"center");
		$(chapter2Title).setStyle('margin',"-50px");
		$(chapter2Title).setStyle('position',"relative");
		$(chapter2Title).setStyle('top',"20px");
		$(chapter2Title).inject(chapter2);
		
		var chapter3Title = new Element("p",
					{
						html:"Chapter&nbsp;3"
					}
		);
		$(chapter3Title).setStyle('text-align',"center");
		$(chapter3Title).setStyle('margin',"-50px");
		$(chapter3Title).setStyle('position',"relative");
		$(chapter3Title).setStyle('top',"20px");
		$(chapter3Title).inject(chapter3);
		
		
		
		//add actions when each chapter is clicked
		$(chapter1).addEvent('click',this.chapters.previous.action);
		$(chapter2).addEvent('click',this.chapters.current.action);
		$(chapter3).addEvent('click',this.chapters.next.action);
		
		$(chapter1).inject(this.posterElem);
		
		$(chapter2).injectAfter(chapter1);
		
		$(chapter3).injectAfter(chapter2);
		
		$(this.posterElem).replaces(elemToPoster);
		
		return this.posterElem;
	},
	
	chapters:{
		previous:{title:"",action:$empty},
		current:{title:"",action:$empty},
		next:{title:"",action:$empty}
		
	},
	
	addChapter: function(type,title,action){
		
		if(this.chapters[type]){
			this.chapters[type].title =title;
			this.chapters[type].action =action;
		}
	}
	
	
});



//PlayerControl is used to define controls in video player
var PlayerControl = new Class({

	Implements: Options,
	options: {
		click:$empty,
		toggleOn:false,
		toggleOff:$empty,
		onOffChange:$empty,
		hover:$empty,
		deactivate:$empty,
		activeStyles:{},
		inactiveStyles:{},
		onStyles:{},
		offStyles:{},
		onHtml:"",
		offHtml:""
	},
	
	initialize: function(name,element, options){
		
		if(element){
		
			this.setOptions(options);
			
			if(this.options.toggleOn){
				
				this.options.click = this.toggleOnOff.bind(this);
			};
			
			this.control = $(element);
			this.name = name;
			this.active=false;
			this.setOnState(true); //on and off states indicate if control is on or off, different from active, inactive
			
		
		}
		
		
	},
	
	activate:function(){
		
		if(!this.control){ return;};
		
		//add click event to control
		this.control.removeEvents('click');
		this.control.addEvent('click',this.options.click);

		//stop action on click (for links)
		this.control.addEvent('click',function(e){ 
			if (e) {//stop any click event from propagating
				e = new Event(e).stop();
				
			}
		});
		
		// add class to control when active
		this.control.addClass(this.name + 'Active');
		this.control.removeClass(this.name + 'Inactive');
		
		this.control.setStyles(this.options.activeStyles);
		this.active = true;
	},
	
	deactivate:function(){
		
		if(!this.control){ return;};
		
		//remove all actions on click
		this.control.removeEvents('click');
		
		// remove active class to control when active
		this.control.removeClass(this.name + 'Active');
		this.control.addClass(this.name + 'Inactive');
		
		//stop action on click (for links)
		this.control.addEvent('click',function(e){ 
			if (e) {//stop any click event from propagating
				e = new Event(e).stop();
				
			}
		});
		
		this.control.setStyles(this.options.inactiveStyles);
		this.active = false;
	},
	
	setOnState:function(isOn){
		
		if(!this.control){ return;};
		
		this.on = isOn;
		
		if (this.options.onOffChange) {
			this.options.onOffChange(isOn,this.control);
		}
		
	},
	
	toggleOnOff:function(){
		
		if(!this.control){ return;};
		
		if(this.on){
			
			this.options.toggleOff(this.control);
			
		}else{
			
			this.options.toggleOn(this.control);
	
		}
		
		this.setOnState(this.on);
	},
	
	hide:function(){
		
		if(!this.control){ return;};
		
		if (this.control.getStyle('display') != "none") {
			this.displayStyle = this.control.getStyle('display');
		}else{
			this.displayStyle = "";
		}
		this.control.setStyles({display:"none"});
		
	},
	
	show:function(){
		
		if(!this.control){ return;};
		
		this.control.setStyles({display:this.displayStyle});
		
	},
	
	hover:function(){
		
	}
	
});

var VideoSlider = new Class({
	Extends: Slider,
	
	initialize:function(name,element, knob, options){
		this.parent(element, knob, options);
		this.name = name;
	},
	
	activate:function(){
		this.element.addClass(this.name + 'Active');
		this.element.removeClass(this.name + 'Inactive');
	},
	
	deactivate:function(){
		this.element.addClass(this.name + 'Inactive');
		this.element.removeClass(this.name + 'Active');
		this.set(0,true);
	},
	
	hide:function(){
		this.displayStyle = this.element.getStyle('display');
		this.element.setStyles({display:"none"});
		
	},
	
	show:function(){
		this.element.setStyles({display:this.displayStyle});
		
	}

});


function embedPageVideos(selector,options,events){
		
	var videoArray = $$(selector);
	
	videoArray.each(function(item,index){
		
		var newVideo = new EmbedVideoPlayer(item,options);
		
		$each(events, function(event, name){
			newVideo.addEventAction(name,event);
		
		});
		
		newVideo.embedPlayer();
	});
}