BROWSER_INTERFACE = false;

RAPIDX_CONTROL_NAME = "rapidxControl";
RAPIDX_PLUGIN_NAME = "GO-Global Browser Add-On";
RAPIDX_PLUGIN_TYPE = "application/x-gg-client-plugin";
RAPIDX_PLUGIN_CODEBASE = "plugins/gg-activex.cab";
RAPIDX_PLUGIN_CLASS_ID = "CLSID:1241F20B-0688-45A5-ADB2-208AFE4A5DDC";
RAPIDX_ROOT_ID = "Ieg.IEGCtrl";

window.onload = init;
var chromeInstalled = false;
var browser = new GetPlatform();
var controlArguments = new Object;

if (browser.chrome)
{
	var request = new XMLHttpRequest();  
	request.open('GET', 'chrome-extension://kkehppgllpkfohejllckommnpfeomhnc/main.html', true);
	request.onreadystatechange = function(){
		if ((request.readyState == 4) && (request.status == 0))
		{
			chromeInstalled = false;	
		}
		else
		{
			chromeInstalled = true;
		}
	};
	request.send();
}

var controlArgs = controlArgs || (function(){
    return { set : function(Args) { controlArguments[Args[0]] = Args[1]; } };
}());

function init() {
	if (document.getElementById("controlFrame") == null)
	{
		// we're being called from a page that doesn't load the plugin or ActiveX control.
		return;
	}
	
	if (browser.chrome)
	{
		var request = new XMLHttpRequest();  
		request.open('GET', 'chrome-extension://kkehppgllpkfohejllckommnpfeomhnc/main.html', true);
		request.onreadystatechange = function(){
			if ((request.readyState == 4) && (request.status == 0))
			{
				DisplayInstallationInstructions();
			}
			else if ((request.readyState == 4) && (request.status == 200))
			{
				if (location.search.substr(1).search("forceUpgrade=true") != -1)
				{
					DisplayInstallationInstructions();
					return;
				}			
			
				var chromeUrl = "chrome-extension://kkehppgllpkfohejllckommnpfeomhnc/main.html?" + location.search.substr(1);
				
				if (location.search.substr(1) == "")
				{
					chromeUrl = "chrome-extension://kkehppgllpkfohejllckommnpfeomhnc/main.html?h=" + window.location.hostname;
				}
				
				if ((location.search.substr(1).search("h=") != 0) && (location.search.substr(1).search("&h=") == -1) &&
					(location.search.substr(1).search("host=") != 0) && (location.search.substr(1).search("&host=") == -1))
				{
					chromeUrl = chromeUrl + "&h=" + window.location.hostname;
				}
				
				// Process any arguments added in logon.html
				for (var property in controlArguments) {
					if (controlArguments.hasOwnProperty(property))
					{
						chromeUrl = chromeUrl + "&" + property + "=" + controlArguments[property];
					}
				}
				
				// Add the version so that the Chrome Extension can compare it to the currently used version.
				chromeUrl += "&version=" + GG_VERSION_PERIOD;
				window.location = chromeUrl;
			}
		};
		request.send();
	}
	else if (browser.firefox || browser.safari)
	{		
		if (IsInstalled())
		{			
			// <embed id="rapidxControl" type="application/x-gg-client-plugin" alt="GO-Global Browser Plug-in"/>
			var newControl = document.createElement("embed");
			newControl.id = RAPIDX_CONTROL_NAME;
			newControl.type = RAPIDX_PLUGIN_TYPE;
			newControl.alt = RAPIDX_PLUGIN_NAME;
			writeURLVars(newControl, "embed");
			
			var frame = document.getElementById('controlFrame');
			frame.appendChild(newControl);
												
			if ((GG_VERSION_PERIOD > GetPluginVersion()) && (browser.win))
			{
				var notify = document.getElementById('notificationFrame');
				notify.innerHTML = '<a class="bright" href="javascript:DisplayInstallationInstructions();"><b>Upgrade Add-on</b></a>';
			}
			else
			{
				var bar = document.getElementById('barFrame');
				bar.parentNode.removeChild(bar);
			}
			
			window.document.rapidxControl.focus();
		}
		else
		{
			if (browser.mac)
			{
				window.location = "installMac.html?plugin=true";
			}
			else if (browser.linux)
			{				
				InstallXPI();
			}
			else
			{
				DisplayInstallationInstructions();
			}		
		}
	}
	else if (browser.msie)
	{
		if (isActiveXControlInstalled())
		{			
			// <object id="rapidxControl" name="rapidxControl" classid="CLSID:1241F20B-0688-45A5-ADB2-208AFE4A5DDC" alt="GO-Global ActiveX Control" codebase="plugins/gg-activex.cab"></object>
			var newControl = document.createElement("object");
			newControl.id = RAPIDX_CONTROL_NAME;
			newControl.name = RAPIDX_CONTROL_NAME;
			newControl.classid = RAPIDX_PLUGIN_CLASS_ID;
			newControl.alt = RAPIDX_PLUGIN_NAME;
			newControl.setAttribute("codebase", RAPIDX_PLUGIN_CODEBASE);
			writeURLVars(newControl, "object");
			
			var frame = document.getElementById('controlFrame');
			frame.appendChild(newControl);
			
			if (browser.msie10orlower)
			{
				// reload the control's HTML in IE10 and lower. appendChild() should do this, but it has no effect pre-IE11.
				var objectHTML = frame.innerHTML;
				frame.innerHTML = objectHTML;
			}
						
			if (GG_VERSION_PERIOD > GetPluginVersion())
			{
				var notify = document.getElementById('notificationFrame');
				notify.innerHTML = '<a class="bright" href="javascript:DisplayInstallationInstructions();"><b>Upgrade Add-on</b></a>';
			}
			else
			{
				var bar = document.getElementById('barFrame');
				bar.parentNode.removeChild(bar);
			}
			
			window.document.rapidxControl.focus();	
		}
		else
		{
			DisplayInstallationInstructions();
		}
	}
	else
	{	
		document.getElementById('msgFrame').innerHTML = '<img src="logon_logo.png" border=0 alt="http://www.GraphOn.com">\
		<h3>Incompatible Browser</h3>\
		<p>Your browser is not currently supported. Please use Firefox, Safari, Chrome or Internet Explorer.</p>';
	}	
	
	if (BROWSER_INTERFACE == true)
	{
		EnterCallbackLoop();
	}
}

