/* perform some initialization */

// set the initial region
var REGIONS = new Array('Forta Region','Corfield Region','Camden Region','Buntell Region','FINAL FOUR');
var REGION_ID = 0;
var TEAMDATA;

/* I don't think you'd want to update the window more often than every
   two seconds.. that's two requests (chat window, and user list) every
   two seconds for every user. */
var refresh = 2000; // every X seconds

function changeRegion(newRegion)
{
	if (REGION_ID != newRegion)
	{
		if (newRegion == 4)
		{
			document.getElementById('pickRegion').style.display='none';
			document.getElementById('pickFinals').style.display='';
		} else {
			document.getElementById('pickRegion').style.display='';
			document.getElementById('pickFinals').style.display='none';
		}
		REGION_ID=newRegion;
		document.getElementById('regionTitle').innerHTML = REGIONS[REGION_ID];
		ncaapoolInit();
	}
}
/*
*/
function ncaapoolInit()
{

	DWREngine._execute(_cfscriptLocation, null, 'ncaapoolInit', ncaapoolInitResult);
	return false;
}

/*
*/
function updatePicks()
{
	// alert('updatePicks called');
	DWREngine._execute(_cfscriptLocation, null, 'getPicks', savePickResult);
	return false;
}

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function saveTiebreaker()
{
	// alert('saveTiebreaker called');
	var winnerTarget = document.getElementById('score_winner');
	var loserTarget = document.getElementById('score_loser');
	var winner = winnerTarget.value;
	var loser = loserTarget.value;
	var err = '';
	if ( winner == '' || loser == '')
	{
		err += 'You must enter a score for both the winner and the loser.\n';
	} else {
		if ( ! isInteger(winner || winner < 1)) {
			err += 'You entered an invalid score for the winner.\n';
		}
		if ( ! isInteger(loser || loser < 1)) {
			err += 'You entered an invalid score for the loser.\n';
		}
	}
	if (err != '')
	{
		alert(err);
		return false;
	} else {
		DWREngine._execute(_cfscriptLocation, null, 'saveTiebreaker', winner, loser, saveTiebreakerResult);
	}
	return false;
}

function saveTiebreakerResult(result)
{
	if (result)
	{
		alert('Your tiebreaker score has been saved.');
	} else {
		alert('An unknown error occurred saving your tiebreaker score.');
	}
}
/*
*/
function ncaapoolInitResult(result)
{
	var cnt = 0;
	var targetId = "";
	var target = "";
	var game_id = 0;
	var gameIdADjust = 0;
	var i = 0;
	var output="";
	var lastGameId = -1;

	TEAMDATA = result;
	gameIdAdjust = REGION_ID;
	for (i=0;i<result.length;i++)
	{
		if (REGION_ID == 4)
		{
			// don't do anything here!
		} else if (result[i].TEAM_REGION == REGIONS[REGION_ID]) {
			cnt++;
			game_id = Math.floor((result[i].TEAM_ID-0.1) / 2)+1;
			targetId = "round1seed";
			if (result[i].TEAM_RANK == 1) {
				targetId = targetId + result[i].TEAM_RANK;
			} else if (result[i].TEAM_RANK == 16) {
				targetId = targetId + '1';
			} else if (result[i].TEAM_RANK == 2) {
				targetId = targetId + result[i].TEAM_RANK;
			} else if (result[i].TEAM_RANK == 15) {
				targetId = targetId + '2';
			} else if (result[i].TEAM_RANK == 3) {
				targetId = targetId + result[i].TEAM_RANK;
			} else if (result[i].TEAM_RANK == 14) {
				targetId = targetId + '3';
			} else if (result[i].TEAM_RANK == 4) {
				targetId = targetId + result[i].TEAM_RANK;
			} else if (result[i].TEAM_RANK == 13) {
				targetId = targetId + '4';
			} else if (result[i].TEAM_RANK == 5) {
				targetId = targetId + result[i].TEAM_RANK;
			} else if (result[i].TEAM_RANK == 12) {
				targetId = targetId + '5';
			} else if (result[i].TEAM_RANK == 6) {
				targetId = targetId + result[i].TEAM_RANK;
			} else if (result[i].TEAM_RANK == 11) {
				targetId = targetId + '6';
			} else if (result[i].TEAM_RANK == 7) {
				targetId = targetId + result[i].TEAM_RANK;
			} else if (result[i].TEAM_RANK == 10) {
				targetId = targetId + '7';
			} else if (result[i].TEAM_RANK == 8) {
				targetId = targetId + result[i].TEAM_RANK;
			} else if (result[i].TEAM_RANK == 9) {
				targetId = targetId + '8';
			}
			target = document.getElementById(targetId);
			if (result[i].TEAM_RANK < 9)
			{
				target.innerHTML = '';
			}
			output = '<a href="javascript:savePick('+game_id+','+result[i].TEAM_ID+');">#'+result[i].TEAM_RANK+'&nbsp;'+result[i].TEAM_NAME+'</a>';
			if (target.innerHTML != '')
			{
				target.innerHTML = target.innerHTML + '<br/>' +output;
			} else {
				target.innerHTML = output;
			}
			lastGameId = game_id;
		}
	}
	output = "Choose A Region: ";
	for (i=0;i<5;i++)
	{
		if (REGION_ID == i)
		{
			output += '<b>'+REGIONS[i]+'</b> ';
		} else {
			output += '<a href="javascript:changeRegion(' + i + ');">' + REGIONS[i] + '</a> ';
		}
	}
	document.getElementById('changeRegionLinks').innerHTML = output;
	updatePicks();
}


