function chance_odds(info)
{
	var chance =parseFloat(document.calc.chance.value);
	if(chance>0)
	{
		european = places(1/chance,2);
		decimal = (1/chance) - 1;
		document.calc.european.value = european;
		
		if (decimal >= 1)
		{
			american='+' + Math.round(100*decimal);
		} else {
			american=Math.round(-100/decimal);
		}
		document.calc.american.value = american;
		
		english=fraction(decimal);
		document.calc.english.value = english;
	} else {
		document.calc.european.value = '';
		document.calc.english.value = '';
		document.calc.american.value = '';
	}
}
function places(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
function fraction(decimal)
{
	for(denom=1;denom<99;denom++)
	{
		if(Math.round(100*decimal*denom) == 100*Math.round(decimal*denom))
		{
			return Math.round(decimal*denom) + '/' + denom;
		}
	}
	return false;
}


var xmlHttp

function stateChanged() 
{ 
	if (xmlHttp.readyState==4)
	{ 
		document.getElementById('interactive').innerHTML=xmlHttp.responseText;
	}
} 

function stateChanged2() 
{ 
	if (xmlHttp.readyState==4)
	{ 
		document.getElementById('interactive2').innerHTML=xmlHttp.responseText;
	}
} 

function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
    {    
		// Firefox, Opera 8.0+, Safari    
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
    {    
		// Internet Explorer    
		try
		{      
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      
		}
		catch (e)
		{      
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}    
	}  
	return xmlHttp;
}


function changeDisplay( elementId, setTo ) {

    if( document.getElementById ) {
        //DOM
        var theElement = document.getElementById( elementId );
    } else {
        if( document.all ) {
            //Proprietary DOM
            var theElement = document.all[ elementId ];
        } else {
            //Create an object to prevent errors further on
            var theElement = new Object();
        }
    }
    if( !theElement ) {
        /* The page has not loaded or the browser claims to support
        document.getElementById or document.all but cannot actually
        use either */
        return;
    }
    //Reference the style ...
    if( theElement.style ) { theElement = theElement.style; }
    if( typeof( theElement.display ) == 'undefined' &&
    !( window.ScriptEngine && ScriptEngine().indexOf('InScript') + 1 ) ) {
      window.alert( 'Sorry Your Browser wont work with these menus' );
      return;
    }
    //Change the display style
    theElement.display = setTo;
}

function bookmakers(field)
{
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
	  alert ("Sorry.  Your browser is too old or unusual for this page to work.  The rest of the site will work fine though.");
	  return;
	} 
	
	Currencynotes=document.filter.Currencynotes.options[filter.Currencynotes.selectedIndex].value;
	Deposit=document.filter.Deposit.options[filter.Deposit.selectedIndex].value;
	Languages=document.filter.Languages.options[filter.Languages.selectedIndex].value;
	
	var url = '/school/units/bookmakers.php?';
	var params = 'Currencynotes=' + Currencynotes
	+ '&Deposit=' + Deposit
	+ '&Languages=' + Languages
	+ '&sid=' + Math.random();
	
	//load data
	xmlHttp.onreadystatechange=stateChanged;
	xmlHttp.open("GET",url + params,true);
	xmlHttp.send(null);
}

function showpop(id)
{
	changeDisplay( id, 'block' );
}
function hidepop(id)
{
	changeDisplay( id, 'none' );
}

function change_content(id,content)
{
	document.getElementById(id).innerHTML=content;
}

function over_odds(runners)
{
	percent = document.bookieodds.overround.options[bookieodds.overround.selectedIndex].value;
	decimal=(100*runners)/percent;
	for(i=0;i<runners;i++) {
		document.getElementById('odds' + i).innerHTML=fraction(decimal-1);
	}
	if(percent<100) {
		var comment='<p><b>Favourable Market</b><p>When the overround is less than 100 this means that the odds are actually in the punters favour.  This is known as arbitrage. No single bookie would ever deliberately price a market in this way but because bookies offer different odds sometimes by taking the best odds from each one you can find a favourable market.  They rarely last long however before the prices change';
	} else if (percent>100) {
		var comment='<p><b>Bookies Margin</b><p>When the overround is over 100 this indicates an unfair market, and that the bookmaker is making a margin.  The higher the number the bigger the bookies margins.  Typical margins for a single bookmaker would be between 5% and 20% but they can be higher especially for novelty bets and markets (e.g. scorecasts) or horse races with lots of runners';
	} else {
		var comment='<p><b>Fair Market</b><p>When the overround = 100 then this is a fair market.  The odds reflect the probabilities of each chance and if	you backed each outcome with the right level of stake then you would be able to get your stake back whatever the outcome';
	}
	document.getElementById('explanation').innerHTML=comment;
		
}

