var baseURL = window.location.protocol + "//" + window.location.host
var xmlhttpObj = "";
var xmlhttpObj1 = "";
var xmlDoc = null;
var xmlDoc2 = null;
var timerID = 0;
var selectedTrackId = ""
var selectedTracks = ""
var selectedRace = ""
var dateOnFileName = "";

function getLink() {
	dateOnFileName = formatDate(getCurrentUTCDate(), "yyyy-MM-dd", true);
	return baseURL + "/totedata/DRF " + selectedTrackId + " " + dateOnFileName + " cycle race " + formatRaceNumber(selectedRace) + ".xml?rand=" + Math.random();
}

function loadRaceData_Begin() {
	window.status = "Loading Race Data...";
	xmlhttpObj = GetXMLHTTPConnection();
	// alert(getLink());
	// window.location=getLink();
	xmlhttpObj.open("GET", getLink(), true);
	xmlhttpObj.onreadystatechange = loadRaceData_End;
	xmlhttpObj.send(null);

}

function loadRaceData_End() {
	// alert("Second Page loadRaceData_End()");
	// if xmlhttp shows "loaded"
	if (xmlhttpObj.readyState == 4) {
		// if "OK"
		// alert(xmlhttpObj.status);
		if (xmlhttpObj.status == 200) {
			var responseXML = xmlhttpObj.responseXML;
			if (responseXML != null) {
				xmlDoc = responseXML.documentElement;
			}
		}
		updateHeader();
		// updateHeaderInformation();

	}
	window.status = ""
}

function loadWillPayData_Begin() {
	dateOnFileName = formatDate(getCurrentUTCDate(), "yyyy-MM-dd", true);

	window.status = "Loading Willpay Data...";
	xmlhttpObj = GetXMLHTTPConnection();
	// xmlhttpObj.open("GET",
	// baseURL+"/toteboard/totexmldata.jsp?TRK="+selectedTrackId+"&RN="+selectedRace+"&TYPE=willpay&rand="+
	// Math.random(), true);
	xmlhttpObj.open("GET", baseURL + "/totedata/JCL " + selectedTrackId + " willpays race " + formatRaceNumber(selectedRace) + ".xml?rand=" + Math.random(), true);
	// xmlhttpObj.open("GET", baseURL+"/totedata/JCL "+selectedTrackId+"
	// "+dateOnFileName+" willpays race "+raceStr+".xml?rand=" + Math.random(),
	// true);
	xmlhttpObj.onreadystatechange = loadWillPayData_End;
	xmlhttpObj.send(null);
}

