// Code sous Copyright (c) 2009 Pronosoft - Nadim Noureddine. Toute réutilisation, copie ou copie partielle interdite

//window.onload=InitAll;

$(document).ready
(
	function()
	{
		InitAll();
	}
);

// unique ID for creation of dynamique Nodes
var sId=0;
function GetUniqueId()
{
	sId++;
	return 'id'+sId;
}

var mNumList = -1;
function InitAll()
{
	RemoveAllSelection();
}

var NbMaxCouponMatch = 6;
var mCurrentNumMatch = 0;
var mCouponMatch=new Array(NbMaxCouponMatch);
var mCouponMatchResult=new Array(NbMaxCouponMatch);
var mCouponMatchId=new Array(4);
mCouponMatchId[0]=new Array(NbMaxCouponMatch);
mCouponMatchId[1]=new Array(NbMaxCouponMatch);
mCouponMatchId[2]=new Array(NbMaxCouponMatch);
mCouponMatchId[3]=new Array(NbMaxCouponMatch); // parent ID

var mUserName='';
var mNetAmount=0;
var mListNetAmount=0;

var mErrorMessage='';
var mSumbissionStatus='';

function UpdateText(id, newText)
{
	var old = document.getElementById(id).firstChild;
	var txt = document.createTextNode(newText);
	document.getElementById(id).replaceChild(txt, old);
}

function GetMatchName(numMatch)
{
	var team1Id='match_team1_'+numMatch;
	var team2Id='match_team2_'+numMatch;
	
	var team1 = document.getElementById(team1Id);
	var team2 = document.getElementById(team2Id);

	return team1.firstChild.nodeValue+'-'+team2.firstChild.nodeValue;
}

function GetResultString(numResult)
{
	var result='?';
	if (numResult==0)
		result='1';
	if (numResult==1)
		result='N';
	if (numResult==2)
		result='2';
	return result;
}

function GetMatchOdds(numMatch, numResult)
{
	var oddsId='cote';
	oddsId+=GetResultString(numResult);
	oddsId+='_'+numMatch;

	var node = document.getElementById(oddsId);
	return node.firstChild.nodeValue;
}


function GetNumMatchFromId(matchId)
{
	var numMatch=-1;
	var i;
	for (i=0; i<NbMaxCouponMatch; i++)
	{
		if (mCouponMatchId[i]==matchId)
		{
			numMatch=i;
			break;
		}
	}
	return numMatch;
}

function RemoveMatch(numMatch)
{
	// remove the match graphically
	indexOfMatch = GetMatchIndex(numMatch);
	if (indexOfMatch != -1)
	{
		var node = document.getElementById(mCouponMatchId[3][indexOfMatch]);
		node.parentNode.removeChild(node);

		// remove the match logically
		var i;
		for (i=indexOfMatch; i<NbMaxCouponMatch-1; i++)
		{
			mCouponMatch[i]=mCouponMatch[i+1];
			mCouponMatchResult[i]=mCouponMatchResult[i+1];
			var j;
			for (j=0; j<4; j++)
			{
				mCouponMatchId[j][i]=mCouponMatchId[j][i+1];
			}
		}
		mCurrentNumMatch--;
	}
}

function RemoveResult(numMatch, numResult)
{
	// remove the result from the string
	indexOfMatch = GetMatchIndex(numMatch);
	if (indexOfMatch != -1)
	{
		var resultString = mCouponMatchResult[indexOfMatch];
		if (resultString.indexOf(numResult)!=-1)
		{
			var indexOfResult=resultString.indexOf(numResult);
			var newResult=resultString.substring(0,indexOfResult);
			newResult+=resultString.substring(indexOfResult+1, resultString.length);
			mCouponMatchResult[indexOfMatch]=newResult;
			
			if (newResult.length>0)
			{
				UpdateMatchDisplay(indexOfMatch);
			}
			else // remove the match !
			{
				RemoveMatch(numMatch);
			}
		}
		ResetMessage();
		DisplaySystemInfo();
	}
}

function IsMatchIncompatible(numMatch)
{
	return false;
}

