var numToShow = 25;
var numOfDots = 0;
var outputEle = null;
var errEle = null;
var isSearching = false;
var isSearchingForGamertag = false;

var pathToService = "../../../XBLLeaderboardSvc/Service.asmx/";
var pathToXboxWeb = "http://live.xbox.com/en-US/profile/profile.aspx?GamerTag="
var xblResultLimit = 1000;

var gameId = 0;
var currentRank = 1;
var currentLB = 0;

var titles = new Array(2);
titles[0] = "Evolved";
titles[1] = "Retro";

$j(document).ready(function(){
	startPage();
});

//Work out what leaderboard/search the user has asked for
function startPage()
{
	var winAnchor = window.location.hash;
	if (!winAnchor) { currentRank=1; initLBPage(0,1); }
	else
	{
		var hashArray = winAnchor.split("_");
		if (hashArray[0] == "#"+titles[1]) { currentLB = 1; }
		else { currentLB = 0; }

		if (hashArray[1] == "search") {
			$j('#gwreGamertag').val(hashArray[2]);
			$j('#LBNav' + currentLB).hide();
			$j('#LBNav' + (1 - currentLB)).show();
			getLeaderboardNearGamertag(currentLB, hashArray[2]);
		} else {
			initLBPage(currentLB, hashArray[2]);
		}
	}
}

function clearGamertagField()
{
	$j('#gwreGamertag').val("");
}

//Initialise everything and fetch a leaderboard
function initLBPage(pageID,rankToStart)
{
	clearGamertagField();

	$j('#LBHeader').html(titles[pageID]+" Leaderboard - Overall");
	$j('#LBNav'+pageID).hide();
	$j('#LBNav'+(1-pageID)).show();

	if ((rankToStart!=null) && (rankToStart.toString().search(/^[0-9]+$/) == 0) && (rankToStart>0)) { currentRank = rankToStart; }
	else { currentRank = 1; }
	currentLB = pageID;
	getLeaderboard(currentLB,currentRank);
}

function prevResults()
{
	clearGamertagField();
	currentRank=parseInt(currentRank);
	currentRank-=numToShow;
	if (currentRank<1) { currentRank=1; }
	toggleButtons();
	getLeaderboard(currentLB,currentRank);
}

function nextResults()
{
	clearGamertagField();
	currentRank=parseInt(currentRank);
	currentRank+=numToShow;
	toggleButtons();
	getLeaderboard(currentLB,currentRank);
}

function toggleButtons()
{
	if (currentRank<2) { $j('#prevButton').hide(); }
	else { $j('#prevButton').show(); }
}

function doInit()
{
    outputEle = $j('#outputEle');
    errEle = $j('#errorMsg');
}

function updateDots()
{
    if (isSearching)
    {
        if (numOfDots==0) { outputEle.html("Searching"); }
        if (numOfDots > 10) { numOfDots=0; }
        else {
            numOfDots++;
            outputEle.append(".");
        }
        setTimeout("updateDots();",100);
    } else { numOfDots = 0; }
}

//Grab a new leaderboard by rank
function getLeaderboard(lbId,rankToStart)
{
    if (outputEle==null) { doInit(); }
    hideError();
    isSearching=true;
	isSearchingForGamertag=false;
    setTimeout("updateDots();",100);
	window.location.hash=encodeURIComponent(titles[lbId]+"_overall_"+rankToStart);

	$j.ajax({
		type:"POST",
		contentType:"application/json",
		cache:false,
		url:pathToService+"getLeaderboard",
		processData:false,
		data:"{gameId:"+gameId+",leaderboardId:"+lbId+",rankToStart:"+rankToStart+",numToShow:"+numToShow+"}",
		dataType:'json',
		success: callComplete,
		error: callError
	});
}

