var httpPlayerNameStatus = getHTTPObject(); 
var MAX_PLAYERS = 15;
var MAX_PLAYER_NAME_SIZE = 16;
var MIN_PLAYERNAME_SIZE = 2;
var NUM_COLUMNS = 3;
var pendingResponse = false;
var doAnotherAfterPendDone = false;
var players;
var playersCount;
var startingVisiblePlayerNum = 1;
var hasFocus = 0;
var timerID = null;

function setMaxValues(players, columns) {
	MAX_PLAYERS = players;
	NUM_COLUMNS = columns;
}

function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function gotFocus()
{
	hasFocus = true;
}

function lostFocus()
{
	hasFocus = false;
}

// called by the onClick event
// Need to check if a return key hit, then do it now
// or if any other key hit, delay 1 second, then do the search
function checkPlayerName(e)
{
	var characterCode;  // literal character code will be stored in this variable

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}

	// Cancel any timers
	if (timerID) clearTimeout(timerID);
	if((characterCode == 13) && (hasFocus)){ //if generated character code is equal to ascii 13 (if enter key)
		// check for player right now (no delay)
		if (timerID) {
			clearTimeout(timerID);
			timerID = null;
		}
		checkPlayerNameNow();
	}
	else{
		// Delay, then check
		timerID = setTimeout("checkPlayerNameNow()", 1000);  // 1 sec
	}

}

// Called with the click of the button
function checkPlayerNameNow()
{
	// Clear any timer that may still be running
	if (timerID) {
		clearTimeout(timerID);
		timerID = null;
	}
	var playerName = trim(document.PLAYER_SEARCH.Player.value);

	try
	{
		// Waiting for last results, lets not hit the server again until they're back
		if (!pendingResponse)
		{
			if (playerName.length > MIN_PLAYERNAME_SIZE) {
				getURL = "/php/player-search-provider.php?PLAYERNAME=" + escape(playerName) + "&X=" + Math.floor(Math.random() * 99999);
				httpPlayerNameStatus.open("GET", getURL, true);
				httpPlayerNameStatus.onreadystatechange = handlePlayerNameResponse;
				httpPlayerNameStatus.send(null);
				pendingResponse = true;
			}
			else if (playerName) {
				// One is specified, but it's too small for us to check
				// Clear the divs initially
				j = 1;
				while (j <= MAX_PLAYERS)
				{
					document.getElementById('PLAYER_'  + j++).innerHTML = '&nbsp;';
				}
				document.getElementById('PLAYER_' + (MAX_PLAYERS/NUM_COLUMNS+1)).innerHTML = "<FONT COLOR=RED><b>" + (MIN_PLAYERNAME_SIZE+1) + " characters</b></FONT>";
				document.getElementById('PLAYER_' + (MAX_PLAYERS/NUM_COLUMNS+2)).innerHTML = "<FONT COLOR=RED><b>required</b></FONT>";
				document.getElementById('PLAYER_' + (MAX_PLAYERS/NUM_COLUMNS+3)).innerHTML = "<FONT COLOR=RED><b>to search</b></FONT>";
				document.getElementById('PLAYER_NOTE').innerHTML = '&nbsp;';
				document.getElementById('PLAYER_TOGGLE_MINUS').innerHTML = '&nbsp;';
				document.getElementById('PLAYER_TOGGLE_PLUS').innerHTML = '&nbsp;';
			}
			else {
				// Clear the divs, no playerName specified, no need to hit server
				j = 1;
				while (j <= MAX_PLAYERS)
				{
					document.getElementById('PLAYER_'  + j++).innerHTML = '&nbsp;';
				}
				document.getElementById('PLAYER_NOTE').innerHTML = '&nbsp;';
				document.getElementById('PLAYER_TOGGLE_MINUS').innerHTML = '&nbsp;';
				document.getElementById('PLAYER_TOGGLE_PLUS').innerHTML = '&nbsp;';
			}
		}
		else {
			doAnotherAfterPendDone = true;
		}
	}
	catch (e)
	{
//		var resultsDiv = document.getElementById('FindaFriendResultBox');
//		resultsDiv.innerHTML = 'Problem Retrieving playerNames!';
	}

}