function GetMatchIndex(numMatch)
{
	var index=-1;
	var i;
	for (i=0; i<mCurrentNumMatch; i++)
	{
		if (mCouponMatch[i]==numMatch)
		{
			index=i;
			break;
		}
	}
	return index;
}

function UpdateMatchDisplay(indexOfMatch)
{
	var rowID = mCouponMatchId[3][indexOfMatch];
	var numMatch = mCouponMatch[indexOfMatch];
	var html='<td id="'+mCouponMatchId[0][indexOfMatch]+'">'+numMatch+'</td>'+'<td>'+GetMatchName(numMatch)+'</td>';
	var i;
	for (i=0; i<3; i++)
	{
		var cellID = mCouponMatchId[i][indexOfMatch];
		html+='<td id="'+mCouponMatchId[i][indexOfMatch]+'">';
		if (mCouponMatchResult[indexOfMatch].indexOf(i)!=-1)
		{
			html+='<a href="javascript:;" onclick="javascript:RemoveResult('+numMatch+', '+i+')" id="'+cellID+'">'+GetMatchOdds(numMatch, i)+'</a>';
		}
		else
		{
			html+='&nbsp;';
		}
		html+='</td>';
	}

	$('#'+rowID).html(html);
}

function AddMatch(numMatch, numResult)
{
	ResetMessage();

	if (IsMatchIncompatible(numMatch))
	{
		mErrorMessage='Le match <'+GetMatchName(numMatch)+'> ne peut être combiné plusieurs fois';
		UpdateCouponSelectionMessage();
	}
	else
	{
		// check if match can be added
		var indexOfMatch = mCurrentNumMatch;
		var table_coupon = document.getElementById('table_coupon');
		if (GetMatchIndex(numMatch)!=-1)
		{
			indexOfMatch = GetMatchIndex(numMatch);
		}
		else
		{
			if (mCurrentNumMatch==NbMaxCouponMatch)
			{
				mErrorMessage='Vous ne pouvez pas sélectionner plus de '+NbMaxCouponMatch+' matches';
				UpdateCouponSelectionMessage();
				indexOfMatch=-1;
			}
			else
			{
				// build ids...
				mCouponMatchId[0][indexOfMatch]=GetUniqueId();
				mCouponMatchId[1][indexOfMatch]=GetUniqueId();
				mCouponMatchId[2][indexOfMatch]=GetUniqueId();
				mCouponMatchId[3][indexOfMatch]=GetUniqueId();
				this.newRow =  table_coupon.insertRow(-1);
				this.newRow.setAttribute('id', mCouponMatchId[3][indexOfMatch]);
		
				mCouponMatchResult[indexOfMatch]='';
				mCurrentNumMatch++;
			}
		}

		if (indexOfMatch!=-1)
		{
			mCouponMatch[indexOfMatch]=numMatch;
			if (mCouponMatchResult[indexOfMatch].indexOf(numResult)==-1) // not already selected
			{
				mCouponMatchResult[indexOfMatch]+=numResult;
			}

			UpdateMatchDisplay(indexOfMatch);
			DisplaySystemInfo();
		}
	}
}

function RemoveAllSelection()
{
	var table_coupon = document.getElementById('table_coupon');
	RemoveAllRows('table_coupon');
	this.newRow =  table_coupon.insertRow(-1);
	this.newCell = this.newRow.insertCell(0);
	this.newCell.colSpan='5';
	this.newCell.setAttribute('id', 'table_coupon_first_cell');

	this.newRow =  table_coupon.insertRow(-1);
	this.newRow.setAttribute('id', 'table_coupon_header');
	this.newRow.setAttribute('class', 'row_gf');

	$('#table_coupon_header').html('<td class="n">N°</td><td>Matches</td><td class="cote1">Cote 1</td><td class="coteN">Cote N</td><td class="cote2">Cote 2</td>');

	mCurrentNumMatch=0;
	ResetMessage();
	DisplaySystemInfo();
}

function UpdateCouponSelectionMessage()
{
	var t='';

	if (mErrorMessage!='')
	{
		t+='<font color="red">'+mErrorMessage+'</font><br/><br/>';
	}
	if (mCurrentNumMatch>0)
		t+='<a href="javascript:;" onclick="javascript:RemoveAllSelection()">Tout retirer</a><br/><br/>';
	else
		t+='<span class="gen">Faites votre sélection de cotes en cliquant dans la liste de gauche</span>';

	$('#table_coupon_first_cell').html(t);
}