//Grab a new leaderboard by GamerTag
function getLeaderboardNearGamertag(lbId)
{
	var gamertag = $j('#gwreGamertag').val();
    if (outputEle==null) { doInit(); }
    if ((gamertag==null) || (gamertag.length == 0) || (gamertag.length > 15)) { handleError("gamertag"); return false; }    
    hideError();
    isSearching=true;
	isSearchingForGamertag=gamertag;
	currentRank = 0;
    setTimeout("updateDots();",100);
	window.location.hash=encodeURIComponent(titles[lbId]+"_search_"+gamertag);
				
	$j.ajax({
		type:"POST",
		contentType:"application/json",
		cache:false,
		url:pathToService+"getLeaderboardNearGamertag",
		processData:false,
		data:"{gameId:"+gameId+",leaderboardId:"+lbId+",gamerTag:\""+gamertag+"\",numToShow:"+numToShow+"}",
		dataType:'json',
		success: callComplete,
		error: callError
	});

	$j('#LBHeader').html(titles[currentLB]+" Leaderboard - GamerTag Search");
}

//Insert data into page
function callComplete(results)
{
	isSearching=false;
	var score=0;
	var gt="";
	var rank;
    
    if ((results.d[0] == null) || (results.d[0].length == 0) || (parseInt(results.d[0])!=(results.d[0]-0)) || (results.d[0] == "Error"))
    {
        if (results.d[1] != null) { handleError(results.d[1]); }
        else { handleError("comms"); }
		$j('#nextButton').hide();
		$j('#prevButton').hide();
        return false;
    } else {
        
        if (results.d[0] == 0)
		{
			$j('#nextButton').hide();
			$j('#prevButton').hide();
			outputEle.html("No results found. Try going <a href=\"javascript:getLeaderboard("+currentLB.toString()+",1);\">back to the top</a> of this leaderboard.");
		} else {
			buffer="";
            for(var i=0; i<results.d[0]; i++)
            {
				gt = results.d[(i*3)+2];
				score = addCommas(results.d[(i*3)+3]);
				rank = results.d[(i*3)+1];
				buffer += "<div class=\"resContainer";
				if (isSearchingForGamertag != false) {
					if (isSearchingForGamertag.toLowerCase() == gt.toLowerCase()) { buffer += "Highlight"; }
					if (currentRank==0) { currentRank = rank; }
				}
                buffer += "\">\n<div class=\"left\">"+rank+".</div>\n<div class=\"mid\"><a href=\""+pathToXboxWeb+encodeURIComponent(gt)+"\" target=\"blank\">"+gt+"</a></div>\n<div class=\"right\">"+score+"</div>\n</div>";
            }
			outputEle.html(buffer);
			//animResults(0,$j('.resContainer').length);
			
			//Hide next button if applicable
			if (results.d[0] < numToShow) { $j('#nextButton').hide(); }
			else { $j('#nextButton').show(); }
			toggleButtons();
			
			//Hide both previous and next if past XBL result limit
			if (results.d[1] > xblResultLimit-numToShow) { $j('#nextButton').hide(); $j('#prevButton').hide(); }
        }
    }

	isSearchingForGamertag=false;
}

//Animate the rows in
function animResults(index,numToLoop)
{
	if (index < numToLoop) {
		$j('.resContainer').eq(index).slideToggle(15,function() { animResults(index + 1,numToLoop); });//, animResults(index + 1,numToLoop));
	}
}

//From http://www.mredkj.com/javascript/nfbasic.html
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function callError(error) { isSearching=false; handleError("comms"); return false; }

//Deal with all errors
function handleError(errorCode)
{
    errEle.show();
    switch (errorCode)
    {
        case "comms":
            errEle.html("A communications error has occured. Please try again in a few minutes.");
            break;
        case "gamertag":
            errEle.html("Please fill in a valid GamerTag");
            break;
        default:
            errEle.html("An error has occured! Code: "+errorCode);
            break;
    }
	
	errEle.append("<br/>If this error continues to occur, please contact the <a href=\"mailto:webdev@bizarrecreations.com\">Web Team</a>.");
}

function hideError() { errEle.hide(); }