//global variables for loading in the js
var tpQVTalreadyInstalling = false;
var tpQVTJsIsLoaded = false;
var tpQVTJsIsLoading = false;
var tpQVTJsIsError = false;
var tpQVTisInvalid = false;
var tpQVTJsErrorTimeout;
var tpQVTWaitObjects;

var tpQVTFirstScriptLoaded = false;
var MN;//trick
///////// js loading functions ////////////////
///////////////////////////////////////////////
function tpQVTLoadScript(waitObj)
{
	if (!tpQVTWaitObjects)
	{
		tpQVTWaitObjects = new Array();
		//only load script the first time
		tpScriptLoader.addScript("http://player.movenetworks.com/pub/63BA7246/llmovenetworks.js", tpQVTScriptLoaded, "movenetworksjs");
		tpQVTJsIsLoading = true;
		tpQVTJsErrorTimeout = setTimeout("tpQVTScriptLoadError()", 15000);//wait fifteen seconds for the player to load in.
	}
	tpQVTWaitObjects.push(waitObj);
}
function tpQVTScriptLoaded(fromTimeout)
{
	tpQVTJsIsLoading = false;
	tpQVTWaitForScript();
}
function tpQVTWaitForScript()
{
	// wait until we have everything we need to start
	if (MN && MN.Log && MN.QVT && MN.QMPInstall)
	{
		clearTimeout(tpQVTJsErrorTimeout)
		tpQVTJsIsError = false;
		tpQVTJsIsLoaded = true;
		//MN.Log.ShowPane();//show debugging for move
		for (var i = 0; i < tpQVTWaitObjects.length; i++)
		{
			tpQVTWaitObjects[i].scriptLoaded(); //QVT library loaded, inform all qvts
		}
	}	
	else
	{
		setTimeout("tpQVTWaitForScript()", 100);
	}
}
function tpQVTScriptLoadError()
{	
	tpQVTJsIsError = true;
	for (var i = 0; i < tpQVTWaitObjects.length; i++)
	{
		tpQVTWaitObjects[i].delayMessage("mediaError");//give up on loading the js; inform all qvts
	}
}




