var oXmlHttp,keyFilePath,TrialIDCode;

function findKeyType(verbose)
{
	loadConfiguration();

	var index, i;
	var productTypes, keyTypes, key, productTypeNames, keyTypesNames;
	var channelID = -1;
	var prodGUID = -1;
	var foundKey = -1;
	var channelFound = -1;
	var ProductTypeID = -1;
	var temp = -1;
	var selectedKey = -1;
	var NodeList;
	var OutString;
	var OutStringTwo;

	OutString = "";
	OutStringTwo = "";

	var fso = new ActiveXObject("Scripting.FileSystemObject");

	Node = g_axConfigurationXml.selectSingleNode("/configuration/regKey");
	NodeList = Node.childNodes;

	var keyStart = NodeList(0).getAttribute('keyStart');
	var keyEnd = NodeList(0).getAttribute('keyEnd');

	Node = g_axConfigurationXml.selectSingleNode("/configuration/programMode");
	NodeList = Node.childNodes;

	var ErrorMode = NodeList(0).getAttribute('value');

	if (ErrorMode == 1)
	{
		showErrorMessage(1);
		setTimeout('showErrorMessage(2);', 7000);
		setTimeout('showErrorMessage(3);', 14000);
		setTimeout('showErrorMessage(4);', 21000);
		setTimeout('showErrorMessage(5);', 28000);

		return -1;
	}

	Node = g_axConfigurationXml.selectSingleNode("/configuration/keyTypes/officeProducts");
	NodeList = Node.childNodes;

	for (i=0; i < NodeList.length; i++)
	{
		OutString += NodeList(i).getAttribute('guidFragment') + ",";
		OutStringTwo += NodeList(i).getAttribute('name') + ",";
	}

	productTypes = OutString;

	if (productTypes != undefined)
	{
		productTypes = productTypes.split(",");
		productTypesNames = OutStringTwo.split(",");

		//Look through the items in the config and get part of the GUID key
		for (index = 0; index < productTypes.length; index++)
		{
			prodGUID = productTypes[index];

			//Now that we found the one we were looking for, we can see if the key exists in the registry
			if (prodGUID != undefined)
			{
				key = keyStart + prodGUID + keyEnd;

				if (KeyExists(key) == 1)
				{
					ProductTypeName = productTypesNames[index];

					if (ProductTypeName != undefined)
					{
						foundKey = 1;
						break;
					}
				}
			}
		}

		if (foundKey == 1)
		{
			//get full path to keyfile text file
			keyFilePath = getKeyFilePath();

			if (verbose != undefined)
			{
				var RequestXml = new ActiveXObject("Msxml2.DOMDocument.3.0");
				RequestXml.async = false;
				RequestXml.resolveExternals = false;
				RequestXml.load("transaction.config");

				var xmlSend = RequestXml.xml;
				var oldValue = "";

				if (strUserLocale == "chs" || strUserLocale == "cht")
				{
				    oldValue = strUserLocale;
				    strUserLocale = navigator.userLanguage;
				}

				if (strUserLocale == "fil")
				{
				    oldValue = strUserLocale;
				    strUserLocale = "en-PH";
				}

				xmlSend = xmlSend.replace("{ProductId}", prodGUID);
				xmlSend = xmlSend.replace("{Culture}", strUserLocale);

				if (oldValue == "chs" || oldValue == "cht" || oldValue == "fil")
				{
				    strUserLocale = oldValue;
				}

				//Check if KeyID file exists
				var fileBool = fso.FileExists(keyFilePath);

				// if key already exists, replace new submit key id with confirmation from key file
				if (fileBool == true)
				{
					var ForReading = 1;
					var TriStateFalse = 0;
					var newFile = fso.OpenTextFile(keyFilePath, ForReading, false, TriStateFalse);

					Node = g_axConfigurationXml.selectSingleNode("/configuration/TrialIDCode");
					NodeList = Node.childNodes;
					var key = NodeList(0).getAttribute('value');
					xmlSend = xmlSend.replace(key, newFile.readline());
				}

				// this will throw an error if run from the network
				oXmlHttp = createXMLHttp();
				Node = g_axConfigurationXml.selectSingleNode("/configuration/DRAddress");
				NodeList = Node.childNodes;
				var DRURL = NodeList(0).text;
				try
				{
					oXmlHttp.open("post", DRURL, true);
					oXmlHttp.setRequestHeader("Content-Type", "text/xml");
					oXmlHttp.onreadystatechange = oXmlHttpReadyStateChange;
					oXmlHttp.send(xmlSend);
				}
				catch(err)
				{
					showErrorMessage(1);
				}
			}

			return selectedKey;
		}
		else
		{
			if (verbose != undefined)
			{
				//Did not find key
				showErrorMessage(3);
			}

			return -1;
		}
	}
	else
	{
		if (verbose != undefined)
		{
			//Did not find product key list
			showErrorMessage(3);
		}

		return -1;
	}
}

