/*
Title: jQuery Unity Plugin v1.0
Author: Derek Jones
Company: Matmi
---------------SHORT EXAMPLE-------------------
$("#unity").unity("tpcg.unity3d");
---------------FULL EXAMPLE--------------------
$("#unity").unity("tpcg.unity3d",
{
    prefix: "unitycontent",
    width: 600,
    height: 450,
    backgroundcolor: "aaaaaa",
    bordercolor: "bbbbbb",
    textcolor: "111111",
    logoimage: "img/logo.png",
    progressbarimage: "img/bar.png",
    progressframeimage: "img/frame.png",
    hideimage: "img/hide.jpg"
});
---------------FUNCTIONS-----------------------
//unity hide option allows you to overlay dialog ontop of unity content
$("#unity").unity("hide");  //hides the unity content and displays the hideimage from init options or blank
$("#unity").unity("hide","img/alternativehide.jpg");  //hides the unity content and displays the supplied image url
$("#unity").unity("show");  //displays the unity content
$("#unity").unity("destroy");  //removes the unity element from the DOM
GetUnity().SendMessage(objectname,functionname,message);  //sends to first unity element in the DOM
GetUnity("unity").SendMessage(objectname,functionname,message);  //sends to unity element identified by id
*/
//MAINTAIN LEGACY COMPATABILITY
function GetUnity(id)
{
    if (!id)
    {
        var sid = jQuery("[classid = 'clsid:444785F1-DE89-4295-863A-D46C3A781394']").attr("id");
    }
    else if (jQuery("#" + id).attr("classid") == "clsid:444785F1-DE89-4295-863A-D46C3A781394")
    {
        var sid = id;
    }
    else
    {
        var sid = jQuery("#" + id + " [classid = 'clsid:444785F1-DE89-4295-863A-D46C3A781394']").attr("id");
    }
    if (navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1)
    {
        return document.getElementById(sid);
    }
    else if (navigator.appVersion.toLowerCase().indexOf("safari") != -1)
    {
        return document.getElementById(sid);
    }
    else
    {
        return document.getElementById(jQuery("#" + sid + " embed").attr("id"));
    }
}
//External functions
function AutomaticReload()
{
    navigator.plugins.refresh();
    if (DetectUnityWebPlayer())
    {
        window.location.reload();
    }
    setTimeout('AutomaticReload()', 500)
    return this;
}
function DetectUnityWebPlayer()
{
    var tInstalled = false;
    if (navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1)
    {
        try
        {
            tInstalled = DetectUnityWebPlayerActiveX();
        }
        catch(err)
        {
            unityvbs();
            try
            {
                tInstalled = DetectUnityWebPlayerActiveX();
            }
            catch(err)
            {
            }
        }
    }
    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;
}
function unityvbs()
{
    if (navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.toLowerCase().indexOf("win") != -1)
    {
        var ss = document.createElement('script');
        ss.setAttribute("type", "text/vbscript");
        ss.setAttribute("language", "vbscript");
        var scr = '' +
            'function DetectUnityWebPlayerActiveX\n' +
                    	'on error resume next\n' +
                    	'dim tControl, res, ua, re, matches, major\n' +
                    	'res = 0\n' +
                    	'set tControl = CreateObject("UnityWebPlayer.UnityWebPlayer.1")\n' +
                    	'if IsObject(tControl) then\n' +
                    		'if tControl.GetPluginVersion() = "2.5.0f5" then\n' +
                    			'\' 2.5.0f5 on Vista and later has an auto-update issue\n' +
                    			'\' on Internet Explorer. Detect Vista (6.0 or later)\n' +
                    			'\' and in that case treat it as not installed\n' +
                    			'ua = Navigator.UserAgent\n' +
                    			'set re = new RegExp\n' +
                    			're.Pattern = "Windows NT (\d+)\."\n' +
                    			'set matches = re.Execute(ua)\n' +
                    			'if matches.Count = 1 then\n' +
                    				'major = CInt(matches(0).SubMatches(0))\n' +
                    				'if major < 6 then\n' +
                    					'res = 1\n' +
                    				'end if\n' +
                    			'end if\n' +
                    		'else\n' +
                    			'res = 1\n' +
                    		'end if\n' +
                    	'end if\n' +
                    	'DetectUnityWebPlayerActiveX = res\n' +
                    'end function';
        ss.text = scr;
        document.getElementsByTagName('head')[0].appendChild(ss);
    }
}
//JQUERY UNITY INITIALIZER
(function ($)
{
    $.fn.unity = function (action, options)
    {
        var url = false;
        switch(action)
        {
            case "destroy":
            destroy(this);
            break;
            case "hide":
            hide(this,options);
            break;
            case "show":
            show(this);
            break;
            default :
            url = action;
        }
        if(!url)
        {
            return this;
        }
        var defaults = { prefix: "unity",
                         width: 600,
                         height: 450,
                         backgroundcolor: "",
                         bordercolor: "",
                         textcolor: "",
                         logoimage: "",
                         progressbarimage: "",
                         progressframeimage: "",
                         hideimage: ""
                       };
        var empty = {};
        var settings =  $.extend(empty, defaults, options);
        this.each(function ()
        {
            var id = 0;
            while($("#"+settings.prefix+id).size()>0)
            {
                id++;
            }
            var unityelement = "";
            var unityobject = "";
            var hasUnity = DetectUnityWebPlayer();
            var brokenUnity = false;
            if (hasUnity)
            {
                var params = "";
             	unityobject += '<object id=\''+settings.prefix+id+'_object'+'\' class=\'unityobject\' classid=\'clsid:444785F1-DE89-4295-863A-D46C3A781394\' width=\''+settings.width+'\' height=\''+settings.height+'\' codebase="http://webplayer.unity3d.com/download_webplayer/UnityWebPlayer.cab#version=2,0,0,0">';
                if(settings.backgroundcolor)
                {
                    params += "backgroundcolor='"+settings.backgroundcolor+"' ";
                    unityobject += "<param name='backgroundcolor' value='"+settings.backgroundcolor+"' />";
                }
                if(settings.bordercolor)
                {
                    params += "bordercolor='"+settings.bordercolor+"' ";
                    unityobject += "<param name='bordercolor' value='"+settings.bordercolor+"' />";
                }
                if(settings.textcolor)
                {
                    params += "textcolor='"+settings.textcolor+"' ";
                    unityobject += "<param name='textcolor' value='"+settings.textcolor+"' />";
                }
                if(settings.logoimage)
                {
                    params += "logoimage='"+settings.logoimage+"' ";
                    unityobject += "<param name='logoimage' value='"+settings.logoimage+"' />";
                }
                if(settings.progressbarimage)
                {
                    params += "progressbarimage='"+settings.progressbarimage+"' ";
                    unityobject += "<param name='progressbarimage' value='"+settings.progressbarimage+"' />";
                }
                if(settings.progressframeimage)
                {
                    params += "progressframeimage='"+settings.progressframeimage+"' ";
                    unityobject += "<param name='progressframeimage' value='"+settings.progressframeimage+"' />";
                }
                unityobject += "<param name='src' value='"+url+"' />";
                unityobject += '<embed id=\''+settings.prefix+id+'_embed'+'\' class="unityembed" src=\''+url+'\' width=\''+settings.width+'\' height=\''+settings.height+'\' '+params+'type=\'application/vnd.unity\' pluginspage=\'http://www.unity3d.com/unity-web-player-2.x\' />';
                unityobject += '</object>';
                unityelement += unityobject;
            	// 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;
            	} */
            }
            if (!hasUnity || brokenUnity)
            {
            	var installerPath = GetInstallerPath();
            	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
            		unityelement += '<div align=\'center\'>';
            		unityelement += '<br /><br /><h2>To play the games you must download the Unity Web Player.<br />Click on the link below to install this trusted gaming software.</h2><br /><br />';
            		if (brokenUnity)
                    {
                        unityelement += '<a href=\'' + installerPath + '\'><img src=\'http://webplayer.unity3d.com/installation/getunityrestart.png\' border=\'0\'/></a>';
            		}
                    else
                    {
                        unityelement += '  <a href=\'' + installerPath + '\'><img src="http://webplayer.unity3d.com/installation/getunity.png" border="0"/></a>';
            		}
                    unityelement += '</div>';
                    if($("#InstallerFrame").size()<1)
                    {
                        unityelement += '<iframe id=\'InstallerFrame\' name=\'InstallerFrame\' height=\'0\' width=\'0\' frameborder=\'0\'></iframe>';
                    }
            	}
                else
                {
                    unityelement += '<div align=\"center">';
            		if (brokenUnity)
                    {
                        unityelement += '  <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>';
                    }
            		else
                    {
            		unityelement += '  <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>';
                    }
                    unityelement += '</div>';
            	}
            	if (!brokenUnity)
                {
            		AutomaticReload();
                }
            }
            var hideimage = "";
            if(settings.hideimage != "")
            {
                hideimage = '<img class="unityhideimage" src="'+settings.hideimage+'"/>';
            }
            var unitycontainer = '<div id="'+settings.prefix+id+'" class="unitycontainer" ><div id="'+settings.prefix+id+'_holder" class="unityholder">'+unityelement+'</div><div class="unityhide">'+hideimage+'</div></div>';
            $(this).append(unitycontainer);
            $("#"+settings.prefix+id).css({ "width" : settings.width+"px", "height" : settings.height+"px", "overflow" : "hidden" });
            $("#"+settings.prefix+id + " div").css({ "width" : settings.width+"px", "height" : settings.height+"px"});
        });
        //JQUERY UNITY FUNCTIONS
        function hide(that, image)
        {
            that.each(function()
            {
                var thisid = $(this).attr("id");
                if(image)
                {
                    $("#"+thisid+" .unityhide").css({"background-image" : "url("+image+")","background-repeat" : "no-repeat"});
                    $("#"+thisid+" .unityhide").empty();
                }
                var height = $("#"+thisid+ " .unitycontainer").css("height");
                $("#"+thisid+ " .unityholder").css({"height" : "9999px"});
                $("#"+thisid+ " .unityhide").css({"height" : height});
                $("#"+thisid+ " .unitycontainer").scrollTop(9999);
            });
        }
        function show(that)
        {
            that.each(function()
            {
                var thisid = $(this).attr("id");
                var height = $("#"+thisid+ " .unitycontainer").css("height");
                $("#"+thisid+ " .unityholder").css({"height" : height});
                $("#"+thisid+ " .unityhide").css({"height" : "0px"});
                $("#"+thisid+ " .unitycontainer").scrollTop(0);
            });
        }
        function destroy(that)
        {
            that.each(function ()
            {
                var thisid = $(this).attr("id");
                $("#" + thisid + " .unitycontainer").remove();
            });
        }
        //JQUERY UNITY MISC FUNCTIONS
        function GetInstallerPath()
        {
            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;
            }
        }
    };
})(jQuery);
