//------------------------------
// MovieEngine.js
//
// Contains the core of all Silverlight event handlers for this movie
//
var lblPlayDate;	//In Theaters text

var movieStage = null;		//Outermost canvas
var outerCanvas = null;	//Movie Core (which is centered in the movieStage)
var fullScreenZoomer = null;
var isFullScreen = false;
var TrailerMedia = null;
var silverlightHost;

//Position Slider State
var sliderMouseDown = false;
var sliderX = 0;
var sliderY = 1;
var positionTimer = null;
var enableSound = (document.domain != "dev.xfiles.hatchinnovations.com");	//For Debugging, so you don't have to hear the Trailer 300,000,000 times

//Sound Effects
var ViewSound;
var isViewSoundLoaded = false;

function onMovieLoad(pluginHost, userContext, rootCanvas)
{
	positionTimer = window.setInterval(checkMediaPosition, 1000);

	silverlightHost = pluginHost;
	silverlightHost.content.onResize = onPlayerResize;

	movieStage = rootCanvas;
	outerCanvas = rootCanvas.FindName("MovieCore");
	fullScreenZoomer = rootCanvas.FindName("FullScreenZoomer");

	LoadLanguageTrailer();	//Start Trailer in all cases
	SetLanguage();

	centerPlayer();

	playTrailer(true);
}

function LoadLanguageTrailer()
{
	//Load Trailer
	TrailerMedia = movieStage.FindName("TrailerMedia");
	TrailerMedia.Source = language.TRAILER_MEDIA_URL;
	stopTrailer();
}

function SetLanguage()
{
	var lblPlayDate = outerCanvas.FindName("lblPlayDate");
	if (lblPlayDate != null) lblPlayDate.Text = language.PLAY_DATE;
}

function onMovieError(sender, errorArgs)
{
	if (document.domain == "dev.xfiles.hatchinnovations.com")
	{
		// The error message to display.
		var errorMsg = "Silverlight Error: \n\n";
		
		// Error information common to all errors.
		errorMsg += "Error Type:    " + errorArgs.errorType + "\n";
		errorMsg += "Error Message: " + errorArgs.errorMessage + "\n";
		errorMsg += "Error Code:    " + errorArgs.errorCode + "\n";
		
		// Determine the type of error and add specific error information.
		switch(errorArgs.errorType)
		{
			case "RuntimeError":
				// Display properties specific to RuntimeErrorEventArgs.
				if (errorArgs.lineNumber != 0)
				{
					errorMsg += "Line: " + errorArgs.lineNumber + "\n";
					errorMsg += "Position: " +  errorArgs.charPosition + "\n";
				}
				errorMsg += "MethodName: " + errorArgs.methodName + "\n";
				break;
			case "ParserError":
				// Display properties specific to ParserErrorEventArgs.
				errorMsg += "Xaml File:      " + errorArgs.xamlFile      + "\n";
				errorMsg += "Xml Element:    " + errorArgs.xmlElement    + "\n";
				errorMsg += "Xml Attribute:  " + errorArgs.xmlAttribute  + "\n";
				errorMsg += "Line:           " + errorArgs.lineNumber    + "\n";
				errorMsg += "Position:       " + errorArgs.charPosition  + "\n";
				break;
			default:
				break;
		}
		// Display the error message.
		alert(errorMsg);
	}
}

//------------------------------------------------
// Sound Effects Related
function onViewFXLoaded(sender, eventArgs)
{
	isViewSoundLoaded = true;
	ViewSound = sender;
}

function playViewSound()
{
	try
	{
		ViewSound.Position = "00:00:00";
		ViewSound.Play();	//Play once
	}
	catch(e)
	{
	}
}

function onButtonDown(sender, mouseEventArgs)
{
	if (sender != null && sender.Name != selectedView)
	{
		setPushState(sender, true);
		sender.CaptureMouse();
	}
}

