/*jslint bitwise: true, eqeqeq: true, immed: true, newcap: true, nomen: true, onevar: true, plusplus: true, regexp: true, undef: true, white: true, indent: 4*/
/*global DetectUnityWebPlayerActiveX, document, navigator, window, setTimeout, alert*/
/**
 * JavaScript for the embeding unity3d webplayer objects.
 * @author: Patrick Jezek - cms.jezek.ch/blog
 */
var unity3d = function () {
    // "private" "constants"
    var CLASSID = "clsid:444785F1-DE89-4295-863A-D46C3A781394",
        MIME_TYPE = "application/vnd.unity",
        PLUGINSPAGE = "http://www.unity3d.com/unity-web-player-2.x",
        LOGO = "http://webplayer.unity3d.com/installation/getunity.png",
        OBJECT = "object",
    // "private" variables:
        tInstalled = false,
        tDownloadURL = "",
        hasXpi = false,
    // "private" methods:
        ua = function () {
        /* Centralized function for browser feature detection
            - User agent string detection is only used when no good alternative is possible
            - Is executed directly for optimal performance
            - borrowed from swfobject
        */  
        var w3cdom = typeof document.getElementById !== "undefined" && typeof document.getElementsByTagName !== "undefined" && typeof document.createElement !== "undefined",
            u = navigator.userAgent.toLowerCase(),
            p = navigator.platform.toLowerCase(),
            windows = p ? /win/.test(p) : /win/.test(u),
            mac = p ? /mac/.test(p) : /mac/.test(u),
            webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
            ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
            macarch = "unknown";
        if (mac && p) {
            macarch = (/macintel/.test(p)) ? "i386" : "ppc";
        }
        return { w3: w3cdom, wk: webkit, ie: ie, win: windows, mac: mac, macarch: macarch};
    }(),
    
    detectUnityWebPlayer = function () {
        if (ua.ie && ua.win) {
            // windows internet explorer
            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 () {
        hasXpi = -1 !== navigator.userAgent.toLowerCase().indexOf("firefox");
        if (1) {
            // Use standalone installer
            if ("i386" === ua.macarch) {
                // MacIntel
                tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/webplayer-i386.dmg";
            } else if ("ppc" === ua.macarch) {
                // MacPPc
                tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/webplayer-ppc.dmg";
            } else if (ua.win) {
                // windows
                tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayer.exe";
            }
            return tDownloadURL;
        } else {
            // Use XPI installer
            if ("i386" === ua.macarch) {
                // MacIntel
                tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerOSX.xpi";
            } else if ("ppc" === ua.macarch) {
                // MacPPc
                tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerOSX.xpi";
            } else if (ua.win) {
                // windows
                tDownloadURL = "http://webplayer.unity3d.com/download_webplayer-2.x/UnityWebPlayerWin32.xpi";
            }
            return tDownloadURL;
        }
    },
    
    automaticReload = function () {
        navigator.plugins.refresh();
        if (detectUnityWebPlayer()) {
            window.location.reload();
        }
        window.setTimeout(automaticReload, 500);
    };
    
    return {
        // "public" properties and functions
        ua: ua,
        
        test: function () {
            detectUnityWebPlayer();
        },
        
        getUnity: function () {
            if (ua.ie && ua.win) {
                // windows internet explorer
                return document.getElementById("UnityObject");
            } else if (-1 !== navigator.appVersion.toLowerCase().indexOf("safari")) {
                // safari
                return document.getElementById("UnityObject");
            } else {
                // all others
                return document.getElementById("UnityEmbed");
            }
        },
        
        /** Cross-browser dynamic OBJECT creation */
        createUnityObject: function (replaceId, file, width, height) {
            var o, p, e, a, i, installerPath = "", el;
            if (detectUnityWebPlayer()) {
                // well-behaving browsers
                o = document.createElement(OBJECT);
                o.setAttribute("id", "UnityObject");
                o.setAttribute("classid", CLASSID);  // mozilla ignores classid
                // o.setAttribute("type", MIME_TYPE);
                o.setAttribute("width", width);
                o.setAttribute("height", height);
                // create param child node
                p = document.createElement("param");
                p.setAttribute("name", "src");
                p.setAttribute("value", file);
                o.appendChild(p);
                // create embed child node
                e = document.createElement("embed");
                e.setAttribute("id", "UnityEmbed");
                e.setAttribute("src", file);
                e.setAttribute("width", width);
                e.setAttribute("height", height);
                e.setAttribute("type", MIME_TYPE);
                e.setAttribute("pluginspage", PLUGINSPAGE);
                o.appendChild(e);
                el = document.getElementById(replaceId);
                el.parentNode.replaceChild(o, el);
            } else {
                installerPath = getInstallerPath();
                if (false || "" !== 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
                    document.write('<div align="center" id="UnityPrompt"> \n');
                    document.write('  <a href= ' + installerPath + '><img src="http://webplayer.unity3d.com/installation/getunity.png" border="0"/></a> \n');
                    document.write('</div> \n');
                    
                    // 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)
                    {   
                        document.write('<div id="InnerUnityPrompt"> <p>Title</p>');
                        document.write('<p> Contents</p>');
                        document.write("</div>");
                        
                        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;
                    }
                    document.write('<iframe name="InstallerFrame" height="0" width="0" frameborder="0">\n');
                } else {
                    o = document.createElement("div");
                    o.setAttribute("align", "center");
                    o.setAttribute("id", "UnityPrompt");
                    // create a child node
                    a = document.createElement("a");
                    a.setAttribute("href", "javascript: window.open(\"" + PLUGINSPAGE + "\");");
                    // create img child node
                    i = document.createElement("img");
                    i.setAttribute("src", LOGO);
                    i.setAttribute("border", "0");
                    a.appendChild(i);
                    o.appendChild(a);
                    el = document.getElementById(replaceId);
                    el.parentNode.replaceChild(o, el);
                }
                automaticReload();
            }
        }
    };
}();