function howmanybets()
{
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
	  alert ("Sorry.  Your browser is too old or unusual for this page to work.  The rest of the site will work fine though.");
	  return;
	} 
	
	bets=document.combos.bets.options[combos.bets.selectedIndex].value;
	
	var url = '/school/units/combos.php?';
	var params = 'bets=' + bets
	+ '&sid=' + Math.random();
	
	//load data
	xmlHttp.onreadystatechange=stateChanged;
	xmlHttp.open("GET",url + params,true);
	xmlHttp.send(null);
}

function multibets()
{
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
	  alert ("Sorry.  Your browser is too old or unusual for this page to work.  The rest of the site will work fine though.");
	  return;
	} 
	
	sels=document.getElementById('sels').value;
	
	var url = '/school/units/multiples.php?';
	var params = 'sels=' + sels
	+ '&sid=' + Math.random();
	
	//load data
	xmlHttp.onreadystatechange=stateChanged2;
	xmlHttp.open("GET",url + params,true);
	xmlHttp.send(null);
}

function calc_return()
{
	var odds=document.getElementsByName('odds');
	var stake=document.getElementById('stake').value;
	var multiple=document.getElementById('combo').value;
	var horse=document.getElementsByName('horse');
	var sels=odds.length;
	
	var betdetail='<table border=0 cellpadding=4 cellspacing=2 width=100%><tr class=\"whiteonblue\"><td>Multiple</td><td>Bet</td><td>Return</td></tr>';
	var thispayout = 0;
	
		
	//validation
	for(i=0;i<sels;i++)
	{
		if(odds[i].value.length==0)
		{
			alert('You need to enter odds for selection ' + (i+1));
			return false;
		}
	}
	if(stake.length==0)
	{
		alert('Please enter a unit stake');
		return false;
	}
	var payout=0;
	

	//singles
	if(multiple==7 || multiple==15 || multiple==31)
	{
		for(i=0;i<sels;i++){
			thispayout = betcalc(stake,i);
			payout = eval(payout + thispayout);
			betdetail += '<tr><td class=\"greybox\">Single</td><td>' +  horse[i].value + '</td><td align=\"right\">' + (Math.round(thispayout*100)/100) + '</td></tr>';
		}	
	}
	
	
	
	//doubles
	if(multiple!=1 || sels==2)
	{
		for(i=0;i<(sels-1);i++){
		for(j=i+1;j<sels;j++){
			//double of i and j
			payout1 = betcalc(stake,i);
			thispayout = betcalc(payout1,j);
			payout = eval(payout + thispayout);
			thisbet = '<tr><td class=\"greybox\">Double</td><td>' + horse[i].value + '/' + horse[j].value + '</td><td align=\"right\">' + (Math.round(thispayout*100)/100) + '</td></tr>';
			betdetail += thisbet;
			//alert(thisbet + ' (Total = ' + payout + ')');
		}}
	}
	
	//threefolds
	if(multiple!=1 || sels==3)
	{
		if(sels>=3)
		{
			for(i=0;i<(sels-2);i++){
			for(j=i+1;j<(sels-1);j++){
			for(k=j+1;k<sels;k++){
				//treble of i and j and k
				payout1 = betcalc(stake,i);
				payout2 = betcalc(payout1,j);
				thispayout = betcalc(payout2,k);
				payout = eval(payout + thispayout);
				thisbet = '<tr><td class=\"greybox\">Treble</td><td>' + horse[i].value + '/' + horse[j].value + '/' + horse[k].value + 				'</td><td align=\"right\">' + (Math.round(thispayout*100)/100) + '</td></tr>';
				betdetail += thisbet;
				//alert(thisbet + ' (Total = ' + payout + ')');
			}}}
		}
	}
	
	//fourfolds
	if(multiple!=1 || sels==4)
	{
		if(sels>=4)
		{
			for(i=0;i<(sels-3);i++){
			for(j=i+1;j<(sels-2);j++){
			for(k=j+1;k<(sels-1);k++){
			for(l=k+1;l<sels;l++){
				//4fold of i and j and k and l
				payout1 = betcalc(stake,i);
				payout2 = betcalc(payout1,j);
				payout3 = betcalc(payout2,k);
				thispayout = betcalc(payout3,l);
				payout = eval(payout + thispayout);
				thisbet = '<tr><td class=\"greybox\">4-Fold</td><td>' + horse[i].value + '/' + horse[j].value + '/' + horse[k].value + '/' + horse[l].value + '</td><td align=\"right\">' + (Math.round(thispayout*100)/100) + '</td></tr>';
				betdetail += thisbet;
				//alert(thisbet + ' (Total = ' + payout + ')');
			}}}}
		}
	}
	
	//fivefold
	if(sels==5)
	{
		for(i=0;i<(sels-4);i++)	{
		for(j=i+1;j<(sels-3);j++) {
		for(k=j+1;k<(sels-2);k++) {
		for(l=k+1;l<(sels-1);l++) {
		for(m=l+1;m<sels;m++) {
			//5fold of i and j and k and l and m
			payout1 = betcalc(stake,i);
			payout2 = betcalc(payout1,j);
			payout3 = betcalc(payout2,k);
			payout4 = betcalc(payout3,l);
			thispayout = betcalc(payout4,m);
			payout = eval(payout + thispayout);
			thisbet = '<tr><td class=\"greybox\">5-Fold</td><td>' +	horse[i].value + '/' + horse[j].value + '/' + horse[k].value + '/' + horse[l].value + '/' + horse[m].value + '</td><td align=\"right\">' + (Math.round(thispayout*100)/100) + '</td></tr>';
			betdetail += thisbet;
			//alert(thisbet + ' (Total = ' + payout + ')');
		}}}}}
	}
	
	betdetail += '<tr class=\"whiteonorange\"><td>&nbsp</td><td align=\"right\">TOTAL</td><td align=\"right\">' + Math.round(payout*100)/100 + '</td></tr></table>';
	
	//total stake
	document.getElementById('totalstake').innerHTML='&pound; ' + stake*multiple;
	//payout

	document.getElementById('payout').innerHTML='&pound; ' + Math.round(payout*100)/100;
	
	//betdetail
	document.getElementById('betdetail').innerHTML=betdetail;
	
	return false;
}

