/*****************************************************************************
 * IranianRadio
 * 
 * Author: Jason Us
 * 
 * Created: July 10, 2006
 * 
 * Filename: player.js
 * 
 * Description: Ajax methods to handle retrieval of the currently playing songs on the shoutcast server, 
 * as well as timer functions to display progress meters while waiting for the song names to load. 
 * 
 * TODO: 
 *   - Add a refresh so that songs are updated every couple few minutes
 * 	 - Refactor getData() method into a more modularized set of methods
 ****************************************************************************/

//****************************** CONSTANTS ***********************************

// The information returned with the response is dependent on the method used in the request
var GET   = "GET";   // an entity corresponding to requested resource is sent in the response
var HEAD  = "HEAD";  // entity-header field corresponding to req resource are sent in resp without any message-body
var POST  = "POST";  // an entity describing or containing the result of the action;
var TRACE = "TRACE"; // an entity containing the request message as received by the end server. 

// Possible XMLHttpRequestObject.readyState
var UNINITIALIZED = 0;
var	LOADING = 1;
var	LOADED = 2;
var	INTERACTIVE = 3;
var COMPLETE = 4;

// A few XMLHttpRequestObject.readyState's
// See the rest at - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
var HTTP_STATUS_OK = 200; 			
var HTTP_STATUS_NOT_FOUND = 404; 

var TICKER_VALUE = 5;
var PROGRESS_INTERVAL = 200;

//****************************** GLOBALS *************************************
var tickerValue = TICKER_VALUE;			// time to next countdown

// PROGRESS BAR VARIABLES
var progressEnd = 19;						// set to number of progress <span>'s tags that make up progress bar
var endColor	  = '#FFFF00';				// progress bar band color
var progressInterval = PROGRESS_INTERVAL;	// set to time between to progress bar updates (milli-seconds)
var progressAt = 0;  						// current progress

// if we have gotten the song name back from the shoutcast server
var popStreamLoaded = false;
var danceStreamLoaded = false;
var sonatiStreamLoaded = false;
var eshgheiranStreamLoaded = false;
var kurdipopStreamLoaded = false;

// definition of URL's for each of the streams, file type is added dynamically 
// by choosing player in drop down list

// ABSOLUTE REFERENCES
//var Pop128URL 		= "http://www.iranianradio.com/radio/iranianradio-pop128.php?file=";
//var Pop24URL 		= "http://www.iranianradio.com/radio/iranianradio-pop24.php?file=";
//var Dance128URL 	= "http://www.iranianradio.com/radio/iranianradio-dance128.php?file=";
//var Sonati128URL 	= "http://www.iranianradio.com/radio/iranianradio-sonati128.php?file=";
//var EshgheIran128URL	= "http://www.iranianradio.com/radio/iranianradio-eshgheiran128.php?file=";
//var KurdiPop128URL	= "http://www.iranianradio.com/radio/kurdiradio-pop128.php?file=";

// RELATIVE REFERENCES
var Pop128URL 		= "radio/iranianradio-pop128.php?file=";
var Pop24URL 		= "radio/iranianradio-pop24.php?file=";
var Dance128URL 	= "radio/iranianradio-dance128.php?file=";
var Sonati128URL 	= "radio/iranianradio-sonati128.php?file=";
var EshgheIran128URL	= "radio/iranianradio-eshgheiran128.php?file=";
var KurdiPop128URL	= "radio/kurdiradio-pop128.php?file=";

//****************************** METHODS *************************************

/**
 * Invokes a page for each of the three music streams passing the streams port and thje div ID
 * to load the page into. The Math.random param solves a caching bug in IE by tricking it into
 * thinking its a unique page.
 *
 * TODO: pass port & div as params
 */
function displayStreams()
{
		// start the asynchronous request for data from the shoutcast server
		// add random # on end to fix IE bug by tricking it to thinking its a new page each time
		getData("./streaming/nowPlaying.php?port=10500&hash=" + Math.random(), "popStreamID");	
		getData("./streaming/nowPlaying.php?port=10600&hash=" + Math.random(), "danceStreamID");
		getData("./streaming/nowPlaying.php?port=10700&hash=" + Math.random(), "sonatiStreamID");
		getData("./streaming/nowPlaying-ovh-eshgheiran.php?port=8002&hash=" + Math.random(), "eshgheiranStreamID");
		getData("./streaming/nowPlaying-ovh-kurdipop.php?port=9000&hash=" + Math.random(), "kurdipopStreamID");
		
		// start the progress bar
		progressUpdate();
}


/**
 * Using AJAX calls to request page content using HTTP and place the response in a 
 * div tag. 
 *
 * @param {	url } dataSource The url we wish to semd a HTTP request to.
 * @param {	id } divID The id of the div tag we wish the load the HTTP response into.
 */