function loadWillPayData_End() {
	// if xmlhttp shows "loaded"
	if (xmlhttpObj.readyState == 4) {
		// if "OK"
		if (xmlhttpObj.status == 200) {
			var responseXML = xmlhttpObj.responseXML;
			if (responseXML != null) {
				xmlDoc2 = responseXML.documentElement;
			}
		}
		updateWager();
	}
	window.status = ""
}
function getHeaderInfo() {

	// alert("Second Page: getHeaderInfo()");
	var rootElement = xmlDoc
	var ProgramTable = "";
	if (xmlDoc == null) {
		noToteDataFound();
		return;
	}
	var mtpVal = rootElement.getAttribute("MTP")
	if (mtpVal == null) {
		mtpVal = 0
	}
	program = rootElement.getElementsByTagName("Program");
	if (program[0] == null) {
		noToteDataFound();
		return;
	}
	pgmRunners = program[0].getElementsByTagName("Runner");
	var oddsRunners = null;
	if (rootElement.getElementsByTagName("Odds")[0] != null) {
		oddsRunners = rootElement.getElementsByTagName("Odds")[0].getElementsByTagName("Runner");
		if ("Y" == rootElement.getElementsByTagName("Odds")[0].getAttribute("Final")) {
			mtpVal = "CLOSED";
		}
	}
	ProgramTable += '<div id="raceInfo">'
	ProgramTable += '<table class="tjctable" width="100%">'
	ProgramTable += '<tr><td width="33%" align="left">' + rootElement.getAttribute("Name") + '&nbsp; - &nbsp; Race ' + rootElement.getAttribute("Race") + '</td>'
	ProgramTable += '<td width="33%" align="center">' + mtpValGenerate(mtpVal) + '</td>'
	ProgramTable += '<td>Post Time: &nbsp; ' + removeSecond(rootElement.getAttribute("Post")) + '</td></tr></table>';

	ProgramTable += '<table width="100%"  border="1" bordercolor="black" style="border-collapse:collapse" class="tjctable"><tr><td width="15%"><b>PROGRAM #</b></td>'
	colWidth = parseInt((85 / pgmRunners.length))
	for ( var i = 0; i < pgmRunners.length; i++) {

		var programNumber = pgmRunners[i].getAttribute("Number")
		if (isNaN(programNumber)) {
			programNumber = programNumber.substring(0, programNumber.length - 1);
		}
		ProgramTable += '<td align="center" width="' + colWidth + '%" class="horse' + programNumber + '">' + pgmRunners[i].getAttribute("Number") + '</td>'
	}
	ProgramTable += '</tr><tr><td><b>ODDS</b></td>'
	var scratchArr = getScratchedHorses(xmlDoc.getAttribute("Scratches"));
	if (oddsRunners != null) {

		var previousOdds = '&nbsp'
		for ( var i = 0; i < pgmRunners.length; i++) {
			var currentOdds = '&nbsp'

			for ( var j = 0; j < oddsRunners.length; j++) {
				if (pgmRunners[i].getAttribute("Number") == oddsRunners[j].getAttribute("Number")) {
					currentOdds = oddsRunners[j].getAttribute("Odd");
					previousOdds = currentOdds;
					if (IsHorseScratched(scratchArr, pgmRunners[i].getAttribute("Number"))) {
						currentOdds = 'SCR'
					}
					break;
				}
			}
			if (isNaN(pgmRunners[i].getAttribute("Number"))) {
				ProgramTable += '<td align="center" >' + previousOdds + '</td>'
			}
			else {
				if (currentOdds == '&nbsp' || currentOdds == null) {
					currentOdds = '&nbsp';
					previousOdds = '&nbsp';
				}
				ProgramTable += '<td align="center" >' + currentOdds + '</td>'
			}
		}
	}
	ProgramTable += '</tr><tr><td><b>MORNING LINE</b></td>'

	var previousMline = '&nbsp'
	for ( var i = 0; i < pgmRunners.length; i++) {
		var mLine = '&nbsp'

		if (pgmRunners[i].getAttribute("Odds") != null) {
			mLine = pgmRunners[i].getAttribute("Odds");
			previousMline = mLine;
		}
		if (isNaN(pgmRunners[i].getAttribute("Number")))
			ProgramTable += '<td align="center" >' + previousMline + '</td>'
		else
			ProgramTable += '<td align="center" >' + mLine + '</td>'
	}
	ProgramTable += '</tr></table>\n'
	ProgramTable += '<table  class="tjctable" width="100%"><tr><td width="100%"> Current Time: &nbsp; ' + getServerTime() + '</td>'
	ProgramTable += '<td width="50%" align="right"> Last Updated: &nbsp; ' + removeDate(rootElement.getAttribute("UpdateTime")) + '</td>'
	ProgramTable += '</tr></table></div>'

	// alert(ProgramTable);

	// document.getElementById("ToteProgramInfo").innerHTML=ProgramTable;
}