function onButtonUp(sender, mouseEventArgs)
{
	if (sender != null && sender.Name != selectedView)
	{
		sender.ReleaseMouseCapture();
		setPushState(sender, false);

		if (selectedButton != null)
		{
			setButtonSelectionState(selectedButton, false);
			hideView(selectedView);
		}

		selectedView = sender.Name;
		selectedButton = sender;
		if (selectedButton != null)
		{
			setButtonSelectionState(selectedButton, true);
			showView(selectedView);

			if (sender.Name == "cmdTrailer" || sender.Name == "cmdStills" || sender.Name == "cmdSynopsis")
			{
				playViewSound();	//Play Click Sound
			}
		}
	}
}

function setPushState(sender, state)
{
	var translate = outerCanvas.FindName(sender.Name + "Translate");
	if (translate != null)
	{
		translate.X = (state ? 1 : 0);
		translate.Y = (state ? 1 : 0);
	}
}

function setButtonSelectionState(button, state)
{
	if (button != null)
	{
		var text = outerCanvas.FindName(button.Name + "ButtonText");
		if (text != null) text.Foreground = (state ? "#FFFFFFFF" : "#FF422D07");

		var textLightOn = outerCanvas.FindName(button.Name + "TextLight_ON");
		var textLightOff = outerCanvas.FindName(button.Name + "TextLight_OFF");
		if (textLightOn != null) textLightOn.visibility = (state ? "Visible" : "Collapsed");
		if (textLightOff != null) textLightOff.visibility = (state ? "Collapsed" : "Visible");

		var symbol = outerCanvas.FindName(button.Name + "Symbol");
		if (symbol != null) symbol.Fill = (state ? "#FFFFFFFF" : "#FF4C4C4C");

		if (button.Name == "PlayButton")
		{
			setButtonSelectionState(outerCanvas.FindName("FSPlayButton"), state);
		}
		else if (button.Name == "StopButton")
		{
			setButtonSelectionState(outerCanvas.FindName("FSStopButton"), state);
		}
		else if (button.Name == "RewindButton")
		{
			setButtonSelectionState(outerCanvas.FindName("FSRewindButton"), state);
		}
		else if (button.Name == "VolumeButton")
		{
			setButtonSelectionState(outerCanvas.FindName("FSVolumeButton"), state);
		}
	}
}

function onButtonMouseLeave(sender, mouseEventArgs)
{
	var mouseLight = sender.FindName(sender.Name + "MouseLight");
	if (mouseLight != null) mouseLight.Opacity = 0;
}

function onButtonMouseEnter(sender, mouseEventArgs)
{
	var mouseLight = sender.FindName(sender.Name + "MouseLight");
	if (mouseLight != null) mouseLight.Opacity = 1;
}

//------------------------------------------------
// Player Button Handlers
function onMediaDownloading(sender, eventArgs)
{
	setMediaProgress();
}

function setMediaProgress()
{
	try
	{
		var TrailerMedia = outerCanvas.FindName("TrailerMedia");
		var percent = TrailerMedia.BufferingProgress;

		var TrailerProgressCanvas = outerCanvas.FindName("TrailerProgressCanvas");
		var TrailerPercent = outerCanvas.FindName("TrailerPercent");
		var FullScreenPercent = outerCanvas.FindName("FullScreenPercent");
		var TrailerPercent = outerCanvas.FindName("TrailerPercent");
		var ProgressFill = outerCanvas.FindName("ProgressFill");
		var ProgressFillLight = outerCanvas.FindName("ProgressFillLight");
		var ProgressBase = outerCanvas.FindName("ProgressBase");

		var width = (ProgressBase.Width - 4) * percent;
		ProgressFill.Width = ProgressFillLight.Width = width;
		TrailerPercent.Text = Math.round(percent * 100) + "%";
		FullScreenPercent.Text = "Buffering [ " + Math.round(percent * 100) + "% ]";

		if (percent > 0.9)
		{
			var ProgressFade = outerCanvas.FindName("ProgressFade");
			ProgressFade.Begin();
		}
		else
		{
			TrailerProgressCanvas.Opacity = 1;
		}

		FullScreenPercent.Opacity = (percent > 0.95 ? 0 : 1);
	}
	catch(e)
	{

	}
}