///// interface object for a move player instance ////
//////////////////////////////////////////////////////
function tpExternal_QMP(swfId, controllerId)
{
	this.timer;//keep track of time
	this.errorTimer;//if the media won't play, time out
	this.bitrate = 0;
	this.duration = 0;
	this.position = 0;
	this.offset = 0;
	this.starting = true;
	this.playing = false;
	this.isHidden = true;
	this.isPaused = false;
	this.isClosed = true;
	this.startURL = null;
	this.swfId = swfId;
	this.controllerId = controllerId;
	this.QVTID = "tpQVT" + controllerId;
	this.QVTDivID = this.QVTID + "Div";
	this.QVT;//reference media player itself
	this.QVTDiv;//div inside which the media player rests
	this.playerDivID = "playerDiv";// TODO set the programmatically
	this.isFullscreen = false;
	
	//size params
	this.vidheight = 1;
	this.vidwidth = 1;
	this.topDelta = 0;
	this.leftDelta = 0;
	
	this.playerTop = 0;//-1 = not set
	
		
	////////// Functions called from Flash /////////////////////
		
	// dynamically resize an external media element... the top and left
	// deltas are adjustments on the current position
	this.resizeMP = function(args)
	{
		this.checkDiv();
		if (args)
		{
			this.vidheight = args[1];
			this.vidwidth = args[2];
			this.leftDelta = args[3];
			this.topDelta = args[4];
		}
		var offsetTop = tpGetTop(tpThisMovie(this.swfId));
		tpThisMovie(this.QVTDivID).style.top = (offsetTop + this.topDelta) + "px";
		var offsetLeft = tpGetLeft(tpThisMovie(this.swfId));
		tpThisMovie(this.QVTDivID).style.left = (offsetLeft + this.leftDelta) + "px";
		if (!args)
		{
			this.showDIV([true]);
		}
	}
	
	this.sizeDIV = function()
	{
		this.QVTDiv.style.height = this.vidheight + "px";
		this.QVTDiv.style.width = this.vidwidth + "px";	
		this.QVTDiv.style.visibility = "visible";
	}
	
	this.showDIV = function(args)
	{
		this.checkDiv();
		if (!this.QVT) return;
		var isShown = args[0];
		
		this.isHidden = !isShown;
		if (isShown)
		{
			this.QVT.Width(this.vidwidth);
			this.QVT.Height(this.vidheight);
			this.sizeDIV();
		}
		else
		{
			this.QVT.Width(0);
			this.QVT.Height(0);
			this.QVTDiv.style.visibility = "hidden";
		}		
	}
	
	this.showPlayerDIV = function()
	{
		window.document.getElementById(this.playerDivID).style.display = "block";
		this.QVTDiv.style.padding = "0px";
		this.QVTDiv.style.border = "";
		this.sizeDIV();
	}

	this.hidePlayerDIV = function()
	{
		window.document.getElementById(this.playerDivID).style.display = "none";
		this.QVTDiv.style.padding = "5px";
		this.QVTDiv.style.border = "solid 1px #bebebe";
		if ((navigator.userAgent.toLowerCase().indexOf("msie") == -1))
		{
			this.QVTDiv.style.height = (this.vidheight - 12) + "px";
			this.QVTDiv.style.width = (this.vidwidth - 12) + "px";
		}
		document.styleSheets[0].insertRule("#moveplay_install a {color:#bebebe}", 0);
		document.styleSheets[0].insertRule(".moveplay_featuretitle {font-weight:bold}", 0);
	}	
	
	
	// called from flash handle setting the URL in Windows Media Player
	this.playURL = function(args)
	{
		var url = args[0];
		this.offset = args[1] ? args[1] / 1000 : 0;
		this.doPlayURL(url);
	}
	
	
	this.doPlayURL = function(url)
	{
		//tpDebug("playURL " + url);
		if (tpQVTJsIsError)//the js has errored by timing out or not loading correctly
		{
			this.delayMessage("mediaError");
		}
		else if (!tpQVTJsIsLoaded)//the js needs to be loaded
		{
			this.startURL = url;//keep a record for when the js loads
			if (!tpQVTJsIsLoading)
			{
				this.beginLoadJS();//begin loading
			}
		}
		else if (tpQVTisInvalid)//the js has loaded but has determined that the system can't play the move file
		{
			this.showErrorBox();
		}
		else if (!this.QVT)//the js has loaded but the code hasn't initialized.
		{
			this.startURL = url;
			this.createPlayer();
		}
		else //everything looks good, let's play the file
		{
			this.delayMessage("acknowledge");
			this.showPlayerDIV();
			if (this.isHidden)
			{
				this.showDIV([true]);
			}
			//tpDebug("start the actual play");
			//code to play url
			this.QVT.Play(url);
			if (this.offset)
			{
				this.QVT.CurrentPosition(this.offset);
				this.offset = 0;
			}
			this.isPaused = false;
			this.isClosed = false;
			this.starting = true;
			this.runErrorTimer();//give it n seconds to find something
		}
	}
	
	// handle seek in Windows Media Player
	this.seek = function(args)
	{
		if (!this.QVT) return;
		position = args[0];
		this.QVT.CurrentPosition(position);
		if (this.isPaused)
		{
			this.isPaused = false;
			this.runTimer();
			this.delayMessage("togglePause");
		}
	}
	
	this.closePlayer = function()
	{
		if (!this.QVT) return;
		//close the player
		this.isClosed = true;
		this.QVT.Stop();
		this.clearTimer();
		if (!this.isHidden)
		{
			this.showDIV([false]);
		}
	}
	
	this.pauseMovie = function(args)
	{
		if (!this.QVT) return;
		this.isPaused = args[0];
		//pause or unpause the movie
		if (this.isPaused)
		{
			this.clearTimer();
		}
		else
		{
			this.runTimer();
		}
		this.QVT.Paused(this.isPaused);
	}
	
	this.setSoundLevel = function(args)
	{
		if (!this.QVT) return;
		var level = args[0];
		//code to set the sound level
		this.QVT.Volume(level);
	}
	
	this.mutePlayer = function(args)
	{
		if (!this.QVT) return;
		var isMute = args[0];
		//code to mute player
		this.QVT.Muted(isMute);
	}
	
	this.fullScreen = function(args)
	{
		if (!this.QVT) return;
		//code to send to fullscreen
		if (args[0])
		{
			setTimeout("tpQVTCallFunction('" + this.swfId + "', '" + this.controllerId + "', 'doFullScreen')", 500);//I guess it has to wait a bit before it actually hits the fullscreen
			var _550 = "http://player.movenetworks.com/pub/D5C75464/controls/";
			var _551 = 30;
			var _552 = 19;
			this.QVT.setControlFrame(_550+"Frame.png", -20);
			// THIS SETCONTROLS CALL IS ONE LINE (email may mess with the CRs)
			this.QVT.setControls({Rewind:{imageURL:_550+"Rewind.png",x:_551+30,y:_552+4},Play:{imageURL:_550+"Play.png",x:_551+70,y:_552},Pause:{imageURL:_550+"Pause.png",x:_551+70,y:_552},FastForward:{imageURL:_550+"FastForward.png",x:_551+110,y:_552+4},FullScreen:{imageURL:_550+"Fullscreen.png",x:-9,y:_552,effect:"zoom",effectSpeed:"500"},ExitFullScreen:{imageURL:_550+"ExitFullscreen.png",x:-9,y:_552}});
			this.QVT.activateControls();
		}
		else
		{
			this.QVT.fullScreen(false);
		}
	}
	//called from fullscreen after a half second to actually do the deed
	this.doFullScreen = function()
	{
		this.QVT.fullScreen(true);
	}
	
	////////////// Internal state functions //////////////
	//////////////////////////////////////////////////////
	
	this.stateChanged = function(oldState, newState)
	{
		if (this.isHidden) return;
		//tpDebug("##### new State: " + newState);
		switch(newState)
		{
			case 0:
				//init
				break;
			case 1:
				//opening
				break;
			case 2: case 8:
				//buffering //authorizing
				this.playing = true;
				this.delayMessage("buffering");
				break;
			case 3:
				//playing
				if(this.starting)
				{
					this.clearErrorTimer();
					this.delayMessage("mediaBegins");
					this.starting = false;
				}
				else
				{
					this.delayMessage("playing");
				}
				if (!this.isPaused)
				{
					this.playing = true;
					this.runTimer();
				}
				else
				{
					this.QVT.SingleStep();
				}
				break;
			case 4:
				//stopped
				this.playing = false;
				this.clearTimer();
				break;
			case 5:
				//media ended
				this.playing = false;
				this.clearTimer();
				this.delayMessage("setPlayerDone");
				break;
			case 6:
				//error
				this.playing = false;
				this.clearTimer();
				break;
			case 7:
				//stalled
				this.clearTimer();
				this.playing = false;
				break;
			case 255:
				//waiting
				break;
			
		}
	}
	
	this.uiStateChanged = function(state)
	{
		if (state == 3) 
		{ 
			//"Exited_FullScreen"
			this.delayMessage("fullScreenOff");
			this.QVT.deactivateControls();
		}
		else if (state == 2 ) 
		{
			// "Entered_FullScreen"
			// put any Full Screen events here
			this.delayMessage("fullScreenOn");
		}
	}
	
	this.delayMessage = function(message)
	{
		setTimeout("tpQVTSendDelayMessage('" + message + "', '" + this.swfId + "', '" + this.controllerId + "')", 1);
	}
	
	/////////// report timer code /////////////
	this.runTimer = function()
	{
		this.clearTimer();
		this.timer = setInterval("tpQVTCallFunction('" + this.swfId + "', '" + this.controllerId + "', 'report')", 300);
	}
	this.clearTimer = function()
	{
		clearInterval(this.timer);
	}
	this.report = function()
	{
		this.bitrate  = this.getBitrate() * 1028;//get bps
		this.duration = this.getDuration();
		this.position = this.getPosition();
		if (this.playing)
		{
			tpExternalController.returnMessage(this.swfId, this.controllerId, "currentBitrate", [this.bitrate]);
			tpExternalController.returnMessage(this.swfId, this.controllerId, "synchPosition", [this.duration, this.position]);
		}
		
	}
	this.getBitrate = function() 
	{
		// without this check, can get errors on IE in the designer on repaint
		if (this.QVT) return this.QVT.CurrentBitRate();
		else return 0;
	}
	this.getDuration = function()
	{
		// without this check, can get errors on IE in the designer on repaint
		if (this.QVT) return this.QVT.Duration();
		else return 0;
	}
	this.getPosition = function()
	{
		// without this check, can get errors on IE in the designer on repaint
		if (this.QVT) return this.QVT.CurrentPosition();
		else return 0;
	}
	
	//////// error timer code //////////////
	this.runErrorTimer = function()
	{
		this.clearErrorTimer();
		this.errorTimer = setTimeout("tpQVTCallFunction('" + this.swfId + "', '" + this.controllerId + "', 'error')", 5000);//give it 5 seconds
	}
	this.clearErrorTimer = function()
	{
		clearInterval(this.errorTimer);
	}
	this.error = function()
	{
		this.delayMessage("mediaError")
	}
	
	///// Functions for loading in scripts and player ///////
	/////////////////////////////////////////////////////////
	
	this.beginLoadJS = function()
	{
		window.MN_LoadLibIntoDOM = true;
		tpExternalController.returnMessage(this.swfId, this.controllerId, "acknowledge", []);
		tpQVTLoadScript(this);
	}
	
	this.scriptLoaded = function()
	{
		// ONLY DO THE INSTALL IF IT DOESN"T NEED AN UPGRADE...
		if (!MN.QMPInstall.CanPlay() && !MN.QMPInstall.UpgradeRequired())
		{
			this.delayMessage("acknowledge");
			this.createPlayer(true);
	
		}
		else if (this.startURL)
		{
			this.doPlayURL(this.startURL);//throw it back to the playURL function
		}
	}
	
	this.createPlayer = function(isInstall)
	{
		this.checkDiv();
		if (isInstall && !tpQVTalreadyInstalling)
		{
			tpQVTalreadyInstalling = true;
			setTimeout("tpQVTCallFunction('" + this.swfId + "', '" + this.controllerId + "', 'doInstall')", 500);
		}
		else if (MN.QMPInstall.UpgradeRequired())
		{
			this.sizeDIV();
			this.hidePlayerDIV();
		}
		var thisPlayer = this;
		MN.QVT.CreatePlayer(this.QVTDivID, function(player){tpQVTCreatePlayer(player, thisPlayer);}, 1, 1, this.QVTID);
	}
	
		
	this.onPlayerCreated = function(player)
	{
		this.QVT = player;
		var thisPlayer = this;
		MN.Event.Observe(this.QVTID, "PlayStateChanged", function(oldState, newState) {tpQVTPlayStateChanged(oldState, newState, thisPlayer);});
		MN.Event.Observe(this.QVTID, "UIStateChanged", function(state){tpQVTUiStateChanged(state, thisPlayer);});
		if (this.startURL)
		{
			this.doPlayURL(this.startURL);
		}
	}
	
	this.doInstall = function()
	{
		this.sizeDIV();
		this.hidePlayerDIV();
		MN.QMPInstall.StartInstall();
	}
	
	this.doConfirm = function()
	{
		if (confirm("This content requires the Move Player, which is not present.\n Click 'OK' to download and install the Move Networks Player" ))
		{
			this.createPlayer(true);
		}
	}
	
	this.showErrorBox = function()
	{
		if (tpQVTalreadyInstalling) 
		{
			return;
		}
		this.delayMessage("acknowledge");
		setTimeout("tpQVTCallFunction('" + this.swfId + "', '" + this.controllerId + "', 'doConfirm')", 10);//time so acknowledge has a chance to fire
	}	
		
	this.cleanup = function()
	{
		if (this.QVTDiv) 
		{
			this.showPlayerDIV();
			if (this.QVT) 
			{
				this.QVT.Stop();
				this.QVT.Width(0);
				this.QVT.Height(0);				
				delete this.QVT;
			}
			window.document.getElementsByTagName('body')[0].removeChild(this.QVTDiv);
			if (typeof MN != "undefined") 
			{
				MN.Event.StopObserving(this.QVTID, "PlayStateChanged", tpQVTStateChanged);
				//remove the div into which the player has been set
				
				delete MN;
				
				//remove all the js files
				var mnjs = tpThisMovie("movenetworksjs");
				window.document.getElementsByTagName('head')[0].removeChild(mnjs);
			}
		}
	}
	
	this.checkDiv = function()
	{
		// create the div if it doesn't already exist
		if (!this.QVTDiv)
		{
			//code to create the player div
			var divEl = window.document.createElement('div');
			divEl.id = this.QVTDivID;
			window.document.getElementsByTagName('body')[0].appendChild(divEl);
			this.QVTDiv = tpThisMovie(this.QVTDivID);
			// set up the basic positioning
			this.QVTDiv.style.position = "absolute";
			this.QVTDiv.style.visibility = "hidden";
			this.QVTDiv.style.top = "0px";
			this.QVTDiv.style.left = "0px";
			this.QVTDiv.style.zIndex = 5000;
			this.QVTDiv.style.overflow = "hidden";
			this.QVTDiv.style.fontFamily = "Verdana";
			this.QVTDiv.style.fontSize = "8pt";
			this.QVTDiv.style.color = "#bebebe";
			this.QVTDiv.style.backgroundColor = "#000000";
		}
	}
	
}

//// global helper functions /////////////
//////////////////////////////////////////

function tpQVTSendDelayMessage(message, swfId, id)
{
	tpExternalController.returnMessage(swfId, id, message);
}

function tpQVTCallFunction(swfId, id, funcName)
{
	tpExternalController.routeMessage(swfId, id, "moveNetworks", funcName);
}

function tpQVTPlayStateChanged(oldState, newState, player)
{
	player.stateChanged(oldState, newState);
}

function tpQVTUiStateChanged(state, player)
{
	player.uiStateChanged(state);
}

function tpQVTCreatePlayer(qvt, player)
{
	player.onPlayerCreated(qvt);
}




//all the functions are set up, register with utils.js
tpExternalController.registerExternalPlayer("moveNetworks", "tpExternal_QMP");