function positionAbbr(position, show_as_combined_receivers, use_short_labels, show_as_combined_def_st)
{
	if (show_as_combined_receivers == null) show_as_combined_receivers = false;
	if (use_short_labels == null) use_short_labels = false;
	if (show_as_combined_def_st == null) show_as_combined_def_st = false;

	var dispPosition = "QB";
	switch (position)
	{
		case "0":
			dispPosition = "QB";
			break;
		case "1": 
			dispPosition = "RB";
			break;
		case "2":
			if (show_as_combined_receivers)
				dispPosition = "WR/TE";
			else
				dispPosition = "WR";
			break;
		case "3": 
			dispPosition = "TE";
			break;
		case "10":
			dispPosition = "DL";
			break;
		case "11": 
			dispPosition =  "LB";
			break;
		case "12":
			dispPosition = "DB";
			break;
		case "4":
			dispPosition = "K";
			break;
		case "20":
			dispPosition = "P";
			break;
		case "5":
			if (show_as_combined_def_st)
				if (use_short_labels)
					dispPosition = "D/ST";
				else
					dispPosition = "Def/ST";
			else
				if (use_short_labels)
					dispPosition = "Def";
				else
					dispPosition = "Defense";
			break;
		case "6":
			if (show_as_combined_def_st)
				if (use_short_labels)
					dispPosition = "D/ST";
				else
					dispPosition = "Def/ST";
			else
				if (use_short_labels)
					dispPosition = "ST";
				else
					dispPosition = "Special Team";
			break;
		case "7":
			if (use_short_labels)
				dispPosition = "HC";
			else
				dispPosition = "Head Coach";
			break;
		case "8":
			if (use_short_labels)
				dispPosition = "Off";
			else
				dispPosition = "Offense";
			break;
		case "99":
			dispPosition = "OL";
		break;
	}
	return dispPosition;
}

function handlePlayerNameResponse() 
{
	try
	{
		if (httpPlayerNameStatus.readyState == 4) 
		{
			pendingResponse = false;
			// if we held up and didn't hit the server when there was a pending request out there
			// and pending request is back now... lets ignore this response and do one more server hit with
			// what the user typed so we don't annoy him with these old results and we don't
			// ignore his last keystrokes
			if (doAnotherAfterPendDone) {
				doAnotherAfterPendDone = false;
				checkPlayerName();
			}
			else {
				if (httpPlayerNameStatus.responseText.indexOf('invalid') == -1) {
					// Use the XML DOM 
					var xmlDocument = httpPlayerNameStatus.responseXML; 

					//
					//  get the result object
					//
					var playersAdded = 0;
					var playersCountElem = xmlDocument.getElementsByTagName('players').item(0);
					playersCount     = playersCountElem.getAttribute('count');
					// Special stuff to put in the center column(s) if there's only a few results
					if ((playersCount > 0) && (playersCount < (MAX_PLAYERS / NUM_COLUMNS))) {
						playersAdded = (MAX_PLAYERS / NUM_COLUMNS);  // Just shifts our results over one column
					}

					// Clear the divs initially
					j = 1;
					while (j <= MAX_PLAYERS)
					{
						document.getElementById('PLAYER_'  + j++).innerHTML = '&nbsp;';
					}
					document.getElementById('PLAYER_NOTE').innerHTML = '&nbsp;';
					document.getElementById('PLAYER_TOGGLE_MINUS').innerHTML = '&nbsp;';
					document.getElementById('PLAYER_TOGGLE_PLUS').innerHTML = '&nbsp;';

					if (playersCount > 0) {
						startingVisiblePlayerNum = 1;
						players = xmlDocument.getElementsByTagName('players');
						i = 0;

						while (i < players[0].childNodes.length) {
							// Continue only if childNode is a tag (ignores white space in some browsers)
							if (players[0].childNodes[i].nodeType == 1) {
								playerName = players[0].childNodes[i].getAttribute('first-name') + " " + players[0].childNodes[i].getAttribute('last-name');
								playerPosTeam = ", " + positionAbbr(players[0].childNodes[i].getAttribute('position'), false, true, false) + ", " + players[0].childNodes[i].getAttribute('team');
								if (playerName.length > MAX_PLAYER_NAME_SIZE) {
									playerName = playerName.substr(0, MAX_PLAYER_NAME_SIZE) + '...';
								}
								resultsDiv = document.getElementById('PLAYER_'  + ++playersAdded);
								resultsDiv.innerHTML = '<a href="/php/draft-guide-player.php?PN=' + players[0].childNodes[i].getAttribute('player-num') + '">' + playerName + '</a>' + playerPosTeam;
								i++;

							} // node_Type == 1
							// row is not of right nodeType
							else {
								i++;
							}

							// Cap this at X rows
							if (playersAdded >= MAX_PLAYERS) {
								// Display a little toggle div to show the rest of the players
								document.getElementById('PLAYER_NOTE').innerHTML = "page 1 of " + Math.ceil(((playersCount * 1)+1) / (MAX_PLAYERS * 1)) ;
								document.getElementById('PLAYER_TOGGLE_PLUS').innerHTML = "<a href=\"javascript:togglePage('+');\"><img border=0 src=http://www.rtsports.com/img/more-right.gif></a>";

								break;
							}
						} // while loop
					}  // if playersCount > 0
					else {
						// Put the "None Found" message in the middle
						document.getElementById('PLAYER_' + (MAX_PLAYERS/NUM_COLUMNS+1)).innerHTML = "<FONT COLOR=RED><b>No Matching</b></FONT>";
						document.getElementById('PLAYER_' + (MAX_PLAYERS/NUM_COLUMNS+2)).innerHTML = "<FONT COLOR=RED><b>Results Found</b></FONT>";
					}
				} // responseText = -1
			} // doAnotherAfterPendDone
		} // readyState == 4
	}
	catch (e)
	{
		pendingResponse = false;
	}

}

