// downloader.js
// Dowload and launch PowerTerm WebConnect Agent using the appropriate download mechanism for the browser and OS
// All functions and globals are prefixed by PT_ to avoid namespace conflicts.
//
// Requires the following input values (as global vars):
//	PT_windowsDownloaderURL		- URL to the Windows Downloader
//	PT_ns6DownloaderURL		- URL to the Java Downloader for NS6 and Mozilla (Firefox)
//	PT_identifyJVM			- URL to the JVM identification applet for IE
//	PT_javaDownloaderImagesURL	- URL to images which Downloader uses
//	PT_windowsAgentURL 		- URL to the Windows agent (used by the Downloader)
//	PT_linuxAgentURL 		- URL to the Linux agent (used by the Downloader)
//	PT_agentParameters 		- Agent parameters
//	PT_selectedConnection		- Selected connection to activate
//	PT_downloaderLog		- Downloader log location (emppty means no log)

// Ericom Software, 2008

// Determine client's Operating System name
function PT_getOS()
{
	var platform = navigator.platform;
	if (platform.indexOf("Linux") >= 0)
		return "Linux";
	if (platform.indexOf("Solaris") >= 0)
		return "Solaris";
	if (platform.indexOf("Mac") >= 0)
		return "Mac";
	return "Windows";
}

// Determine client's browser name (IE, MZ, NS4, NS6 or HJ)
function PT_getBrowser()
{
	var appName = navigator.appName;
	if (appName.indexOf("Mozilla") >= 0)
		return "MZ";
	if (appName.indexOf("Netscape") >= 0)
		return appName.indexOf("HotJava") >= 0 ? "HJ" : parseFloat(navigator.appVersion) >= 5 ? "NS6" : "NS4";
	return "IE";
}

// Determine client's browser version
function PT_getBrowserVersion()
{
	var browser = PT_getBrowser();
	var version = navigator.appVersion;
	switch (browser) {
		case "IE":
			var verpos = version.indexOf("MSIE");
			var versendpos = version.indexOf(";", verpos);
			var subversion = version.substring(verpos + 5, versendpos);
			return "IE v." + subversion;

		case "HJ":
			return "HJ v." + version;

		case "NS6":
		case "NS4":
			return "NS v." + version;

		default:
			return browser;
	}
}

function PT_getArchive()
{
    return ' archive="' + PT_ns6DownloaderURL + '">';
}

// Generate applet tag with with OS and browser values passed as parameters 
function PT_appletByOS(os)
{
	var applet		= '<applet width="1" height="1" code="Downloader.class" ';
	var paramOS     	= '<param name="OS"   value="' + os + '">';	
	var paramBrowser 	= '<param name="brow" value="' + PT_getBrowserVersion() + '">';
	var paramImage		= '<param name="img" value="' + PT_javaDownloaderImagesURL + '">';
	return applet + PT_getArchive() + paramOS + paramBrowser + paramImage;
}

// Generate applet parameters based on operating system (Windows or UNIX-like)
function PT_appletParameters(os)
{
	var sParamURL, sParamDestPath, sParamExe, sAddParam, sParamInstall;
	if (os == "Windows") {
		sParamURL	= '<param name="src" value="' + PT_windowsAgentURL + '">';
		sParamDestPath	= '<param name="dst" value="' + PT_clientDst + '">';
		sParamExe	= '<param name="parameters" value="' + PT_agentParameters + ' /NOSELFUPDATE ' + PT_selectedConnection + '">';
		sAddParam	= '<param name="add_param"  value=""> ';
		sParamInstall	= '<param name="install"    value=""> ';
	}
	else {
		sParamURL	= '<param name="src" value="' + PT_linuxAgentURL + '">';
		sParamDestPath	= '<param name="dst" value="/opt/WebConnectPtAgent">';
		sParamExe	= '<param name="parameters" value="' + PT_agentParameters + ' /SHORTCUT=Disabled ' + PT_selectedConnection + '">';
		sAddParam	= '<param name="add_param"  value="SHORTCUT_DISABLE">';
		sParamInstall	= '<param name="install"    value=""> ';
	}
	return sParamURL + sParamDestPath + sParamExe + sAddParam + sParamInstall;
}

// Generate the complete applet tag
function PT_applet(os, browser)
{
    var response = PT_appletByOS(os) + PT_appletParameters(os) + "</applet>";
    
    //changed code to add functionality for AZ from new clienturls. code needs to be polished in next versions
    if (location.pathname.toLowerCase().indexOf("applicationzone.html") > 0)
    {
        var setApp = /Downloader_NS6WS_Signed.jar\S/;
        var setAppCor = "Downloader_NS6WS_Signed.jar\" mayscript=\"mayscript\"";

        var setCallJS = /<param name=\Ssrc\S value=[^>]+qterm-wc.zip\S>/;
        var setCallJSCor = "<param name=\"log\" value=\"\">";
        setCallJSCor += "<param name=\"console\" value=\"false\">";
        setCallJSCor += "<param name=\"call_js\" value=\"false\">";
        setCallJSCor += "<param name=\"src\" value=\"" + PT_linuxAgentURL + "\"> ";
            
        var setParama = /name=.parameters. value=.[^\>]*>/i;
        var setParamaCor = "name=\"parameters\" value=\" -wc-client " + location.hostname + " \/NOSELFUPDATE \/SHORTCUT=BOTH \/AUTOLOGIN=NO\">";

        var setAddparam = /name=.add_param.\s*value=.SHORTCUT_DISABLE./i;
        var setAddparamCor = "name=\"add_param\" value=\"SHORTCUT_DESKTOP\"";
            
        response = response.replace(setApp,         setAppCor);
        response = response.replace(setCallJS,      setCallJSCor);
        response = response.replace(setParama,      setParamaCor);
        response = response.replace(setAddparam,    setAddparamCor);
        
    }

    return response;
}

