/*************

Install Helper

@require cookie.js
@require statlogger.js
@require prototype.js, livepipeui, scriptaculous, cookie


**************/
        
var InstallHelper = {

    browser : "other",
    browserMajor : 0,
    
    dotNET : false,
    dotNETMajor : 0,
    dotNETMinor : 0,
    
    firstWindowHeight: window.innerHeight,    
    windowHeight: 0,
    
    exeInstallerUrl : "download/KikinInstaller.exe",
    dotNETInstallerUrl : "download/Kikin.Installer.application",
    cabInstallerUrl : "download/KikinInstaller.cab",
    xpiInstallerUrl : "download/KikinInstaller.xpi",
    
    os : "other",
    osMajor : 0,
    osMinor : 0,
    
    /** 
     * Read browser info.
     * Sets the "browser" member variable to one of the following:
     * 
     * ff
     * ie
     * opera
     * other
     *
     * Sets the "browserMajor" member variable to the browser major version.
     * Sets the "dotNET" member variable to true if user has .NET installed, false otherwise.
     * Sets the "dotNETMajor" member variable to the .NET major version.
     * Sets the "dotNETMinor" member variable to the .NET minor version.
     * Sets the "os" member variable to one of the following:
     *
     * winNT
     * other
     *
     * Sets the "osMajor" member variable to the OS major version.
     * Sets the "osMinor" member variable to the OS minor version.
     */
    readBrowserInfo : function() {
        
        // Test browser name
        if (/Firefox[\/\s](\d+)\.(\d+)/.test(navigator.userAgent)) {
        
            // Firefox/x.x or Firefox x.x
            InstallHelper.browser = "ff";
            
            // Parse versions
            InstallHelper.browserMajor = new Number(RegExp.$1)
         }
         else if (/MSIE (\d+)\.(\d+);/.test(navigator.userAgent)) {
            
            // MSIE x.x
            InstallHelper.browser = "ie";
            
            // Parse versions
            InstallHelper.browserMajor = new Number(RegExp.$1)
        }
        else if (/Opera[\/\s](\d+)\.(\d+)/.test(navigator.userAgent)) {
         
            // Opera/x.x or Opera x.x   
            InstallHelper.browser = "opera";
            
            // Parse versions
            InstallHelper.browserMajor = new Number(RegExp.$1)
        }
        else {
            InstallHelper.browser = "other";
            InstallHelper.browserMajor = 0;
        }
        
        // Read .NET
        if (/\.NET CLR ([0-9]+)\.([0-9]+)\.([0-9]+)/.test(navigator.userAgent)) {
            InstallHelper.dotNET = true;
            InstallHelper.dotNETMajor = new Number(RegExp.$1);
            InstallHelper.dotNETMinor = new Number(RegExp.$2);
        }         
        
        // Read OS
        if (/Windows NT ([0-9]+)\.([0-9]+)/.test(navigator.userAgent)) {
            InstallHelper.os = "winNT";
            InstallHelper.osMajor = new Number(RegExp.$1);
            InstallHelper.osMinor = new Number(RegExp.$2);
        } else {
        
            // Other OS
            InstallHelper.os = "other";
        }
    },
    
    /** Called when the browser loads. */
    onLoad : function() {
    
        // Read browser info
        InstallHelper.readBrowserInfo();
        
        // If IE do IE specific loading
        if (InstallHelper.browser == "ie") {
            InstallHelper.onIELoad();
        }
    },
    
    /** Called when the user initiates the download. */
    startInstall : function() {

	// Get current window height        
        InstallHelper.windowHeight = window.innerHeight;
        
        // Switch on browser type
        if (InstallHelper.browser == "ff") {
            
            // Begin FF install
            return InstallHelper.startFirefoxInstall();
            
        } else if (InstallHelper.browser == "ie") {
       
            // Begin IE install
            return InstallHelper.startIEInstall();
        } else {
            return InstallHelper.browser_not_supported();
        
        /*} else {
        
            // Not a supported browser
            alert("Sorry, the kikin plugin is not yet available for your browser.");*/
        }
        
        
        return false;
        
    },
    
    browser_not_supported: function() {    
        InstallHelper.displayHelper('browser_not_supported', "Other");
        return false;
    },
    
    os_not_supported : function() {
        InstallHelper.displayHelper('os_not_supported', "Other");
        return false;
    },
    
    helper: false,
    current: false,
    displayHelper: function(container, title) {
    
        if (!InstallHelper.helper)
            InstallHelper.helper = InstallHelper.window_factory($('divInstallHelper'));
        
        if (container)
        { 
            if (InstallHelper.current)
            {
                Effect.Fade(InstallHelper.current, { duration: 0.5 });
                setTimeout("Effect.Appear('" + container + "', { duration: 0.5 })", 500);
            } 
            else
            {
                Effect.Appear(container);
            }
            InstallHelper.current = container;
        }    
        
        if (!InstallHelper.helper.isOpen)
            InstallHelper.helper.open();
    },
    
    // LivePipe UI, Ryan Johnson
    // styled examples use the window factory for a shared set of behavior
    window_factory: function(container) {
            var w = new Control.Modal(container,Object.extend({
                overlayOpacity: 0.90,
                className: 'installhelper_window',
                //width: 350,
                //minHeight: 150,
                position: [document.viewport.getWidth() - 385, 0],
                fade: true
                
            }, {}));
            
            if ((InstallHelper.browser != "ie") || (InstallHelper.browserMajor != 6)) 
            {
                Control.Overlay.container.setStyle({
                    position: 'fixed',
                    left: '0px',
                    top: '0px',
                    right: '0px',
                    bottom: '0px'
                });
                
                $('divInstallHelper').style.position = 'fixed';
            }
            return w;
    },
           
    /**************
    
        FIREFOX
    
    **************/
    
    ff_install_try: false,
    
    /** Starts ClickOnce install under Firefox. */
    startFirefoxClickOnceInstall : function() {
        self.location.href = InstallHelper.dotNETInstallerUrl;
        return true;
    },
    
    /** Called to start the download/install process under Firefox. */
    startFirefoxInstall : function() 
    {
        // InstallHelper.displayHelper('');
        if (InstallHelper.os == "winNT") {
        
            // Switch on browser type
            if (InstallHelper.dotNET && (InstallHelper.dotNETMajor >= 2)) {
            
                // ClickOnce install
                return InstallHelper.startFirefoxClickOnceInstall();
            } else if (InstallHelper.browserMajor >= 3) {
            
                // Firefox 3
                return InstallHelper.startFirefox3Install();            
            } else if (InstallHelper.browserMajor >= 2) {
            
                // Firefox 2
                return InstallHelper.startFirefox2Install();
            } else {
                
                // Some other Firefox
                return InstallHelper.browser_not_supported();
            }
        } else {
            return InstallHelper.os_not_supported();
        }
    },
        
    ff_tryInstall: function() 
    {
        var result = false;
        try {
            var params = new Array();
            params["kikin plugin"] = {
                    URL : InstallHelper.xpiInstallerUrl
                };
            result = InstallTrigger.install(params);
        } catch (e) {}
        InstallHelper.ff_install_try = result;
        return result;
    },
    
    ff_barPresent : function() 
    {
        if (InstallHelper.windowHeight > window.innerHeight)
            return true;
        
        var diff = InstallHelper.firstWindowHeight - InstallHelper.windowHeight;
        
        return (diff != 0 && (diff < 35 || diff > -35) )
    
    },
    
    /*************
        FF3
    *************/
    
    startFirefox3Install : function() {
        InstallHelper.ff3_waitForBarDown(1);
        return InstallHelper.ff_tryInstall();        
    },    
    
    ff3_waitForBarDown: function(iteration) {
        if (iteration > 5) {
            // Redundant, no? well yes, its cause if you refresh with bar down, then the other check doesnt work.
            InstallHelper.ff3_allowBarUp(); 
        } else if (InstallHelper.ff_barPresent()) {
            InstallHelper.ff3_allowBarDown();
            
        } else {
            setTimeout("InstallHelper.ff3_waitForBarDown(" + (iteration + 1) + ")", 500);    
        }
    },
    
    ff3_allowBarDown: function() {
        // ADD STATS Allow Bar Down        
        
        // Show instructions        
        InstallHelper.displayHelper('ff3_instructions');
        
        InstallHelper.ff3_waitForBarUp();
    },
    
    
    ff3_waitForBarUp: function() {
        if (InstallHelper.windowHeight == window.innerHeight) {
            InstallHelper.ff3_allowBarUp();
        } else {
            setTimeout("InstallHelper.ff3_waitForBarUp()", 500);    
        }
    },
    
    ff3_allowBarUp: function() {
        // ADD STATS Clicked Allow on Allow Bar        
    },
    
    /*************
        FF2
    *************/
    startFirefox2Install : function() {
        
        InstallHelper.ff2_waitForBarDown(1);
        InstallHelper.ff_tryInstall();
        return false;
    },    
    
    ff2_waitForBarDown: function(iteration) {
        if (iteration > 5) {
            // ADD STATS 'Already Allowed'
           // InstallHelper.ff2_allowBarDown(); // Redundant, no? well yes, its cause if you refresh with bar down, then the other check doesnt work.
        } else if (InstallHelper.windowHeight > window.innerHeight) {
            InstallHelper.ff2_allowBarDown();
            
        } else {
            setTimeout("InstallHelper.ff2_waitForBarDown(" + (iteration + 1) + ")", 500);    
        }
    },
    
    ff2_allowBarDown: function() {
        InstallHelper.displayHelper('ff2_instructions');
        InstallHelper.ff2_waitForBarUp();
    },
    
    
    ff2_waitForBarUp: function() {
        if (InstallHelper.windowHeight == window.innerHeight) {
            InstallHelper.ff2_allowBarUp();
        } else {
            setTimeout("InstallHelper.ff2_waitForBarUp()", 500);    
        }
    },
    
    ff2_allowBarUp: function() {
        setTimeout("InstallHelper.ff2_clickedAllow()", 4000);
    },
    
    ff2_clickedAllow: function() {
        // This cannot actually be detected, so we dont log a stat.
        // It is just estimated via time. 
    },
    
    ff2_clickedDownloadAgain: function() {
        // ADD STATS CLICK DL AGAIN
                
        InstallHelper.windowHeight = window.innerHeight;
        InstallHelper.startFirefox2Install();
        
    },
    
    /****************
    
    INTERNET EXPLORER
    
    ****************/
    
    ie_cookie: "activexinstall",
    ie_cookie_val: false,
    ie_ax_on: false,
    ie_retry_switch: false,
    ie_cookie_exp: .0052, // in days. this is roughly 7.5 mins. these cookies are short lived.
   
    /** Starts ClickOnce install under IE. */
    startIEClickOnceInstall : function() {
        self.location.href = InstallHelper.dotNETInstallerUrl;
        return true;
    },
 
    startIEInstall : function() 
    {
        // InstallHelper.displayHelper('');
        if (InstallHelper.os == "winNT") {

            if (InstallHelper.dotNET && (InstallHelper.dotNETMajor >= 2)) {
    
                // ClickOnce install
                return InstallHelper.startIEClickOnceInstall();
            } else {
                //InstallHelper.ie_cookie_func();
                InstallHelper.ie_ax_write();
                setTimeout(InstallHelper.ie_ax_ask, 500);
                return false;
            }
        } else {
            return InstallHelper.os_not_supported();
        }
    },
    
    onIELoad: function() 
    {
        // Check if this is the activex control install refresh.
        if (Cookie.get(InstallHelper.ie_cookie) == "try" || Cookie.get(InstallHelper.ie_cookie) == "try2")
        {    
            InstallHelper.ie_retry_switch = true;
            setTimeout(InstallHelper.ie_begin_retry, 500);
        }
    },
    
    ie_begin_retry: function()
    {
        if (InstallHelper.ie_retry_switch)
        {
            InstallHelper.ie_ax_write();
            setTimeout("InstallHelper.ie_begin_retry()", 4000);
        }
    },
        
    ie_cookie_func: function() 
    {
        var coo = Cookie.get(InstallHelper.ie_cookie);
        if (coo == "try")
        {
            Cookie.set(InstallHelper.ie_cookie, "try2", InstallHelper.ie_cookie_exp);
            InstallHelper.ie_cookie_val = "try";
            InstallHelper.ie_ax_on = true;
        } 
        else if (coo == "try2")
        {
            Cookie.eat(InstallHelper.ie_cookie);
            InstallHelper.ie_cookie_val = "try2"
            InstallHelper.ie_ax_on = true;
        }
        else if (!coo)
        {
            // ADD STATS First Hit.
            Cookie.set(InstallHelper.ie_cookie, "try", InstallHelper.ie_cookie_exp);
            InstallHelper.ie_cookie_val = false;
        }
    },
    
    /* EXE Functions */ 
    
    ie_EXE_begin: function() 
    {
        InstallHelper.displayHelper('ie_install'); 
        window.location = InstallHelper.exeInstallerUrl;
        return false;
    },
    
    /* Active X Functions */
    ie_ax_plinstaller: false,
    ie_ax_write: function(add) 
    {
        var pl = '<object id="plinstaller" classid="clsid:E601996F-E400-41CA-804B-CD6373A7EEE2" codebase="' + 
            InstallHelper.cabInstallerUrl + '"></object>'; 
        
        var iframe = $('activexiframe');
        var iframeDoc = iframe.contentWindow || iframe.contentDocument;
        if (iframeDoc.document) {
            iframeDoc = iframeDoc.document;
        }
        iframeDoc.open();
        iframeDoc.write(pl);
        InstallHelper.ie_ax_plinstaller = iframeDoc.getElementById('plinstaller');
        InstallHelper.ie_ax_attach();
        iframeDoc.close();

    },

    ie_ax_attach: function() 
    {
        InstallHelper.ie_ax_plinstaller.attachEvent('ControlStarted',   InstallHelper.ie_ax_onControlStarted  );
        InstallHelper.ie_ax_plinstaller.attachEvent('DownloadStarting', InstallHelper.ie_ax_onDownloadStarting);
        InstallHelper.ie_ax_plinstaller.attachEvent('DownloadProgress', InstallHelper.ie_ax_onDownloadProgress);
        InstallHelper.ie_ax_plinstaller.attachEvent('DownloadComplete', InstallHelper.ie_ax_onDownloadComplete);
        InstallHelper.ie_ax_plinstaller.attachEvent('InstallStarting',  InstallHelper.ie_ax_onInstallStarting );
        InstallHelper.ie_ax_plinstaller.attachEvent('InstallFailed',    InstallHelper.ie_ax_onInstallFailed   );
        InstallHelper.ie_ax_plinstaller.attachEvent('InstallSucceeded', InstallHelper.ie_ax_onInstallSucceeded);
    },
    
    ie_ax_ask : function() 
    {
        if (!InstallHelper.ie_ax_on)
        {
            InstallHelper.displayHelper("ie_ask_AX");
        }
    },

    ie_ax_yes: function(installprompt) 
    {
        InstallHelper.ie_cookie_func();
        InstallHelper.displayHelper('ie_AX_instructions');
    },
        
    /* AX Events */
        
    ie_ax_onControlStarted: function() 
    {
        InstallHelper.ie_retry_switch = false;
        InstallHelper.ie_ax_on = true;        
        Cookie.eat(InstallHelper.ie_cookie);
        
        // Here the original code initiated the ActiveX control,
        // requested its version and compared it with the current version
        // Let's first try to see if the automatic versioning of ActiveX
        // controls, which is expressed in the <object> tag can take care
        // of this.
    },
    
    ie_ax_onDownloadStarting: function() 
    {
        InstallHelper.displayHelper('ie_download');
    },
    
    ie_ax_onDownloadProgress: function(bytesLoaded, bytesTotal) 
    {
        if (bytesLoaded > 0 && bytesTotal > 0)
        {
            var percentage = bytesLoaded / bytesTotal * 99;
            $('ie_progressbar_fill').style.width = percentage + '%';
            
        }
    },
    ie_ax_onDownloadComplete: function(success) 
    {
        if (success)
        {
            $('ie_progressbar_fill').style.width = '99%';    
            Effect.Appear('ie_download_complete', {duration: 0.5});
        } 
        else
        {
            InstallHelper.ie_EXE_instructions();
        }
    },
    
    ie_ax_onInstallStarting: function() 
    {
        InstallHelper.displayHelper('ie_install');
    },
    
    ie_ax_onInstallFailed: function() 
    {
        InstallHelper.ie_EXE_instructions();
    },
    
    ie_ax_onInstallSucceeded: function() {
    },
        
    
    end : true
};