function writeURLVars(control, type) {

	var width = 0;
	var height = 0;
	var isEmbedded = false;
	var query = location.search.substr(1);	
	var data = query.split("&");
	
	// Process any arguments added in logon.html
	for (var property in controlArguments) {
		if (controlArguments.hasOwnProperty(property)) {
			if (data[0] == "")
			{
				data[0] = property + "=" + controlArguments[property];
			}
			else
			{
				data[data.length] = property + "=" + controlArguments[property];
			}
		}
	}

	if (data[0] == "")
	{
		// No URL or arguments to process
		control.setAttribute("width", "0");
		control.setAttribute("height", "0");
		return;
	}

    try
	{ 	
		for (var i = 0; i < data.length; i++)
		{		
			var item = data[i].split("=");
			
			var name = item[0];
			var value = decodeURIComponent(item[1]);
			
			switch (name) {	
				case "bInBrowser":
					name = "inbrowserprocess";
					break;
				case "app":
					name = "application";
					break;
				case "embed":
					name = "isembeddedwin";
					isEmbedded = true;
					break;
				case "port":
					name = "hostport";
					break;			
				case "autoclose":
					name = "autoclosebrowser";
					break;					
				case "printerconfig":
					name = "autoconfigprinters";
					break;			
				case "width":
					width = value;
					break;			
				case "height":
					height = value;
					break;
				default:
					// supported by default: user, password, host, compression, clientframe, multimonitor, noscale,
					// authority, credentials, sessionid, autoreconnect, windowless, maxbpp, keyboard, desktop, args
					break;
			}
			
			if (type == "embed")
			{
				control.setAttribute(name, value);
			}
			else if (type = "object")
			{
				switch (name)
				{	
					case "width":
					case "height":
						control.setAttribute(name, value);
						break;
					default:
						var param = document.createElement("param");
						param.setAttribute("name", name);
						param.setAttribute("value", value);
						control.appendChild(param);
						
						if ((name == "isembeddedwin") && (value == "true"))
						{						
							var param2 = document.createElement("param");
							param2.setAttribute("name", "bInBrowser");
							param2.setAttribute("value", "true");
							control.appendChild(param2);					
						}
						
						break;
				}			
			}
		}
		
		if (isEmbedded == true)
		{				
			if (width == 0)
			{
				control.setAttribute("width", "100%");
			}
			
			if (height == 0)
			{
				control.setAttribute("height", "100%");
			}
		}
		else
		{		
			if (width == 0)
			{
				control.setAttribute("width", "0");
			}
			
			if (height == 0)
			{
				control.setAttribute("height", "0");
			}		
		}
    }
	catch(err)
	{
		console.log("writeURLVars(): " + err);
	}
    console.log();
}

