var deleteMatchNextAction = "";
var getMatchesNextAction = "";
function deleteMatchThenShowMatches(id) {
	params = new Array("matchid", id);
	sendAJAX("xml/deletematch.php", params, getMatchesByCompAfterAJAXRequest);
}

function getMatchesByCompAfterAJAXRequest(xmlDoc) {
	status = xmlDoc.getElementsByTagName('response')[0].getAttribute('status');
	if (status == "0") {
		id = xmlDoc.getElementsByTagName("id")[0].childNodes[0].nodeValue;
		params = new Array("id", compId);
		sendAJAX("xml/getmatchesbycomp.php", params, displayMatchesByComp);
	} else {
		alert ("Status " + status + " returned in getMatchesByCompAfterAJAXRequest.");
		alert(xmlDoc.getElementsByTagName('errorMessage')[0].childNodes[0].nodeValue);
	}
}

function getPlayersInCompResponse(xmlDoc) {
	status = xmlDoc.getElementsByTagName('response')[0].getAttribute('status');
	if (status == "0") {
		var players = xmlDoc.getElementsByTagName("player");
		playersInCompArray = new Array(players.length);
		for (var i = 0; i < players.length; i++) {
			playersInCompArray[i] = new Array();
			playersInCompArray[i]['id'] = players[i].getAttribute('id');
			playersInCompArray[i]['firstName'] = players[i].getAttribute('firstName');
			playersInCompArray[i]['lastName'] = players[i].getAttribute('lastName');
			playersInCompArray[i]['army'] = players[i].getAttribute('army');
		}
		newMatchPopupPopulatePlayerSelects();
	} else {
		alert("Status " + status + " returned in getPlayersInCompResponse.");
		alert(xmlDoc.getElementsByTagName('errorMessage')[0].childNodes[0].nodeValue);
	}
}

function newMatchPopupPopulatePlayerSelects() {
	var playerlist = "";
	playerDefaultArmy = new Array();
	for (var i = 0; i < playersInCompArray.length; i++) {
		playerlist += "<option value=\"" + playersInCompArray[i]['id'] + "\">" + playersInCompArray[i]['firstName'] + " " + playersInCompArray[i]['lastName'] + "</option>\n";
		playerDefaultArmy[playersInCompArray[i]['id']] = playersInCompArray[i]['army'];
	}
	document.getElementById('winnerid0').innerHTML = playerlist;
	playerlist += "<option value=\"-1\">BYE</option>\n";
	document.getElementById('loserid0').innerHTML = playerlist;
	selectPlayersDefaultArmy('w',0);
	selectPlayersDefaultArmy('l',0);
}

function validateNewMatchData(compId) {
	if (parseInt(document.getElementById('loserscore').value,10) > parseInt(document.getElementById('winnerscore').value,10)) {
		alert("Loser score cannot be greater than winner score");
		var tempVar = document.getElementById('loserscore').value;
		document.getElementById('loserscore').value = document.getElementById('winnerscore').value;
		document.getElementById('winnerscore').value = tempVar;
		tempVar = numLosers;
		numLosers = numWinners;
		numWinners = tempVar;
	} else {
		params = new Array();
		params.push("compid");
		params.push(compId);
		params.push("matchdate");
		params.push(document.getElementById('matchdate').value);
		params.push("glicko_eligible");
		params.push(document.getElementById('glickoeligible').value);
		params.push("winners");
		params.push(numWinners);
		for (var i = 0; i < numWinners; i++) {
			params.push("winnerid" + i);
			params.push(document.getElementById('winnerid' + i).value);
		}
		params.push("losers");
		params.push(numLosers);
		for (var i = 0; i < numLosers; i++) {
			params.push("loserid" + i);
			params.push(document.getElementById('loserid' + i).value);
		}
		params.push("round");
		params.push(document.getElementById('round').value);
		params.push("winnerscore");
		params.push(document.getElementById('winnerscore').value);
		params.push("loserscore");
		params.push(document.getElementById('loserscore').value);
		sendAJAX("xml/creatematch.php", params, createMatchResponse);
		
	}
}