function getWagerInfo(currentPool, poolName) {

	var rootElement = xmlDoc
	var ProgramTable = "";
	if (rootElement == null)
		return;
	var currentRace = parseInt(rootElement.getAttribute("Race"))
	ProgramTable += '<br/><div id="wagerInfo">'
	ProgramTable += '<table cellspacing="0" cellpadding="0" width="100%" ><tr><td width="50%">&nbsp;</td><td width="80%" align="center">'
	ProgramTable += '<table  class="tjctable" style="border-collapse:collapse">'
	ProgramTable += '<tr><td>Probables & Will Pays</td></tr>'
	var probableList = "";
	if (currentPool != 'WPS')
		probableList = '<td width="25%"  align="center"><a href="' + getFileName("WPS") + '">W/P/S</a></td>'
	probableList += getProbableList(currentPool, poolName, currentRace);
	ProgramTable += '</tr><tr><td><table width="100%" cellspacing="0" cellpadding="0">'
	ProgramTable += '<tr>'
	ProgramTable += probableList
	ProgramTable += '</tr></table></td></tr>'
	ProgramTable += '<tr><td><table width="100%" cellspacing="0" cellpadding="0">'
	ProgramTable += '<tr bgcolor="black">'
	ProgramTable += getWillPayList(currentPool, poolName, currentRace)
	ProgramTable += '</tr></table></td></tr></table>'
	ProgramTable += '<td>'
	ProgramTable += '<td width="10%"><table><tr><td><a href="javascript:gotoResult()" style={color:black}" ><b>RESULTS</b></a></td></tr>'
	var Track = document.getElementById("Track");
	if (Track != null) {
		ProgramTable += '<tr><td nowrap="nowrap"><a href="javascript:gotoToteIndex()" style={color:black}" ><b>TRACK INDEX</b></a></td></tr>'
	}
	ProgramTable += '</td>'
	ProgramTable += '</tr></table></div>\n';
	document.getElementById("ToteWagerInfo").innerHTML = ProgramTable;
}
function getProbableList(currentPool, currentPoolName, currentRace) {
	var probableList = "";
	var probable = xmlDoc.getElementsByTagName('Probable');
	for (index = 0; index < probable.length; index++) {
		if (probable[index].hasChildNodes()) {
			var poolId = probable[index].getAttribute("Pool");
			var poolName = probable[index].getAttribute("Name");
			if (currentPool != poolId) {
				probableList += '<td width="25%" align="center"><a href="' + getFileName(poolId) + '">' + replaceName(poolName) + '</a></td>'
			}
			else {
				if (currentPoolName == 'DAILY DOUBLE WILL PAY') {
					probableList += '<td width="25%" align="center"><a href="' + getFileName(poolId) + '">' + replaceName(poolName) + '</a></td>'
				}
			}
		}
	}
	return probableList;
}
function getWillPayList(currentPool, currentPoolName, currentRace) {
	var willPayList = "";
	if (xmlDoc2 == null)
		return willPayList;
	var willpay = xmlDoc2.getElementsByTagName('Willpay');
	for (index = 0; index < willpay.length; index++) {
		if (willpay[index].hasChildNodes()) {
			var poolId = willpay[index].getAttribute("Pool");
			var poolName = willpay[index].getAttribute("Name");
			if (currentPool != poolId) {
				if (poolId == 'DBL') {
					willPayList += '<td width="25%" align="center"><a href="' + getFileName("DBLAF") + '">DOUBLE(' + (currentRace - 1) + ',' + currentRace + ')</a></td>'
				}
				else {
					willPayList += '<td width="25%" align="center"><a href="' + getFileName(poolId) + '" >' + replaceName(poolName) + '</a></td>'
				}
			}
			else {
				if (currentPoolName == 'DAILY DOUBLE PROBABLE') {
					willPayList += '<td width="25%" align="center"><a href="' + getFileName("DBLAF") + '">DOUBLE(' + (currentRace - 1) + ',' + currentRace + ')</a></td>'
				}
			}
		}
	}
	return willPayList;
}
function getPoolInfo(currentPoolId, currentPoolName) {
	var rootElement = xmlDoc
	if (rootElement == null) {
		noToteDataFound();
		return;
	}
	var ProgramTable = "";
	// go thru each Probable node and find out the Exacta Runners
	var colWdith = 0;
	var probable = rootElement.getElementsByTagName('Probable');
	poolRunners = null;
	var totalValue = 0
	var minimumAmt = null;
	for (index = 0; index < probable.length; index++) {
		if (probable[index].hasChildNodes()) {
			if (probable[index].getAttribute("Pool") == currentPoolId) {
				totalValue = probable[index].getAttribute("Total")
				minimumAmt = probable[index].getAttribute("Minimum")
				poolRunners = probable[index].getElementsByTagName("Runner");
			}
		}
	}

	if (poolRunners != null && poolRunners.length > 0) {
		rowIndex = poolRunners[0].getAttribute("MaxRunner")
		colWidth = parseInt((85 / rowIndex))
		ProgramTable += '<br/><div id="dataInfo"> '
		ProgramTable += '<table width="100%"  border="1" bordercolor="black" style="border-collapse:collapse"><tr><td width="15%" align="center">' + currentPoolName + ' PROBABLES</td>'
		for ( var i = 0; i < rowIndex; i++) {
			ProgramTable += '<td align="center">' + (i + 1) + '</td>'
		}
		ProgramTable + '</tr></table>'
		for ( var i = 0; i < pgmRunners.length; i++) {
			if (isNaN(pgmRunners[i].getAttribute("Number")))
				continue;
			if (i == 0)
				ProgramTable += '<tr><td><table width="100%" cellpadding="0" cellspacing="0"><tr><td width="45%">&nbsp;</td><td width="20%">' + pgmRunners[i].getAttribute("Number") + '</td><td>&nbsp;WITH</td></tr></table></td>'
			else
				ProgramTable += '<tr><td><table width="100%" cellpadding="0" cellspacing="0"><tr><td width="45%">&nbsp;</td><td width="20%">' + pgmRunners[i].getAttribute("Number") + '</td><td>&nbsp;</td></tr></table></td>'
			index = null
			for (j = 0; j < poolRunners.length; j++) {
				if (pgmRunners[i].getAttribute("Number") == poolRunners[j].getAttribute("Number")) {
					index = j;
					break;
				}
			}
			if (index != null) {
				var withVal = poolRunners[index].getElementsByTagName('With');
				for (j = 0; j < withVal.length; j++) {
					if (withVal[j].getAttribute("Price") != null) {
						ProgramTable += '<td width="' + colWidth + '%" align="center">' + convertTo2Dollar(minimumAmt, withVal[j].getAttribute("Price")) + '</td>'
					}
					else {
						ProgramTable += '<td width="' + colWidth + '%">&nbsp;</td>'
					}
				}
			}
			else {
				for (j = 0; j < rowIndex; j++) {
					ProgramTable += '<td width="' + colWidth + '%" align="center">---</td>'
				}
			}
			ProgramTable += '</tr>'
		}
		ProgramTable += '<tr><td colspan="' + (rowIndex + 1) + '" align="center" >' + currentPoolName + ' TOTAL: &nbsp;' + removeCents(totalValue) + '</td></tr>'
		ProgramTable += '</table></div>\n'
		document.getElementById("TotePoolInfo").innerHTML = ProgramTable;
	}
	else {
		noToteDataFound();
		return;
	}
}

