var xmlHttp;
var xmlHttp2;
var uniqueXmlHttp;
var currentInformationFrameId	= null;
var currentUniqueInformationFrameId	= null;
var helpAnchorLocation			= null;
var formIconObject				= null;


function createXMLHttpRequestObject() {
	var xmlHttpRequest;
	
	if (window.ActiveXObject) {
		
		for(var i = 6; i; i--) { 
			try { 
				if(i == 2) { 
					xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
				} else { 
					xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP." + i + ".0");
				}
				break;
			} catch(excNotLoadable) {
				xmlHttpRequest = false;
			}
		}
		return xmlHttpRequest;
		
	} else if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	}
}


function createXMLHttpRequest() {
	xmlHttp = createXMLHttpRequestObject();
}


function createSecondaryXMLHttpRequest() {
	xmlHttp2 = createXMLHttpRequestObject();
}


function createUniqueXMLHttpRequest() {
	uniqueXmlHttp = createXMLHttpRequestObject();
}


function sendXMLHttpRequest(requestUri, method) {

	createXMLHttpRequest();
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.open(method, requestUri, true);
	xmlHttp.send(null);
}


function handleStateChange() {
	
	if(xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			addInformation(currentInformationFrameId, xmlHttp.responseText);
		}
	}
}


function sendUniqueXMLHttpRequest(requestUri, method) {

	createUniqueXMLHttpRequest();
	uniqueXmlHttp.onreadystatechange = handleUniqueStateChange;
	uniqueXmlHttp.open(method, requestUri, true);
	uniqueXmlHttp.send(null);
}

function handleUniqueStateChange() {
	
	if(uniqueXmlHttp.readyState == 4) {
		if (uniqueXmlHttp.status == 200) {
			addInformation(currentUniqueInformationFrameId, uniqueXmlHttp.responseText);
		}
	}
}

// Send a http request for data to populate a html object (only select atm)
function populateSelectUsingAjax(queryType, targetSelectObject, sourceSelectedValue, targetPreSelectedValue) {
	
	var requestUri = "/common/ajaxFeeds/dataQueryEngine.asp?queryType=" + queryType + "&targetObjectId=" + targetSelectObject.name + "&sourceKey=" + sourceSelectedValue + "&targetPreSelected=" + targetPreSelectedValue;
	
	// Empty the object first
	emptySelectObjectOptions(targetSelectObject);
	
	createXMLHttpRequest();
	xmlHttp.onreadystatechange = handlePopulateSelectStateChange;
	xmlHttp.open("GET",requestUri , true);
	xmlHttp.send(null);
}


// Send a http request for data to populate a html object (only select atm)
function populateSelectUsingAjaxWithLabel(queryType, targetSelectObject, sourceSelectedValue, sourceSelectedLabel, targetPreSelectedValue) {
	
	var requestUri = "/common/ajaxFeeds/dataQueryEngine.asp?queryType=" + queryType + "&targetObjectId=" + targetSelectObject.name + "&sourceKey=" + sourceSelectedValue + "&sourceSecondKey=" + sourceSelectedLabel + "&targetPreSelected=" + targetPreSelectedValue;
	
	// Empty the object first
	emptySelectObjectOptions(targetSelectObject);
	
	createXMLHttpRequest();
	xmlHttp.onreadystatechange = handlePopulateSelectStateChange;
	xmlHttp.open("GET",requestUri , true);
	xmlHttp.send(null);
}


// Handle the response from the populate query
function handlePopulateSelectStateChange() {

	if(xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			
			// Load the response XML and populate the specified object with the data
			responseXml = loadResponseXML(xmlHttp.responseText);
			targetObjectId = responseXml.documentElement.getAttribute("targetObjectId");
			targetPreSelectedValue = responseXml.documentElement.getAttribute("targetPreSelected");
			chainObjectId = responseXml.documentElement.getAttribute("chainObjectId");
			chainPopType = responseXml.documentElement.getAttribute("chainPopulationType");
			responseOptions = responseXml.getElementsByTagName("option");
			
			// Populate the target object
			var targetSelectObject = document.getElementById(targetObjectId);
			for(var tsoI = 0; tsoI < responseOptions.length; tsoI++) {
				targetSelectObject[targetSelectObject.length] = new Option(responseOptions.item(tsoI).getAttribute("label"), responseOptions.item(tsoI).getAttribute("value"));
				
				// If there is a target pre selected defined and it matches this one then set it selected
				if (targetPreSelectedValue == responseOptions.item(tsoI).getAttribute("value")) {
					targetSelectObject.selectedIndex = tsoI;
				}
			}
			
			// If a chain object and population is specified then chain another request
			if (document.getElementById(chainObjectId) && chainPopType) {
				populateSelectUsingAjax(chainPopType, document.getElementById(chainObjectId), targetSelectObject[targetSelectObject.selectedIndex].value, '');
			}
		}
	}
}


