/** GLOBAL **/
var playerBaseUrl = "/appresource/vsi/lib/";

/** SLIDER UPDATER OBJECT **/
slider = {
	init: function(sliderDiv, sliderPipeDiv, start_time, end_time) {
		this.sliderDiv = $('slider_progress_bar');
		this.sliderPipeDiv = $('slider_progress_pipe');
		this.SLIDER_MAX_WIDTH = 439;
		this.startTime = start_time;
		this.endTime = end_time;
		this.result_hit = false;
		setInterval(this.onTimeChange.bind(this), 100);
	},

	onTimeChange: function() {
		if (playerPage.player) {
			var currentTime = Math.round(playerPage.player.CurrentPosition() * 1000) - this.startTime;
			var sliderSize = this.endTime - this.startTime;
			var progress = Math.round((currentTime/1./sliderSize) * 100);

			var width = Math.round(progress * (this.SLIDER_MAX_WIDTH/100));
			var sliderPipeMarginLeft = width + 99;

			this.sliderPipeDiv.style.marginLeft = sliderPipeMarginLeft + 'px';
			this.sliderDiv.style.width = width + 'px';

			if (width > 180 && width < 230 && !this.result_hit) {
				new Effect.Opacity('result_red_frame', { from: 0.0, to: 1.0, duration: 1.0 });
				this.result_hit = true;
			}
			if (width > 230 && this.result_hit) {
				new Effect.Opacity('result_red_frame', { from: 1.0, to: 0.0, duration: 2.0 });
				this.result_hit = false;
			}
		}
	}
};


/** PLAYER WRAPPER OBJECT **/
playerPage = {
	// Entry point method 
	load: function(episode, playerDiv) {
		var id = episode.fep;
		var centerTime = episode.time;
		this.container = $(playerDiv);
		this.container.innerHTML = playerHTML;
		this.container.style.opacity = 0;

		$('scene_thumbnail').src = episode.imageurl;
		
		this.playPauseButtonImg = $('play_pause_button');
		this.playPauseButtonImg.observe('click', this.togglePause.bind(this));
		this.playFromBeggining = false;

		this.fromTimeMs = 0;
		this.fromTime = "00:00:00";
		if ((timestampFromString(centerTime) - 5 * 1000) > 0) {
			this.fromTimeMs = timestampFromString(centerTime) - (15 * 1000);
			this.fromTime = timestampToString(this.fromTimeMs);
		}

		this.centerTimeMs = timestampFromString(centerTime);
		this.centerTime = centerTime;

		this.toTimeMs = timestampFromString(centerTime) + (5 * 1000);
		this.toTime = timestampToString(this.toTimeMs);

		this.id = id;
		
		new Ajax.Request(playerBaseUrl+"util/fepfeed.xml", {method: 'get', onSuccess: this.fetchEpisodeFromXml.bind(this)});
		new Effect.Appear(this.container, { duration:1, from:0.0, to:1.0 });
	},

	fetchEpisodeFromXml: function(response) {
		var episodes = response.responseXML.getElementsByTagName('episode');
		var episodeFound = null;
		for (var i = 0; i < episodes.length; i++) {
			var episodeId = episodes[i].getElementsByTagName('id')[0].firstChild.nodeValue;
			if (episodeId == this.id) {
				episodeFound = episodes[i];
				break;
			}
		}
		if (episodeFound) {
			if (episodeFound.getElementsByTagName('HighProgURL')[0].childNodes.length == 0) {
				this.showError();
				return;	
			}

			if (episodeFound.getElementsByTagName('expired')[0].firstChild.nodeValue == "true") {
				this.showError();
				return;
			}

			var highProgUrl = episodeFound.getElementsByTagName('HighProgURL')[0].firstChild.nodeValue;
			var episodeTitle = episodeFound.getElementsByTagName('title')[0].firstChild.nodeValue;
			var seasonTitle = episodeFound.parentNode.getElementsByTagName('label')[0].firstChild.nodeValue;
			var showNode = episodeFound.parentNode.parentNode;
			var showId = showNode.getElementsByTagName('id')[0].firstChild.nodeValue;
			var showTitle = showNode.getElementsByTagName('title')[0].firstChild.nodeValue;

			this.episode = this.episode = {id: this.id, 
				show: showTitle,
				showId: showId,
				season: seasonTitle, 
				episode: episodeTitle, 
				highProgUrl: highProgUrl};
			this.playEpisode();
		} else {
			this.showError();
		}
	},

	showError: function() {
		alert('Sorry this episod can\'t be played.');
	},

	playEpisode: function() {
		//$('start_over').observe('click', this.play.bind(this));
		$('start_over').observe('click', function(){
			window.location.reload();
		});
		$('watch_fep').observe('click', function() {
			window.open ("http://beta.vp2.abc.com/watch/lost/" + this.episode.showId + "/" + this.episode.id, 
					"ABC.com Full Episode Player","location=0,status=0");
		}.bind(this));
		$('show_title').innerHTML = this.episode.show;
		$('season_title').innerHTML = this.episode.season;
		$('episode_title').innerHTML = this.episode.episode;
		$('seek_time').innerHTML = this.centerTime;

		// Init plugin
		if (this.player == null) {
			MN.QVT.CreatePlayer("player_div", this.onPlayerLoaded.bind(this), 433, 246);
		} else {
			this.play();
		}
	},

	onPlayerLoaded: function(playerObject) {
		this.player = playerObject;
	    MN.Event.Observe(this.player, 'PausedChanged', this.onPauseChanged.bind(this));
	    MN.Event.Observe(this.player, 'PlayStateChanged', function(o, n) {
	    	if (o == 3 && n == 5) {
	    		this.togglePause();
	    		this.setPlayFromBeggining();
	    	}
	    }.bind(this));
		this.play();
		slider.init($('slider_progress_bar'), $('slider_progress_pipe'), this.fromTimeMs, this.toTimeMs);
	},

	onPauseChanged: function() {
		if (this.player.Paused()) {
			this.playPauseButtonImg.src = playerBaseUrl+'images/player/play.gif'
			this.playPauseButtonImg.name = 'play';
		} else {
			this.playPauseButtonImg.src = playerBaseUrl+'images/player/pause.gif'
			this.playPauseButtonImg.name = 'pause';
		}
	},

	stop: function() {
		this.player.Stop();
	},

	play: function() {
		this.player.Play(this.episode.highProgUrl, this.fromTime, this.toTime);
		this.player.Paused(false);
	},

	togglePause: function() {
		if (this.playFromBeggining) {
			this.play();
			this.playFromBeggining = false;
			this.player.Paused(!this.player.Paused());
		} else {
			this.player.Paused(!this.player.Paused());
		}
	},
	
	setPlayFromBeggining: function() {
		this.playFromBeggining = true;
	}
};