// New Method to get WageringInfo

function getWagerInfoPool(currentPool, poolName) {

	var calendarDate = getCalendarDate();
	var clockTime = getServerTime();
	var rootElement = xmlDoc
	var PrgTbl = "";
	if (rootElement == null)
		return;
	var currentRace = parseInt(rootElement.getAttribute("Race"))
	pgmPool = rootElement.getElementsByTagName("Pool");

	// Track = document.getElementById("Track");
	// var TrackName = document.getElementByID("Name");
	// alert("TrackName"+TrackName)
	PrgTbl += '<br/><div id="wagerInfoPool">'
	PrgTbl += '<table class="tjctable" ><tr><td width="50%">&nbsp;</td><td width="80%" align="center">'
	PrgTbl += '<table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="black" style="border-collapse:collapse">'
	PrgTbl += '<tr><td align="center">' + selectedTrackId + '</td></tr>'
	PrgTbl += '</tr><tr><td><table width="100%" cellspacing="0" cellpadding="0">'
	PrgTbl += '<tr><td align="center">Wagering Format</td></tr>'
	PrgTbl += '<tr><td align="center">Date</tr>'
	PrgTbl += '</tr></table></td></tr>'
	var poolTable = "";
	poolTable += '<table border = "1" width = "100%" bordercolor="black" >'
	poolTable += '<tr><td>Race - ' + currentRace + '</td>'
	for ( var i = 0; i < pgmPool.length; i++) {
		var programMin = pgmPool[i].getAttribute("Minimum");
		var programName = pgmPool[i].getAttribute("Name");
		// alert("programMin"+programMin);
		// alert("programName"+programName);

		poolTable += '<td align="Right">' + programMin + '</td></tr>'

	}
	poolTable += '</table>'
	document.getElementById("ToteWagerInfoPool").innerHTML = poolTable;
}
// End of new method