// Send a http request for data to populate a html object (only select atm)
function populateSelectUsingSecondaryAjax(queryType, targetSelectObject, sourceSelectedValue, targetPreSelectedValue) {
	
	var requestUri = "/common/ajaxFeeds/dataQueryEngine.asp?queryType=" + queryType + "&targetObjectId=" + targetSelectObject.name + "&sourceKey=" + sourceSelectedValue + "&targetPreSelected=" + targetPreSelectedValue;
	
	// Empty the object first
	emptySelectObjectOptions(targetSelectObject);
	
	createSecondaryXMLHttpRequest();
	xmlHttp2.onreadystatechange = handleSecondaryPopulateSelectStateChange;
	xmlHttp2.open("GET",requestUri , true);
	xmlHttp2.send(null);
}


// Handle the response from the populate query
function handleSecondaryPopulateSelectStateChange() {

	if(xmlHttp2.readyState == 4) {
		if (xmlHttp2.status == 200) {
			
			// Load the response XML and populate the specified object with the data
			responseXml = loadResponseXML(xmlHttp2.responseText);
			targetObjectId = responseXml.documentElement.getAttribute("targetObjectId");
			targetPreSelectedValue = responseXml.documentElement.getAttribute("targetPreSelected");
			chainObjectId = responseXml.documentElement.getAttribute("chainObjectId");
			chainPopType = responseXml.documentElement.getAttribute("chainPopulationType");
			responseOptions = responseXml.getElementsByTagName("option");
			
			// Populate the target object
			var targetSelectObject = document.getElementById(targetObjectId);
			for(var tsoI = 0; tsoI < responseOptions.length; tsoI++) {
				targetSelectObject[targetSelectObject.length] = new Option(responseOptions.item(tsoI).getAttribute("label"), responseOptions.item(tsoI).getAttribute("value"));
				
				// If there is a target pre selected defined and it matches this one then set it selected
				if (targetPreSelectedValue == responseOptions.item(tsoI).getAttribute("value")) {
					targetSelectObject.selectedIndex = tsoI;
				}
			}
			
			// If a chain object and population is specified then chain another request
			if (document.getElementById(chainObjectId) && chainPopType) {
				populateSelectUsingSecondaryAjax(chainPopType, document.getElementById(chainObjectId), targetSelectObject[targetSelectObject.selectedIndex].value, '');
			}
		}
	}
}


// Load XML response string into a XMLDOM object
function loadResponseXML(xmlString) {
	var xmlObject;

	if (window.ActiveXObject) {
		xmlObject = new ActiveXObject("Microsoft.XMLDOM");
		xmlObject.async="false";
		xmlObject.loadXML(xmlString);
		return xmlObject;

	} else {
		var parser = new DOMParser();
		xmlObject = parser.parseFromString(xmlString, "text/xml");
		var roottag = xmlObject.documentElement;
		//if ((roottag.tagName == "parserError") || (roottag.namespaceURI == "http://www.mozilla.org/newlayout/xml/parsererror.xml")) {
		//	alert(xmlString);
		//}
		return xmlObject;
	}	
}


function showRealtimeStandings(runId, sortOrder) {
	
	showInformationWindow("standingsdata", "Realtime Run Standings");
	addInformation("standingsdata", "&nbsp;&nbsp;Loading data <img src='/images/common/processing/ajax-loader-small.gif' />");
	currentInformationFrameId = "standingsdata";
	sendXMLHttpRequest("/raiding/ajaxfeeds/standingsdata.asp?runid=" + runId + "&sortby=" + sortOrder, "GET");
}


function getHelpData(pageUrl) {
	
	// Show the "loading" message
	addInformation("helpdata", "Loading help data <img src='/images/common/processing/ajax-loader-small.gif' />");
	
	// Register the anchor if there is one
	var anchorName = null;
	if (pageUrl.indexOf("#") != -1) {
		anchorName = pageUrl.substring(pageUrl.indexOf("#") + 1, pageUrl.length);
	}
	helpAnchorLocation = anchorName;
	
	// Make the request
	createXMLHttpRequest();
	xmlHttp.onreadystatechange = handleHelpStateChange;
	xmlHttp.open("GET", "/common/code/asp/getHelpData.asp?page=" + pageUrl, true);
	xmlHttp.send(null);
}


