var httpPlayerNameStatus = getThisHTTPObject(); 
var MAX_AS_PLAYERS_FROM_SERVER = 3000;
var MAX_AS_PLAYERS_FOR_DISPLAY = 20;
var MAX_AS_PLAYER_NAME_SIZE = 35;
var MIN_AS_PLAYERNAME_SIZE = 0;
var DIV_OFFSET = -50;
var NUM_AS_COLUMNS = 3;
var pendingAsResponse = false;
var doAnotherAfterAsPendDone = false;
var players;
var timerID = null;
var autoSuggestObject = null;
var leagueNumberAS = -1;
var uidAS = '';
var theAsYear = 2008;
var myPlayerLinks = new Array();
var idpLeague = false;

var SEPARATE_DEFENSE_AND_ST = 0;  // show both
var DEFENSE_AND_ST_COMBINED = 1;  // show def
var DEFENSE_ONLY = 2;             // show def
var ST_ONLY = 3;                  // show st
var NEITHER_D_NOR_ST = 4;         // show bubkus
var IDP_CONFIG_POS=0;
var OFFENSE_CONFIG_POS=1;
var COACH_CONFIG_POS=2;
var TEAMQB_CONFIG_POS=3;
var TEAMTE_CONFIG_POS=4;
var TEAMK_CONFIG_POS=5;
var DEFST_CONFIG_POS=6;
var leagueConfig = new Array();


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 doSetupPlayerNameCheck()
{
	var emptyArray = new Array();

	autoSuggestObject = new AutoSuggest(document.getElementById('fieldPlayerSearch'),emptyArray,1,checkPlayerNameNow,
                                       LinkToPlayerPage, MAX_AS_PLAYERS_FOR_DISPLAY, DIV_OFFSET, "autosuggest", "hideMyDiv()");
}

function setupPlayerNameCheck(ln, uid, yr, useIDP, UseOffense, useCoach, useTeamQB, useTeamTE, useTeamK, defenseConfig)
{
	theAsYear = yr;
	uidAS = uid;
	leagueNumberAS = ln;
   if (useIDP != null)
      leagueConfig[IDP_CONFIG_POS] = (useIDP == "0" || useIDP == 0 ? 0 : 1);

   if (UseOffense != null)
      leagueConfig[OFFENSE_CONFIG_POS] = (UseOffense == "0" || UseOffense == 0 ? 0 : 1);

   if (useCoach != null)
      leagueConfig[COACH_CONFIG_POS] = (useCoach == "0" || useCoach == 0 ? 0 : 1);

   if (useTeamQB != null)
      leagueConfig[TEAMQB_CONFIG_POS] = (useTeamQB == "0" || useTeamQB == 0 ? 0 : 1);

   if (useTeamTE != null)
      leagueConfig[TEAMTE_CONFIG_POS] = (useTeamTE == "0" || useTeamTE == 0 ? 0 : 1);

   if (useTeamK != null)
      leagueConfig[TEAMK_CONFIG_POS] = (useTeamK == "0" || useTeamK == 0 ? 0 : 1);

   if (defenseConfig != null)
      leagueConfig[DEFST_CONFIG_POS] = (defenseConfig == "0" || defenseConfig == 0 ? 0 : defenseConfig);

	// Delay a bit so object is defined on the page before the class defines events for it
	t=setTimeout("doSetupPlayerNameCheck()",1000);
}