function onTrailerStateChanged(sender, eventArgs)
{
	var TrailerMedia = outerCanvas.FindName("TrailerMedia");
	if (TrailerMedia.CurrentState == "Playing")
	{
		var ProgressFade = outerCanvas.FindName("ProgressFade");
		ProgressFade.Begin();
	}
}

function onTrailerOpened(sender, eventArgs)
{
	if (enableSound)
	{
		sender.IsMuted = false;

		var VolumeButton = outerCanvas.FindName("VolumeButton");
		setButtonSelectionState(VolumeButton, true);

		if (TrailerMedia.CurrentState == "Playing")
		{
			var ProgressFade = outerCanvas.FindName("ProgressFade");
			ProgressFade.Begin();
		}
	}
}

function onTrailerFinish(sender, eventArgs)
{
	var PlayButton = outerCanvas.FindName("PlayButton");
	setButtonSelectionState(PlayButton, false);
	TrailerMedia.Position = "00:00:00";

	var PositionThumb = outerCanvas.FindName("PositionThumb");
	PositionThumb.SetValue("Canvas.Left", -5);
}

function checkMediaPosition()
{
	if (null != TrailerMedia && TrailerMedia.CurrentState == "Playing")
	{
		var PositionThumb = outerCanvas.FindName("PositionThumb");
		var PositionTrack = outerCanvas.FindName("PositionTrack");

		var currentSecs = TrailerMedia.Position.Seconds;
		var totalSeconds = TrailerMedia.NaturalDuration.Seconds;
		var posX = Math.min(Math.max(0, (currentSecs / totalSeconds) * PositionTrack.Width), PositionTrack.Width);
		PositionThumb.SetValue("Canvas.Left", posX - 5);
	}
}

function onPlayerButtonDown(sender, mouseEventArgs)
{
	try
	{
		if (sender != null)
		{
			setPushState(sender, true);
			sender.CaptureMouse();
		}
	}
	catch(e)
	{
		alert("Exception in onPlayerButtonDown");
	}
}

function onPlayerButtonUp(sender, mouseEventArgs)
{
	if (sender != null)
	{
		sender.ReleaseMouseCapture();
		setPushState(sender, false);

		//Execute Player Command
		if (sender.Name == "PlayButton" || sender.Name == "FSPlayButton")
		{
			toggleTrailerPlay();
		}
		else if (sender.Name == "StopButton" || sender.Name == "FSStopButton")
		{
			stopTrailer();
		}
		else if (sender.Name == "RewindButton" || sender.Name == "FSRewindButton")
		{
			rewindTrailer();
		}
		else if (sender.Name == "VolumeButton" || sender.Name == "FSVolumeButton")
		{
			toggleTrailerSound();
		}
		else if (sender.Name == "FullScreenButton")
		{
			setFullScreen(!isFullScreen);
		}
		else if (sender.Name == "ExitFullScreenButton")
		{
			exitFullScreen();
		}
		else if (sender.Name == "MessageBoxButton")
		{
			showMessageBox(false);
		}
	}
}

function onPlayerButtonMouseEnter(sender, mouseEventArgs)
{
	var mouseLight = sender.FindName(sender.Name + "MouseLight");
	if (mouseLight != null) mouseLight.Opacity = 1;

	var glow = sender.FindName(sender.Name + "Glow");
	if (glow != null) glow.Opacity = 1;
}

function onPlayerButtonMouseLeave(sender, mouseEventArgs)
{
	var mouseLight = sender.FindName(sender.Name + "MouseLight");
	if (mouseLight != null) mouseLight.Opacity = 0.7;	//NOTE: 0.7 for Mouse out on player buttons

	var glow = sender.FindName(sender.Name + "Glow");
	if (glow != null) glow.Opacity = 0;
}