function handleHelpStateChange() {
	
	if(xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			addInformation("helpdata", xmlHttp.responseText);
			if (helpAnchorLocation != null) {
				location.href = "#" + helpAnchorLocation;
			}
		}
	}
}


function sendMiniFormData(pageUrl, formObject, iconObject) {
	
	// Register the icon
	formIconObject = iconObject;
	
	// Loop through the form objects and build the query string
	var parameters = buildQueryStringFromFormObjects(formObject);
	
	// Make the request
	createXMLHttpRequest();
	xmlHttp.onreadystatechange = handleMiniFormDataStateChange;
	xmlHttp.open("POST", pageUrl, true);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", parameters.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(parameters);
}


function handleMiniFormDataStateChange() {
	
	if(xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			// Show the "success" icon
			if (formIconObject) {
				formIconObject.src = "/images/common/minigreentickicon.png";
			}
		}
	}
}


function buildQueryStringFromFormObjects(formObject) {
	
	var queryString = "";
	
	for(var formI=0; formI < formObject.elements.length; formI++) {
		if (formObject.elements[formI].type == "hidden" || formObject.elements[formI].type == "textarea") {
			if (queryString != "") {queryString = queryString + "&";}
			queryString = queryString + formObject.elements[formI].name + "=" + escape(formObject.elements[formI].value)
		}
	}
	
	return queryString;
}


function forwardPostData(requestUri, formObject) {
	
	createXMLHttpRequest();
	xmlHttp.open("POST", requestUri, false);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlHttp.onreadystatechange = handleForwardResponse;
	xmlHttp.send(formData2QueryString(formObject));	
}


function handleForwardResponse() {
	
	if(xmlHttp.readyState == 4) {
		
		strResponse = xmlHttp.responseText;

		switch (xmlHttp.status) {
			
			// Page-not-found error
			case 404:
				document.getElementById("warningresponsecontainer").innerHTML = 'Error: Not Found. The requested URL ' + requestUri + ' could not be found.';
			break;
			
			// Display results in a full window for server-side errors
			case 500:
				document.getElementById("warningresponsecontainer").innerHTML = "There was a problem with the request. The problem has been logged and a member of the Raidbuilder team has been notified of the problem.";
			break;
			
			default:
				document.getElementById("okresponsecontainer").innerHTML = "Processing completed successfully";
				location.replace(strResponse);
			break;
       }
	}
}


function renderInformationWindow(infoWindowId) {

	document.write("<div id='" + infoWindowId + "frame' class='informationframe'><div class='informationframeheader'><table width='100%'><tr><td width='10%'>&nbsp;</td><td width='80%' align='center'><div id='" + infoWindowId + "infowindowtitle'></div></td><td width='10%' align='right'><a href='javascript:hideInformationWindow(\"" + infoWindowId + "\");'>Close</a></td></tr></table></div><div id='" + infoWindowId + "window' class='informationwindow'>&nbsp;</div></div>");
}


function renderFixedInformationWindow(infoWindowId) {

	document.write("<div id='" + infoWindowId + "frame' class='fixedinformationframe'><div class='informationframeheader'><table width='100%'><tr><td width='10%'>&nbsp;</td><td width='80%' align='center'><div id='" + infoWindowId + "infowindowtitle'></div></td><td width='10%' align='right'><a href='javascript:hideInformationWindow(\"" + infoWindowId + "\");'>Close</a></td></tr></table></div><div id='" + infoWindowId + "window' class='informationwindow'>&nbsp;</div></div>");
}


function showInformationWindow(infoWindowId, title) {
	
	document.getElementById(infoWindowId + "infowindowtitle").innerHTML = HTMLEntities(title);
	//document.getElementById(infoWindowId + "frame").style.top = 60 + document.documentElement.scrollTop + 'px';
	//document.getElementById(infoWindowId + "frame").style.left = 100 + document.documentElement.scrollLeft + 'px';
	putInCenter(infoWindowId + "frame");
	document.getElementById(infoWindowId + "frame").style.visibility = "visible";
	
	// If we're running in IE6 then hide any select boxes to get round the z-index IE6 bug
	if (browserIsIE6()) {
		hideAllSelectObjects();
	}
}


function hideInformationWindow(infoWindowId) {
	
	document.getElementById(infoWindowId + "frame").style.visibility = "hidden";
	
	// If we're running in IE6 then show any select boxes to get round the z-index IE6 bug
	if (browserIsIE6()) {
		showAllSelectObjects();
	}
}