// Called with the click of the button
function checkPlayerNameNow(theName)
{
	// Clear any timer that may still be running
	if (timerID) {
		clearTimeout(timerID);
		timerID = null;
	}
	var playerName;
	if (theName) {
		playerName = theName;
	}
	else {
		playerName = trim(document.PLAYER_SEARCH.Player.value);
	}

	try
	{
		// Waiting for last results, lets not hit the server again until they're back
		if (!pendingAsResponse)
		{
			if (playerName.length > MIN_AS_PLAYERNAME_SIZE) {
				getURL = "/football/player-search-provider.php?PLAYERNAME=" + escape(playerName) + 
                     (leagueConfig[IDP_CONFIG_POS]>=0 ? "&IDP=" + leagueConfig[IDP_CONFIG_POS] : "") + 
                     (leagueConfig[OFFENSE_CONFIG_POS]>=0 ? "&OFF=" + leagueConfig[OFFENSE_CONFIG_POS] : "") + 
                     (leagueConfig[COACH_CONFIG_POS]>=0 ? "&COACH=" + leagueConfig[COACH_CONFIG_POS] : "") + 
                     (leagueConfig[TEAMQB_CONFIG_POS]>=0 ? "&TQB=" + leagueConfig[TEAMQB_CONFIG_POS] : "") + 
                     (leagueConfig[TEAMTE_CONFIG_POS]>=0  ? "&TTE=" + leagueConfig[TEAMTE_CONFIG_POS] : "") + 
                     (leagueConfig[TEAMK_CONFIG_POS]>=0  ? "&TK=" + leagueConfig[TEAMK_CONFIG_POS] : "") + 
                     (leagueConfig[DEFST_CONFIG_POS]>=0 ? "&DEFST=" + leagueConfig[DEFST_CONFIG_POS] : "") + 
                     "&X=" + Math.floor(Math.random() * 99999);
				httpPlayerNameStatus.open("GET", getURL, true);
				httpPlayerNameStatus.onreadystatechange = handlePlayerNameResponse;
				httpPlayerNameStatus.send(null);
				pendingAsResponse = true;
			}
		}
		else {
			doAnotherAfterAsPendDone = true;
		}
	}
	catch (e)
	{
//		var resultsDiv = document.getElementById('FindaFriendResultBox');
//		resultsDiv.innerHTML = 'Problem Retrieving playerNames!';
	}

}


function handlePlayerNameResponse() 
{
	try
	{
		if (httpPlayerNameStatus.readyState == 4) 
		{
			pendingAsResponse = 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 (doAnotherAfterAsPendDone) {
				doAnotherAfterAsPendDone = 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');

					if (playersCount > 0) {
						players = xmlDocument.getElementsByTagName('players');
						i = 0;
						var autoPlayers = new Array();
						// Reset this array
						myPlayerLinks = new Array();
						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('last-name') + ", " + players[0].childNodes[i].getAttribute('first-name');
								playerPosTeam = ", " + players[0].childNodes[i].getAttribute('position') + ", " + players[0].childNodes[i].getAttribute('team');
								if (playerName.length > MAX_AS_PLAYER_NAME_SIZE) {
									playerName = playerName.substr(0, MAX_AS_PLAYER_NAME_SIZE) + '...';
								}
								myPlayerLinks[playersAdded] = players[0].childNodes[i].getAttribute('player-num');
								autoPlayers[playersAdded] = "<a href='javascript:PlayerCard(" + leagueNumberAS + ",\"" + uidAS + "\"," + myPlayerLinks[playersAdded] + "," + theAsYear + ",true)'>" +
                                                      playerName + playerPosTeam + "</a>";
								playersAdded++;
								i++;

							} // node_Type == 1
							// row is not of right nodeType
							else {
								i++;
							}

							// Cap this at X rows
							if (playersAdded >= MAX_AS_PLAYERS_FROM_SERVER) {
								// Todo - should do something here, a ... list item or something
								break;
							}
						} // while loop
					}  // if playersCount > 0
					else {
						// Put the "None Found" message in the middle
						// Todo - Hmmm, what to do here...
					}
					//
					// Call the function to load the auto-player-search
					//
					if (autoSuggestObject) {
						autoSuggestObject.suggestions = autoPlayers;
						autoSuggestObject.resetSuggestions();
					}
					else {
						autoSuggestObject = new AutoSuggest(document.getElementById('fieldPlayerSearch'),
															autoPlayers, 1, checkPlayerNameNow, LinkToPlayerPage, 
															MAX_AS_PLAYERS_FOR_DISPLAY, DIV_OFFSET, "autosuggest", "hideMyDiv()");
						autoSuggestObject.resetSuggestions();
					}
				} // responseText = -1
			} // doAnotherAfterAsPendDone
		} // readyState == 4
	}
	catch (e)
	{
		pendingAsResponse = false;
	}

}

function LinkToPlayerPage(index)
{

	// User selected the special last row, wanting to see all results
	if (index == -1) {
		document.PlayerSearch.submit();
		return true;
	}
	else {
		this.elem.value = '';
		PlayerCard(leagueNumberAS, uidAS, myPlayerLinks[index], theAsYear, true);
		return false;
	}

}

function hideMyDiv()
{
	autoSuggestObject.hideDiv();
}

function getThisHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}