// Write to target IFRAME
function PT_writeToTarget(html)
{
	var doc = PT_target.document;
	doc.open();
	doc.writeln(html);
	doc.close();
}

// With IE only new SUN JVM can be used (not old MS JVM)
function PT_checkJVMSupport(JVMVersion, JVMVendor)
{
	if ((JVMVendor.indexOf("MS") >= 0 || JVMVendor.indexOf("Microsoft") >= 0) && JVMVersion <= "1.1.8")
		return false;

	if (JVMVendor.indexOf("Sun") >= 0 && sJVMVersion >= "1.4.0")
		return true;

	return false;
}

// Write downloader applet into IFRAME
function runJavaClientIE(JVMVersion, JVMVendor, os)
{
	os = PT_getOS()
	if (PT_checkJVMSupport(JVMVersion, JVMVendor))
		PT_writeToTarget(PT_appletByOS(os) + PT_appletParameters(os) + "</applet>");
	else
		alert("This Java version is not supported.\n" +
		      "For more information about system requirements " +
		      "see the PowerTerm WebConnect documentation.\n" +
		      "To upgrade the Java version please contact your System Administrator." );
}

// Write applet into IFRAME that determines the JVM type
function PT_javaDownloader()
{
	if (navigator.javaEnabled() &&
	    window.confirm("Do you want to download and install \nthe PowerTerm WebConnect client using Java Applet?")) {
		var os      = PT_getOS();
		var browser = PT_getBrowser();
		PT_writeToTarget(PT_applet(os, browser));
	}
	return false;
}


function compareVersion(v, u)
{
	var a = u.split(".");
	var b = v.split(".");
	for ( var i = 0 ; i < a.length ; ++i ) {
		var x = parseInt(a[i]);
		var y = parseInt(b[i]);
		if (x > y)
			return false;
	}
	return true;
}

//on FireFox, install AZ through XPI
function PowerTermXPInstall()
{
 // Address of the WebConnect server
// Leave as is if the WebConnect server is installed on the same computer as the Web server
// Replace with explicit address if WebConnect server is installed on a different computer
//
var server = location.hostname;

// The version of the WebConnect Agent component
// Component will only be downloaded if the online version is newer (higher version number)
// than the Agent already installed
//
var version = "5,6,0,1007";

// The location of the PtAgent.zip
// Leave as is if the file is located next to this html file
//
var url = "linux/ix86/qterm-wc.zip";

// The local directory in which to install the Agent package
//
var dest = "/opt/WebConnectPtAgent";

var xpi_params = "#/NOSELFUPDATE#/SHORTCUT=BOTH#/AUTOLOGIN=NO";


	var CVR_Name = dest + "/qterm-wc";
	var installedVersion = InstallTrigger.getVersion(CVR_Name);
	installedVersion = installedVersion ? String(installedVersion) : "-1";
	if (compareVersion(installedVersion, version))
		return false;

	var args =  server + xpi_params + ";" + version + ";" + dest;
	var xpi = {
		"Ericom PowerTerm WebConnect Application Zone for Linux" :
		url + "?" + args
	};
	InstallTrigger.install(xpi);
	return true;
}


// Create and write the downloader directly into the HTML
function PT_downloader()
{
	var os = PT_getOS();
	var browser = PT_getBrowser();
	if (browser.indexOf("NS4") > 0 || browser.indexOf("HJ") > 0) 
        {
		alert("PowerTerm WebConnect Application Portal does not support this browser.\n" +
			"For more information about system requirements "+
			"see the PowerTerm WebConnect documentation.\n" +
			"To upgrade your browser please contact your System Administrator.");
	}
	else if (os != "Windows" || browser != "IE") 
        {
		// None-Microsoft - use applet
		if (navigator.javaEnabled())
			document.writeln(PT_applet(os, browser));
		else
		    if (navigator.userAgent.toLowerCase().indexOf("firefox") > 0)//) 
		    {
		        //browser is FF, not JavaEnabled
		        if (!PowerTermXPInstall())
		            alert("PowerTerm WebConnect Application Zone for Linux already installed.\nDouble-click PtAgent desktop icon to launch the application.");
		    }
		    else
		    {
		        //browser is not FF, not JavaEnabled
			alert("PowerTerm WebConnect Application Portal requires Java in order to support this platform.\n" +
			      "To install Java please contact your System Administrator.");
	            }
	}
	else 
        {
		// Windows & IE - try to use ActiveX and if that fails use applet
		document.writeln('<IFRAME ID="PT_target" WIDTH=0 HEIGHT=0 SRC="Empty.html"></IFRAME>');
		document.writeln('<OBJECT ID="Downloader" WIDTH=0 HEIGHT=0 STYLE="DISPLAY:none" ' +
				 'CODEBASE="' + PT_windowsDownloaderURL + '#Version=5,6,0,1007" ' +
				 'CLASSID="CLSID:7EC816D4-6FC3-4C58-A7DA-A770EE461602" ' +
				 'ONERROR="window.setTimeout(\'PT_javaDownloader()\', 8000)">' +
				 '<PARAM NAME="Src" VALUE="' + PT_windowsAgentURL + '">' +
				 '<PARAM NAME="Dst" VALUE="' + PT_clientDst + '">' +
				 '<PARAM NAME="Parameters" VALUE="' + PT_agentParameters + ' /NOSELFUPDATE ' + PT_selectedConnection + '">' +
				 '<PARAM NAME="Log" VALUE="' + PT_downloaderLog + '">' +
				 '</OBJECT>');
	}
}

// Generate the downloader
PT_downloader();