function addInformation(infoWindowId, informationHtml) {
	
	document.getElementById(infoWindowId + "window").innerHTML = informationHtml;
}


function showLootHistoryInformation(lootName, instanceName, offspec) {
	
	showInformationWindow("loothistoryinfo", "Loot History for " + lootName);
	addInformation("loothistoryinfo", "&nbsp;&nbsp;Loading data <img src='/images/common/processing/ajax-loader-small.gif' />");
	currentInformationFrameId = "loothistoryinfo";
	sendXMLHttpRequest("/guild/reports/ajaxfeeds/loothistorydata.asp?loot=" + lootName + "&instance=" + instanceName + "&offspec=" + offspec, "GET");
}


function showCharacterLootHistoryInformation(characterId, characterName, relevantGuilds, startDate) {
	
	showInformationWindow("loothistoryinfo", "Loot History for " + characterName);
	addInformation("loothistoryinfo", "&nbsp;&nbsp;Loading data <img src='/images/common/processing/ajax-loader-small.gif' />");
	currentInformationFrameId = "loothistoryinfo";
	sendXMLHttpRequest("/guild/reports/ajaxfeeds/characterloothistorydata.asp?characterid=" + characterId + "&guilds=" + relevantGuilds + "&reportstartdate=" + startDate, "GET");
}


function showCharacterDkpInformation(characterId, characterName, guildId, poolId) {
	
	showInformationWindow("chardkpinfo", "DKP Information for " + characterName);
	addInformation("chardkpinfo", "&nbsp;&nbsp;Loading " + characterName + "'s data <img src='/images/common/processing/ajax-loader-small.gif' />");
	currentInformationFrameId = "chardkpinfo";
	sendXMLHttpRequest("/public/wow/ajaxfeeds/characterdkpdata.asp?characterid=" + characterId + "&guildid=" + guildId + "&dkppool=" + poolId, "GET");
}


function showRaidInformation(runId, runTitle) {
	
	showInformationWindow("raidinfo", "Run Information for " + runTitle);
	addInformation("raidinfo", "&nbsp;&nbsp;Loading data for " + HTMLEntities(runTitle) + " <img src='/images/common/processing/ajax-loader-small.gif' />");
	currentInformationFrameId = "raidinfo";
	sendXMLHttpRequest("/public/wow/ajaxfeeds/rundata.asp?runid=" + runId, "GET");
}


function showShortCharacterSummary(runId, sortBy) {
	
	showInformationWindow("scharsummary", "Short Character Summary");
	addInformation("scharsummary", "&nbsp;&nbsp;Loading data <img src='/images/common/processing/ajax-loader-small.gif' />");
	currentInformationFrameId = "scharsummary";
	sendXMLHttpRequest("/raiding/teams/ajaxfeeds/shortcharactersummary.asp?runid=" + runId + "&sortby=" + sortBy, "GET");
}


function showRaidComposition(raidCompositionData) {
	
	showInformationWindow("scharsummary", "Raid Composition");
	addInformation("scharsummary", "&nbsp;&nbsp;Loading data <img src='/images/common/processing/ajax-loader-small.gif' />");
	currentInformationFrameId = "scharsummary";
	sendXMLHttpRequest("/raiding/teams/ajaxfeeds/raidcomposition.asp?compositiondata=" + raidCompositionData, "GET");
	return false;
}


function showRaidTemplate(raidTemplateId) {
	
	showInformationWindow("rtemplatedata", "Raid Template");
	addInformation("rtemplatedata", "&nbsp;&nbsp;Loading data <img src='/images/common/processing/ajax-loader-small.gif' />");
	currentInformationFrameId = "rtemplatedata";
	sendXMLHttpRequest("/public/wow/ajaxfeeds/viewraidtemplate.asp?raidtemplateid=" + raidTemplateId, "GET");
	return false;
}


function refreshRealTimePlayerData() {
	currentUniqueInformationFrameId = "realtime-logged-data-";
	sendUniqueXMLHttpRequest("/common/ajaxfeeds/realtimeplayerdata.asp", "GET");
	if (window.doCustomTimedTasks) {
		doCustomTimedTasks();
	}
	setTimeout("refreshRealTimePlayerData();", 60000);
}


// Convert formdata to a query string
function formData2QueryString(formObject) {

	var strSubmit       = '';

	for (i = 0; i < formObject.elements.length; i++) {
		if (i > 0) {
			strSubmit += "&";
		}
		strSubmit += formObject.elements[i].name + '=' + escape(formObject.elements[i].value);
	}

	return strSubmit;
}