function oXmlHttpReadyStateChange()
{

	// was xml successfully loaded
	if (oXmlHttp.readyState == 4)
	{
		// did response return "OK"
		if (oXmlHttp.status == 200)
		{
			var fso = new ActiveXObject("Scripting.FileSystemObject");
			var sData = oXmlHttp.responseText;

			var ResponseXml = new ActiveXObject("Msxml2.DOMDocument.3.0");
			ResponseXml.async = false;
			ResponseXml.resolveExternals = false;
			ResponseXml.loadXML(sData);

			var checkForErrors = ResponseXml.xml;

			if (checkForErrors.indexOf("ErrorNumber") != -1)
			{
				showErrorMessage(1);
			}
			else
			{
				Nodes = ResponseXml.selectSingleNode("/TrialKeyResponse/KeyId");
				NodesList = Nodes.childNodes;

				try
				{
					var s = fso.CreateTextFile(keyFilePath, true);
					TrialIDCode = NodesList(0).text
					s.writeline(TrialIDCode);
					s.Close();
				}
				catch(err)
				{
					showErrorMessage(1);
				}

				Nodes = ResponseXml.selectSingleNode("/TrialKeyResponse/TrialKey");
				NodesList = Nodes.childNodes;
				document.getElementById("5x5Box").value = NodesList(0).text;
				gotTrialKey();
			}
		}
		else
		{
			showErrorMessage(1);
		}
	}
}

// get the full path to the write file
function getKeyFilePath()
{
	var retPath;
	var keyFilePath = "\\Office2007TrialActivationKey.txt";
	var MyDocs = g_axWScriptShell.SpecialFolders("MyDocuments");

	/* use this in case security as user prohibits access.
	var cmd = 'cmd /C "echo %USERPROFILE%"'; // environment is not available have to hack it
	var oExec = g_axWScriptShell.Exec(cmd);

	// wait for command to run
	while (oExec.Status == 0)
	{
	     setTimeout("void()",100);
	}

	// get the response line
	var out = oExec.StdOut;
	if (!out.AtEndOfStream)
	{
		var path = out.ReadLine();
		retPath = path + keyFilePath;
	}
	else
	{
		retPath = keyFilePath;
	}
	*/

	return MyDocs + keyFilePath;
}

function findOtherInstalls()
{
	var hadError = 0;

	Node = g_axConfigurationXml.selectSingleNode("/configuration/keyLocations");
	NodeList = Node.childNodes;

	for (i=0; i < NodeList.length; i++)
	{
		if (KeyExists(NodeList(i).getAttribute('location')) == 1 && hadError == 0)
		{
			showErrorMessage(4);
			hadError = 1;
			break;
		}
	}

	return hadError;
}

function findInstallRoot(verbose)
{
    self.clearInterval(timerID);

    if (pushedRecBtn == false)
    {
        document.getElementById("bul_recommended").src = strUserLocale + "/bul_recommended_anim.gif";
    }
    else
    {
        document.getElementById("bul_recommended").src = strUserLocale + "/bul_recommended.gif";
    }

    document.getElementById("btn_step_2").src = strUserLocale + "/btn_step_2.gif";

    pushedBtnTwo = true;

	loadConfiguration();
	Node = g_axConfigurationXml.selectSingleNode("/configuration/programMode");
	NodeList = Node.childNodes;

	var ErrorMode = NodeList(0).getAttribute('value');

	if (ErrorMode == 1)
	{
		showErrorMessage(2);
	}

	var foundKey = -1;
	var InstallRoot = "";

	Node = g_axConfigurationXml.selectSingleNode("/configuration/installLocations");
	NodeList = Node.childNodes;

	//Word
	var key = NodeList(0).getAttribute('location');

	if (KeyExists(key) == 1 && ErrorMode != 1)
	{
		InstallRoot = KeyValue(key);

		if (InstallRoot != undefined)
		{
			g_axWScriptShell.Run("\"" + InstallRoot.replace("\\", "\\\\") + "\\WINWORD.EXE\"");
			return 1;
		}
		else
		{
			if (verbose != undefined)
			{
				//Could not find Word
				findExcelInstallRoot(1);
			}

			return -1;
		}
	}
	else
	{
		if (verbose != undefined)
		{
			//Did not find Install Root
			findExcelInstallRoot(1);
		}

		return -1;
	}
}

function findExcelInstallRoot(verbose)
{
	var foundKey = -1;
	var InstallRoot = "";

	Node = g_axConfigurationXml.selectSingleNode("/configuration/installLocations");
	NodeList = Node.childNodes;

	//Excel
	var key = NodeList(1).getAttribute('location');

	if (KeyExists(key) == 1)
	{
		InstallRoot = KeyValue(key);

		if (InstallRoot != undefined)
		{
			g_axWScriptShell.Run("\"" + InstallRoot.replace("\\", "\\\\") + "\\EXCEL.EXE\"");
			return 1;
		}
		else
		{
			if (verbose != undefined)
			{
				//Could not find Word or Excel
				showErrorMessage(2);
			}

			return -1;
		}
	}
	else
	{
		if (verbose != undefined)
		{
			//Did not find Install Root
			showErrorMessage(2);
		}

		return -1;
	}
}

function KeyExists(key)
{
	try
	{
		var bKey = g_axWScriptShell.RegRead(key);
	}
	catch (err)
	{
		return 0;
	}

	return 1;
}

function KeyValue(key)
{
	var bKey = g_axWScriptShell.RegRead(key);

	return bKey;
}

function createXMLHttp()
{
	var aVersions = [ "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp" ];

	for (var i = 0; i < aVersions.length; i++)
	{
		try
		{
			var oXmlHttp = new ActiveXObject(aVersions[i]);
			return oXmlHttp;
		}
		catch (oError)
		{
			//Do nothing
		}
	}

	showErrorMessage(1);
}