function GetPlatform()
{
	// Browser name string, major version, and agent string
	var name     = navigator.appName;
	var ver      = parseInt(navigator.appVersion);
	var agent    = navigator.userAgent;
	var platform = navigator.platform;

	// Microsoft Internet Explorer and version
	this.msie     = (document.documentMode != undefined);
	this.msie4up  = (document.documentMode >= 4);  
	this.msie6up  = (document.documentMode >= 6);
	this.msie7up  = (document.documentMode >= 7);
	this.msie10orlower  = (document.documentMode <= 10);

	// Netscape Navigator and version
	this.ns = (name.indexOf("Netscape") != -1);
	this.ns4up = (this.ns && (ver >= 4));

	// Netscape 6 version is actually version 5.0 when getting the appVersion property.	
	this.ns6up = (this.ns && (ver >= 5));

	this.ff3     = (agent.toLowerCase().indexOf("firefox/3") != -1);
	this.ff4     = (agent.toLowerCase().indexOf("firefox/4") != -1);
	this.firefox = (agent.toLowerCase().indexOf("firefox") != -1);

	this.chrome  = (agent.toLowerCase().indexOf("chrome") != -1);
	
	if (this.chrome == true)
	{
		this.safari = false;
	}
	else
	{
		this.safari = (agent.toLowerCase().indexOf("safari") != -1);
	}

	// Operating system, test both Netscape agent or MSIE agent strings.
	this.win95 = ((agent.indexOf("Win95")!=-1) || (agent.indexOf("Windows 95")!=-1));
	this.win98 = ((agent.indexOf("Win98")!=-1) || (agent.indexOf("Windows 98")!=-1));
	this.winnt = ((agent.indexOf("WinNT")!=-1) || (agent.indexOf("Windows NT")!=-1));
	this.win   = (agent.indexOf("Win") != -1);
	this.mac   = (agent.indexOf("Mac") != -1);
	this.sun   = (agent.indexOf("SunOS") != -1);
	this.linux = (agent.indexOf("Linux") != -1);
	this.os2   = (agent.indexOf("OS2") != -1) || (agent.indexOf("OS/2") != -1);
	this.ce    = (platform.indexOf("CE") != -1);
	this.ppc   = (agent.indexOf("PPC") != -1);
}


function IsInstalled()
{
	var browserInfo = GetPlatform();
	
	if (browser.chrome == true)
	{
		return chromeInstalled;
	}
	
	var pluginFound = false;

	if (navigator.plugins && navigator.plugins.length > 0) 
	{
		var pluginsArrayLength = navigator.plugins.length;

		for (pluginsArrayCounter=0; pluginFound != true && pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ )
		{
			var plugin=navigator.plugins[pluginsArrayCounter];
		
			for (type = 0; type < plugin.length; type++)
			{	
				if (plugin[type].type != null)
				{
					if (plugin[type].type.toLowerCase().indexOf(RAPIDX_PLUGIN_TYPE) != -1)
					{
						pluginFound = true;
						break;
					}	
				}
			}
		}
	}
	return pluginFound;
}

