/*
	Roku.PCPlayer
*/

if(typeof(Roku) == "undefined")
    Roku = { classes : [] };

Roku.PCPlayer =
{
	playerId				: "pcPlayer",
	sliderClassName			: "slider",
	statusClassName			: "status",
	
	commandPanelId			: "command_panel",
	commandButtonId			: "command_button",
	volumeSliderId			: "player_slider",
	
	mediaPlayerId			: "media_player",
	embedMediaPlayerId		: "media_player_embed",
	
	rankPanelClassName		: "rank_panel",

	streamListId			: "stream_list",
	streamListAttrEntry		: "stream_entry_",
	
	playButtonEnableSrc		: "images/pcplayer-play.png",
	playButtonDisableSrc	: "images/pcplayer-play-disabled.png",
	stopButtonEnableSrc		: "images/pcplayer-stop.png",
	stopButtonDisableSrc	: "images/pcplayer-stop-disabled.png",
	
	stationAttrUrl			: "station_url",
	stationAttrTitle		: "station_title",
	stationAttrDescription	: "station_description",
	stationAttrGenres		: "station_genres",
	stationAttrLocation		: "station_location",
	stationAttrReliability	: "station_reliability",
	stationAttrPopularity	: "station_popularity",
	stationAttrRating		: "station_rating",
	
	statusPlaying			: "Now Playing",
	statusLoaded			: "Ready",
	statusFailed			: "Failed to Play",
	statusConnecting		: "Connecting...",
	statusBuffering			: "Buffering...",
	statusRetrieving		: "Retrieving Data ...",
	statusDropAvailalbe		: "Ready to Play",
	statusEmpty				: "Drop station here...",
	
	openPlayListTimeout		: 100,
	openStaionUrlTimeout	: 100,

	queryPlayListAttrName	: "query_playlist_key",

	macAttribName			: "player_mac",

	player					: null,
	command_button			: null,
	media_player			: null,
	play_list				: null,
	play_index				: -1,
	stream_list				: null,
	stream_list_index		: 0,
	mac						: "",
	play_url				: "",
	play_url_time_started	: null,
	play_url_time_played	: 0,
	play_url_rebuffers		: 0,
	play_url_failures		: 0
};

Roku.classes.push(Roku.PCPlayer);

Roku.PCPlayer.play = function()
{
	try { this.media_player.controls.play(); } catch(e) {}
}

Roku.PCPlayer.is_playing = function()
{
	var playing = false; 
	try { playing = (this.media_player.playState == 3) ? true : false; } catch(e) {}
	return playing;
}

Roku.PCPlayer.stop = function()
{
	try { this.media_player.controls.stop(); } catch(e) {}
}

Roku.PCPlayer.close = function()
{
	try { this.media_player.close(); } catch(e) {}
}

Roku.PCPlayer.get_volume = function()
{
	var volume = 0;
	try { volume = this.media_player.settings.volume; } catch(e) {}
	return volume; 
}

Roku.PCPlayer.set_volume = function(volume)
{
	try { this.media_player.settings.volume = volume; } catch(e) {}
}

Roku.PCPlayer.on_volume_changed = function(slider)
{
	this.set_volume(Math.ceil(Roku.Slider.getPos(slider) * 100));
}

Roku.PCPlayer.onMediaPlayerStateChange = function(state)
{
	switch(state)
	{
		case  1:	// stopped
			this.enableCommands(true, false, this.statusLoaded);
			this.play_url_stopped();
			break;
		
		case  3:	// playing
			this.enableCommands(false, true, this.statusPlaying);
			this.play_url_started();
			break;

		case  6:	// buffering
			this.enableCommands(false, false, this.statusBuffering);
			this.play_url_buffered();
			break;

		case  9:	// transporting
			this.enableCommands(false, false, this.statusConnecting);
			break;
			

		case 10: // ready
			if(this.media_player && this.media_player.error && (0 < this.media_player.error.errorCount))
			{
				this.enableCommands(false, false, this.statusFailed);
			}
			else
			{
				this.enableCommands(true, false, this.statusLoaded);
			}
			break;

	}
}