/*
*/
function savePick(resultNum,team_id)
{
	// alert('savePick called');
	DWREngine._execute(_cfscriptLocation, null, 'savePick', resultNum, team_id, savePickResult);
}

/*
*/
function clearPicks(clearAll)
{
	if (!clearAll)
	{
		DWREngine._execute(_cfscriptLocation, null, 'clearPicks', REGION_ID, savePickResult);
	} else {
		DWREngine._execute(_cfscriptLocation, null, 'clearPicks', savePickResult);
	}
}


function savePickResult(result)
{
	/*
		This should update ALL of the results
	*/
	var output="";
	var i = 0;
	var game_id = 0;
	var targetId = "";
	var target = "";
	for (i=0;i<result.length;i++)
	{
		game_id = i + 1;
		targetGameId = calculateTargetGameId(game_id);
		thisRegionId = getRegionByGameId(game_id)-1;
		if (REGION_ID == 4)
		{
			if (game_id >= 57)
			{
				pick = result[i];
				switch (game_id)
				{
					case 57:
						target = document.getElementById('region1seed1');
						break;
					case 58:
						target = document.getElementById('region3seed1');
						break;
					case 59:
						target = document.getElementById('region2seed1');
						break;
					case 60:
						target = document.getElementById('region4seed1');
						break;
					case 61:
						target = document.getElementById('finalfourA');
						break;
					case 62:
						target = document.getElementById('finalfourB');
						break;
					case 63:
						target = document.getElementById('championship');
						break;
					case 64:
						target = document.getElementById('score_winner');
						break;
					case 65:
						target = document.getElementById('score_loser');
						break;
				}
				if (pick == 0 && game_id < 64) {
					target.innerHTML = '';
				} else if (game_id==63) {
					teamInfo = getTeamInfo(pick);
	 				output = '#' + teamInfo.TEAM_RANK+'&nbsp;'+teamInfo.TEAM_NAME;
	 				target.innerHTML = output;
				} else if (game_id==64) {
					target.value = pick;
				} else if (game_id==65) {
					target.value = pick;
				} else {
					teamInfo = getTeamInfo(pick);
	 				output = '<a href="javascript:savePick('+targetGameId+','+teamInfo.TEAM_ID+');">#'+teamInfo.TEAM_RANK+'&nbsp;'+teamInfo.TEAM_NAME+'</a>';
	 				target.innerHTML = output;
				}
			}
		} else if (thisRegionId == REGION_ID) {
			pick = result[i];
			targetId = getTargetId(game_id)
			target = document.getElementById(targetId);
			if (pick == 0) {
				target.innerHTML = '';
			} else if (game_id > 56) {
				teamInfo = getTeamInfo(pick);
 				output = '#' + teamInfo.TEAM_RANK+'&nbsp;'+teamInfo.TEAM_NAME;
 				target.innerHTML = output;
			} else {
				teamInfo = getTeamInfo(pick);
 				output = '<a href="javascript:savePick('+targetGameId+','+teamInfo.TEAM_ID+');">#'+teamInfo.TEAM_RANK+'&nbsp;'+teamInfo.TEAM_NAME+'</a>';
 				target.innerHTML = output;
			}
		}
	}

}