function ResetMessage()
{
	if (mErrorMessage!='')
	{
		mErrorMessage='';
	}
	UpdateCouponSelectionMessage();
	RemoveAllRows('validated_coupons');
}

function RemoveAllRows(id)
{
	var Parent = document.getElementById(id);
	while(Parent.hasChildNodes())
	{
	  Parent.removeChild(Parent.firstChild);
	}
}

function DisplaySystemInfo()
{
	var system_info='';
	var nbDouble = GetNbDouble();
	var nbTriple = GetNbTriple();
	var nbCombi = GetNbCombination();

	var table_system = document.getElementById('system_info');
	RemoveAllRows('system_info');
	this.newRow =  table_system.insertRow(-1);
	this.newRow.setAttribute('id', 'table_system_name');
	this.newRow.setAttribute('class', 'row_gc');

	system_info='<td>Système '+nbTriple+'T'+nbDouble+'D</td><td>'+nbCombi+' combinaison'+(nbCombi>1?'s':'')+'</td>';
	$('#table_system_name').html(system_info);

	var maxOdds =GetMaxOdds().toFixed(2);
	var minOdds =GetMinOdds().toFixed(2);

	this.newRow =  table_system.insertRow(-1);
	this.newRow.setAttribute('id', 'table_system_max');
	this.newRow.setAttribute('class', 'row_gtc');
	system_info='<td>Cote Maximum</td><td>'+maxOdds+'</td>';
	$('#table_system_max').html(system_info);
	this.newRow =  table_system.insertRow(-1);
	this.newRow.setAttribute('id', 'table_system_min');
	this.newRow.setAttribute('class', 'row_gc');
	system_info='<td>Cote Minimum</td><td>'+minOdds+'</td>';
	$('#table_system_min').html(system_info);
}

function DisplaySystemGrids()
{
	ResetMessage();
	var nbCombi = GetNbCombination();
	var validated_coupons = document.getElementById('validated_coupons');
	RemoveAllRows('validated_coupons');

	this.newRow =  validated_coupons.insertRow(-1);
	this.newRow.setAttribute('id', 'validated_coupons_header');
	this.newRow.setAttribute('class', 'row_gf');
	var header='<td class="n">N°</td>';
	for (i=0; i<NbMaxCouponMatch; i++)
	{
		var numMatch='-';
		if (i<mCurrentNumMatch)
			numMatch=mCouponMatch[i];
		header+='<td class="n">'+numMatch+'</td>';
	}
	header+='<td class="cote1">Cote</td>';
	$('#validated_coupons_header').html(header);
	sNumGridIntoArray=0;
	GenerateCombination();
}

var sNumGridIntoArray=0;
// this is the callback of the GetNbCombination
function AddGridToArray(gridString)
{
	var validated_coupons = document.getElementById('validated_coupons');
	var gridID = 'validated_coupons_grid_'+gridString;
	this.newRow =  validated_coupons.insertRow(-1);
	this.newRow.setAttribute('id', gridID);
	if (sNumGridIntoArray%2)
		this.newRow.setAttribute('class', 'row_gc');
	else
		this.newRow.setAttribute('class', 'row_gtc');
	var grid='<td>'+(sNumGridIntoArray+1)+'.';
	for (j=0; j<NbMaxCouponMatch; j++)
	{
		var matchResult='-';
		if (j<mCurrentNumMatch)
		{
			matchResult=':'+GetResultString(gridString.charAt(j))+':';
		}
		grid+='<td>'+matchResult+'</td>';
	}
	grid+='<td>'+GetCouponOdds(gridString).toFixed(2)+'</td>';
	$('#'+gridID).html(grid);

	sNumGridIntoArray++;
}

function GetNbCombination()
{
	var nbCombi=1;
	var nbDouble = GetNbDouble();
	var nbTriple = GetNbTriple();
	for (i=0; i<nbDouble; i++)
	{
		nbCombi*=2;
	}
	for (i=0; i<nbTriple; i++)
	{
		nbCombi*=3;
	}
	return nbCombi;
}