function InstallXPI()
{
    var browser = new GetPlatform();
	
    if (browser.firefox)
    {
        if (!IsInstalled())
        {
            var xpi = {'RapidX Firefox Plugin':'plugins/gg-nsplugin_ff3.windows.xpi'};  // default
            if ( browser.linux )
            {
                xpi = {'RapidX Firefox Plugin':'plugins/gg-nsplugin_ff3.linux.xpi'};
            }
            InstallTrigger.install(xpi);
        }
    }
    else
    {
       document.write("<p>Your browser is not currently supported.</p>");
    }
} 

function GetSearchString()
{
	return_value = '';
	get_string = document.location.search;

	if (get_string != '')
	{
		question_index = get_string.indexOf('?');
		return_value = get_string.substr(question_index + 1, get_string.length - 1);
	}

	return (return_value);  
}

function GetVarDecoded(name)
{
    var result = GetVar(name);
    return decodeURIComponent(result);
}

function GetVar(name)
{
	get_string = document.location.search;         
	return_value = '';
	
	do 
	{
		name_index = get_string.indexOf(name + '=');
		
		if (name_index != -1)
		{
			get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);
			
			end_of_value = get_string.indexOf('&');

			if (end_of_value != -1)     
			{           
				value = get_string.substr(0, end_of_value);       
			}         
			else                
			{
				value = get_string;        
			}        
			
			if (return_value == '' || value == '')
			{
				return_value += value;
			}
			else
			{
				return_value += ', ' + value;
			}
		}
	} 
	while (name_index != -1)
	
	space = return_value.indexOf('+');

	while (space != -1)
	{ 
		return_value = return_value.substr(0, space) + ' ' + 
		return_value.substr(space + 1, return_value.length);
		space = return_value.indexOf('+');
	}

	return (return_value);
}

function InstallXPISilent()
{
	var browser = new GetPlatform();

	if (browser.firefox || browser.safari)
	{
		if (!IsInstalled())
		{
			InstallXPI();
		}
	}
}

function GetDocumentTitle()
{
    var title = "GO-Global";

    return title;
}

function GetHostConfig(paramName)
{
	var retVal = "";
	
	try
	{
		retVal = document.getElementById(RAPIDX_CONTROL_NAME).GetHostConfig(paramName);
	}
	catch(err){}
	
	return retVal;
}

function SetHostConfig(paramName, paramValue)
{
	var retVal = 0;
	
	try
	{
		retVal = document.getElementById(RAPIDX_CONTROL_NAME).SetHostConfig(paramName, paramValue);
	}
	catch(err){}
	
	return retVal;
}

function InstallHost()
{
	var retVal = 0;
	
	try
	{
		retVal = document.getElementById(RAPIDX_CONTROL_NAME).InstallHost();
	}
	catch(err){}
	
	return retVal;
}

function ConnectHostToGateway()
{
	var retVal = 0;
	
	try
	{
		retVal = document.getElementById(RAPIDX_CONTROL_NAME).ConnectHostToGateway();
	}
	catch(err){}
	
	return retVal;
}

function PromptForReboot(message, caption)
{
	var retVal = 0;
	
	try
	{
		retVal = document.getElementById(RAPIDX_CONTROL_NAME).PromptForReboot(message, caption);
	}
	catch(err){}
	
	return retVal;
}

function InstallerDownloadProgress()
{	
	if (arguments.length > 0)
	{
		var percentComplete = arguments[0];
		
		if (percentComplete < 100)
		{
			document.getElementById('myAnchor').innerHTML = 'Downloading GO-Global Online. Percent complete: ' + percentComplete + '%.';
		}
		else
		{
			document.getElementById('myAnchor').innerHTML = 'Installing GO-Global Online.';
		}
	}

	return ReturnValue(percentComplete );
}

