var unitySize_width = 1;
var unitySize_height = 1;
var unityVisibility = "false";

function InstallFlashIfNeeded()
{
	// Version check for the Flash Player that has the ability to start Player Product Install (6.0r65)
	var hasProductInstall = DetectFlashVer( 6, 0, 65 );

	// Check for the version we require in order to run
	var hasRequestedVersion = DetectFlashVer( 9, 0, 28 );

	if( !hasProductInstall )
	{
		// Flash is too old or we can't detect the plugin
		document.write('<div align="center" id="FlashPrompt">');
		document.write( '<h1>iPerform3D requires the Adobe Flash Plugin. Please install it from '
			+ '<a href="http://www.adobe.com/go/getflash/">here</a></h1>' );
		document.write('</div>');
		return false; // It's not installed and it will need to navigate away to install
	}
	else if( !hasRequestedVersion )
	{
		// DO NOT MODIFY THE FOLLOWING FOUR LINES
		// Location visited after installation is complete if installation is required
		var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
		var MMredirectURL = window.location;
		document.title = document.title.slice(0, 47) + " - Flash Player Installation";
		var MMdoctitle = document.title;

		AC_FL_RunContent(
			"src", "playerProductInstall",
			"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
			"width", "100%",
			"height", "100%",
			"align", "middle",
			"id", "iPerform",
			"quality", "high",
			"bgcolor", "#000000",
			"name", "iPerform",
			"allowScriptAccess","sameDomain",
			"type", "application/x-shockwave-flash",
			"pluginspage", "http://www.adobe.com/go/getflashplayer"
		);
	}
	return true;
}

function InstallUnityIfNeeded()
{
	if( !DetectUnityWebPlayer() )
	{
		var platform = GetPlatform();
		var installerPath = GetUnityInstallerPath( platform );
		if( installerPath != "" )
		{
			// Place a link to the right installer depending on the platform we are on.
			// The iframe is very important! Our goals are:
			// 1. Don't have to popup new page
			// 2. This page still remains active, so our automatic reload script will refresh the page when the plugin is installed
			var browserType = GetBrowserType();
			
			document.write('<div align="center" style="overflow:auto" id="UnityPrompt">');
			document.write('<br><h1>iPerform3D<sup>&reg;</sup> needs to install/upgrade the Unity<sup>&reg;</sup> browser plug-in</h1><br>');
			document.write('Please click on the "Unity Web Player Install Now!" button below to install Unity<sup>&reg;</sup><br><br>');
			document.write('<a href="' + installerPath + '"><img src="http://webplayer.unity3d.com/installation/getunity.png" border="0"/></a><br>');
			WriteUnityInstructions( platform, browserType );
			document.write('<iframe name="InstallerFrame" height="0" width="0" frameborder="0">');
			document.write('</div>');
		}
		else
		{
			document.write('<div align="center" id="UnityPrompt"> \n');
			document.write('<a href="javascript: window.open("http://www.unity3d.com/unity-web-player-3.x");"><img src="http://webplayer.unity3d.com/installation/getunity.png" border="0"/></a>\n');
			document.write('</div> \n');
		}
		AutomaticUnityReload();
	}
}

function DetectUnityWebPlayer( platform, browser )
{
	var tInstalled = false;
	if( navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1 )
	{
		tInstalled = DetectUnityWebPlayerActiveX();
	}
	else
	{
		if( navigator.mimeTypes && navigator.mimeTypes["application/vnd.unity"] )
		{
			if( navigator.mimeTypes["application/vnd.unity"].enabledPlugin 
					&& navigator.plugins 
					&& navigator.plugins["Unity Player"]
					&& !(navigator.plugins["Unity Player"].version < "3.4.1") )
			{
				tInstalled = true;
			}
		}
	}
	return tInstalled;
}

function GetPlatform()
{
	if( navigator.platform == "MacIntel" )
		return "MacIntel";
	else if( navigator.platform == "MacPPC" )
		return "MacPPC";
	else if( navigator.platform.toLowerCase().indexOf("win") != -1 )
		return "Windows";
	return "";
}