function getWillPayInfo(currentPoolId, currentPoolName, endOfRaceVal) {
	if (xmlDoc2 == null) {
		noToteDataFound();
		return;
	}
	var willpay = xmlDoc2.getElementsByTagName('Willpay');
	var poolRunners = null;
	var totalValue = 0
	var willPayRace = 0
	var minimumAmt = null;
	for (index = 0; index < willpay.length; index++) {
		if (willpay[index].hasChildNodes()) {
			if (willpay[index].getAttribute("Pool") == currentPoolId) {
				poolRunners = willpay[index].getElementsByTagName("Runner");
				totalValue = willpay[index].getAttribute("Net")
				minimumAmt = willpay[index].getAttribute("Minimum")
				willPayRace = willpay[index].getAttribute("BeginRace")
			}
		}
	}
	if (poolRunners != null && poolRunners.length > 0) {

		var winner = poolRunners[0].getAttribute("Winners")
		var maxRunner = poolRunners[0].getAttribute("MaxRunner")
		var ProgramTable = "";
		ProgramTable += '<br/><div id="dataInfo"> '
		ProgramTable += '<table width="100%"  border="1" bordercolor="black" style="border-collapse:collapse"><tr><td width="20%" align="center">' + currentPoolName + ' WILL PAY</td>'
		for ( var i = 0; i < maxRunner; i++) {
			ProgramTable += '<td align="center">' + (i + 1) + '</td>'
		}
		ProgramTable += '</tr>'
		ProgramTable += '<tr><td  nowrap="nowrap" align="center">' + winner + '&nbsp;&nbsp;&nbsp;WITH </td>'
		pays = poolRunners[0].getElementsByTagName("Pays");
		for ( var i = 0; i < pays.length; i++) {
			ProgramTable += '<td align="center">' + convertTo2Dollar(minimumAmt, pays[i].getAttribute("Price")) + '</td>'
		}
		ProgramTable += '</tr>'
		ProgramTable += '<tr><td colspan="' + (maxRunner + 1) + '" align="center" >' + currentPoolName + ' (' + willPayRace + '-' + endOfRaceVal + ')  TOTAL: &nbsp;' + removeCents(totalValue)
				+ '</td></tr></table>'
		ProgramTable += '</div>\n'
		document.getElementById("TotePoolInfo").innerHTML = ProgramTable;
		ProgramTable = ""
	}
	else {
		noToteDataFound();
		return;
	}
}

function isWillPayExists(poolId) {
	if (poolId == 'EX' || poolId == 'QU' || poolId == 'WPS')
		return true;
	var flag = false;
	if (xmlDoc2 == null) {
		return false;
	}
	var willpay = xmlDoc2.getElementsByTagName('Willpay');
	if (willpay[0] == null) {
		return false;
	}
	else {
		for (i = 0; i < willpay.length; i++) {
			if (willpay[i].getAttribute("Pool") == poolId) {
				flag = true;
				break;
			}
		}
	}
	return flag;
}
function getPriceInfo(pools, currentPoolId, currentPoolName) {
	var ProgramTable = ""
	var prices = null;
	for (index = 0; index < pools.length; index++) {
		if (pools[index].getAttribute("Pool") == currentPoolId) {
			prices = pools[index].getElementsByTagName("Price");
			break;
		}
	}
	if (prices != null && prices.length > 0) {
		ProgramTable += '<br/><div id="dataInfo"> '
		ProgramTable += '<table width="50%"  border="1" bordercolor="black" style="border-collapse:collapse">'
		ProgramTable += '<tr><td colspan="2" align="center">' + currentPoolName + '</td></tr>'
		ProgramTable += '<tr><td align="center">Winner</td><td align="center">Price</td></tr>'
		for ( var i = 0; i < prices.length; i++) {
			ProgramTable += '<tr>'
			ProgramTable += '<td align="center">' + prices[i].getAttribute("Winners") + '</td>'
			ProgramTable += '<td align="center">' + prices[i].getAttribute("Price") + '</td>'
			ProgramTable += '</tr>'
		}
		ProgramTable += '</table></div>\n'
		document.getElementById("TotePoolInfo").innerHTML = ProgramTable;
		ProgramTable = ""
	}
	else {
		noToteDataFound();
		return;
	}
}