function HostConfigComplete()
{
	var key = GetHostConfig("key");

	document.getElementById('myAnchor').innerHTML = 'Installation Complete.';
	
	//alert(key);
	// TODO: call the register host API on the Gateway to update the public key.
	
	PromptForReboot("GO-Global Online has finished installing. A restart is required. Would you like to restart now?", "Restart Windows")
}

function callGetHostStatus(timeout) {
    var retVal = 0;
    try { 
        retVal = document.getElementById(RAPIDX_CONTROL_NAME).GetHostStatus(timeout);
    } catch(err) { console.log("GetHostStatus("+timeout+"): "+err); }
    console.log(timeout + "=" + retVal);
    return retVal;
}

function callIsRemoteAccessAllowed() {
    var retVal = 0;
    try { 
        retVal = document.getElementById(RAPIDX_CONTROL_NAME).IsRemoteAccessAllowed();
    } catch(err) { console.log("IsRemoteAccessAllowed(): "+err); }
    console.log(retVal);
    return retVal;
}

function GetPluginVersion()
{
    var retVal = "";
	
	try
	{
		if (browser.msie)
		{
			retVal = document.getElementById(RAPIDX_CONTROL_NAME).GetPluginVersion();
		}
		else if (browser.firefox || browser.safari)
		{
			var numPlugins = navigator.plugins.length;

			for (var i = 0 ; i < numPlugins; i++)
			{
				if (navigator.plugins[i].filename == "npg4.dll")
				{
					retVal = navigator.plugins[i].version;
					break;
				}
			}	
		}
	}
	catch(err){}
	
	return retVal;
}

function isActiveXControlInstalled(){
    axobj = null;
	
    try {
        axobj = new ActiveXObject(RAPIDX_ROOT_ID);
    }
    catch(e) {}
	
    if (axobj) {
		axobj = null;
        return true;
    }
	
    return false;
}

function DisplayInstallationInstructions(){
		if (browser.msie)
		{
			document.getElementById('msgFrame').innerHTML = '<p><ul><li><b>PMS</b> benötigt ein Browser Add-on um ausgeführt zu werden:<li>\
				<li>&nbsp;</li>\
				<li><a href="clients/gg-client.ie.exe"><b>Laden Sie</b></a> das GO-Global Add-on Installationspaket.</li>\
				<li><b>Installieren</b></a> Sie das Add-on und folgen den Anweisungen.</li>\
				<li><b>Starten</b> Sie Ihren Browser neu um die Installation abzuschließen.</li></ul></p>';
		}
		else if (browser.firefox)
		{
			document.getElementById('msgFrame').innerHTML = '<p><ul><li><b>PMS</b> benötigt ein Browser Add-on um ausgeführt zu werden:<li>\
				<li>&nbsp;</li>\
				<li><a href="clients/gg-client.firefox.exe"><b>Laden Sie</b></a> das GO-Global Add-on Installationspaket.</li>\
				<li><b>Installieren</b></a> Sie das Add-on und folgen den Anweisungen.</li>\
				<li><b>Starten</b> Sie Ihren Browser neu um die Installation abzuschließen.</li></ul></p>';
		}
		else if (browser.chrome)
		{
			document.getElementById('msgFrame').innerHTML = '<p><ul><li><b>PMS</b> benötigt ein Browser Add-on um ausgeführt zu werden:<li>\
				<li>&nbsp;</li>\
				<li><a href="clients/gg-client.chrome.exe"><b>Laden Sie</b></a> das GO-Global Add-on Installationspaket.</li>\
				<li><b>Installieren</b></a> Sie das Add-on und folgen den Anweisungen.</li>\
				<li><a href="https://chrome.google.com/webstore/detail/kkehppgllpkfohejllckommnpfeomhnc" target="_blank"><b>Installieren</b></a> Sie die Erweiterung über den Chrome Web Store.</li>\
				<li><b>Laden</b> Sie die Seite neu um die Installation abzuschließen.</li></ul></p>';
		}
}