function GetBrowserType()
{
	if( /Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
		return "FF";
	else if( navigator.appVersion.indexOf("MSIE") )
		return "IE";
	else if( navigator.appVersion.toLowerCase().indexOf( "safari" ) != -1 )
		return "Safari";
	return "";
}

function WriteUnityInstructions( platform, browserType )
{
	var str = "";
	
	switch( platform )
	{
	case "MacIntel":
	case "MacPPC":
		if( navigator.userAgent.indexOf( "Safari" ) >= 0 )
		{
			str += '<hr>1. Click "Continue" in the window asking if you want to continue downloading webplayer<br>';
		}
		else if( navigator.userAgent.indexOf( "Firefox" ) >= 0 )
		{
			str += '<hr>1. Click "OK" to open a file with DiskImageMounter.app<br>';
			str += '<img src="http://d2media.iventa.com/guitarschool/b9aea52e-cc6b-4e21-bebe-eebee1acfabb.jpg"><br><br>';
			str += '<hr>Select web player=i386 or MACIntel-Firefox-SS-2 from the Finder and double-click "Install Unity Player.pkg" file<br>';
		}
		str += '2. Click "Continue" in the "Install Unity Web Player" window<br>';
		str += '<hr>3. Select destination (you can just use the one pre-selected for you by default) in the next window and click "Continue"<br>';
		str += '<img src="http://d2media.iventa.com/guitarschool/0871d13d-1055-4269-8d2e-9b86e8015365.jpg"><br><br>';
		str += '<hr>4. Click "Install" in the next window<br>';
		str += '<img src="http://d2media.iventa.com/guitarschool/de6f2c1c-2737-4181-a149-5e50ee1510e2.jpg"><br><br>';
		str += '<hr>5. Authenticate when promped to authenticate<br>';
		str += '<img src="http://d2media.iventa.com/guitarschool/7c6f4e3e-7274-436f-b964-c88bb7cca580.jpg"><br><br>';
		str += '<hr>6. Click "Close" after you get a window with the message that software was successfully installed.<br>';
		str += '<img src="http://d2media.iventa.com/guitarschool/a23a7384-f04f-48c3-b28d-236f6abec743.jpg"><br><br>';
		str += '7. Go back to your browser. Login page should be displayed. Refresh the page or reopen the browser if you don&rsquo;t see it.';
		break;
	case "Windows":
		if( navigator.appVersion.indexOf( "MSIE" ) >= 0 )
		{
			str += '<hr>1. The "File Download" window below will appear. Click "Run"<br>';
			str += '<img src="http://d2media.iventa.com/guitarschool/2b3be061-3aed-4055-ae32-3764a3d6e9a6.JPG"><br><br>';
			str += '<hr>2. Click "Run" again for "Do you want to run this software?"<br>';
			str += '<img src="http://d2media.iventa.com/guitarschool/0955d206-2e06-42f8-a70e-d43a2d855968.JPG"><br><br>';
			str += '<hr>3. In the next window click "Finish" to Complete The Unity Web Player Setup Wizard.<br>';
			str += '<img src="http://d2media.iventa.com/guitarschool/c3911912-c9af-478f-8916-16844dfff19c.JPG"><br><br>';
			str += '4. Go back to your browser. Login page should be displayed. Refresh the page in case you don"t see it.';
		}
		else if( navigator.userAgent.indexOf( "Firefox" ) >= 0 )
		{
			str += '<hr>1. Choose "Save File" when "Opening UnityWebPlayer.exe" window appears.<br>';
			str += '<img src="http://d2media.iventa.com/guitarschool/49409a89-1edf-482c-93f7-e253aa9a678f.JPG"><br><br>';
			str += '<hr>2. Double-click UnityWebPlayer.exe in the "Downloads" window.<br>';
			str += '<img src="http://d2media.iventa.com/guitarschool/0ae64d9d-4d4a-4e63-b627-683566409d04.JPG"><br><br>';
			str += '<hr>3. Click "OK" button in the "Open Executable File?" window if such window appears.<br>';
			str += '<img src="http://d2media.iventa.com/guitarschool/622d31e4-10b5-4458-925b-edb489e193d6.JPG"><br><br>';
			str += '<hr>4. Click "Run" in "Do you want to run this file?" window.<br>';
			str += '<img src="http://d2media.iventa.com/guitarschool/41776124-fc72-4f76-8784-585df75e796c.JPG"><br><br>';
			str += '<hr>5. Click "Finish" in the next window to complete the Unity Web Player Setup Wizard.<br>';
			str += '<img src="http://d2media.iventa.com/guitarschool/0495efb0-26e5-4376-a0be-a30447a44c17.JPG"><br><br>';
			str += '6. Go back to your browser. Login page should be displayed . Refresh the page or reopen the browser if you don&rsquo;t see it.<br>';
			str += '<hr><i>If you encounter any windows that say "Error opening file for writing", click on Abort, reboot your system, access application again and go through steps 1-6</i><br>';
			str += '<img src="http://d2media.iventa.com/guitarschool/ea552175-05f7-43b0-af8b-3f8714ee50b0.JPG">';
		}
		break;
	}
	document.write( str );
}

function GetUnityInstallerPath( platform )
{
	var tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-3.x/";
	switch( platform )
	{
		case "MacIntel":
			tDownloadURL += "webplayer-i386.dmg";
			break;
		case "MacPPC":
			tDownloadURL += "webplayer-ppc.dmg";
			break;
		case "Windows":
			tDownloadURL += "UnityWebPlayer.exe";
			break;
	}
	return tDownloadURL;
}

function AutomaticUnityReload()
{
	navigator.plugins.refresh();
	if( DetectUnityWebPlayer() )
	{
		window.location.reload();
	}
	setTimeout( 'AutomaticUnityReload()', 1000 );
}

// This method assumes that both Flash and Unity are properly installed
function LoadApplication( appPath )
{
	var unityPath = appPath + ".unity3d";
	
	document.write('<div class="container">\n');
	document.write('	<div class="viewer">\n');
	document.write('<object id="UnityObject" classid="clsid:444785F1-DE89-4295-863A-D46C3A781394" width="100px" height="100px">\n');
	document.write('  <param name="src" value="' + unityPath + '" />\n');
	document.write('  <param name="backgroundcolor" value="101010" />\n');
	document.write('  <param name="logoimage" value="images/iPerform3DLogo.png" />\n');
	document.write('  <param name="disableContextMenu" value="true" />\n');
	document.write('  <param name="disableFullscreen" value="true" />\n');
	document.write('  <embed id="UnityEmbed" src="' + unityPath + '" type="application/vnd.unity"\n');
	document.write('    pluginspage="http://www.unity3d.com/unity-web-player-3.x"\n');
	document.write('    disableContextMenu="true" disableFullscreen="true"\n');
	document.write('    backgroundcolor="101010" logoimage="images/iPerform3DLogo.png"/>\n');
	document.write('</object>\n');
	document.write('</div>\n');
	document.write('<div class="iperformapp">\n');

	
	// If we've detected an acceptable version, embed the Flash Content SWF when all tests are passed
	AC_FL_RunContent(
		"src", appPath,
		"width", "100%",
		"height", "100%",
		"align", "middle",
		"id", "iPerform",
		"quality", "high",
		"bgcolor", "#000000",
		"name", "iPerform",
		"allowScriptAccess","sameDomain",
		"type", "application/x-shockwave-flash",
		"pluginspage", "http://www.adobe.com/go/getflashplayer"
	);
	
	document.write('</div>\n');
	document.write('</div>\n');

	Move3DViewer(0, 0, 1, 1);
}

function GetUnity()
{
	if( navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1 )
		return document.getElementById("UnityObject");
	else if( navigator.appVersion.toLowerCase().indexOf("safari") != -1 )
		return document.getElementById("UnityObject");
	else
		return document.getElementById("UnityEmbed");
}

function GetUnityForMessage()
{
	if( navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1 )
		return document.getElementById("UnityObject");
	else
		return document.getElementById("UnityEmbed");
}

// Internet Explorer and Mozilla-based browsers refer to the Flash application object differently.
// This function returns the appropriate reference, depending on the browser.
function GetFlashApp()
{
	if( navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1 )
		return document.getElementById("iPerform");
	else if( navigator.appVersion.toLowerCase().indexOf( "safari" ) != -1 )
		return document.getElementById("iPerform");
	else
		return document.getElementById("iPerform");
}

function ShowObject( object, onOff )
{
	// Get a reference to the cross-browser style object and make sure the object exists
	var styleObject = object;
	if( styleObject )
	{
		if( onOff )
		{
			styleObject.style.visibility = "visible";
			styleObject.style.height = unitySize_height;
			styleObject.style.width = unitySize_width;
		}
		else
		{
			styleObject.style.visibility = "visible";
			styleObject.style.height = "1px";
			styleObject.style.width = "1px";
		}
		return true;
	}
	else
	{
		// we couldn't find the object, so we can't change its visibility
		alert( "Invalid object passed to ShowObject" );
		return false;
	}
}

//
// Calls from Flex to Unity
//

function Call3DViewerFunction( objectName, functionName, arg )
{
	mylog(objectName + "=>" + functionName + "(" + arg + ")");
	GetUnityForMessage().SendMessage( objectName, functionName, arg );
}

function Show3DViewer( onOff )
{
	mylog('Show3DViewer' + onOff);
	ShowObject( GetUnityForMessage(), onOff );
	ShowObject( GetUnity(), onOff );
	unityVisibility = onOff;
}

function fnScaleFactorX() {
	if( navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1 )
	{
		var nScaleFactor = screen.deviceXDPI / screen.logicalXDPI;
		return nScaleFactor;
	}
	else
		return 1.0;
}

function fnScaleFactorY() {
	if( navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1 )
	{
		var nScaleFactor = screen.deviceYDPI / screen.logicalYDPI;
		return nScaleFactor;
	}
	else 
		return 1.0;
}

function Move3DViewer( x, y, width, height )
{
	var scaleX = fnScaleFactorX();
	var scaleY = fnScaleFactorY();
	if (width > 2 && height > 2 && scaleX > 0 && scaleY > 0 )
	{
		x /= scaleX;
		y /= scaleY;
		width /= scaleX;
		height /= scaleY;
	}

	mylog('Move3DViewer' + width + ", " + height);
	viewer = GetUnity();
	if( viewer )
	{
		viewer.top = y;
		viewer.left = x;
		viewer.width = width;
		viewer.height = height;
		unitySize_width = width;
		unitySize_height = height;
		ShowObject( GetUnityForMessage(), unityVisibility );
		ShowObject( GetUnity(), unityVisibility );
	}
}

//
// Calls from Unity to Flex
//

// Called from Unity to indicate that it has been initialized and is ready to work.
function OnViewerIntialized()
{
	mylog("OnViewerIntialized");
	app = GetFlashApp();
	app.OnViewerIntialized();
}

// Called from Unity to signal when playback has finished
function OnPlaybackFinished()
{
	mylog("OnPlaybackFinished");
	app = GetFlashApp();
	app.OnPlaybackFinished();
}

var timeChanges = 0;
// Called from Unity to update the playhead indicator.
function OnTimeChange( time )
{
	timeChanges++;
	if (timeChanges % 30 == 0)
		mylog("OnTimeChange " + timeChanges);
	app = GetFlashApp();
	app.OnTimeChange( time );
}

// Called from Unity when a new download is started. This may get called multiple
// times before FinishProgress().
function StartProgress()
{
	mylog("StartProgress");
	app = GetFlashApp();
	app.StartProgress();
}

// Called between StartProgress and FinishProgress to update download progress
function OnProgress( progress )
{
	mylog("OnProgress");
	app = GetFlashApp();
	app.OnProgress( progress );
}

// Called from Unity when a download is finished. There must be a matching call to
// StartProgress() that precedes calls to FinishProgress. True or false is passed in
// to indicate whether the download was successful or not.
function FinishProgress()
{
	mylog("FinishProgress");
	app = GetFlashApp();
	app.FinishProgress();
}

// Called to signal when a newly defined segment is ready to play.
function OnSetSegmentLength( startTime, endTime )
{
	mylog("OnSetSegmentLength");
	app = GetFlashApp();
	app.OnSetSegmentLength( startTime, endTime );
}

// Called to report information (type=0), a warning (type=1), or an error (type=2) to the
// Flash application interface.
function LogMessage( message, type )
{
	//alert(message);
	app = GetFlashApp();
	app.LogMessage( message, type );
}

function mylog(msg) {
    //setTimeout(function() {
    //    throw new Error(msg);
    //}, 0);
}

function mylogA() {
	mylog('A');
}

function mylogB() {
	mylog('B');
}

function mylogC() {
	mylog('C');
}

function mylogD() {
	mylog('D');
}

function mylogE() {
	mylog('E');
}

function mylogF() {
	mylog('F');
}

function mylogP() {
	mylog('P');
}

