var baseURL = window.location.protocol + "//" + window.location.host
var xmlhttpObj="";
var xmlhttpObj1="";
var xmlDoc = null;
var xmlDoc2 = null;
var timerID=0;
var selectedTrackId=""
var selectedRace=""
var dateOnFileName = ""

function getLink() {
	//return baseURL+"/toteboard/totexmldata.jsp?TRK="+selectedTrackId+"&RN="+selectedRace+"&TYPE=cycle&rand="+ Math.random();
	dateOnFileName = formatDate(new Date(),"yyyy-MM-dd")
	//alert("the date value on file  name is "+ dateOnFileName)
	return baseURL+"/totedata/JCL "+selectedTrackId+" cycle race "+selectedRace+".xml?rand=" + Math.random();
	//return baseURL+"/totedata/JCL "+selectedTrackId+" "+dateOnFileName+" cycle race "+selectedRace+".xml?rand=" + Math.random();
}

function loadRaceData_Begin()
{
window.status = "Loading Race Data...";
xmlhttpObj = GetXMLHTTPConnection();
xmlhttpObj.open("GET", getLink(), true);
xmlhttpObj.onreadystatechange = loadRaceData_End;
xmlhttpObj.send(null);
}

function loadRaceData_End()
{
        // if xmlhttp shows "loaded"
        if (xmlhttpObj.readyState==4)
        {
                // if "OK"
                if (xmlhttpObj.status == 200) {
                        var responseXML = xmlhttpObj.responseXML;
                        if (responseXML != null )
                        {
                                xmlDoc = responseXML.documentElement;
                        }
                }
                updateHeader();
        }
        window.status=""
}

function loadWillPayData_Begin()
{
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 "+selectedRace+".xml?rand=" + Math.random(), true);
//xmlhttpObj.open("GET", baseURL+"/totedata/JCL "+selectedTrackId+" "+dateOnFileName+" willpays race "+selectedRace+".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() {
    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="DetailHeader" width="100%">'
    ProgramTable+='<tr><td class="TrackHeader" width="33%" align="left">'+rootElement.getAttribute("Name")+'&nbsp; - &nbsp; Race '+rootElement.getAttribute("Race")+'</td>'
    ProgramTable+='<td class="TrackHeader" width="33%" align="center">'+mtpValGenerate(mtpVal)+'</td>'
    ProgramTable+='<td class="TrackHeader" width="33%" align="right">Post Time: &nbsp; '+removeSecond(rootElement.getAttribute("Post"))+'</td></tr></table>';

    ProgramTable+='<table width="100%"  border="1" bordercolor="black" style="border-collapse:collapse"><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="RowHeader" width="100%"><tr><td width="33%"> Current Time: &nbsp; '+getClockTime()+'</td>'
    ProgramTable+='<td width="33%" align="right"> Last Updated: &nbsp; '+removeDate(rootElement.getAttribute("UpdateTime"))+'</td>'
    ProgramTable+='</tr></table></div>'
    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="10%">&nbsp;</td><td width="80%" align="center">'
    ProgramTable+='<table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="black" style="border-collapse:collapse">'
    ProgramTable+='<tr class="DetailHeader"><td align="center" class="WagerHeader" >Probables & Will Pays</td></tr>'
    var probableList="";
    if (currentPool !='WPS')
        probableList='<td width="25%"  align="center"><a href="'+getFileName("WPS")+'" class="wager">W/P/S</a></td>'
	probableList+=getProbableList(currentPool, poolName, currentRace);
    ProgramTable+='</tr><tr><td><table width="100%" cellspacing="0" cellpadding="0">'
    ProgramTable+='<tr bgcolor="black">'
    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)+'" class="wager">'+replaceName(poolName)+'</a></td>'
			} else {
				if (currentPoolName == 'DAILY DOUBLE WILL PAY') {
					probableList+='<td width="25%" align="center"><a href="'+getFileName(poolId)+'" class="wager">'+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")+'" class="wager">DOUBLE('+(currentRace - 1 )+','+currentRace+')</a></td>'
				} else {
					willPayList+='<td width="25%" align="center"><a href="'+getFileName(poolId)+'"  class="wager">'+replaceName(poolName)+'</a></td>'
				}
			} else {
				if (currentPoolName == 'DAILY DOUBLE PROBABLE') {
					willPayList+='<td width="25%" align="center"><a href="'+getFileName("DBLAF")+'" class="wager">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 class="RowHeader"><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 class="RowHeader"><table width="100%" cellpadding="0" cellspacing="0"><tr><td width="45%">&nbsp;</td><td width="20%" class="RowHeader">'+pgmRunners[i].getAttribute("Number")+'</td><td class="RowHeader">&nbsp;WITH</td></tr></table></td>'
	        else 
	            ProgramTable+='<tr><td class="RowHeader"><table width="100%" cellpadding="0" cellspacing="0"><tr><td width="45%">&nbsp;</td><td width="20%" class="RowHeader">'+pgmRunners[i].getAttribute("Number")+'</td><td class="RowHeader">&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 class="RowTotal" ><td class="RowTotal" colspan="'+(rowIndex+1)+'" align="center" >'+currentPoolName+' TOTAL: &nbsp;'+removeCents(totalValue)+'</td></tr>'                 
        ProgramTable+='</table></div>\n'
        document.getElementById("TotePoolInfo").innerHTML=ProgramTable;
    } else {
    noToteDataFound();
    return;
    }
}


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 class="RowHeader"><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" class="RowHeader">'+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 class="RowTotal" ><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 class="RowHeader"><td colspan="2" align="center">'+currentPoolName+'</td></tr>'    
	    ProgramTable+='<tr class="RowHeader"><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()
{
    if(timerID)
    {
            clearTimeout(timerID);
            timerID  = 0;
    }

    // why is there a delay here?
    // timerIDRaceChange = setTimeout("dataLoader()",500);
    dataLoader();
    timerID = setTimeout("timedEvents()", 60000);
}
function timedEvents()
{
    dataLoader();
    timerID = setTimeout("timedEvents()",60000);
}
// Load all associated data with selected race
function dataLoader()
{
    loadTrackData_Begin();
}

function setTrackData(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 width="28%" class="TrackHeader" 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){
}

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/toteboard.shtml';
}
}