//------------------------------------------------
// Message Box
function showMessage(caption, text)
{
	var MessageBoxCaption = outerCanvas.FindName("MessageBoxCaption");
	var MessageBoxBody = outerCanvas.FindName("MessageBoxBody");

	if (MessageBoxCaption != null) MessageBoxCaption.Text = caption;
	if (MessageBoxBody != null) 
	{
		MessageBoxBody.Width = 268;
		MessageBoxBody.Text = text;
		MessageBoxBody.SetValue("Canvas.Top", 24 + ((72 - MessageBoxBody.ActualHeight) / 2));
	}

	showMessageBox(true);
}

function showMessageBox(state)
{
	var MessageBoxSB = outerCanvas.FindName("MessageBoxSB");
	var MessageBoxOpacity = outerCanvas.FindName("MessageBoxOpacity");
	if (MessageBoxOpacity != null && MessageBoxSB != null)
	{
		MessageBoxOpacity.From = (state ? 0 : 1);
		MessageBoxOpacity.To = (state ? 1 : 0);
		MessageBoxSB.Begin();
	}
}

//------------------------------------------------
// Trailer Movie Controllers
function toggleTrailerPlay()
{
	try
	{
		if (TrailerMedia.CurrentState == "Playing")
		{
			pauseTrailer();
		}
		else if (TrailerMedia.CurrentState == "Paused" || TrailerMedia.CurrentState == "Stopped")
		{
			playTrailer(false);
		}
		else
		{
			playTrailer(true);
		}
	}
	catch(e)
	{

	}
}

function playTrailer(fromStart)
{
	var playButton = outerCanvas.FindName("PlayButton");

	if (fromStart) TrailerMedia.Position = "00:00:00";
	TrailerMedia.Play();
	setButtonSelectionState(playButton, true);
}

function pauseTrailer()
{
	TrailerMedia.Pause();
	setButtonSelectionState(playButton, false);
}

function stopTrailer()
{
	var playButton = outerCanvas.FindName("PlayButton");

	if (TrailerMedia.CurrentState == "Paused" || TrailerMedia.CurrentState == "Playing")
	{
		TrailerMedia.Stop();
		TrailerMedia.Position = "00:00:00";
		setButtonSelectionState(playButton, false);
	}
}

function rewindTrailer()
{
	if (TrailerMedia.CurrentState == "Paused" || TrailerMedia.CurrentState == "Playing" || TrailerMedia.CurrentState == "Stopped")
	{
		TrailerMedia.Position = "00:00:00";
	}
}

function toggleTrailerSound()
{
	var VolumeButton = outerCanvas.FindName("VolumeButton");
	TrailerMedia.IsMuted = !TrailerMedia.IsMuted;
	setButtonSelectionState(VolumeButton, !TrailerMedia.IsMuted);
}

function GrabPositionSlider(sender, mouseEventArgs)
{
	var PositionThumb = outerCanvas.FindName("PositionThumb");
	PositionThumb.CaptureMouse();

	var track = outerCanvas.FindName("PositionTrack");
	sliderX = mouseEventArgs.GetPosition(PositionThumb).X;

	TrailerMedia.Pause();
	sliderMouseDown = true;
}

function ReleasePositionSlider(sender, mouseEventArgs)
{
	var PositionThumb = outerCanvas.FindName("PositionThumb");
	PositionThumb.ReleaseMouseCapture();
	TrailerMedia.Play();
	sliderMouseDown = false;
}