Roku.PCPlayer.onMediaPlayerError = function()
{
	//Roku.Util.Trace("debug_out", "onMediaPlayerError: " + this.media_player.error, true);
	if(this.media_player && this.media_player.error && (0 < this.media_player.error.errorCount))
	{
		this.play_url_failed();

		if(this.play_list)
		{
			this.play_index++;
			try { this.media_player.close(); }  catch(e) {}
			window.setTimeout("Roku.PCPlayer.openPlayListEntry()", this.openPlayListTimeout);
		}
		else if(this.play_url && (0 <= this.play_url.indexOf("=pls")))
		{
			this.loadPlayList(this.play_url);
		}
		else if(this.stream_list)
		{
			this.stream_list_index++;
			try { this.media_player.close(); }  catch(e) {}
			window.setTimeout("Roku.PCPlayer.openStreamListEntry()", this.openStaionUrlTimeout);
		}
		else
		{
			this.init_play_url("");
		}
	}
}

Roku.PCPlayer.onMediaPlayerStatusChange = function()
{
	//var status = this.media_player ? this.media_player.status : ""; 
	//Roku.Util.Trace("debug_out", this.media_player.playState + " : " + status);
}

Roku.PCPlayer.onMediaPlayerMediaChange = function(item)
{
	//var media = this.media_player.currentMedia;
}

Roku.PCPlayer.openStation = function()
{
	if(!this.media_player)
		return;

	this.play_list = null;
	this.play_index = -1;

	var url = this.player.getAttribute(this.stationAttrUrl);
	//Roku.Util.Trace("debug_out", "openStation:  " + url, true);
	this.init_play_url(url);

	if(Roku.Util.splitUrl(url).extention == ".pls")
	{
		this.loadPlayList(url);
	}
	else
	{
		this.playUrl(url);
	}
}

Roku.PCPlayer.loadPlayList = function(url)
{
	var queryKey = this.player.getAttribute(this.queryPlayListAttrName);
	var queryValue = encodeURIComponent(url);
	var queryParam = queryKey + "=" + queryValue;
	
	//Roku.Util.Trace("debug_out", "AJAX query: " + queryParam, true);
	Roku.Query.invoke(queryParam,
		function (content, custom_data) { Roku.PCPlayer.openPlayList(content, custom_data); },
		null);
}

Roku.PCPlayer.openPlayList = function(content, custom_data)
{
	var urls = [];
	//Roku.Util.Trace("debug_out", "AJAX response: ", true);
	
	var entries = content.split('\n');
	var entries_count = entries.length;
	for(var iEntry = 0; iEntry < entries_count; iEntry++)
	{
		var entry = entries[iEntry];
		if(Roku.Util.CompareNoCase(entry.substr(0, 4), "file"))
		{
			var pos = entry.indexOf("=");
			if(0 < pos)
			{
				var url = Roku.Util.Trim(entry.substr(pos + 1, entry.length - pos - 1));
				urls.push(url);
				//Roku.Util.Trace("debug_out", "    PlayListUrl=" + url, true);
			}
		} 
	}
	
	if(0 < urls.length)
	{
		this.play_list = urls;
		this.play_index = 0;
	}
	
	this.openPlayListEntry();
}

Roku.PCPlayer.openPlayListEntry = function()
{
	if(this.play_list && (0 <= this.play_index) && (this.play_index < this.play_list.length))
	{
		this.playUrl(this.play_list[this.play_index]);
	}
	else
	{
		this.play_list = null;
		this.play_index = -1;

		if(this.stream_list)
		{
			this.stream_list_index++;
			this.openStreamListEntry();
		}
	}
}

Roku.PCPlayer.openStreamListEntry = function()
{
	if(!this.stream_list)
		return;
	
	var url = this.stream_list.getAttribute(this.streamListAttrEntry + this.stream_list_index);
	if(url)
	{
		this.player.setAttribute(this.stationAttrUrl, url);
		this.openStation();
	}
	else
	{
		this.stream_list = null;
		this.stream_list_index = -1;
	}
}

Roku.PCPlayer.playUrl = function(url)
{
	if(!this.media_player)
		return;

	//Roku.Util.Trace("debug_out", "Playing:  " + url, true);

	try
	{
		this.media_player.close();
		this.media_player.url = url;
		this.media_player.controls.play();
	}
	catch(e) {}
}


Roku.PCPlayer.setStatus = function(status)
{
	var status_element = Roku.Util.childClassElement(this.player, this.statusClassName);
	if(status_element)
		status_element.innerHTML = status;
}

Roku.PCPlayer.enableCommands = function(enable_play, enable_stop, status)
{
	if(this.command_button)
	{
		if(enable_play)
			this.command_button.src = this.playButtonEnableSrc;
		else if(enable_stop)
			this.command_button.src = this.stopButtonEnableSrc;
		else
			this.command_button.src = this.stopButtonDisableSrc;
		this.command_button.cursor = (enable_play || enable_stop) ? "pointer" : "default";
	}
	
	if(typeof(status) == "string")
		this.setStatus(status);
}

