/**
 * Java auto installation wizard
 *  
 * creates global scope class JavaWebStartAutoInstall with parametrized constructor 
 * and method launch(). Method launch provides JNLP invocation with Java Web Start 
 * environment check. (appJnlpUrl, version, detectFailureMsg, ..) are parametrized.
 *
 * @category Symmetrics
 * @package Symmetrics_Filechunkupload
 * @author symmetrics gmbh <info@symmetrics.de>, Yauhen Yakimovich <yy@symmetrics.de>
 * @copyright symmetrics gmbh
 * @license http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */


var JavaWebStartAutoInstall = function() {

    var agentInfo = navigator.userAgent.toLowerCase();

    var launchTID = false;       

    var RETRIES_LIMIT = 10 * 600; // 10 min

    var INTERVAL_TIME = 100;

    var JAVA_UPDATE_OBJECT = 'codebase="http://java.sun.com/update/1.6.0/jinstall-1_6-windows-i586.cab#Version=6,0,0,0"';    
    JAVA_UPDATE_OBJECT +=  'classid="clsid:5852F5ED-8BF4-11D4-A245-0080C6F74284"';

    var DETECT_FAILURE_MSG = 'Java Web Start is not found in your System Environment. ';
    DETECT_FAILURE_MSG += 'Please, make sure to download and install latest <A href="http://jdl.sun.com/webapps/getjava/BrowserRedirect?locale=en&host=java.com">Java RE</a> ';
    DETECT_FAILURE_MSG += 'in order to use our application. We also kindly recommend you to use a free browser ';
    DETECT_FAILURE_MSG += '<a href="http://www.mozilla.com/firefox/">Mozilla Firefox</a> in case of additional troubleshooting.';


    function JavaAutoInstall(appJnlpUrl, version, detectFailureMsg, doContinousLaunch,  detectFailureCallback) {
        // URL to JNLP description of Java Web Start application
        this.appJnlpUrl = appJnlpUrl;

    	// version of Java Runtime to be checked/installed
        if (version == null)  {
            this.version = '1.6';
        } else {
        	this.version = version;
        }

        // Text shown in case of detection failure
        if (detectFailureMsg == null)  {
            this.detectFailureMsg = DETECT_FAILURE_MSG;
        } else {
            this.detectFailureMsg = detectFailureMsg;
        }        

        // if true, we continously check for webstart in background to do the launch
        this.doContinousLaunch = (doContinousLaunch != null);

        // external callback function for failure msg reporting
        this.detectFailureCallback = detectFailureCallback;

        this.retry = 0;

        this.checkPlatform = function(string) {
            place = agentInfo.indexOf(string) + 1;
            return place;
        }

        // true if MS Windows and IE detected
        this.isWindowsIE = this.checkPlatform("msie") && this.checkPlatform("win");

        // check Java is detectable
        this.browserCanDetectWebStart = function() {
            // Check if browser is IE or Mozilla (has mime types)
            return (this.isWindowsIE || navigator.mimeTypes && navigator.mimeTypes.length);
        }

        // launch Java
        this.launchJava = function() {
            if (this.isWindowsIE) {
                //this.launchJavaIE();
                this.launchJavaIeAlt();
            } else {
                this.launchJavaMozilla();
            }
        }

        // launch java for IE browsers
        this.launchJavaIE = function() {
            document.open();
            document.write('<OBJECT ' + JAVA_UPDATE_OBJECT + ' height=0 width=0>');
            document.write("<PARAM name=app VALUE=" + this.appJnlpUrl + ">");
        	document.write("<PARAM NAME=back VALUE=false>");
            document.write('<!-- Alternate HTML for browsers which cannot instantiate the object -->');
            document.write(this.detectFailureMsg);
        	document.write("</OBJECT>");
            document.close();
        }

        // alternative IE launch
        this.launchJavaIeAlt = function() {
            if (this.webstartCheckIE()) {
            	// We have Java Web Start installed
                window.location = this.appJnlpUrl;
            } else {
                this.installJava();
            }
        }

        // launch java for non-IE browsers
        this.launchJavaMozilla = function() {
            if (this.webstartCheckMozilla()) {
                window.location = this.appJnlpUrl;
            } else {
                this.installJava();
            }
        }

        // report detection failure, open link to java download
        this.installJava = function () {
            if (this.doContinousLaunch) {
                continousJnlpLaunch = this.continousJnlpLaunch;
                launchTID=setInterval('continousJnlpLaunch', INTERVAL_TIME);
            }
            this.reportFailure();
            window.open("http://jdl.sun.com/webapps/getjava/BrowserRedirect?locale=en&host=java.com",
                "Java_Download"
            );
        }

        // repeatedly attempt to check and launch web start application
        this.continousJnlpLaunch = function () {
            // check if java was installed
            if (this.webstartCheck()) {
                clearInterval(launchTID);
                window.location = this.appJnlpUrl;
            }
            // assert retries
            if (this.retry >= RETRIES_LIMIT) {
                // no more retries left
                clearInterval(launchTID);
                this.retry++;
            }
        }
        
        if (this.isWindowsIE) {
            this.webstartCheck = this.webstartCheckIE;
        } else {
            this.webstartCheck = this.webstartCheckMozilla;
        }

        this.webstartCheckIE = function() {
            // check if ActiveX objects can be created
            var pluginObject = null;
            var jwsObject = null;
            try {
                // Create Sun Java plugin ActiveX object
                pluginObject = new ActiveXObject("JavaPlugin");
                // Create Java Web Start ActiveX object
                jwsObject = new ActiveXObject("JavaWebStart.isInstalled");
            } catch(e)  { // they cannot be created
            	// Sun Java plugin and Java Web Start not installed
                return false;
            }
            return (jwsObject != null);
        }

        this.webstartCheckMozilla = function() {
            // Mozilla may not recognize new plugins without this refresh
            navigator.plugins.refresh(false); // false = refresh without open documents
            // Check if browser has mime types
            if (!(navigator.mimeTypes && navigator.mimeTypes.length))
                return false;
            // Determine if Web Start is available
            if (navigator.mimeTypes['application/x-java-jnlp-file']) {
                return true;
            }
            return false;
        }

        // report detection failure 
        this.reportFailure = function() {
            if (this.detectFailureCallback != null) {
                // call external function to do failure reporting
                this.detectFailureCallback();
            }else{
                document.open();
                document.write(this.detectFailureMsg);
                document.close();
            }
        }

        // perform Java auto install if required, otherwise launch jnlp applications
        this.launch = function() {
            if (this.browserCanDetectWebStart()) {
                this.launchJava();
            } else {
                this.reportFailure();
            }
        }
    }

    // return a reference to a class constructor
    return JavaAutoInstall;
}();