function TrackPositionSlider(sender, mouseEventArgs)
{
	if (sliderMouseDown == true)
	{
		var track = outerCanvas.FindName("PositionTrack");
		var trackX = mouseEventArgs.GetPosition(track).X - sliderX;
		var posX = Math.min(Math.max(0, trackX), track.Width);

		//Limit based on Buffering Postiion....
		var maxX = track.Width * TrailerMedia.BufferingProgress;
		posX = Math.min(posX, maxX);

		//Set Thumb Position
		var PositionThumb = outerCanvas.FindName("PositionThumb");
		PositionThumb.SetValue("Canvas.Left", posX - 5);	//Thumb is 10 pixels wide

		//Set Media Position
		try
		{
			var seconds = Math.round((posX * TrailerMedia.NaturalDuration.Seconds) / track.Width, 2);
			var mins = 0;
			if (seconds >= 60) 
			{
				while(seconds >= 60)
				{
					mins++;
					seconds -= 60;
				}
			}

			TrailerMedia.Position = "00:" + mins + ":" + seconds;
		}
		catch(e)
		{
			alert("Invalid Postion: " + seconds + ",Duration:" + TrailerMedia.NaturalDuration.Seconds);
		}
	}
}

function setFullScreen(state)
{
	var FullScreenAnim = outerCanvas.FindName("FullScreenAnim");

	isFullScreen = state;

	sizeSilverlight();

	if (FullScreenAnim != null)
	{
		//Opacity Anim
		var opacityAnim = FullScreenAnim.FindName("FullScreenOpacity");

		//Screen Transforms
		var frameX = FullScreenAnim.FindName("FullScreenX");
		var frameY = FullScreenAnim.FindName("FullScreenY");
		var frameWidth = FullScreenAnim.FindName("FullScreenWidth");
		var frameHeight = FullScreenAnim.FindName("FullScreenHeight");
		var backWidth = FullScreenAnim.FindName("FullScreenBackHeight");
		var backHeight = FullScreenAnim.FindName("FullScreenBackHeight");

		//Media Anims
		var mediaWidth = FullScreenAnim.FindName("MediaWidth");
		var mediaHeight = FullScreenAnim.FindName("MediaHeight");

		//Final Positions etc...
		var pageWidth = truebody().clientWidth;
		var pageHeight = truebody().clientHeight;

		var trailerCanvas = outerCanvas.FindName("TrailerCanvas");
		var trailerPlayer = outerCanvas.FindName("TrailerPlayer");
		
		var normalX = 0;
		var normalY = 0;
		var normalWidth = 597;
		var normalHeight = 250;

		var endX = -(GetElementX(fullScreenZoomer));
		var endY = -(GetElementY(fullScreenZoomer));
		var endWidth = pageWidth;
		var endHeight = pageHeight;

		if (true == state)	//To Full Screen
		{
			showFooter(false);

			frameX.From = normalX;
			frameX.To = endX;

			frameY.From = normalY;
			frameY.To = endY;

			frameWidth.From = backWidth.From = normalWidth;
			frameWidth.To = backWidth.To = endWidth;

			frameHeight.From = backHeight.From = normalHeight;
			frameHeight.To = backHeight.To = endHeight;

			mediaWidth.From = normalWidth;
			mediaWidth.To = endWidth;

			mediaHeight.From = normalHeight;
			mediaHeight.To = endHeight;

			opacityAnim.From = 0;
			opacityAnim.To = 1;

			FullScreenAnim.Begin();
		}
		else	//Back to Normal
		{
			showFooter(true);

			var FullScreenBarFade = outerCanvas.FindName("FullScreenBarFade");
			var FullScreenBarOpacity = outerCanvas.FindName("FullScreenBarOpacity");
			FullScreenBarOpacity.From = 1;
			FullScreenBarOpacity.To = 0;

			frameX.From = endX;
			frameX.To = normalX;

			frameY.From = endY;
			frameY.To = normalY;

			frameWidth.From = backWidth.From = endWidth;
			frameWidth.To = backWidth.To = normalWidth;

			frameHeight.From = backHeight.From = endHeight;
			frameHeight.To = backHeight.To = normalHeight;

			mediaWidth.From = endWidth;
			mediaWidth.To = normalWidth;

			mediaHeight.From = endHeight;
			mediaHeight.To = normalHeight;

			opacityAnim.From = 1;
			opacityAnim.To = 0;

			FullScreenAnim.Begin();
			FullScreenBarFade.Begin();
		}
	}
}