Roku.PCPlayer.do_command_button = function(ev)
{
	var src = this.command_button ? this.command_button.src : "";
	if(0 <= src.indexOf(this.playButtonEnableSrc))
		this.play();
	else if(0 <= src.indexOf(this.stopButtonEnableSrc))
		this.stop();
}

Roku.PCPlayer.init_play_url = function(url)
{
	this.report_play_url(false);

	this.play_url				= url;
	this.play_url_time_started	= null;
	this.play_url_time_played	= 0;
	this.play_url_rebuffers		= 0;
	this.play_url_failures		= 0;
}

Roku.PCPlayer.report_play_url = function(wait)
{
	if(!this.mac || !this.play_url)
		return;

	var report = "pc_player_stat=" + this.mac + "&url=" + encodeURIComponent(this.play_url);
	
	this.play_url_stopped();
	if(this.play_url_time_played)
		report += "&time_played=" + this.play_url_time_played;

	if(this.play_url_rebuffers)
		report += "&rebuffers=" + this.play_url_rebuffers;

	if(this.play_url_failures)
		report += "&failures=" + this.play_url_failures;

	// clear all play data
	this.play_url				= "";
	this.play_url_time_started	= null;
	this.play_url_time_played	= 0;
	this.play_url_rebuffers		= 0;
	this.play_url_failures		= 0;

	//alert(report);
	if(wait)
		Roku.Query.invoke_sync(report);
	else
		Roku.Query.invoke(report);
}


Roku.PCPlayer.play_url_started = function()
{
	if(!this.play_url || this.play_url_time_started)
		return;

	this.play_url_time_started = new Date();
}

Roku.PCPlayer.play_url_stopped = function()
{
	if(!this.play_url || !this.play_url_time_started)
		return;

	var play_url_time_ended = new Date();
	var duration = Math.floor((play_url_time_ended.getTime() - this.play_url_time_started.getTime()) / 1000);	// pass seconds?
	this.play_url_time_played += duration;
	this.play_url_time_started = null;
}

Roku.PCPlayer.play_url_buffered = function()
{
	if(!this.play_url || !this.play_url_time_started)
		return;
	
	var play_url_time_ended = new Date();
	var duration = (play_url_time_ended.getTime() - this.play_url_time_started.getTime());
	if(1000 < duration)	// WMP always fires buffering when starting to play - count it only if we have been playing at least 1 sec.
		this.play_url_rebuffers++;
}

Roku.PCPlayer.play_url_failed = function()
{
	if(!this.play_url)
		return;
	
	this.play_url_failures++;
}

Roku.PCPlayer.initialize = function()
{
	this.player = document.getElementById(this.playerId);
	
	this.media_player = Roku.Util.childIdElement(this.player, this.mediaPlayerId);
		
	this.command_button = Roku.Util.childIdElement(this.player, this.commandButtonId);
	if(this.command_button)
		Roku.Util.eventHandler(this.command_button, "click", function(ev) { return Roku.PCPlayer.do_command_button(ev); });

	var volume_slider = Roku.Util.childIdElement(this.player, this.volumeSliderId);
	if(volume_slider)
	{
		var volumeHandler = function(ev) { return Roku.PCPlayer.on_volume_changed(ev); };
		volume_slider.changing_handler = volumeHandler;
		volume_slider.changed_handler = volumeHandler;
	}
		
	// var media_player = Roku.Util.childIdElement(player, this.mediaPlayerId);
	// may try to handle playStateChange(play_state) event 

	this.stream_list = Roku.Util.childIdElement(this.player, this.streamListId);
	
	this.mac = this.player ? this.player.getAttribute(this.macAttribName) : "";
}

Roku.PCPlayer.onBodyLoad = function()
{
	if(this.media_player)
	{
		var sCookie = Roku.Util.getCookie("pcPlayer");
		var data = Roku.Util.parseCookie(sCookie);
		
		var volume = data["volume"];
		if(volume)
		{
			this.set_volume(volume);
			
			var slider = Roku.Util.childClassElement(this.player, this.sliderClassName);
			Roku.Slider.setPos(slider, volume / 100.0);
		}

		this.openStation();
	}
	else
	{
		var url = this.player ? this.player.getAttribute(this.stationAttrUrl) : "";
		
		this.init_play_url(url);
		this.play_url_started();
	}
}

Roku.PCPlayer.onBodyUnload = function()
{
	this.report_play_url(true);

	if(this.media_player)
	{
		Roku.Util.setCookie("pcPlayer", "volume=" + this.get_volume());
		this.close();
	}
}