function addWinner() {
	winnername = new Array();
	for (a = 0; a < numWinners; a++) {
		winnername[a] = document.getElementById('winnerid'+a).selectedIndex;
		//alert('winnerid' + a + " is " + winnername[a]);
	}
	winnerhtml = document.getElementById('winnerdiv').innerHTML;
	winnerhtml += '<div><select name="winnerid' + numWinners;
	winnerhtml += '" id="winnerid' + numWinners;
	winnerhtml += '" onChange=\"javascript:selectPlayersDefaultArmy(\'w\', ' + numWinners + ');\">"';
	winnerhtml += playerlist;
	winnerhtml += '</select>';
	winnerhtml += '<select name="winnerarmy' + numWinners;
	winnerhtml += '" id="winnerarmy' + numWinners;
	winnerhtml += '">"';
	winnerhtml += armylist;
	winnerhtml += '</select></div>';
	document.getElementById('winnerdiv').innerHTML = winnerhtml;
	for (a = 0; a < numWinners; a++) {
		document.getElementById('winnerid'+a).selectedIndex = winnername[a];
	}
	for (a = 0; a < numWinners; a++) {
		// TODO - work out how to select the main army choice as default
		document.getElementById('winnerarmy'+a).selectedIndex = 0;
	}
	numWinners++;
}

function addLoser() {
	losername = new Array();
	for (a = 0; a < numLosers; a++) {
		losername[a] = document.getElementById('loserid'+a).selectedIndex;
	}
	loserhtml = document.getElementById('loserdiv').innerHTML;
	loserhtml += '<div><select name="loserid' + numLosers;
	loserhtml += '" id="loserid' + numLosers;
	loserhtml += '" onChange=\"javascript:selectPlayersDefaultArmy(\'l\', ' + numLosers + ');\">"';
	loserhtml += playerlist;
	loserhtml += "<option value=\"-1\">BYE</option>\n";
	loserhtml += '</select></div>';
	document.getElementById('loserdiv').innerHTML = loserhtml;
	for (a = 0; a < numLosers; a++) {
		document.getElementById('loserid'+a).selectedIndex = losername[a];
	}
	numLosers++;
}

function selectPlayersDefaultArmy(playerRole, playerNumber) {
	if (playerRole == 'w') {
		id = document.getElementById('winnerid' + playerNumber).value;
		army = playerDefaultArmy[id];
		document.getElementById('winnerarmy' + playerNumber).value = army;
	} else if (playerRole == 'l') {
		id = document.getElementById('loserid' + playerNumber).value;
		army = playerDefaultArmy[id];
		document.getElementById('loserarmy' + playerNumber).value = army;
	}
}

function newMatchPopup(message, compId, matchDate, glickoEligible) {
	// This is about as complex as it gets, so I will actually comment it.
	// First time we present this popup, we need to call getarmies.php to build the array
	// getArmiesForMatchResponse will then do the population of the army selects as the screen will have rendered
	// before the AJAX call returns
	if (typeof armyListArray == 'undefined') {
		postPopulateArmySelects = 0;
		sendAJAX("xml/getarmies.php", null, getArmiesForMatchResponse);
	} else {
		// do nothing now because there are no fields to populate, so set a flag
		postPopulateArmySelects = 1;
	}
	newMatchPopupMessage = message;
	numWinners = 1;
	numLosers = 1;
	playerlist = '';
	html = "<div class=\"popup\" id=\"addMatchPopup\">\n";
	html += "	<div class=\"ampl1c1\">Add Match</div>\n";
	html += "	<div class=\"ampl2c1\"><span id=\"messagelabel\">" + message + "</span></div>\n";
	html += "	<div class=\"ampl3c1\"><span id=\"matchdatelabel\">Match Date</span></div>\n";
	html += "	<div class=\"ampl3c2\"><input name=\"matchdate\" id=\"matchdate\" value=\"" + matchDate + "\"/></div>\n";
	html += "	<div class=\"ampl4c1\"><span id=\"glickolabel\">Eligible for Glicko</span></div>\n";
	html += "	<div class=\"ampl4c2\"><select name=\"glickoeligible\" id=\"glickoeligible\">\n";
	if (0 == glickoEligible) {
		html += "			<option value=\"0\" selected>No</option>\n";
	} else {
		html += "			<option value=\"0\">No</option>\n";
	}
	if (1 == glickoEligible) {
		html += "			<option value=\"1\" selected>Yes</option>\n";
	} else {
		html += "			<option value=\"1\">Yes</option>\n";
	}
	html += "   </select></div>\n";
	html += "	<div class=\"ampl5c1\"><span id=\"roundlabel\">Round</span></div>\n";
	html += "	<div class=\"ampl5c2\"><input name=\"round\" id=\"round\" onChange=\"winnowNewMatchPopupPlayersByRound(this.value);\"></div>\n";
	html += "	<div class=\"ampl6c1\"><span id=\"winnerslabel\">Winner(s)</span></div>\n";
	html += "	<div class=\"ampl6c2\"><div id=\"winnerdiv\"><select name=\"winnerid0\" id=\"winnerid0\" onChange=\"javascript:selectPlayersDefaultArmy('w', 0);\">\n";
	html += "       <option value=\"0\">Loading players...</option>\n";
	html += "   </select>\n";
	html += "	<select name=\"winnerarmy0\" id=\"winnerarmy0\">\n";
	html += "       <option value=\"0\">Loading armies...</option>\n";
	html += "   </select></div>\n";
	html += "   </div>\n";
	html += "	<div class=\"ampl6c3\"><span class=\"button\"><a href=\"javascript:addWinner();\">Add winner</a></span></div>\n";
	html += "	<div class=\"ampl7c1\"><span id=\"winscorelabel\">Winning Score</span></div>\n";
	html += "	<div class=\"ampl7c2\"><input name=\"winnerscore\" id=\"winnerscore\"></div>\n";
	html += "	<div class=\"ampl8c1\"><span id=\"losescorelabel\">Losing Score</span></div>\n";
	html += "	<div class=\"ampl8c2\"><input name=\"loserscore\" id=\"loserscore\"></div>\n";
	html += "	<div class=\"ampl9c1\"><span id=\"loserslabel\">Loser(s)</span></div>\n";
	html += "	<div class=\"ampl9c2\"><div id=\"loserdiv\"><select name=\"loserid0\" id=\"loserid0\" onChange=\"javascript:selectPlayersDefaultArmy('l', 0);\">\n";
	html += "       <option value=\"0\">Loading players...</option>\n";
	html += "   </select>\n";
	html += "	<select name=\"loserarmy0\" id=\"loserarmy0\">\n";
	html += "       <option value=\"0\">Loading armies...</option>\n";
	html += "   </select></div>\n";
	html += "   </div>\n";
	html += "	<div class=\"ampl9c3\"><span class=\"button\"><a href=\"javascript:addLoser();\">Add loser</a></span></div>\n";
	html += "	<div class=\"ampl10c1\">\n";
	html += "   	<span class=\"button\"><a href=\"javascript:validateNewMatchData(compId);\">Insert</a></span>\n";
	html += "		<span class=\"button\"><a href=\"javascript:removeNewMatchPopup();\">Cancel</a></span>\n";
	html += "	</div>\n";
	html += "</div>\n";
	document.getElementById('addNewMatchHolder').innerHTML = html;
	if (postPopulateArmySelects == 1) {
		newMatchPopupPopulateArmySelects();
	}
}