function GetNbDouble()
{
	var nbDouble=0;
	for (i=0; i<mCurrentNumMatch; i++)
	{
		if (mCouponMatchResult[i].length==2)
		{
			nbDouble++;
		}
	}
	return nbDouble;
}

function GetNbTriple()
{
	var nbTriple=0;
	for (i=0; i<mCurrentNumMatch; i++)
	{
		if (mCouponMatchResult[i].length==3)
		{
			nbTriple++;
		}
	}
	return nbTriple;
}

function GenerateCombination()
{
	// sort prono
	var i;
	for (i=0; i<mCurrentNumMatch; i++)
	{
		if (mCouponMatchResult[i].length==2)
		{
			if (mCouponMatchResult[i]=='10')
				mCouponMatchResult[i]='01';
			else if (mCouponMatchResult[i]=='20')
				mCouponMatchResult[i]='02';
			else if (mCouponMatchResult[i]=='21')
				mCouponMatchResult[i]='12';
		}
		else if (mCouponMatchResult[i].length==3)
		{
			mCouponMatchResult[i]=='012';
		}
	}

/*
	// sort matches
	var currentIndex=0;
	var sortedMatchNumber=new Array(mCurrentNumMatch);
	for (i=1; i<=60; i++)
	{
		indexOfMatch = GetMatchIndex(i);
		if (indexOfMatch!=-1)
		{
			sortedMatchNumber[currentIndex]=i;
			currentIndex++;
		}
	}
*/

	var current=GetFirstCombination();

	var nb=0;
	while (current!='')
	{
		// transform grid
		var transformedGrid='';
		for (i=0; i<mCurrentNumMatch; i++)
		{
			transformedGrid+=mCouponMatchResult[i].charAt(current.charAt(i));
		}
		AddGridToArray(transformedGrid);
		current=GetNextCombination(current);
		nb++;
	}
}

function setCharAt(string, index, chr) 
{
	if(index > string.length-1) return str;
	return string.substr(0,index) + chr + string.substr(index+1);
}

function GetFirstCombination()
{
	var current='';
	for (i=0; i<mCurrentNumMatch; i++)
	{
		current+='0';
	}
	return current;
}

function GetNextCombination(current)
{
	var numMatch = 0;
	var currentResult = (parseInt(current.charAt(numMatch)))+1;
	while (currentResult == mCouponMatchResult[numMatch].length)
	{
		numMatch++;
		if (numMatch==mCurrentNumMatch)
		{
			return '';
		}
		current = setCharAt(current,numMatch-1,'0');
		currentResult = (parseInt(current.charAt(numMatch)))+1;
	}
	current = setCharAt(current,numMatch,currentResult);

	return current; 
}



function GetMinOdds()
{
	var odds=1.0;
	for (i=0; i<mCurrentNumMatch; i++)
	{
		var numMatch = mCouponMatch[i];
		var minOdds=999.0;
		for (j=0; j<mCouponMatchResult[i].length; j++)
		{
			var numResult=mCouponMatchResult[i][j];
			var matchOdds=GetMatchOdds(numMatch, numResult).replace(',','.');
			if (matchOdds<minOdds)
				minOdds=matchOdds;
		}
		odds*=minOdds;
	}
	return odds;
}

function GetMaxOdds()
{
	var odds=1.0;
	for (i=0; i<mCurrentNumMatch; i++)
	{
		var numMatch = mCouponMatch[i];
		var maxOdds=1.0;
		for (j=0; j<mCouponMatchResult[i].length; j++)
		{
			var numResult=mCouponMatchResult[i][j];
			var matchOdds=GetMatchOdds(numMatch, numResult).replace(',','.');
			if (matchOdds>maxOdds)
				maxOdds=matchOdds;
		}
		odds*=maxOdds;
	}
	return odds;
}

function GetCouponOdds(gridString)
{
	var cumulatedOdds=1.0;
	for (j=0; j<mCurrentNumMatch; j++)
	{
		var numMatch = mCouponMatch[j];
		var numResult=gridString.charAt(j);
		var matchOdds=GetMatchOdds(numMatch, numResult).replace(',','.');
		cumulatedOdds*=matchOdds;
	}
	return cumulatedOdds;
}