function showFooter(state)
{
	var footer = document.getElementById("footer");
	footer.style.display = (state ? "block" : "none");
}

function exitFullScreen()
{
	setFullScreen(false);
}

function onFullScreenComplete(sender, eventArgs)
{
	if (outerCanvas != null)
	{
		if (isFullScreen)
		{
			var FullScreenBarFade = outerCanvas.FindName("FullScreenBarFade");
			var FullScreenBarOpacity = outerCanvas.FindName("FullScreenBarOpacity");

			FullScreenBarOpacity.From = 0;
			FullScreenBarOpacity.To = 1;
			FullScreenBarFade.Begin();
		}
	}
}

//------------------------------------------------
// Generic Helpers
function alignButtonText(canvas, textBlock)
{
	canvas.Cursor = "Hand";
	canvas.IsHitTestVisible = true;

	var arrowNudge = 6;

	if (canvas.Name == "StillsBackButton")
	{
		textBlock.setValue("Canvas.Left", ((canvas.Width - textBlock.ActualWidth) / 2) + arrowNudge);
		textBlock.setValue("Canvas.Top", (canvas.Height - textBlock.ActualHeight) / 2);
	}
	else if (canvas.Name == "StillsNextButton")
	{
		textBlock.setValue("Canvas.Left", ((canvas.Width - textBlock.ActualWidth) / 2) - arrowNudge);
		textBlock.setValue("Canvas.Top", (canvas.Height - textBlock.ActualHeight) / 2);
	}
	else
	{
		textBlock.setValue("Canvas.Left", (canvas.Width - textBlock.ActualWidth) / 2);
		textBlock.setValue("Canvas.Top", (canvas.Height - textBlock.ActualHeight) / 2);
	}

	if (null != textBlock.RenderTransform) textBlock.RenderTransform.CenterX = textBlock.ActualWidth / 2;

	var buttonLightOn = outerCanvas.FindName(canvas.Name + "TextLight_ON");
	var buttonLightOff = outerCanvas.FindName(canvas.Name + "TextLight_OFF");
	if (buttonLightOn != null)
	{
		buttonLightOn.setValue("Canvas.Left", (canvas.Width - textBlock.ActualWidth) / 2);
		buttonLightOn.setValue("Canvas.Top", (canvas.Height - textBlock.ActualHeight) / 2);
		buttonLightOn.Width = textBlock.ActualWidth;
		buttonLightOn.Height = textBlock.ActualHeight;
	}

	if (buttonLightOff != null)
	{
		buttonLightOff.setValue("Canvas.Left", (canvas.Width - textBlock.ActualWidth) / 2);
		buttonLightOff.setValue("Canvas.Top", (canvas.Height - textBlock.ActualHeight) / 2);
		buttonLightOff.Width = textBlock.ActualWidth;
		buttonLightOff.Height = textBlock.ActualHeight;
	}
}

function createXamlElement(parentElement, name, xaml)
{
	try
	{
		var pluginHost = document.getElementById("SilverlightControlHost");
		var element = pluginHost.content.createFromXaml(xaml);
		if (element != null)
		{
			element.setValue("FrameworkElement.Name", name);
			parentElement.children.add(element);
		}
	}
	catch(e)
	{
		alert(e);
	}
}

function GetElementX(element)
{
	return (element == null ? 0 : element.GetValue("Canvas.Left"));
}

function GetElementY(element)
{
	return (element == null ? 0 : element.GetValue("Canvas.Top"));
}

function LaunchSiteLink(sender, mouseEventArgs)
{
	if (sender.Name == "linkFox")
	{
		window.open(language.FOX_LINK, "_top");
	}
	else if (sender.Name == "linkMovie")
	{
		window.open(language.MOVIE_LINK, "_top");
	}
	else if (sender.Name == "linkRegency")
	{
		window.open(language.REGENCY_LINK, "_top");
	}
}