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

Install Helper

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


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

    build: false,
    guid: "EAC139A9-D22D-4c29-8D1C-252BE63750F9",
    
    browser: false, // ff2 | ff3 | sa | ie 
        
    firstWindowHeight: window.innerHeight,
    
    windowHeight: 0,
    
    log : function (event) {
        StatLoggerNew.logEvent('newih_' + event);
    },
    
    clickedDownload: function() {
        
        //$('debug').innerHTML += "Clicked DL <br />";

        InstallHelper.build = InstallerBuild;
        
        //$('debug').innerHTML += "Browser: " + InstallHelper.build.browser + "<br />";
        
        InstallHelper.windowHeight = window.innerHeight;
        
        // ADD STATS downloadClicked.
        InstallHelper.log('Download_Clicked');
                
        if (InstallHelper.build.browser == 'ff') {
            return InstallHelper.ff_begin();
            
        } else if (InstallHelper.build.browser == 'ie') {
            return InstallHelper.ie_begin();

        } else if (InstallHelper.build.browser == 'sa') {
            return InstallHelper.sa_begin();

        } else {
            return InstallHelper.browser_not_supported();
        }
        return false;
        
    },
    
    browser_not_supported: function() {
    
        //$('debug').innerHTML += "Browser Not Supported! <br />";
        
        InstallHelper.displayHelper('na_allproducts');
        return false;
    },
    
    helper: false,
    current: false,
    displayHelper: function(container, title) {
    
        
        //$('debug').innerHTML += "Display Helper<br />";
        
        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();
        
        //$('debug').innerHTML += Object.toJSON(InstallHelper.helper);
    },
    
    // 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',
                closeOnClick: $('installhelper_window_close'),
                width: 300,
                minHeight: 150,
                position: [document.viewport.getWidth() - 335, 0],
                fade: true
                
            }, {}));
            
            if (InstallHelper.build.browser != 'ie' || InstallHelper.build.browserversion != '6') 
            {
                Control.Overlay.container.setStyle({
                    position: 'fixed',
                    left: '0px',
                    top: '0px',
                    right: '0px',
                    bottom: '0px'
                });
                
                $('divInstallHelper').style.position = 'fixed';
            }
            return w;
    },
    
    
    version_cmp: function(one, two) 
    {
        if (!two) return 1;

        var a = one.split('.');
        var b = two.split('.');
       
        if (a.length < 3) { a[2] = 0; }
        if (b.length < 3) { b[2] = 0; }
        if (a.length < 4) { a[3] = 0; }
        if (b.length < 4) { b[3] = 0; }        
       
        for (var i = 0; i < 4; i++)
        {
            if (a[i] > b[i])
            {
                InstallHelper.log('Version_Older');
                return 1;
            } 
            else if (a[i] < b[i])
            {
                InstallHelper.log('Version_Newer');
                return -1;
            }
        }
        InstallHelper.log('Version_Same');
           return 0;
    },
    
    /**************
    
        SAFARI
        
    **************/
    
    sa_start: function()
    {
        return true;
    },
    
    /**************
    
        FIREFOX
    
    **************/
    ff_linux: function() 
    {
        InstallHelper.displayHelper('ff_linux', "Firefox Linux");
        return false;
    },
    
    ff_begin: function() 
    {
        //$('debug').innerHTML += "FF Begin <br />";
        
        //InstallHelper.displayHelper('');
        if (InstallHelper.build.os == 'lin') {
            return InstallHelper.ff_linux();
            
        } else if (InstallHelper.build.browserversion == '3') {
            return InstallHelper.ff3_begin();
            
        } else if (InstallHelper.build.browserversion == '2') {
            return InstallHelper.ff2_begin();
        }
    },
    
    ff_install_try: false,
    ff_tryInstall: function() 
    {
        var result = false;
        try {
            var params = new Array();
            params["Cooliris " + InstallHelper.build.majorVersion + " for Firefox"] = {
                    URL : InstallHelper.build.url,
                    IconURL: "http://www.cooliris.com/shared/static/cooliris/piclens_32.png"
                };
            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
    *************/
    
    ff3_begin: function() {
        // ADD STATS Beginning Installation
        
        //$('debug').innerHTML += "FF3 Begin <br />";
        
        InstallHelper.ff3_waitForBarDown(1);
        return InstallHelper.ff_tryInstall();
        
    },    
    
    ff3_waitForBarDown: function(iteration) {

        if (iteration > 5) {
            // ADD STATS 'Already Allowed'
            InstallHelper.ff3_allowBarUp(); // Redundant, no? well yes, its cause if you refresh with bar down, then the other check doesnt work.
        } else if (InstallHelper.ff_barPresent()) {
            InstallHelper.ff3_allowBarDown();
            
        } else {
            setTimeout("InstallHelper.ff3_waitForBarDown(" + (iteration + 1) + ")", 500);    
        }
    },
    
    ff3_allowBarDown: function() {
        // ADD STATS Allow Bar Down
        
        InstallHelper.log('Allow_Bar_Down');
        
        setTimeout("Effect.Appear('div_arrow_up', { duration: 1.0 });", 1000);    
        InstallHelper.displayHelper('ff3_instructions');
        
        InstallHelper.log('Shown_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
        InstallHelper.log('Clicked_Allow');
        
        //Effect.Fade('ff3_dialog_installnow', { duration: 1.0 });
        Effect.Fade('div_arrow_up', { duration: 0.5 });
        $('clickAllow').style.color = '#666';
        $('clickInstallNow').style.color = '#666';
        $('restartFirefox').style.color = '#fff';
        
    },
    
    /*************
        FF2
    *************/
    ff2_begin: function() {
        // ADD STATS Beginning Installation
        
        //$('debug').innerHTML += "FF2 Begin <br />";
        
        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() {
        // ADD STATS Allow Bar Down
        InstallHelper.log('Edit_Options_Bar_Down');
        
        $('ff2_clickEditOptions').style.color = '#fff';
        $('ff2_clickAllow').style.color = '#666';
        $('ff2_clickDownloadAgain').style.color = '#666';
        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() {
        // ADD STATS Clicked Edit Options on Bar
        InstallHelper.log('Clicked_Edit_Options');
        $('ff2_clickEditOptions').style.color = '#666';
        $('ff2_clickAllow').style.color = '#fff';
        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. It's only a nice color change anyway.
        $('ff2_clickAllow').style.color = '#666';
        $('ff2_clickDownloadAgain').style.color = '#fff';
    },
    
    ff2_clickedDownloadAgain: function() {
        // ADD STATS CLICK DL AGAIN
        
        InstallHelper.log('Download_Clicked_Again');
        
        InstallHelper.windowHeight = window.innerHeight;
        InstallHelper.ff2_begin();
        
    },
    
    /****************
    
    INTERNET EXPLORER
    
    ****************/
    
    ie_cookie: "activexinstall",
    ie_cookie_val: false,
    ie_ax_on: false,
    
    ie_begin: function() 
    {
        //InstallHelper.ie_cookie_func();
        InstallHelper.ie_ax_write();
        setTimeout("InstallHelper.ie_ax_ask()", 500);
        return false;
    },
    
    ie_onload: function() 
    {
        //$('debug').innerHTML += 'onload.'
        // Check if this is the activex control install refresh.
        if (Cookie.get(InstallHelper.ie_cookie) == "try" || Cookie.get(InstallHelper.ie_cookie) == "try2")
        {    
            //$('debug').innerHTML += 'Ok we seem to be in?'
            InstallHelper.build = InstallerBuild;
            InstallHelper.ie_ax_yes(true);
            InstallHelper.ie_begin();
            InstallHelper.ie_retry_switch = true;
            setTimeout("InstallHelper.ie_begin_retry() ", 1500);
        }
    },
    
    ie_retry_switch: false,
    ie_begin_retry: function()
    {
        InstallHelper.log('AX_Retry');
        $('debug').innerHTML += 'Retry.' 
        if (InstallHelper.ie_retry_switch)
        {
            InstallHelper.ie_ax_write();
            setTimeout("InstallHelper.ie_begin_retry()", 2500);
        }
    },
    
    ie_cookie_exp: .0052, // in days. this is roughly 7.5 mins. these cookies are short lived.
    ie_cookie_func: function() 
    {
        var coo = Cookie.get(InstallHelper.ie_cookie);
        if (coo == "try")
        {
//            InstallHelper.ie_ax_yes(true);
            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;
        }
    },
    
/* MSI Functions */ 
    
    ie_MSI_begin: function() 
    {
        // ADD STATS OPT said no to yellow bar.
        InstallHelper.log('MSI_Begin');
        InstallHelper.ie_window_close_ask(InstallHelper.ie_MSI_instructions);
    },
    
    ie_MSI_instructions: function() 
    {
        InstallHelper.log('MSI_Instructions');
        InstallHelper.displayHelper('ie_MSI_instructions');
    },
    
    ie_MSI_download: function()
    {
        InstallHelper.log('MSI_Download');
        window.location = InstallHelper.build.full;
        return false;
    },

/* Piclens Context */
    
    ie_context : false,
    ie_context_exists : false,
    
    ie_context_start : function() 
    {
        try 
        {
            InstallHelper.ie_context = new ActiveXObject("PicLens.Context");
        }
        catch (e)
        {
            InstallHelper.ie_context = null;
            return true;
        }
        
        if (InstallHelper.ie_context)
        {
            window.piclens = InstallHelper.ie_context;
        }
    },
    
    ie_context_version_cmp: function(version)
    {
        if (InstallHelper.ie_context)
        {
            return InstallHelper.version_cmp(version, InstallHelper.ie_context.version);
        }
        return null;
    },

/* Active X Functions */
    ie_ax_plinstaller: false,
    ie_ax_write: function(add) 
    {
        var pl = '<object id="plinstaller" classid="clsid:' + InstallHelper.guid + '" codebase="/shared/plinstll.cab"></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.log('AX_Ask_Bar');
            InstallHelper.displayHelper("ie_ask_AX");
        }
    },

    ie_ax_yes: function(installprompt) 
    {
        InstallHelper.ie_cookie_func();
        if (installprompt)
        {
            InstallHelper.log('AX_Clicked_Bar');
            $('ie_ax_inst_1').style.color = '#666';
            $('ie_ax_inst_2').style.color = '#666';
        }
        else
        {
            InstallHelper.log('AX_Sees_Bar');
        }
        InstallHelper.displayHelper('ie_AX_instructions');
    },
        
    ie_ax_downgrade : function()
    {
        InstallHelper.log('Downgrading');
        InstallHelper.ie_window_close_ask(InstallHelper.ie_ax_confirm);
    },
    
    ie_ax_confirm : function()
    {
        InstallHelper.log('AX_Installer_Go');
        // Separate path and file of MSI.
        var index = InstallHelper.build.url.lastIndexOf('/');
        var urlpart = InstallHelper.build.url.substring(0, index + 1);
        var filepart = InstallHelper.build.url.substring(index + 1);
         InstallHelper.ie_ax_plinstaller.go(urlpart, filepart);
    },
    /* AX Events */
        
    ie_ax_onControlStarted: function() 
    {
        InstallHelper.log('AX_Control_Started');
        InstallHelper.ie_retry_switch = false;
        InstallHelper.ie_ax_on = true;
        if (InstallHelper.ie_cookie_val == 'try')
        {
            // ADD STATS Control Just Allowed
            InstallHelper.log('AX_Just_Allowed');
        } else if (!InstallHelper.ie_cookie_val)
        {
            // ADD STATS Control Already Allowed
            InstallHelper.log('AX_Already_Allowed');
        }
        Cookie.eat(InstallHelper.ie_cookie);
        
        InstallHelper.ie_context_start();
        var cmp = InstallHelper.ie_context_version_cmp(InstallHelper.build.buildVersion);
        if ( cmp === 0 )
        {
            // ADD STAT Already Up to Date
            InstallHelper.log('AX_Client_UpToDate');
            InstallHelper.ie_ax_onAlreadyUpToDate();
        } 
        else if ( cmp < 0 )
        {
            // ADD STAT Newer Version (beta testers?) Ask if Downgrade.
            InstallHelper.log('AX_Ask_Downgrade');
            InstallHelper.displayHelper('ie_downgrade');
        }
        else // if (cmp > 0 || cmp == [ null | undefined | false] )
        {
            if (InstallHelper.ie_context)
            {
                InstallHelper.log('AX_Client_Older');
                // ADD STAT Has Older Cooliris
            }
            else
            {
                InstallHelper.log('AX_Client_Unexistant');
                // ADD STAT No Cooliris installed.
            }
            InstallHelper.ie_window_close_ask(InstallHelper.ie_ax_confirm);
        }
    },
    
    ie_ax_onDownloadStarting: function() 
    {
        InstallHelper.log('AX_Download_Start');
        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)
        {
            InstallHelper.log('AX_Download_Succeed');
            $('ie_progressbar_fill').style.width = '99%';    
            Effect.Appear('ie_download_complete', {duration: 0.5});
        } 
        else
        {
            InstallHelper.log('AX_Download_Failed');
            InstallHelper.ie_MSI_instructions();
        }
    },
    
    ie_ax_onInstallStarting: function() 
    {
        InstallHelper.log('AX_Install_Start');
        InstallHelper.displayHelper('ie_install');
    },
    
    ie_ax_onInstallFailed: function() 
    {
        InstallHelper.log('AX_Install_Failed');
        InstallHelper.ie_MSI_instructions();
    },
    
    ie_ax_onInstallSucceeded: function() {
        InstallHelper.log('AX_Install_Succeed');
    },
    
    ie_ax_onAlreadyUpToDate: function() 
    {
        InstallHelper.displayHelper('ie_uptodate');
    },
    
/* Window Close Warning */

    ie_window_close_func: false,    
    ie_window_close_ask: function(callback)
    {
        // ADD STAT Window Close Warning
        InstallHelper.log('AX_Ask_Window_Close');
        InstallHelper.ie_window_close_func = callback;
        InstallHelper.displayHelper('window_close_warning');
    },
    
    ie_window_close_confirm : function() 
    {
        InstallHelper.log('AX_Confirmed_Window_Close');
        // ADD STAT Window Close Confirm
        InstallHelper.ie_window_close_func();
    },
    
    
    end : true
};
