/**
 * @author carl
 */

if(Mixamo == undefined) Mixamo = {};
if(Mixamo.Unity == undefined) Mixamo.Unity = {};
if(Mixamo.Unity.version == undefined) Mixamo.Unity.version = 4;    // see _global_javascript.html.erb for where this REALLY gets set

// using extend instead so that we can build up the object in multiple parts of the code
// see 
extend(Mixamo.Unity, {
    LaunchParamters: {},
    
	GetUnity: function() {
		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");
	},

	DetectUnityWebPlayer: function() {
		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"]) {
	     			tInstalled = true;
				}
				}
		}
		return tInstalled;
	},

	GetInstallerPath: function() {
		var tDownloadURL = "";
			var hasXpi = navigator.userAgent.toLowerCase().indexOf( "firefox" ) != -1;

		// Use standalone installer
		if (1)
		{
			if (navigator.platform == "MacIntel")
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/webplayer-i386.dmg";
			else if (navigator.platform == "MacPPC")
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/webplayer-ppc.dmg";
			else if (navigator.platform.toLowerCase().indexOf("win") != -1)
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayer.exe";
			return tDownloadURL;
		}
		// Use XPI installer
		else
		{
			if (navigator.platform == "MacIntel")
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerOSX.xpi";
			else if (navigator.platform == "MacPPC")
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerOSX.xpi";
			else if (navigator.platform.toLowerCase().indexOf("win") != -1)
				tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerWin32.xpi";
			return tDownloadURL;
		}
	},

	AutomaticReload: function() {
		navigator.plugins.refresh();

		if (Mixamo.Unity.DetectUnityWebPlayer())
			window.location.reload();
	    else
		    setTimeout('Mixamo.Unity.AutomaticReload()', 500)
	} ,

	WriteUnity: function( container_ele , object_params , state_params) {
        // populate cookie string init params

        // store init params for later serving to Unity
        // see Mixamo.Unity.LaunchCallback
        Mixamo.Unity.LaunchParamters = state_params;

		var hasUnity = Mixamo.Unity.DetectUnityWebPlayer();

		var brokenUnity = false;
		if (hasUnity) {

            var logoUrl = "/images/logo.png";

			var embedHtml = '<object id="UnityObject" classid="clsid:444785F1-DE89-4295-863A-D46C3A781394" width="' + object_params.width + '" height="' + object_params.height + '"> \n' +
            '  <param name="src" value="/unity-viewer/MixamoViewer.unity3d?' + Mixamo.Unity_Version +'" /> \n' +
            '  <param name="disableContextMenu" value="true" /> \n' +
            '  <param name="logoimage" value="' + logoUrl + '" /> \n' +
			'  <embed id="UnityEmbed" src="/unity-viewer/MixamoViewer.unity3d?' + Mixamo.Unity_Version +'" width="' + object_params.width + '" height="' + object_params.height + '" type="application/vnd.unity" pluginspage="http://www.unity3d.com/unity-web-player-2.x" disableContextMenu="true" logoimage="' + logoUrl + '"/> \n' +
			'</object>'

			container_ele.innerHTML = embedHtml;

            Mixamo.Unity.TestBrokenUnity(hasUnity, true, container_ele, 6);

		}
	},
	
	queuedHideRequests: {},
	num_queuedHideRequests: 0,
	/**
	 * Takes a unique id of the function that has opened this window
	 * @param {Object} queue
	 */
	Hide: function( queue ) {
	   if( !this.queuedHideRequests[queue] ) {
	       this.queuedHideRequests[queue] = true;
		   this.num_queuedHideRequests += 1;
	   }
	   $("#UnityObject").css("visibility", "hidden");
	   $("#bgMessageLoading .backgroundMessageMiddle").html( "<span><img src='/images/logo.png' alt='mixamo' /><br/><br/>(Mixamo viewer is currently hidden)</span>" );
	},
	
	Show: function( queue ) {
		if( this.queuedHideRequests[queue] ) {
			this.queuedHideRequests[queue] = false;
			this.num_queuedHideRequests -= 1;
		}
	    if( this.num_queuedHideRequests == 0 ) {
            $("#UnityObject").css("visibility", "visible");
			$("#bgMessageLoading .backgroundMessageMiddle").html( "" );
		}
	},

    //
    // do this in a setTimeout loop because it doesn't necessarily
    // IsUnityBroken isn't always correct first thing...
    //
    TestBrokenUnity : function(hasUnity, brokenUnity, container, remaining) {
		//Mixamo.console.info( "TestBrokenUnity: " + hasUnity + "," + brokenUnity + ", ," + remaining );
        // don't have unity, handle it
        if(!hasUnity)
            Mixamo.Unity.HandleNoBrokenUnity(hasUnity, brokenUnity, container);

        // broken? test again if it is still broken
        if(brokenUnity)
            brokenUnity = Mixamo.Unity.IsUnityBroken();

        // if it isn't broken anymore, we are good
        if(!brokenUnity) {
            return; // we are good
        }

        // keep testing
        if(remaining > 0) {
            setTimeout(Mixamo.Unity.TestBrokenUnity.bind( this , hasUnity, brokenUnity, container, --remaining), 500);
        } else {
            Mixamo.Unity.HandleNoBrokenUnity(hasUnity, brokenUnity, container);
        }
    },

    IsUnityBroken : function() {
        
		var brokenUnity = false;
		
        // if Unity does not define to GetPluginVersion on Safari on 10.6, we presume the plugin
        // failed to load because it is not compatible with 64-bit Safari.
        if (navigator.appVersion.indexOf("Safari") != -1 &&
			navigator.appVersion.indexOf("Mac OS X 10_6") != -1 &&
			document.getElementById("UnityEmbed").GetPluginVersion == undefined) {
				brokenUnity = true;
				//Mixamo.console.info( "Unity broken Safari!");
		}
		// 2.5.0 cannot auto update on ppc. Treat as broken.
		else {
			if (document.getElementById("UnityEmbed") &&
			(!document.getElementById("UnityEmbed").GetPluginVersion || document.getElementById("UnityEmbed").GetPluginVersion() == "2.5.0f5") &&
			navigator.platform == "MacPPC") {
				brokenUnity = true;
				//Mixamo.console.info( "Unity broken Other Browser!");
			}
		}
        /*
        if(brokenUnity)
            alert("Unity is broken right now...")
        else
            alert("Unity is good now...")
        */

        return brokenUnity;
    },

    HandleNoBrokenUnity : function(hasUnity, brokenUnity, container) {
		if (!hasUnity || brokenUnity) {

            container.innerHTML = Mixamo.Unity.InstallUnityHtml(brokenUnity);
			
			// hide broken player
			/*if (brokenUnity)
				document.getElementById("UnityEmbed").height = 0;*/

			// Reload when detected unity plugin - but only if no previous plugin is installed
			// - in that case a browser restart is needed.
			if (!brokenUnity)
				Mixamo.Unity.AutomaticReload();
		}
    },

    InstallUnityHtml : function(brokenUnity) {
        var installerPath = Mixamo.Unity.GetInstallerPath();
        if (installerPath != "") {

            var embedHtml = "";
            // 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
            embedHtml += ('<div id="UnityPrompt">');
            if (brokenUnity)
                embedHtml += ('  <a href= ' + installerPath + '><img src="http://webplayer.unity3d.com/installation/getunityrestart.png" border="0" /></a>');
            else
                embedHtml += ('  <a href= ' + installerPath + '><img src="http://webplayer.unity3d.com/installation/getunity.png" border="0" /></a>');
            embedHtml += ('</div>');

            /*
            // By default disable ActiveX cab installation, because we can't make a nice Install Now button
//						if (navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1)
            if (0)
            {
                embedHtml += ('<div id="InnerUnityPrompt"> <p>Title</p>');
                embedHtml += ('<p> Contents</p>');
                embedHtml += ("</div>");

            }

            embedHtml += ('<iframe name="InstallerFrame" height="0" width="0" frameborder="0"></iframe>\n');
            */

            return embedHtml;

            /*
            if( 0 )
            {
                var innerUnityPrompt = document.getElementById("InnerUnityPrompt");

                var innerHtmlDoc =
                    '<object id="UnityInstallerObject" classid="clsid:444785F1-DE89-4295-863A-D46C3A781394" width="320" height="50" codebase="http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayer.cab#version=2,0,0,0">\n' +
                    '</object>';

                innerUnityPrompt.innerHTML = innerHtmlDoc;
            }
            */
        }
        else {
            var embedHtml = "";
            embedHtml += ('<div align="center" id="UnityPrompt"> \n');
            if (brokenUnity)
                embedHtml += ('  <a href="javascript: window.open("http://www.unity3d.com/unity-web-player-2.x"); "><img src="http://webplayer.unity3d.com/installation/getunityrestart.png" border="0"/></a> \n');
            else
                embedHtml += ('  <a href="javascript: window.open("http://www.unity3d.com/unity-web-player-2.x"); "><img src="http://webplayer.unity3d.com/installation/getunity.png" border="0"/></a> \n');
            embedHtml += ('</div> \n');
            return embedHtml;
        }
    },
    
	/**
	 * Add callback function
	 */
	AddCallbackWhenUnityLaunches: function( call ) {
		this.launchCallbackCallbacks.push( call );
	},
	
	launchCallbackCallbacks: [],
    /**
     * Calls back into the Unity player with the launch paramters for this unity instance.
     *
     * (i could not immediately find a way to specify init parameters as part of the object/embed HTML tags) --ewebb
     */
    LaunchCallback: function() {
        var unity = Mixamo.Unity.GetUnity();		
        unity.SendMessage("ViewerCoordinators", "InitializeViaJavascript", JSON.stringify(Mixamo.Unity.LaunchParamters));
		setTimeout( function() {		
			$("#bgMessageLoading .backgroundMessageMiddle").html( "" );
			for( var i=0;i<Mixamo.Unity.launchCallbackCallbacks.length;i++) {
                Mixamo.Unity.launchCallbackCallbacks[i].call();
            }
		} , 50);
    },
	
	
	Shutdown: function() {
		var unity = Mixamo.Unity.GetUnity();
		if( unity != null )
			unity.SendMessage( "ViewerCoordinators" , "Shutdown" , "");
	}

});