// Race On Change Event
function OnDataChange() {
	// alert("Second Page: OnDataChange()");
	if (timerID) {
		// alert("OnDataChange IF" +timerID);
		clearTimeout(timerID);
		timerID = 0;
	}

	// why is there a delay here?
	// timerIDRaceChange = setTimeout("dataLoader()",500);
	dataLoader();
	// Changed by Raghu on 06/04/2008
	// timerID = setTimeout("timedEvents()", 60000);
	timerID = setTimeout("timedEvents()", 20000);
}
function timedEvents() {
	// alert("timedEvents ");
	dataLoader();
	// alert("timedEvents after data loader")
	// Changed by Raghu on 06/04/2008
	// timerID = setTimeout("timedEvents()",60000);
	timerID = setTimeout("timedEvents()", 20000);
}
// Load all associated data with selected race
function dataLoader() {
	// alert("Second Page: dataLoader()");
	loadTrackData_Begin();
}

function setTrackData(trk) {
	// alert("trk "+trk);
	selectedTrackId = trk;
	OnDataChange();
}

function noToteDataFound() {
	// document.getElementById("TotePoolInfo").innerHTML='<br/><b>No records
	// found.</b><br/><br/>';
}

function replaceName(poolName) {
	if (poolName == 'PICK THREE')
		return 'PICK 3';
	else if (poolName == 'PICK FOUR')
		return 'PICK 4';
	else if (poolName == 'PICK SIX')
		return 'PICK 6';
	else
		return poolName;
}
function mtpValGenerate(mtpVal) {
	if (mtpVal == null)
		return "&nbsp";
	mtpCol = '<table class="tjctable" border="1" bordercolor="black" style="border-collapse:collapse"><tr>'
	if ("CLOSED" == mtpVal)
		mtpCol += '<td nowrap="nowrap" align="center" class="normal">&nbsp;' + mtpVal + '&nbsp;</td>';
	else if (mtpVal > 3 && mtpVal < 10)
		mtpCol += '<td nowrap="nowrap" align="center" class="warning">&nbsp;' + mtpVal + ' MTP&nbsp;</td>'
	else if (mtpVal > 0 && mtpVal <= 3)
		mtpCol += '<td nowrap="nowrap" align="center" class="danger">&nbsp;' + mtpVal + ' MTP&nbsp;</td>'
	else
		mtpCol += '<td nowrap="nowrap" align="center" class="normal">&nbsp;' + mtpVal + ' MTP&nbsp;</td>';
	mtpCol += '</tr></table>'
	return mtpCol;
}

function Track_OnChange(value) {
	selectedTrackId = value.substring(0, value.indexOf(','));
	selectedRace = value.substring(value.indexOf(',') + 1)
	gotoPool('WPS')
}
function Links_OnChange(value) {
}
// Go Back to Parent Window
function closeAndFocusParent() {
	if (typeof version != 'undefined' && version == 'jsp') {
		window.location = baseURL + '/tote/Home/drftoteboard.jsp';
	}
	else {
		window.location = baseURL + '/tote/Home/drftoteboard.jsp';
	}
}
// Close the current window
/*
 * function closeAndFocusParent() { self.close() if (window.opener != null)
 * window.opener.focus(); }
 */

function gotoToteIndex() {
	if (typeof version != 'undefined' && version == 'jsp') {
		window.location = baseURL + '/jhome/toteboard/toteboard.jsp';
	}
	else {
		window.location = baseURL + '/tote/Home/drftoteboard.jsp';
	}
}