function getTeamInfo(team_id)
{
	for (var i=0; i<TEAMDATA.length; i++)
	{
		if (TEAMDATA[i].TEAM_ID == team_id)
		{
			return TEAMDATA[i];
		}
	}
	return;
}

function getTargetId(game_id)
{
	var gameTargets = new Array('round2seed1','round2seed8','round2seed5','round2seed4','round2seed3','round2seed6','round2seed7','round2seed2','round2seed1','round2seed8','round2seed5','round2seed4','round2seed3','round2seed6','round2seed7','round2seed2','round2seed1','round2seed8','round2seed5','round2seed4','round2seed3','round2seed6','round2seed7','round2seed2','round2seed1','round2seed8','round2seed5','round2seed4','round2seed3','round2seed6','round2seed7','round2seed2','round3seed1','round3seed4','round3seed3','round3seed2','round3seed1','round3seed4','round3seed3','round3seed2','round3seed1','round3seed4','round3seed3','round3seed2','round3seed1','round3seed4','round3seed3','round3seed2','round4seed1','round4seed2','round4seed1','round4seed2','round4seed1','round4seed2','round4seed1','round4seed2','round5seed1','round5seed1','round5seed1','round5seed1','finalfourA','finalfourB','championship');
	return gameTargets[game_id-1];
}

function getRegionByGameId(game_id)
{
	if (game_id <=8 ||
		(game_id >= 33 && game_id <= 36) ||
		(game_id >= 49 && game_id <= 50) ||
		game_id == 57)
	{
		return 1;
	} else if (game_id <=16 ||
		(game_id >= 37 && game_id <= 40) ||
		(game_id >= 51 && game_id <= 52) ||
		game_id == 58)
	{
		return 2;
	} else if (game_id <=24 ||
		(game_id >= 41 && game_id <= 44) ||
		(game_id >= 53 && game_id <= 54) ||
		game_id == 59)
	{
		return 3;
	} else if (game_id <=32 ||
		(game_id >= 45 && game_id <= 48) ||
		(game_id >= 55 && game_id <= 56) ||
		game_id == 60)
	{
		return 4;
	} else {
		// final four
		return 5;
	}
}

// do I need to comment my popup window?
function popup_ultraslim(url,x,y) 
{
	newWindow = window.open(url,"","width="+x+",height="+y+",left=10,top=10,bgcolor=white,resizable,scrollbars");
	if ( newWindow != null )
	{
		// make sure we're not hiding!
		newWindow.focus();
	}
}

function dumpTeamData(pick)
{
	output = '';
	if (pick == -1)
	{
		for(i=0;i<TEAMDATA.length;i++)
		{
			output += TEAMDATA[i].TEAM_RANK + ' ';
			output += TEAMDATA[i].TEAM_NAME + '\n';
		}
	} else {
		output += TEAMDATA[pick].TEAM_RANK + ' ';
		output += TEAMDATA[pick].TEAM_NAME + '\n';
	}
}

function getRoundByGameId(game_id)
{
	if (game_id <= 32) {
		return 1;
	} else if (game_id <= 48) {
		return 2;
	} else if (game_id <= 56) {
		return 3;
	} else if (game_id <= 60) {
		return 4;
	} else if (game_id <= 62) {
		return 5;
	} else if (game_id <= 63) {
		return 6;
	}
}

function calculateTargetGameId(game_id,round,region)
{
	var round = getRoundByGameId(game_id);
	var region = getRegionByGameId(game_id);
	
	if (round == 1) {
		return Math.round(game_id/2)+32;
	} else if (round == 2) {
		return Math.round((game_id-32)/2)+48;
	} else if (round == 3) {
		return Math.round((game_id-48)/2)+56;
	} else if (round == 4) {
		return Math.round((game_id-56)/2)+60;
	} else if (round == 5) {
		return Math.round((game_id-60)/2)+62;
	}
}