function getData(dataSource, divID) {

	var obj = document.getElementById(divID); 	// get handle to the div tag
	var XMLHttpRequestObject = false			// init the XHR
	var responseText = "";						// will contain the reponse from the server
	 
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
	{
		try 
		{
			XMLHttpRequestObject = new XMLHttpRequest();
		} 
		catch (e)
		{
				obj.innerHTML = "An Error IR00001 has occured: " + e;
		}	
	}
	else if (window.ActiveXObject) // if IE
	{ 
		try 
		{
			XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch (e)
		{
			obj.innerHTML = "An Error IR00002 has occured.";
		}
	}
	else obj.innerHTML = "An Error IR00003 has occured.";

	// get page asynchronously, last param = true specifies this, although its the default
	XMLHttpRequestObject.open(GET, dataSource, true) ;
	XMLHttpRequestObject.onreadystatechange = function() 
	{
		// verify that our request complete and its status is "OK"
		if (XMLHttpRequestObject.readyState==COMPLETE && XMLHttpRequestObject.status==HTTP_STATUS_OK)
		{
			 
			 responseText = XMLHttpRequestObject.responseText;
			 
			 if ( divID == "popStreamID" ) 
			 { 
				popStreamLoaded = true; 
			 
				obj.innerHTML = "<span class='songName'>" + responseText + "</span>";
			 }
			 else if ( divID == "danceStreamID" ) 
			 { 
					 
				danceStreamLoaded = true; 
			
				obj.innerHTML = "<span class='songName'>" + responseText + "</span>";
			 }
			 else if ( divID == "sonatiStreamID" ) 
			 { 
							 
				sonatiStreamLoaded = true; 
				
				obj.innerHTML = "<span class='songName'>" + responseText + "</span>";
			 }
			 else if ( divID == "eshgheiranStreamID" ) 
			 { 
							 
				eshgheiranStreamLoaded = true; 
				
				obj.innerHTML = "<span class='songName'>" + responseText + "</span>";
			 }
			 else if ( divID == "kurdipopStreamID" ) 
			 { 
							 
				kurdipopStreamLoaded = true; 
				
				obj.innerHTML = "<span class='songName'>" + responseText + "</span>";
			 }
		}
	}

	XMLHttpRequestObject.send(null);	// send the request
}


/**
 * Update progress bar to the correct % complete. 
 * 
 * TODO: ?we may be able to correlate the progress bar to an
 * actual value if we know the connection speed of the user, and the
 * size of the stream that is being buffered. Its all so quick anyway it's probably moot. 
 */ 
function progressUpdate() 
{
	progressAt++;
	if (progressAt >= progressEnd) 
	{
		progressClear();
	}
	else 	
	{
		var popProgressDiv = document.getElementById('popProgress' + progressAt); 
		var danceProgressDiv = document.getElementById('danceProgress' + progressAt); 
		var sonatiProgressDiv = document.getElementById('sonatiProgress' + progressAt);
		var eshgheiranProgressDiv = document.getElementById('eshgheiranProgress' + progressAt);
		var kurdipopProgressDiv = document.getElementById('kurdipopProgress' + progressAt);
		
		// make sure our references are valid
		if (popProgressDiv)    
		{ 
			popProgressDiv.style.backgroundColor = endColor; 

		
		}
		if (danceProgressDiv)      { danceProgressDiv.style.backgroundColor = endColor; }
		if (sonatiProgressDiv)     { sonatiProgressDiv.style.backgroundColor = endColor; }
		if (eshgheiranProgressDiv) { eshgheiranProgressDiv.style.backgroundColor = endColor; }
		if (kurdipopProgressDiv)   { kurdipopProgressDiv.style.backgroundColor = endColor; }
	}
	// set the call progressUpdate() function to be called again in 100 milliseconds 
	setTimeout('progressUpdate()', progressInterval);
}



/**
 * Set the progress bars back to zero (transparent)
 */
function progressClear() 
{
   for (var i = 1; i <= progressEnd; i++) 
   {
	   	var popProgressDiv = document.getElementById('popProgress' + i); 
		var danceProgressDiv = document.getElementById('danceProgress' + i); 
		var sonatiProgressDiv = document.getElementById('sonatiProgress' + i); 
		var eshgheiranProgressDiv = document.getElementById('eshgheiranProgress' + i); 
		var kurdipopProgressDiv = document.getElementById('kurdipopProgress' + i); 
	
		// make sure our references are valid
		if (popProgressDiv)    
		{ 
			popProgressDiv.style.backgroundColor = 'transparent'; 
	
		}
		if (danceProgressDiv)      { danceProgressDiv.style.backgroundColor = 'transparent'; }
		if (sonatiProgressDiv)     { sonatiProgressDiv.style.backgroundColor = 'transparent'; }
		if (eshgheiranProgressDiv) { eshgheiranProgressDiv.style.backgroundColor = 'transparent'; }
		if (kurdipopProgressDiv)   { kurdipopProgressDiv.style.backgroundColor = 'transparent'; }
   }
   progressAt = 0;
}


/**
 * Sends the browser to a particular URL 
 * @param {	string } streamURL The URL of the shoutcast stream the user wishes to listen to.
 */
function gotoURL(streamURL) 
{
	var listenerForm = document.getElementById("playerForm");  // get handle to form
	var playerIndex = document.getElementById("playerList").selectedIndex; // get selected player string - pls, ram, wax or pls
	var playerString = listenerForm.playerList[playerIndex].value;
	window.location.href = streamURL + playerString;
	return true;
}