/** UTILITY FUNCTIONS **/
function timestampFromString(time) {
	var splited = time.split(":", 3);
	if (splited.length == 3) {
		return parseInt(splited[2] * 1000) + 
			parseInt(splited[1] * 60 * 1000) + 
			parseInt(splited[0] * 60 *60 * 1000);
	}
}

function timestampToString(timestamp) {
	var dt = new Date(parseInt(timestamp));
	var hours = dt.getUTCHours();
	var mins = dt.getUTCMinutes();
	var sec = dt.getUTCSeconds();
	return (((hours + '').length == 1) ? '0' + hours : hours) + ':' +
		(((mins + '').length == 1) ? '0' + mins : mins) + ':' +
		(((sec + '').length == 1) ? '0' + sec : sec);
}

playerHTML = '<div style="width: 629px; height: 531px; background-image: url(\''+playerBaseUrl+'images/player/player_background.gif\');">' +
'<div id="result_red_frame" style="width: 629px; height: 531px; margin-left: 0px; margin-top: 0px; z-index: 1000; position: absolute; opacity: 0">' +
'<img src="'+playerBaseUrl+'images/player/player_background_red.gif">' +
'</div>' +
'<div style="color: #FFFFFF; padding-bottom: 5px;"><span id="show_title">Show</span> | <span id="season_title">Season</span> | <span id="episode_title">Episode</span></div>' +
'<div id="player_div" style="width: 433px; height: 246px; margin-left: 103px; margin-top: 34px; clear: both"></div>' +
'<div id="slider_progress_pipe" style="width: 5px; height: 15px; margin-left: 99px; margin-top: 24px; position: absolute; background-image: url(\''+playerBaseUrl+'images/player/slider_progress_pipe.jpg\'); background-repeat: repeat-x"></div>' +
'<div id="slider_progress_bar" style="width: 0px; height: 6px; margin-left: 99px; margin-top: 28px; position: absolute; background-image: url(\''+playerBaseUrl+'images/player/slider_progress_background.jpg\');"></div>' +
'<div style="width: 35px; height: 33px; margin-left: 299px; margin-top: 47px; position: absolute; z-index: 100000; cursor: pointer;"><img id="play_pause_button" src="'+playerBaseUrl+'images/player/pause.gif" name="pause"/></div>' +
'<div style="width: 139px; height: 77px; margin-left: 249px; margin-top: 87px; position: absolute; z-index: 100;"><img id="scene_thumbnail" style="width: 139px; height: 77px;"/></div>' +
'<div style="width: 139px; height: 20px; margin-left: 249px; margin-top: 167px; position: absolute; z-index: 100; "><span id="seek_time"></span></div>' +
'<div id="start_over" class="blkbtn" style="width: 139px; height: 20px; margin-left: 65px; margin-top: 100px; position: absolute; z-index: 100000; ">Start Over</div>' +
'<div id="watch_fep" class="blkbtn" style="width: 139px; height: 20px; margin-left: 410px; margin-top: 100px; position: absolute; z-index: 100000; ">Watch Full Episode</div></div>';