function betcalc(amount,n) //n=row number
{
	var odds=document.getElementsByName('odds');
	var sodds=odds[n].value;
	
	
	
	var bet=document.getElementsByName('bet');
	var sbet=bet[n].value;
	
	var betresult=document.getElementsByName('betresult');
	var sresult=betresult[n].value;
	
	//var ewfraction=document.multi.fraction[n].value;
	if(sbet=='Win')
	{
		var output = win_bet(sodds,amount,sresult);
	} else { //its EW and =0.2 or 0.25
		var output = ew_bet(sodds,amount,sresult,sbet);
	}
	return output;
}

function ew_bet(fodds,fstake,fresult,ffraction)
{
	fodds=fodds-1; //make fractional
	var ew_return = (fstake/2)*(1 + (fodds*ffraction));
	var win_return = (fstake/2)*(1 + fodds);
	if(fresult=='Win')
	{
		return win_return + ew_return;
	} else if(fresult=='Lose') {
		return 0;
	} else if(fresult=='Place') {
		return ew_return;
	}
}

function win_bet(fodds,fstake,fresult)
{
	if(fresult == 'Win')
	{
		return fstake*fodds;
	} else {
		return 0;
	} 
	return false;
}

function notes(text) //horse,1
{
	var data=window.document.multi.field.value;
	if (window.Event)
	{
		var keyChar = String.fromCharCode(text.which);
	} else {
		var keyChar = String.fromCharCode(event.keyCode);
	}
	data=data+keyChar;
	if (notes.length>0)
	{
		SetCookie('horse',data,6);
	}
}
function SetCookie(cookieName,cookieValue,nDays)
{
	 var today = new Date();
	 var expire = new Date();
	 if (nDays==null || nDays==0) nDays=7;
	 expire.setTime(today.getTime() + 3600000*24*nDays);
	 document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}

function oddsprofit()
{
	var stakes=parseInt(document.profitcalc.stakes.value);
	var profit=parseInt(document.profitcalc.profit.value);
	var increase=parseFloat(document.profitcalc.increase.value);
	
	if(document.profitcalc.stakes.value.length==0)
	{
		alert("Please enter your typical monthly stakes");
		return false;
	}
	if(document.profitcalc.profit.value.length==0)
	{
		alert("Please enter your typical monthly profit or loss");
		return false;
	}
	
	var current_return = stakes+profit;
	var extra = current_return * increase;
	
	document.profitcalc.currentprofit.value=parseInt(profit*365);
	document.profitcalc.possibleprofit.value=parseInt(profit+extra)*365;
	document.profitcalc.extraprofit.value=parseInt(extra*365);
	return false;
}

function mybookie(multi)
{
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
	  alert ("Sorry.  Your browser is too old or unusual for this page to work.  The rest of the site will work fine though.");
	  return;
	} 
	
	//bookie = document.compare.bookie.options[compare.bookie.selectedIndex].value;
	bookie = document.getElementById('bookie').value;
	var url = '/school/units/bookieodds.php?';
	var params = 'providerid=' + bookie
	+ '&m=' + multi 
	+ '&sid=' + Math.random();
	
	//load data
	xmlHttp.onreadystatechange=stateChanged;
	xmlHttp.open("GET",url + params,true);
	xmlHttp.send(null);
}
function stakecalc(f){
    var pool = document.kelly.pool.value;
    var chance = document.kelly.chance.value/100;
    var odds = document.kelly.odds.value-1;
	var reduce= (1-chance)/odds;
	var proportion = chance - reduce;
	var stake = Math.round(proportion*pool);
	if (stake<0 || odds<0)
	{
		document.kelly.stake.value = "No Bet";
	} else {
    	document.kelly.stake.value = stake;
	}
	return false;
}