function newMatchPopupPopulateArmySelects() {
	var armyListOptions = "";
	for (var a = 0; a < armyListArray.length; a++) {
		armyListOptions += "<option value=\"" + armyListArray[a]['id'] + "\">" + armyListArray[a]['name'] + " (" + armyListArray[a]['system'] + " v" + armyListArray[a]['version'] + ")</option>\n";
	}
	for (var w = 0; w < numWinners; w++) {
		document.getElementById('winnerarmy' + w).innerHTML = armyListOptions;
	}
	for (var l = 0; l < numLosers; l++) {
		document.getElementById('loserarmy' + l).innerHTML = armyListOptions;
	}
}

function removeNewMatchPopup() {
	document.getElementById('addNewMatchHolder').innerHTML = "";
}

function winnowNewMatchPopupPlayersByRound(roundId) {
	//the idea of this is to remove any players that already have matches this round from the player dropdown
	// need to rebuild the dropdown from the main playerlist first
	newMatchPopupPopulatePlayerSelects();
	try{
		if (roundId != null || roundId < 1) {
			var playerList = document.getElementById('winnerid0');
			var i = 0;
			while (i < playerList.length) {
				var thisPlayer = playerList.options[i].value;
				for (j = 0; j < matchesArray[roundId].length; j++) {
					try {
						if (thisPlayer == matchesArray[roundId][j]) {
							document.getElementById('winnerid0').remove(i);
							document.getElementById('loserid0').remove(i);
							var foundPlayer = true;
							break;
						} else {
							var foundPlayer = false;
						}
					} catch (Exception) {
						var foundPlayer = flase;
					}
				}
				if (!foundPlayer) {
					i++;
				}
			}
		}
	} catch(Exception) {
		// There are no matches, so no rounds yet, so we can't winnow, but no problem with that, we don't need to
	}
}

function createMatchResponse(xmlDoc) {
	status = xmlDoc.getElementsByTagName('response')[0].getAttribute('status');
	if (status == "0") {
		compId = xmlDoc.getElementsByTagName("match")[0].getAttribute('compId');
		removeNewMatchPopup();
		params = new Array("id", compId);
		sendAJAX("xml/getmatchesbycomp.php", params, displayMatchesByComp);
	} else if (status == "1") {
		alert("You do not have permission to create a match for this competition");
	} else {
		alert(xmlDoc.getElementsByTagName('errorMessage')[0].childNodes[0].nodeValue);
	}
}
