if (typeof(Collactive) == 'undefined') {
	Collactive = {};
}

Collactive.InstallManager = function(ui, config) {
    this._ui = ui;
    this._installed = false;
    this._ieCodebaseLocation = config.ieCodebaseLocation;
    this._firefoxXPILocation = config.firefoxXPILocation;
    this._saveInstallPointURL = config.saveInstallPointURL;
    this._ieClsid = 'B49FD7AD-E949-4CFD-91E1-70F37391E5F6';

    // ************************************************
    // IE Installation
    // ************************************************

    this._displayYellowBarInfo = function() {
        var m = [];
        m[m.length] = '<div align="center"><img width="558" height="306" src="' + ui.getImageUrl("yellow_bar.gif") + '"></div>';
        this._ui.displayContent('Allow Internet Explorer Add-on Installation',
                                null, null, m.join(""));
    };

    this._performIEInstall = function() {
        this._notifyOperation("start");
        this._ui.displayProgressMessage("Initializing Collactive Web Assistant " + (this._upgrade ? "Upgrade" : "Installation"));
        this._addIEAddonObject();
        setTimeout(Collactive.bind(this, this._displayYellowBarInfo), 2500);
        var loc = document.location.toString();
        loc = this.cleanURL(loc);
        loc += "#ip1=" + new Date().getTime();
        this._replaceLocation(loc);
        this._addIEAddonObject();
        this._checkIEInstall();	// In case the user doesn't have a yellow bar & hits Install...
    };



    this._displayCabInstallInfo = function() {
        this._notifyOperation("cab_dialog");
        var m = [];
        m[m.length] = '<div align="center"><img src="' + ui.getImageUrl("install_cab.gif") + '"></div>';
        this._ui.displayContent('Install Internet Explorer Add-on',
                                null, null, m.join(""));

    };

    this._displayInstallCompleted = function(loc) {
        this._notifyOperation("completed");
		if (!this._upgrade) {
	        var m = [];
	        m[m.length] = '<div style="padding-top: 20px">Thank you for installing Collactive Web Assistant!<br><br>';
	        m[m.length] = '  <a target="_new" href="http://www.collactive.com/webassistant.html">Click here</a> to learn more about Collactive Web Assistant</a>';
	        m[m.length] = '</div>';

	        m[m.length] = '<div class="collactive_wallet_text" style="padding-top: 20px; padding-bottom: 10px">Please proceed to <b>' + this._ui.getSiteName() + '</b> account registration.</div>';

	        this._ui.displayContent('Installation Completed',
	                                null, null, m.join(""),
	                                [["Continue", Collactive.bind(this, function() {
	                                                this._notifyOperation("continue_to_action");
	                                                setTimeout(Collactive.bind(this, this._postInstallCloseWindow), 500);
	                                                window.open(loc, 'collactive_page_' + new Date().getTime());
	                                            })]],
	                                [["Cancel", Collactive.bind(this, function() {
	                                    if (confirm("Are you sure you want to use " + this._ui.getSiteName() + " on your own?")) {
	                                        this._ui.hideUI();
	                                        this._ui.showArticle();
	                                        Collactive.CSAUtils.notifyOperation("assist_no_continue_to_action");
	                                    }
	                                    })]]
	                                );
		} else {
	        var m = [];
	        m[m.length] = '<div style="padding-top: 20px">Thank you for upgrading Collactive Web Assistant!<br>';
	        m[m.length] = '  <a target="_new" href="http://www.collactive.com/webassistant.html">Click here</a> to learn more about Collactive Web Assistant</a>';
	        m[m.length] = '</div>';

	        m[m.length] = '<div class="collactive_wallet_text" style="padding-top: 20px; padding-bottom: 10px">Please close all your browser windows and restart for these changes to take effect.</div>';

	        this._ui.displayContent('Upgrade Completed',
	                                null, null, m.join(""),
	                                [["Close", Collactive.bind(this, function() {
	                                                this._notifyOperation("continue_to_action");
	                                                setTimeout(Collactive.bind(this, function() { window.close() }), 500);
	                                            })]],
	                                [["Cancel", Collactive.bind(this, function() {
	                                    if (confirm("Are you sure you want to use " + this._ui.getSiteName() + " on your own?")) {
	                                        this._ui.hideUI();
	                                        this._ui.showArticle();
	                                        Collactive.CSAUtils.notifyOperation("assist_no_continue_to_action");
	                                    }
	                                    })]]
	                                );
		}
    };

    this._postInstallCloseWindow = function() {
        document.body.innerHTML = '<br><br><center><button style="font-size: 16px" onclick="window.close()">Close window</button></center>';
    };


    this._addIEAddonObject = function() {
		// We're forcing installation with this version number.
		var contents = '<object classid="clsid:' + this._ieClsid + '" codebase="' + this._ieCodebaseLocation + '#Version=9,9,9,9"></object>';
		var div = document.createElement('div');
		div.innerHTML = contents;
		document.appendChild(div);
    };

    this._initIEInstall = function() {
        this._displayInstallIntro();
    };



	this._ieAddonInstalled = function(ver) {
        if (this._installed) {
           return;
        }
		this._installed = true;

        var loc = document.location.toString();
        loc = this.cleanURL(loc);
        loc += "#ip2=" + new Date().getTime();

		this._displayInstallCompleted(loc);
	};



	this._checkIEInstall = function() {
		if (this._installed) {
			return;
		}

        if (Collactive.CSAUtils.ieCheckCSA()
			&& Collactive.CSAUtils.isCSAEngineVersionSatisfactory(config)) {
            // TODO: Extract version
            this._ieAddonInstalled('0.0.0.0');
        } else {
            window.setTimeout(Collactive.bind(this, this._checkIEInstall), 1000);
        }
        return;

	};

    // ************************************************
    // Firefox Installation
    // ************************************************

    this._continueAllowedFirefoxInstall = function(noXPIRedirect) {
        this._notifyOperation("install_dialog");
        var m = [];
        if (navigator.userAgent.toLowerCase().indexOf('firefox/2.0') != -1) {
            m[m.length] = '<div align="center" style="padding-top: 10px"><img src="' + ui.getImageUrl("firefox_install_20.gif") + '"></div>';
        } else {
            m[m.length] = '<div align="center" style="padding-top: 10px"><img src="' + ui.getImageUrl("firefox_install_15.gif") + '"></div>';
        }

        this._ui.displayContent('Install Firefox Add-on',
                                null, null, m.join(""));

        if ((typeof(noXPIRedirect) == 'undefined') || !noXPIRedirect) {
            setTimeout(Collactive.bind(this, this._directToXPI), 2500);
        }

        var loc = document.location.toString();
        loc = this.cleanURL(loc);
        loc += "#ip2=" + new Date().getTime();
        this._replaceLocation(loc);

    };

    this._directToXPI = function() {
        var loc = document.location.toString();
        loc = this.cleanURL(loc);
        loc += "#ip2=" + new Date().getTime();

        var iframe = document.createElement('iframe');
        iframe.src = this._saveInstallPointURL + "?url=" + encodeURIComponent(loc);
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
        setTimeout(Collactive.bind(this, function() { this._replaceLocation(this._firefoxXPILocation) }), 300);
    };

    this._displayFirefoxYellowBarInfo = function() {
        var m = [];
        m[m.length] = '<div align="center" style="padding-top: 10px"><img src="' + ui.getImageUrl("firefox_allow_both.gif") + '"></div>';
        m[m.length] = '<div align="center" style="padding-top: 15px"></div>';
        m[m.length] = '<div style="padding-top: 13px; font-size: 12px; color: #404040">If instead you see a Software Installation dialog, click <i>Install Now</i> and then <a id="collactive_already_allowed" style="text-decoration: underline; color: blue; cursor: pointer">click here</a>.</div>';

        this._ui.displayContent('Allow Firefox Add-on Installation',
                                null, null, m.join(""),
                                [ ["Continue", Collactive.bind(this, function() { this._continueAllowedFirefoxInstall(false) } )]]);

        Collactive.DomUtils.registerListener(Collactive.DomUtils.gEBI('collactive_already_allowed'), 'click',
                                             Collactive.bind(this, function() { this._continueAllowedFirefoxInstall(true) }));
        var loc = document.location.toString();
        loc = this.cleanURL(loc);
        loc += "#ip1=" + new Date().getTime();
        this._replaceLocation(loc);
    };

    this._initFirefoxInstall = function() {
        this._displayInstallIntro();
    };


    this._performFirefoxInstall = function() {
        this._notifyOperation("start");
        this._ui.displayProgressMessage("Initializing Collactive Web Assistant Installation");
        setTimeout(Collactive.bind(this, this._displayFirefoxYellowBarInfo), 500);
        setTimeout(Collactive.bind(this, this._directToXPI), 2500);
    };

    // ************************************************
    // General
    // ************************************************

    this._notifyOperation = function(operationName) {
        if (this._isIE()) {
            operationName = "ieai_" + operationName;
        } else if (this._isFirefox()) {
            operationName = "ffai_" + operationName;
        }
        Collactive.CSAUtils.notifyOperation(operationName);
    };

    this._performInstall = function() {
        if (this._isIE()) {
            this._performIEInstall();
        } else if (this._isFirefox()) {
            this._performFirefoxInstall();
        }

    };

    this._displayInstallIntro = function() {

        var m = [];
        m[m.length] = '<div style="margin: 40px 0px; font-size: 13px">';
        m[m.length] = '  <a target="_new" href="http://www.collactive.com/webassistant.html">Click here</a> to learn more about Collactive Web Assistant</a>';
        m[m.length] = '</div>';

        m[m.length] = '<div style="padding-top: 10px; padding-bottom: 10px; font-weight: bold; font-size: 12px">By continuing you agree to Collactive Web Assistant' + "'" + 's <a target="collactive_license" href="http://www.collactive.com/license.html">license agreement</a></div>';

		if (!this._upgrade) {
	        this._ui.displayContent('Install Collactive Web Assistant',
	                            '<b>' + this._ui.getSiteName() +'</b> requires you to open an account in order to participate.<br>Collactive Web Assistant can help you open your account in just a few clicks.<br>' +
	                            'A simple installation is required for activating Collactive Web Assistant.',
	                            null,
	                            m.join(""),
	                            [["Continue", Collactive.bind(this, this._performInstall)]],
	                            [["Cancel", Collactive.bind(this, function() {
	                                if (confirm("Are you sure you want to use " + this._ui.getSiteName() + " on your own?")) {
	                                    this._ui.hideUI();
	                                    this._ui.showArticle();
						                this._notifyOperation("no_install");
	                                }
	                                })]]
	                            );
		} else {
	        this._ui.displayContent('Upgrade Collactive Web Assistant',
	                            'A newer version of Collactive Web Assistant is available and required to participate in this action.',
	                            null,
	                            m.join(""),
	                            [["Continue", Collactive.bind(this, this._performInstall)]],
	                            [["Cancel", Collactive.bind(this, function() {
	                                if (confirm("Are you sure you want to use " + this._ui.getSiteName() + " on your own?")) {
	                                    this._ui.hideUI();
	                                    this._ui.showArticle();
						                this._notifyOperation("no_upgrade");
	                                }
	                                })]]
	                            );
		}
    };

	this.cleanURL = function(url) {
    	  return url.replace(/#.*$/, '');
	};

    this._replaceLocation = function(loc) {
        if (document.location.realReplace) {
            document.location.realReplace(loc);
        } else {
            document.location.replace(loc);
        }
    };

    this._isIE = function() {
        return (navigator.userAgent.toLowerCase().indexOf('msie') != -1);
    };

    this._isFirefox = function() {
        return (navigator.userAgent.toLowerCase().indexOf('firefox') != -1);
    };

    this._cleanInstallURL = function() {
        var loc = document.location.toString();
        if (loc.match(/#/)) {
            loc = loc.replace(/#.*$/, '');
	        this._replaceLocation(loc + '#');
		}
    };

    this._isRecent = function(timeStr, paramName, recentPeriod) {
        var re = new RegExp(paramName + "=(\\d+)");
        var pageTime = parseInt(re.exec(timeStr)[1]);
        return (new Date().getTime() - pageTime < 1000*60*60);
    };


    this.addWizardStep = function() {
        this._ui.addStepAfter(["installation", (this._upgrade ? "Upgrade" : "Install") + " Collactive Web Assistant"], "description");
        this._ui.refreshStepDisplay();
    };

    this.checkInstallState = function() {
		this._upgrade = Collactive.CSAUtils.hasCSA();
        var loc = document.location.toString();
        // TODO: Organize
        if (loc.match(/#/)) {
	      this._ui.displayStep('installation');

		  var params = /#(.*)$/.exec(loc)[1];

          // If no CSA is installed and we were in phase 1
          if ((!Collactive.CSAUtils.hasCSA() ||!Collactive.CSAUtils.isCSAEngineVersionSatisfactory(config))
		  	&& params.match(/ip1=\d+/)) {
            // Ignore old phase 1 markers
            if (!this._isRecent(params, "ip1", 1000*60*60*2)) {
                this._cleanInstallURL();
                return "none";
            }

            // Continue installation of phase 2
            if (this._isIE()) {
                this._displayCabInstallInfo();
                setTimeout(Collactive.bind(this, this._addIEAddonObject), 2000);
                this._checkIEInstall();
                return "inprogress";
            } else if (this._isFirefox()) {
                this._continueAllowedFirefoxInstall(false);
                return "inprogress";
            }

          // If we were in phase 2
          } else if (params.match(/ip2=\d+/)) {
            // If CSA is installed, continue the action page (as if the action button was clicked)
            if (Collactive.CSAUtils.hasCSA() && Collactive.CSAUtils.isCSAEngineVersionSatisfactory(config)) {
                if (!this._isRecent(params,"ip2", 1000*60*60*2)) {
                    this._cleanInstallURL();
                    return "none";
                }
                this._cleanInstallURL();
                this._notifyOperation("action_continued");
                this._focusWindow();
                return "completed";
            // If no CSA is installed and we are in Firefox, re-run phase 2
            } else if (this._isFirefox()) {
                this._continueAllowedFirefoxInstall();
                return "inprogress";
            }
          // If we were in phase 1, CSA is installed and we are in firefox, continue the action page
          } else if (params.match(/ip1=\d+/) && this._isFirefox()) {
                if (!this._isRecent(params,"ip1", 1000*60*60*2)) {
                    this._cleanInstallURL();
                    return "none";
                }
                this._cleanInstallURL();
                this._notifyOperation("action_continued");
                this._focusWindow();
                return "completed";
          }
        } else if (Collactive.CSAUtils.hasCSA() && Collactive.CSAUtils.isCSAEngineVersionSatisfactory(config)) {
            this._cleanInstallURL();
            return "none";
        }
        return "none";
    };

    this._focusWindow = function() {
        try {
            if (window.focus) {
                window.focus();
            }
            window.moveTo(0,0);
            window.resizeTo(screen.width, screen.height);
        } catch(e) {
        }

    };

    this.initInstall = function() {
	    this._ui.displayStep('installation');
		this._upgrade = Collactive.CSAUtils.hasCSA();
        if (this._isIE()) {
           this._initIEInstall();
        } else if (this._isFirefox()) {
           this._initFirefoxInstall();
        } else {
           alert("Your browser does not support Collactive Web Assistant, which is required for proceeding.\nCurrently only Internet Explorer and Firefox browsers are supported.");
        }
    };
};