function togglePage(direction) {
	// This is for when there's more results than fit on the page and the user can toggle up and down pages
	// Results are stored in the players array, just need to move around the window of which of those are in the PLAYER_X divs
	if (direction == '+') {
		startingVisiblePlayerNum += MAX_PLAYERS;
	}
	else {
		startingVisiblePlayerNum -= MAX_PLAYERS;
	}
	
	currentPageNum = Math.floor(startingVisiblePlayerNum / (MAX_PLAYERS * 1)) + 1;
	lastPageNum    = Math.ceil(((playersCount * 1)+1) / (MAX_PLAYERS * 1));
	if (currentPageNum <= 1)
	{
		document.getElementById('PLAYER_TOGGLE_PLUS').innerHTML = "<a href=\"javascript:togglePage('+');\"><img border=0 src=http://www.rtsports.com/img/more-right.gif></a>";
		document.getElementById('PLAYER_TOGGLE_MINUS').innerHTML = '&nbsp;';
	}
	else if (currentPageNum >= lastPageNum)
	{
		document.getElementById('PLAYER_TOGGLE_MINUS').innerHTML = "<a href=\"javascript:togglePage('-');\"><img border=0 src=http://www.rtsports.com/img/more-left.gif></a>";
		document.getElementById('PLAYER_TOGGLE_PLUS').innerHTML = '&nbsp;';
	}
	else {
		document.getElementById('PLAYER_TOGGLE_MINUS').innerHTML = "<a href=\"javascript:togglePage('-');\"><img border=0 src=http://www.rtsports.com/img/more-left.gif></a>";
		document.getElementById('PLAYER_TOGGLE_PLUS').innerHTML = "<a href=\"javascript:togglePage('+');\"><img border=0 src=http://www.rtsports.com/img/more-right.gif></a>";
	}

	// Clear the divs initially
	j = 1;
	while (j <= MAX_PLAYERS)
	{
		document.getElementById('PLAYER_'  + j++).innerHTML = '&nbsp;';
	}
	document.getElementById('PLAYER_NOTE').innerHTML = "page " + currentPageNum + " of " +  lastPageNum;

	var playersAdded = 0;
	var playersSkipped = 0;
	i = 0;
	while (i < players[0].childNodes.length) {
		// Continue only if childNode is a tag (ignores white space in some browsers)
		if (players[0].childNodes[i].nodeType == 1) {
			// Skip nodes until we can start at the right player
			if (playersSkipped < (startingVisiblePlayerNum - 1)) {
				playersSkipped++;
			}
			else {
				playerName = players[0].childNodes[i].getAttribute('first-name') + " " + players[0].childNodes[i].getAttribute('last-name');
				playerPosTeam = ", " + positionAbbr(players[0].childNodes[i].getAttribute('position'), false, true, false) + ", " + players[0].childNodes[i].getAttribute('team');
				if (playerName.length > MAX_PLAYER_NAME_SIZE) {
					playerName = playerName.substr(0, MAX_PLAYER_NAME_SIZE) + '...';
				}
				resultsDiv = document.getElementById('PLAYER_'  + ++playersAdded);
				resultsDiv.innerHTML = '<a href="/php/draft-guide-player.php?PN=' + players[0].childNodes[i].getAttribute('player-num') + '">' + playerName + '</a>' + playerPosTeam;
			}
			i++;
		} // node_Type == 1
		// row is not of right nodeType
		else {
			i++;
		}

		// Cap this at X rows
		if (playersAdded >= MAX_PLAYERS) {
			break;
		}
	} // while loop
}
