// Paramètres de calcul
var chevaux_max = 9;
var mise_base = 1.5;
var mise_max_report = 1000;

// Variables utilisateurs
var mise_coef = 1;
var nb_chevaux = 0;
var rapportsG, rapportsP, reports;

function get_input()
{
	rapportsG = new Array();
	rapportsP = new Array();
	reports = new Array();
	for (var c = 1; c <= chevaux_max; c++)
	{
		var cG = document.getElementById('cG'+c).value;
		var cP = document.getElementById('cP'+c).value;
		if ((cG != "") || (cP != ""))
		{
			rapportsG.push((cG == "") ? -1 : parseFloat(cG.replace(/,/, ".")));
			rapportsP.push((cP == "") ? -1 : parseFloat(cP.replace(/,/, ".")));
			if (reports.length == 0) reports.push(1);
			else reports.push(document.getElementById('demi'+c).checked ? 0.5 : 1);
		}
	}
	nb_chevaux = rapportsG.length;
	mise_coef = parseInt(document.getElementById('mise_coef').value);
}

function extract_jeu(num)
{
	var jeu = new Array();
	var cheval_id = 1;
	for (var c = 0; c < nb_chevaux; c++)
	{
		var bet = ((num & cheval_id) == 0) ? rapportsG[c] : rapportsP[c];
		if (bet < 0) return null;
		jeu.push(bet);
		cheval_id = cheval_id << 1;
	}
	return jeu;
}

function calcul_gain_jeu(mise, rapports)
{
	var gain_jeu = 0;
	for (var c = 0; c < rapports.length; c++)
	{
		if (rapports[c] > 0)
		{
			var gain_cheval = mise * rapports[c];
			var gain_reporte_coef = Math.floor(gain_cheval / mise_base);
			if (reports[c+1] == 0.5) gain_reporte_coef = Math.ceil(gain_cheval / mise_base / 2);
			if (gain_reporte_coef > mise_max_report) gain_reporte_coef = mise_max_report;
			mise = gain_reporte_coef * mise_base;
			gain_jeu += gain_cheval - mise;
		}
		else
		{
			mise = 0;
			break;
		}
	}
	return (gain_jeu + mise);
}

function calcul_gain()
{
	get_input();
	var jeux_max = (nb_chevaux > 0) ? (1 << nb_chevaux) : 0;
	var nb_jeux = 0;
	var gain_total = 0;
	for (var j = 0; j < jeux_max; j++)
	{
		var jeu = extract_jeu(j);
		if (jeu != null)
		{
			++nb_jeux;
			gain_total += calcul_gain_jeu(mise_base * mise_coef, jeu);
		}
	}
	
	display(document.getElementById('result_cost'), mise_base * mise_coef * nb_jeux);
	display(document.getElementById('result_gain'), gain_total);
}

function display(obj, value)
{
	obj.innerHTML = value.toFixed(2).replace(/\./, ",") + " &euro;";
}

function update_input()
{
	if (this.value != '')
		this.value = parseFloat(this.value.replace(/,/, ".")).toFixed(2);
	calcul_gain();
}

// Initialisation
function init_reports()
{
	var inputs = document.getElementById('reports').getElementsByTagName('input');
	for (var i = 0; i < inputs.length; i++) if (inputs[i].className != "text")
	{
		inputs[i].onchange = update_input;
	}
	calcul_gain();
}

function addOnLoad(someinit)
{
	if (document.addEventListener)
		window.addEventListener("load", someinit, false);
	else if (attachEvent)
		window.attachEvent("onload", someinit);
}

addOnLoad(init_reports);
