// ===================================================================
// syntaxe d'appel :
//
// pour un diagramme isolé :
// MontreUnDiagramme(titre,PosIni,ListeCps,TypeD,FlagMontreSelection)
//
// pour une série de diagrammes
// DebutSerieDiagrammes(TypeD)
// AjouteDiagramme(titre,PosIni,ListeCps,FlagMontreSelection);
// AjouteDiagramme(titre,PosIni,ListeCps,FlagMontreSelection);
// ....
// AjouteDiagramme(titre,PosIni,ListeCps,FlagMontreSelection);
// FinSerieDiagrammes()
//
// ===================================================================
//
// Dans l'état actuel, TypeD="pb" ou TypeD="visu"
// Dans le premier cas, on travaille dans un diagramme unique
// dont le contenu change en fonction du pb activé.
//
// Dans le second cas les diagrammes sont placés
// les uns en dessous des autres.
//
// ===================================================================
//
// En mode "pb", le résultat du test est renvoyé au script associé
// au formulaire "Form" supposé présent dans la page HTML en cours
// en utilisant les deux champs (cachés) "scores" et "temps". 
// Ce formulaire doit être créé avant de faire appel à ce script.
//
// ===================================================================


// Variables necessaires au fonctionnement du script


// Mode de fonctionnement du script
var ModeResolutionPb;
var NombreDiag=-1
var DiagEnCours=1;
var ModeTest=false;

//positionnement des cadres
var vpos=30;
var hpos=0;

// Variables utilisées pour jouer un coup
// Case de départ, d'arrivée, pièce se trouvant sur la case de départ, d'arrivée
var DepCase
var ArrCase
var DepPiece
var ArrPiece


// Variables associees a chaque diagramme x
// Il est possible de travailler avec
// plusieurs parties...)
// sur une meme feuille html
//
// C'est pour cette raison qu'il y a differents
// tableaux (PositionIni, coup...)
//
// En general, ces parties
// sont designes par la variable x
// dans le code des differentes fonctions
// definies dans ce scripts


// Définition du diagramme (informations transmises lors de l'appel)

// 1 - Type du diagramme
// TypeDiagramme[x] peut être égal à
// "visu" : simple visualisation
// "pb" : mode problème
// "jeu" : non utilisé pour l'instant, mais prévu pour une utilisation pour jouer à distance
TypeDiagramme = new Array();


// 2 - Titre du diagramme
titreDiag=new Array();

// 3 - Position initiale
PositionIni = new Array();

// 4 - Liste des coups
ListeCoups = new Array();

// 5 - Commentaires
Commentaires = new Array();

// 6 - Mise en evidence des coups possibles
MontreSelection=new Array();


//Temps initial, temps final, temps cumulé, flag de décompte du temps
tini=new Array();
tfinal=new Array();
tcumul=new Array();
flagtimer=new Array();

//Numero du coup en cours
Coup = new Array();

//Numero du premier coup : 0 si c'est les blancs, pour les noirs 
FirstCp = new Array();

//Diagramme entierement vu
DiagrammeFini=new Array();

//Affichage de la barre de navigation (changements de coup)
AfficheSol=new Array();


// cases sélectionnées
CaseDepart=new Array();
CaseArrivee=new Array();
CasesDepArr=new Array();

CoupsIncorrects=new Array();
CoupsInvalides=new Array();
NombreCoups=new Array();

HistoriquePrises = new Array();
NotationCoup = new Array();
Selection=new Array();
Score = new Array();

// ------------


function Prechargement()
{
if (document.images)						
{											
	imag = new Array();
	imag[0]  = "n/__.gif";		
	imag[1]  = "n/cb.gif";	
	imag[2]  = "n/cn.gif";	
	imag[3]  = "n/db.gif";	
	imag[4]  = "n/dn.gif";	
	imag[5]  = "n/fb.gif";		
	imag[6]  = "n/fn.gif";	
	imag[7]  = "n/pb.gif";	
	imag[8]  = "n/pn.gif";		
	imag[9]  = "n/rb.gif";		
	imag[10] = "n/rn.gif";	
	imag[11] = "n/tb.gif";	
	imag[12] = "n/tn.gif";	
	imag[13] = "b/__.gif";		
	imag[14] = "b/cb.gif";	
	imag[15] = "b/cn.gif";	
	imag[16] = "b/db.gif";	
	imag[17] = "b/dn.gif";	
	imag[18] = "b/fb.gif";		
	imag[19] = "b/fn.gif";	
	imag[20] = "b/pb.gif";	
	imag[21] = "b/pn.gif";		
	imag[22] = "b/rb.gif";		
	imag[23] = "b/rn.gif";	
	imag[24] = "b/tb.gif";	
	imag[25] = "b/tn.gif";	
	imag[26] = "g/__.gif";		
	imag[27] = "g/cb.gif";	
	imag[28] = "g/cn.gif";	
	imag[29] = "g/db.gif";	
	imag[30] = "g/dn.gif";	
	imag[31] = "g/fb.gif";		
	imag[32] = "g/fn.gif";	
	imag[33] = "g/pb.gif";	
	imag[34] = "g/pn.gif";		
	imag[35] = "g/rb.gif";		
	imag[36] = "g/rn.gif";	
	imag[37] = "g/tb.gif";	
	imag[38] = "g/tn.gif";	
	imag[39] = "j/__.gif";		
	imag[40] = "j/cb.gif";	
	imag[41] = "j/cn.gif";	
	imag[42] = "j/db.gif";	
	imag[43] = "j/dn.gif";	
	imag[44] = "j/fb.gif";		
	imag[45] = "j/fn.gif";	
	imag[46] = "j/pb.gif";	
	imag[47] = "j/pn.gif";		
	imag[48] = "j/rb.gif";		
	imag[49] = "j/rn.gif";	
	imag[50] = "j/tb.gif";	
	imag[51] = "j/tn.gif";	
	im = new Array();								
	for (var i = 0; i < imag.length; i++)			
	{												
		im[i] = new Image();						
		im[i].src = imag[i];						
	}												

}
}


function MontreUnDiagramme(titre,PosIni,ListeCps,TypeD,FlagMontreSelection)
{

ModeResolutionPb=(TypeD=="pb");
if(ModeResolutionPb)
	{
	InitialiseEchiquierCommun();
	InitialiseTitrePage(titre);
	}	
AjouteDiagramme(titre,PosIni,ListeCps,FlagMontreSelection);
ActiveDiagramme(0);
}


function DebutSerieDiagrammes(TypeD)
{

ModeResolutionPb=(TypeD=="pb");
if(ModeResolutionPb)
	{
	ModeTest=true;
	InitialiseEchiquierCommun();
	}

}


function FinSerieDiagrammes()
{
if(ModeResolutionPb)
	{
	InitialiseNavigation();
	InitialiseTitrePage("Cliquer sur un numéro de diagramme...");
	}
}



function AjouteDiagramme(titre,PosIni,ListeCps,FlagMontreSelection)
{
var i;
var j;
var k;
var s1;
var s2;
var com;
var coup;
var x;

NombreDiag++;

x=NombreDiag;

titreDiag[x]=titre;
MontreSelection[x]=FlagMontreSelection;


//Récupération de la position initiale

PositionIni[x] = new Array();
for(i=0;i<8;i++)
	{
	PositionIni[x][i] = PosIni.substr(8*i,8);
	s1=PosIni.substr(8*i,8);
	//alert("|" + PositionIni[x][i] + "|" + NombreDiag+ i);
	}

//Récupération des coups et des commentaires

ListeCoups[x] = new Array();
Commentaires[x] = new Array();
NombreCoups[x]=0;
i=0;

while(ListeCps!="")
	{
	j=ListeCps.indexOf(":")
	if(j>-1)
		{
		s1=ListeCps.substring(0,j);
		//substr sans second argument : jusqu'à la fin de la chaine
		s2=ListeCps.substr(j+1);
		}
	else
		{
		s1=ListeCps;
		s2="";
		}


	k=s1.indexOf("$")
	coup=s1.substring(0,k);
	com=s1.substr(k+1);

	if(i==0)
		{
		Commentaires[x][i]=com;
		//alert(com);
		}
	else
		{
		//alert("|" + com + "| - |" + coup + "|");
		Commentaires[x][i]=com;
		ListeCoups[x][i-1]=coup;
		NombreCoups[x]++;
		}	
	ListeCps=s2;
	i++;
	}

// Définition des variables associées au diagramme
HistoriquePrises[x]=new Array();
NotationCoup[x]=new Array();
FirstCp[x]=0;
Score[x]=0;
Selection[x]="";
CaseDepart[x]="";
CaseArrivee[x]="";
CasesDepArr[x]="";
CoupsIncorrects[x]=0;
CoupsInvalides[x]=0;
DiagrammeFini[x]=false;
tfinal[x]=0;
tini[x]=0;
tcumul[x]=0;

// Détermination du mode d'affichage...

if(!ModeResolutionPb) 
	{
	TypeDiagramme[x]="visu";
	InitialiseEchiquier(NombreDiag);
	AffichePositionIni(NombreDiag);
	AfficheSol[x]=true;
	flagtimer[x]=false;
	}
else
	{
	TypeDiagramme[x]="pb";
	AfficheSol[x]=false;
	flagtimer[x]=true;
	}
}

function SetImage(x,NomCase,p,CouleurCase)
{
if(ModeResolutionPb) changeImageCalque("calqueEchiquier",NomCase,CouleurCase + "/" + p + ".gif")
else changeImageCalque("calqueEchiquier"+ x.toString(),NomCase + x.toString(),CouleurCase + "/" + p + ".gif")
}

function ImageCase(x, NomCase)
{
if(ModeResolutionPb) return calqueImage("calqueEchiquier",NomCase).src
else return calqueImage("calqueEchiquier"+ x.toString(),NomCase + x.toString()).src
}

function setformulaire(x,champ,s)
{
if(ModeResolutionPb) calqueForm("calqueCommentaire","formulaire").elements[champ].value=s
else calqueForm("calqueCommentaire"+ x.toString(),"formulaire"+ x.toString()).elements[champ].value=s
}

function CacheChamp(x,champ)
{
if(ModeResolutionPb) calqueForm("calqueCommentaire","formulaire").elements[champ].style.visibility='hidden'
else calqueForm("calqueCommentaire"+ x.toString(),"formulaire"+ x.toString()).elements[champ].style.visibility='hidden'
}

function MontreChamp(x,champ)
{
if(ModeResolutionPb) calqueForm("calqueCommentaire","formulaire").elements[champ].style.visibility='visible'
else calqueForm("calqueCommentaire"+ x.toString(),"formulaire"+ x.toString()).elements[champ].style.visibility='visible'
}




// GESTION DES SCORES


function CalculeScore(x)
{
	if(NombreCoups[x]<4) Score[x]=5-2*(CoupsIncorrects[x]+CoupsInvalides[x]);
	else Score[x]=5-CoupsIncorrects[x]-CoupsInvalides[x];
	if(Score[x]<0)Score[x]=0;
}

function FinTest()
{
var i;
document.forms["Form"].elements["scores"].value="";
for(i=0;i<=NombreDiag;i++)
	{
	if(i>0)document.forms["Form"].elements["scores"].value += ":";
	document.forms["Form"].elements["scores"].value += Score[i].toString();
	}
document.forms["Form"].elements["temps"].value="";
for(i=0;i<=NombreDiag;i++)
	{
	if(i>0)document.forms["Form"].elements["temps"].value += ":";
	document.forms["Form"].elements["temps"].value += tcumul[i].toString();
	}
document.forms["Form"].submit();
}

// GESTION DES CADRES 

function CacheCalques(i)
{
document.getElementById("calqueEchiquier"+ i.toString()).style.visibility='hidden';
document.getElementById("calqueCommentaire"+ i.toString()).style.visibility='hidden';
document.getElementById("calqueTitre"+ i.toString()).style.visibility='hidden';
}

function AfficheInfos(x)
{
// Cette fonction n'est utile que si on utilise un diagramme commun
if(ModeResolutionPb)
	{
	document.getElementById("calqueEchiquier").style.visibility='visible';
	document.getElementById("calqueCommentaire").style.visibility='visible';
	document.getElementById("calqueTitre").style.visibility='visible';
	document.getElementById("calqueTitre").style.background='white';
	document.getElementById("calqueTitre").style.color='blue';
	ecritCalque("calqueTitre","<H2><CENTER>"+titreDiag[x]+"</CENTER></H2>")
	if (AfficheSol[x]==false)
		{
		MontreChamp(x,"AFFSOL");
		CacheChamp(x,"A");
		CacheChamp(x,"B");
		CacheChamp(x,"C");
		CacheChamp(x,"D");
		CacheChamp(x,"E");
		CacheChamp(x,"F");
		AffichePositionIni(x);
		flagtimer[x]=true;
		timer(x);
		}
	else
		{
		CacheChamp(x,"AFFSOL");
		MontreChamp(x,"A");
		MontreChamp(x,"B");
		MontreChamp(x,"C");
		MontreChamp(x,"D");
		MontreChamp(x,"E");
		MontreChamp(x,"F");
		AffichePositionIni(x);
		flagtimer[x]=false;
		}
	}
else alert ("Erreur d'utilisation de AfficheInfos");

}


function InitialiseNavigation()
{
var g;
var i;
var j;
g=""
g+="<table><tr>";
for(i=0;i<=NombreDiag;i++)
	{
	j=i+1;
	g+="<td><A href=# onclick='ActiveDiagramme("+ i + ")'>Diag " + j +"</td>";
	}
g+="</tr></table>";
creerCalque("calqueNavigation",g,vpos,hpos+10,700,30,'visible');
document.getElementById("calqueNavigation").style.background='white';
document.getElementById("calqueNavigation").style.color='blue';
}

function InitialiseTitrePage(titre)
{
creerCalque("calqueTitre","<H2><CENTER>" + titre + "</CENTER></H2>",vpos+20,hpos,700,50,'visible');
document.getElementById("calqueTitre").style.background='white';
document.getElementById("calqueTitre").style.color='blue';
}

function InitialiseEchiquierCommun()
{
var f;
var g;
var i;
var j;
var k;
var f; 
var t; 
var y;

y=DiagEnCours+1;

var action1;
var action2;
var action3;
var nomcase;
var couleur;

// nombre d'images avant ce diagramme

f="";
f+="<FORM NAME='formulaire'>";
f+="<TEXTAREA NAME='Coups' COLS='45' ROWS='16' ></TEXTAREA>";
f+="<br>";
f+="<INPUT TYPE='BUTTON' NAME ='A' VALUE=' |< ' onclick='AffichePositionIni(DiagEnCours)'>";
f+="<INPUT TYPE='BUTTON' NAME ='B' VALUE=' < ' onclick='Retour(DiagEnCours)'>"; 
f+="<INPUT TYPE='BUTTON' NAME ='C' VALUE=' > ' onclick='Avance(DiagEnCours)'>"; 
f+="<INPUT TYPE='BUTTON' NAME ='D' VALUE=' >| ' onclick='Fin(DiagEnCours)'>"; 
f+="<INPUT TYPE='BUTTON' NAME ='E' VALUE=' << ' onclick='DebutTempo(DiagEnCours)'>";
f+="<INPUT TYPE='BUTTON' NAME ='F' VALUE=' >> ' onclick='FinTempo(DiagEnCours)'>";
f+="<INPUT TYPE='BUTTON' NAME='AFFSOL' VALUE='Solution du pb.' onclick='AfficheBarreControle(DiagEnCours)'>";
if(ModeTest) f+="<INPUT TYPE='BUTTON' NAME ='FIN' VALUE='Fin du test' onclick='FinTest()'>";
f+="</FORM>";

t="<table BORDER=0 CELLSPACING=0 WIDTH=32 CELLPADDING=0>";

for(i=0;i<8;i++)
	{
	t+="<tr>";
	t= t + "<td>" + (8-i) + "&nbsp;</td>";
	for(j=0;j<8;j++) 
		{
		action1="Choix(DiagEnCours, " + i + ", " +j + ")";
		nomcase=CaseCoord(i,j);
		k=(i+j)&1;

		if(k==0) couleur="b/--.gif";
		else couleur="n/--.gif";

		if (TypeDiagramme[DiagEnCours]!="visu") {t+="<td><A HREF=# OnMouseDown='" + action1 + "'><IMG SRC='" + couleur + "' NAME='" + nomcase+ "' BORDER='0'></A></td>";}
		else {t+="<td><IMG SRC='" + couleur + "' NAME='" + nomcase+ "' BORDER='0'></td>";}
		}
	t+="</tr>";
	}
t+="<td ALIGN=CENTER>&nbsp;</td><td ALIGN=CENTER>A</td><td ALIGN=CENTER>B</td><td ALIGN=CENTER>C</td><td ALIGN=CENTER>D</td><td ALIGN=CENTER>E</td><td ALIGN=CENTER>F</td><td ALIGN=CENTER>G</td><td ALIGN=CENTER>H</td>";
t+="</table>";

creerCalque("calqueEchiquier",t,vpos+70,10,300,300,'visible');
creerCalque("calqueCommentaire",f,vpos+70,310,400,300,'hidden');

}




function tempstotal(d)
{
	return d.getSeconds()+60*d.getMinutes()+3600*d.getHours()
}

function timer(x)
{
  	tini[x]=tempstotal(new Date())
	timerMot(x);

}
function timerMot(x)
{
  var t;
  var y;
  y=x;	
  y++;
  tfinal[x]=tempstotal(new Date()) 
  t=	tfinal[x] - tini[x] + tcumul[x];

  texte="Diag " + y + " - Temps de réflexion : " + t + "s."; 
  texte+=" - Essai(s) incorrect(s) : " ;
  texte+= CoupsIncorrects[x] ;
  
  if (flagtimer[x]==false)window.status=""
  else 
	{
	window.status=texte;
	setTimeout("timerMot('"+x+"')",100);
	}
}


function AffichePositionIni(x)
{
	var i, j
	var Gif
	var Case
	var CodePiece
	var NomPiece
	Coup[x]=0;
	MajListeCoups(x,-1);
	
	for ( i=0; i<8; i++)
	{
		for ( j=0; j<8; j++)
		{
			CodePiece = PositionIni[x][i].substring(j,j+1);
			if (CodePiece == "." || CodePiece == " ")
				NomPiece ="--";
			else
			{
				if ( CodePiece > "Z" )
					NomPiece = CodePiece.toLowerCase() + "b";
				else
					NomPiece = CodePiece.toLowerCase() + "n";
			}
			PlacePiece(x,CaseCoord(i,j),NomPiece)
		}
	}

	//alert("AffichePositionIni");

var c0;
c0=ListeCoups[x][0].substring(0,2);
if(CouleurPieceCase(x,c0)=="n")FirstCp[x]=1;
if(CouleurPieceCase(x,c0)=="b")FirstCp[x]=0;
}

function LireCoup(x, y)
{
	DepCase = ListeCoups[x][y].substring(0,2);
	ArrCase = ListeCoups[x][y].substring(2,4);

	ArrPiece = PieceCase(x,ArrCase);
	DepPiece = PieceCase(x,DepCase);
}

function Avance(x)
{
	var i
	var str

	if (Coup[x] < ListeCoups[x].length)
	{
		LireCoup(x, Coup[x])

		PlacePiece(x,DepCase,"--")
		PlacePiece(x,ArrCase,DepPiece)

		str = DepPiece.substring(0,1).toUpperCase();
		if (str=="P") str = "";
		str = str + DepCase;
		if (ArrPiece != "--") str = str + "x";
		else str = str + "-";
		str=str + ArrCase;
		if (DepPiece=="rb" && DepCase=="e1" && ArrCase=="g1")
		{
			str="0-0";
			PlacePiece(x,"h1","--")
			PlacePiece(x,"f1","tb")
		}
		if (DepPiece=="rb" && DepCase=="e1" && ArrCase=="c1")
		{
			str="0-0-0";
			PlacePiece(x,"a1","--")
			PlacePiece(x,"d1","tb")
		}
		if (DepPiece=="rn" && DepCase=="e8" && ArrCase=="g8")
		{
			str="0-0";
			PlacePiece(x,"h8","--")
			PlacePiece(x,"f8","tn")
		}
		if (DepPiece=="rn" && DepCase=="e8" && ArrCase=="c8")
		{
			str="0-0-0";
			PlacePiece(x,"a8","--")
			PlacePiece(x,"d8","tn")
		}
		HistoriquePrises[x][Coup[x]]=ArrPiece;
		if (DepPiece=="pb" && ArrPiece=="--" && DepCase.substring(0,1) != ArrCase.substring(0,1))
		{
			PlacePiece(x,CaseVoisine(ArrCase,-1,0),"--")
			HistoriquePrises[x][Coup[x]]="ep";
		}
		if (DepPiece=="pn" && ArrPiece=="--" && DepCase.substring(0,1) != ArrCase.substring(0,1))
		{
			PlacePiece(x,CaseVoisine(ArrCase,1,0),"--")
			HistoriquePrises[x][Coup[x]]="ep";
		}
		if (DepPiece=="pb" && ArrCase.substring(1,2)=="8")
		{
			PlacePiece(x,ArrCase,ListeCoups[x][Coup[x]].substring(4,5)+"b")
			HistoriquePrises[x][Coup[x]]=HistoriquePrises[x][Coup[x]] + "x";
		}
		if (DepPiece=="pn" && ArrCase.substring(1,2)=="1")
		{
			PlacePiece(x,ArrCase,ListeCoups[x][Coup[x]].substring(4,5)+"n")
			HistoriquePrises[x][Coup[x]]=HistoriquePrises[x][Coup[x]] + "x";
		}
		i = Coup[x] + FirstCp[x];
		if (i%2==1) str = ((i+1)/2) + "..." + str;
		else str = ((i+2)/2) + "." + str;
		if (ListeCoups[x][Coup[x]].length>4) str=str + ListeCoups[x][Coup[x]].substring(4,ListeCoups[x][Coup[x]].length).toUpperCase();
		NotationCoup[x][Coup[x]]=str
		MajListeCoups(x,Coup[x]);	

		Coup[x]++;
		//alert(Coup[x] + " / " + ListeCoups[x].length);
		if (Coup[x] == ListeCoups[x].length)DiagrammeFini[x]=true;
	

	}
}


function Retour(x)
{
	if (Coup[x] > 0)
	{
		Coup[x]--
		LireCoup(x, Coup[x])
		if (ArrPiece=="pb" && HistoriquePrises[x][Coup[x]]=="ep")
		{
			PlacePiece(x,CaseVoisine(ArrCase,-1,0),"pn")
			HistoriquePrises[x][Coup[x]]="--";
		}
		if (ArrPiece=="pn" && HistoriquePrises[x][Coup[x]]=="ep")
		{
			PlacePiece(x,CaseVoisine(ArrCase,1,0),"pb")
			HistoriquePrises[x][Coup[x]]="--";
		}
		if (HistoriquePrises[x][Coup[x]].substring(2,3)=="x")
		{
			HistoriquePrises[x][Coup[x]]=HistoriquePrises[x][Coup[x]].substring(0,2);
			ArrPiece = "p" + ArrPiece.substring(1,2);
		}		
		PlacePiece(x,ArrCase,HistoriquePrises[x][Coup[x]])
		PlacePiece(x,DepCase,ArrPiece)

		if (ArrPiece=="rb" && DepCase=="e1" && ArrCase=="g1")
		{
			PlacePiece(x,"h1","tb")
			PlacePiece(x,"f1","--")
		}
		if (ArrPiece=="rb" && DepCase=="e1" && ArrCase=="c1")
		{
			PlacePiece(x,"a1","tb")
			PlacePiece(x,"d1","--")
		}
		if (ArrPiece=="rn" && DepCase=="e8" && ArrCase=="g8")
		{
			PlacePiece(x,"h8","tn")
			PlacePiece(x,"f8","--")
		}
		if (ArrPiece=="rn" && DepCase=="e8" && ArrCase=="c8")
		{
			PlacePiece(x,"a8","tn")
			PlacePiece(x,"d8","--")

		}

		MajListeCoups(x, Coup[x]-1);	
	}
}

function Fin(x)
{
	AvanceDirectement(x,ListeCoups[x].length);
}

function AvanceDirectement(x, NrCoup)
{
	if (NrCoup >= 0 && NrCoup <= ListeCoups[x].length)
	{
		if (NrCoup < Coup[x])
		{
			while (Coup[x]>NrCoup) Retour(x)
		}
		if (NrCoup > Coup[x])
		{
			while (Coup[x]<NrCoup) Avance(x)
		}
	}
}


function FinTempo(x)
{
	AvanceTempo(x,ListeCoups[x].length, 1000);
}

function DebutTempo(x)
{
	AvanceTempo(x,0, 1000);
}



function AvanceTempo(x, NrCoup, Attente)
{
	var i=0
	var action
	if (NrCoup >= 0 && NrCoup <= ListeCoups[x].length)
	{
		if (NrCoup < Coup[x])
		{
			action = "Retour("+x+")";
			while (Coup[x]-i>NrCoup) {i++;setTimeout(action, i*Attente);};
		}
		if (NrCoup > Coup[x])
		{
			action = "Avance("+x+")";
			while (Coup[x]+i<NrCoup) {i++;setTimeout(action, i*Attente);}
		}
	}
}



function InitialiseEchiquier(x)
{

// Utilisee pour visualiser plusieurs diagrammes sur la même page
// en mode visualisation

var f;
var g;
var i;
var j;
var k;
var f; 
var t; 
var y;
y=x+1;

var action1;
var action2;
var action3;
var nomcase;
var couleur;

// nombre d'images avant ce diagramme

f="";
f+="<FORM NAME='formulaire" + x.toString()+ "'>";
f+="<TEXTAREA NAME='Coups' COLS='45' ROWS='16' ></TEXTAREA>";
f+="<br>";
f+="<INPUT TYPE='BUTTON' NAME ='A' VALUE=' |< ' onclick='AffichePositionIni(" +x+ ")'>";
f+="<INPUT TYPE='BUTTON' NAME ='B' VALUE=' < ' onclick='Retour(" +x+ ")'>"; 
f+="<INPUT TYPE='BUTTON' NAME ='C' VALUE=' > ' onclick='Avance(" +x+ ")'>"; 
f+="<INPUT TYPE='BUTTON' NAME ='D' VALUE=' >| ' onclick='Fin(" +x+ ")'>"; 
f+="<INPUT TYPE='BUTTON' NAME ='E' VALUE=' << ' onclick='DebutTempo(" +x+ ")'>";
f+="<INPUT TYPE='BUTTON' NAME ='F' VALUE=' >> ' onclick='FinTempo(" +x+ ")'>";
//if (AfficheSol[x]==false) f+="<INPUT TYPE='BUTTON' NAME='AFFSOL' VALUE='Solution du pb.' onclick='AfficheBarreControle(" + x + ")'>";
//f+="<INPUT TYPE='BUTTON' NAME ='FIN' VALUE='Fin du test' onclick='FinTest()'>";
f+="</FORM>";

t="<table BORDER=0 CELLSPACING=0 WIDTH=32 CELLPADDING=0>";

for(i=0;i<8;i++)
	{
	t+="<tr>";
	t= t + "<td>" + (8-i) + "&nbsp;</td>";
	for(j=0;j<8;j++) 
		{
		action1="Choix(" + x + ", " + i + ", " +j + ")";
		nomcase=CaseCoord(i,j)+x.toString();
		k=(i+j)&1;

		if(k==0) couleur="b/--.gif";
		else couleur="n/--.gif";

		if (TypeDiagramme[x]!="visu") {t+="<td><A HREF=# OnMouseDown='" + action1 + "'><IMG SRC='" + couleur + "' NAME='" + nomcase+ "' BORDER='0'></A></td>";}
		else {t+="<td><IMG SRC='" + couleur + "' NAME='" + nomcase+ "' BORDER='0'></td>";}
		}
	t+="</tr>";
	}
t+="<td ALIGN=CENTER>&nbsp;</td><td ALIGN=CENTER>A</td><td ALIGN=CENTER>B</td><td ALIGN=CENTER>C</td><td ALIGN=CENTER>D</td><td ALIGN=CENTER>E</td><td ALIGN=CENTER>F</td><td ALIGN=CENTER>G</td><td ALIGN=CENTER>H</td>";
t+="</table>";

creerCalque("calqueTitre"+ x.toString(),"<H2><CENTER>" + titreDiag[x] + "</CENTER></H2>",vpos+350*x,10,700,30,'visible');
document.getElementById("calqueTitre"+ x.toString()).style.background='white';
document.getElementById("calqueTitre"+ x.toString()).style.color='blue';

creerCalque("calqueEchiquier"+ x.toString(),t,vpos+350*x+30,10,300,300,'visible');
creerCalque("calqueCommentaire"+ x.toString(),f,vpos+350*x+30,310,400,300,'visible');

}

function ActiveDiagramme(x)
// Cette fonction n'est utilisée que dans le cas où il y a plusieurs pb à traiter
// avec un seul échiquier commun
{
var i;

if(ModeResolutionPb)
	{
	DiagEnCours=x;
	if(DiagrammeFini[x]==true)
		{
		i=x+1;
		alert ("Le diagramme " + i +" a déjà été traité.");
		}
	else
		{
		for(i=0;i<=NombreDiag;i++)
			{
			flagtimer[i]=false;
			tcumul[i]=tcumul[i]+tfinal[i]-tini[i];
			tini[i]=tfinal[i];
			}
		AfficheInfos(x);
		}
	}
}


function AfficheBarreControle(x)
{
var y;
y=x;
y++;
if(ModeTest)alert ("Diag" + y + " - Vous avez demandé l'affichage de la solution. Ce problème ne sera donc pas comptabilisé.");
CacheChamp(x,"AFFSOL");
MontreChamp(x,"A");
MontreChamp(x,"B");
MontreChamp(x,"C");
MontreChamp(x,"D");
MontreChamp(x,"E");
MontreChamp(x,"F");
AfficheSol[x]=true;
CoupsIncorrects[x]=100;
Score[x]=0;
flagtimer[x]=false;
}


function SelectionCaseDepart(x,NomCase)
{
if (NomCase!="" && !CaseSelectionnee(x,NomCase))
	{
	PlacePieceSelectionCase(x,NomCase,PieceCase(x,NomCase));
	Selection[x]+=NomCase;
	}
}


function SelectionCase(x,NomCase)
{
if (NomCase!="")
	{
	if(MontreSelection[x]) PlacePieceSelectionCase(x,NomCase,PieceCase(x,NomCase));
	Selection[x]+=NomCase;
	}
}


function DeSelection(x)
{
while(Selection[x].length>0) DeSelectionCase(x,Selection[x].substr(0,2))
}


function supprStr(chaine1,chaine2)
{
var valeur;
  if ((chaine1 == "") || (chaine2 == "")) return chaine1;
  valeur = chaine1.indexOf(chaine2);
  if (valeur == -1) return chaine1;
  strFinale = "";
  strTmp = chaine1;
  while (valeur != -1)
  {
    strFinale = strFinale.concat(strTmp.substring(0,valeur));
    strTmp = strTmp.substr(valeur+chaine2.length);
    valeur = strTmp.indexOf(chaine2);
  }
  strFinale = strFinale.concat(strTmp);
  return strFinale;
}

function DeSelectionCase(x,NomCase)
{
PlacePiece(x,NomCase,PieceCase(x,NomCase))
Selection[x]=supprStr(Selection[x],NomCase)
}


function CouleurNormale(NomCase)
{
var i;
var j;
var k;
i=parseInt(NomCase.substring(1,2)); 
j=NomCase.substring(0,1).charCodeAt(0) - 97;
k=(i+j)&1;
if(k==0) return "b";
else return "n";
}

function CouleurSelection(NomCase)
{
var i;
var j;
var k;
i=parseInt(NomCase.substring(1,2)); 
j=NomCase.substring(0,1).charCodeAt(0) - 97;
k=(i+j)&1;
if(k==0) return "j";
else return "g";
}


function PlacePiece(x,NomCase,p)
{
SetImage(x,NomCase,p,CouleurNormale(NomCase))
}

function PlacePieceSelectionCase(x,NomCase,p)
{
SetImage(x,NomCase,p,CouleurSelection(NomCase))
}


function SetCaseDepart(x,NomCase)
{
CaseDepart[x]=NomCase
}

function SetCaseArrivee(x,NomCase)
{
CaseArrivee[x]=NomCase
}

function SetCasesDepArr(x,NomCase)
{
CasesDepArr[x]=NomCase
}


function CouleurCase(x,NomCase)
{
var Source
var Couleur
	Source = ImageCase(x, NomCase);
	Couleur = Source.substring(Source.length - 8, Source.length - 7 );
	return Couleur;
}

function PieceCase(x,NomCase)
{
var Source;
var p;
	Source = ImageCase(x, NomCase);
	p = Source.substring(Source.length - 6, Source.length -4 );
	return p;
}

function CouleurPieceCase(x,NomCase)
{
var Source;
var p;
	Source = ImageCase(x, NomCase);
	p = Source.substring(Source.length - 6, Source.length -4 );
	return p.substr(1,1);
}


function CaseCoord(i,j)
{
var c;
var NomCase;
c=new Array("a","b","c","d","e","f","g","h");
NomCase=c[j] + (8-i);
return NomCase;
}


function CaseVoisine(NomCase,di,dj)
{
// di : décalage de ligne (1 vers le haut, -1 vers le bas)
// dj : décalage de colonne (-1 à gauche, 1 à droite)
var cv;
var i;
var j;
var ni;
var nj;
i=parseInt(NomCase.substring(1,2)) ; 
i=8-i;
j=NomCase.substring(0,1).charCodeAt(0) - 97;
ni=i-di;
nj=j+dj;

if(ni>=0 && ni<8 && nj>=0 && nj<8)cv=CaseCoord(ni,nj);
else cv="";

return cv;
}


function CoupsValides(x,NomCase)
{
switch (PieceCase(x,NomCase))
	{
	case "pn" :
		SelectionCaseSiVide(x,NomCase,-1,0);
		if(NomCase.substr(1,1)=="7" && CaseSelectionnee(x,CaseVoisine(NomCase,-1,0))) SelectionCaseSiVide(x,NomCase,-2,0);
		SelectionCaseSiOccupee(x,NomCase,-1,-1);
		SelectionCaseSiOccupee(x,NomCase,-1,1);
	break;

	case "pb" :
		SelectionCaseSiVide(x,NomCase,1,0);
		if(NomCase.substr(1,1)=="2" && CaseSelectionnee(x,CaseVoisine(NomCase,1,0)))SelectionCaseSiVide(x,NomCase,2,0);
		SelectionCaseSiOccupee(x,NomCase,1,-1);
		SelectionCaseSiOccupee(x,NomCase,1,1);
	break;

	case "rn" :
		if(NomCase=="e8" && PieceCase(x,"f8")=="--" && PieceCase(x,"g8")=="--" && PieceCase(x,"h8")=="tn") SelectionCase(x,"g8");
		if(NomCase=="e8" && PieceCase(x,"d8")=="--" && PieceCase(x,"c8")=="--" && PieceCase(x,"b8")=="--" && PieceCase(x,"a8")=="tn") SelectionCase(x,"c8");
		ExploreCaseVoisine(x,NomCase,1,0);
		ExploreCaseVoisine(x,NomCase,1,1);
		ExploreCaseVoisine(x,NomCase,1,-1);
		ExploreCaseVoisine(x,NomCase,-1,0);
		ExploreCaseVoisine(x,NomCase,-1,1);
		ExploreCaseVoisine(x,NomCase,-1,-1);
		ExploreCaseVoisine(x,NomCase,0,0);
		ExploreCaseVoisine(x,NomCase,0,1);
		ExploreCaseVoisine(x,NomCase,0,-1);
	break;

	case "rb" :
		if(NomCase=="e1" && PieceCase(x,"f1")=="--" && PieceCase(x,"g1")=="--" && PieceCase(x,"h1")=="tb") SelectionCase(x,"g1");
		if(NomCase=="e1" && PieceCase(x,"d1")=="--" && PieceCase(x,"c1")=="--" && PieceCase(x,"b1")=="--" && PieceCase(x,"a1")=="tb") SelectionCase(x,"c1");
		ExploreCaseVoisine(x,NomCase,1,0);
		ExploreCaseVoisine(x,NomCase,1,1);
		ExploreCaseVoisine(x,NomCase,1,-1);
		ExploreCaseVoisine(x,NomCase,-1,0);
		ExploreCaseVoisine(x,NomCase,-1,1);
		ExploreCaseVoisine(x,NomCase,-1,-1);
		ExploreCaseVoisine(x,NomCase,0,0);
		ExploreCaseVoisine(x,NomCase,0,1);
		ExploreCaseVoisine(x,NomCase,0,-1);
	break;

	case "fn" :
		ExploreDirection(x,NomCase,1,1);
		ExploreDirection(x,NomCase,1,-1);
		ExploreDirection(x,NomCase,-1,1);
		ExploreDirection(x,NomCase,-1,-1);
	break;

	case "fb" :
		ExploreDirection(x,NomCase,1,1);
		ExploreDirection(x,NomCase,1,-1);
		ExploreDirection(x,NomCase,-1,1);
		ExploreDirection(x,NomCase,-1,-1);
	break;

	case "tn" :
		ExploreDirection(x,NomCase,1,0);
		ExploreDirection(x,NomCase,-1,0);
		ExploreDirection(x,NomCase,0,1);
		ExploreDirection(x,NomCase,0,-1);
	break;

	case "tb" :
		ExploreDirection(x,NomCase,1,0);
		ExploreDirection(x,NomCase,-1,0);
		ExploreDirection(x,NomCase,0,1);
		ExploreDirection(x,NomCase,0,-1);
	break;

	case "cb" :
		ExploreCaseVoisine(x,NomCase,2,1);
		ExploreCaseVoisine(x,NomCase,2,-1);
		ExploreCaseVoisine(x,NomCase,-2,1);
		ExploreCaseVoisine(x,NomCase,-2,-1);
		ExploreCaseVoisine(x,NomCase,1,2);
		ExploreCaseVoisine(x,NomCase,-1,2);
		ExploreCaseVoisine(x,NomCase,1,-2);
		ExploreCaseVoisine(x,NomCase,-1,-2);
	break;

	case "cn" :
		ExploreCaseVoisine(x,NomCase,2,1);
		ExploreCaseVoisine(x,NomCase,2,-1);
		ExploreCaseVoisine(x,NomCase,-2,1);
		ExploreCaseVoisine(x,NomCase,-2,-1);
		ExploreCaseVoisine(x,NomCase,1,2);
		ExploreCaseVoisine(x,NomCase,-1,2);
		ExploreCaseVoisine(x,NomCase,1,-2);
		ExploreCaseVoisine(x,NomCase,-1,-2);
	break;

	case "dn" :
		ExploreDirection(x,NomCase,1,1);
		ExploreDirection(x,NomCase,1,-1);
		ExploreDirection(x,NomCase,-1,1);
		ExploreDirection(x,NomCase,-1,-1);
		ExploreDirection(x,NomCase,1,0);
		ExploreDirection(x,NomCase,-1,0);
		ExploreDirection(x,NomCase,0,1);
		ExploreDirection(x,NomCase,0,-1);
	break;

	case "db" :
		ExploreDirection(x,NomCase,1,1);
		ExploreDirection(x,NomCase,1,-1);
		ExploreDirection(x,NomCase,-1,1);
		ExploreDirection(x,NomCase,-1,-1);
		ExploreDirection(x,NomCase,1,0);
		ExploreDirection(x,NomCase,-1,0);
		ExploreDirection(x,NomCase,0,1);
		ExploreDirection(x,NomCase,0,-1);
	break;
	}
}



function SelectionCaseSiVide(x,NomCase,di,dj)
{
var c;
var ca;
var cca;
c=CouleurPieceCase(x,NomCase);
ca=CaseVoisine(NomCase,di,dj);
if(ca!="")
	{
	if (CouleurPieceCase(x,ca)=="-") SelectionCase(x,ca);
	}
}

function SelectionCaseSiOccupee(x,NomCase,di,dj)
{
var c;
var ca;
var cca;
c=CouleurPieceCase(x,NomCase);
ca=CaseVoisine(NomCase,di,dj);
if(ca!="")
	{
	if (CouleurPieceCase(x,ca)!="-" && CouleurPieceCase(x,ca)!=c) SelectionCase(x,ca);
	}
}


function ExploreCaseVoisine(x,NomCase,di,dj)
{
var c;
var ca;
var cca;
c=CouleurPieceCase(x,NomCase);
ca=CaseVoisine(NomCase,di,dj);
if(ca!="")
	{
	if (CouleurPieceCase(x,ca)!=c) SelectionCase(x,ca);
	}
}



function ExploreDirection(x,NomCase,di,dj)
{
var c;
var ca;
var cca;
var k;
var blocage;
k=1;
blocage=false;
c=CouleurPieceCase(x,NomCase);
while (!blocage)
	{
	ca=CaseVoisine(NomCase,k*di,k*dj);
	if(ca=="") blocage=true;
	else
		{
		cca=CouleurPieceCase(x,ca);
		if (cca==c) blocage=true;
		else
			{
			if (cca=="-") SelectionCase(x,ca);
			else
				{
				SelectionCase(x,ca);
				blocage=true;
				}

			}
		}
	k++;
	}
}


function CaseSelectionnee(x,NomCase)
{
return(Selection[x].indexOf(NomCase)>0)
}

function Choix(x,i,j)
{
var s;
NomCase=CaseCoord(i,j);

//alert(x);


if (CaseDepart[x]=="" && PieceCase(x,NomCase)!="--" )
	{
	if( (CouleurPieceCase(x,NomCase)=="n" && FirstCp[x]==1) || (CouleurPieceCase(x,NomCase)=="b" && FirstCp[x]==0) )
		{
		SetCaseDepart(x,NomCase);
		SelectionCaseDepart(x,NomCase);
		CoupsValides(x,NomCase);
		} 
	}
else
	{
	if (!CaseSelectionnee(x,NomCase) || NomCase==CaseDepart[x])
		{
		if (!CaseSelectionnee(x,NomCase) && NomCase!=CaseDepart[x])
			{
			alert("Coup invalide");
			CoupsInvalides[x]++;
			}
		SetCaseDepart(x,"");
		DeSelection(x);
		}
	else
		{
		SetCaseArrivee(x,NomCase);
		SetCasesDepArr(x,CaseDepart[x]+CaseArrivee[x]);
		s=CasesDepArr[x]
		
		DepCase = CaseDepart[x];
		ArrCase = CaseArrivee[x];
		
		DeSelection(x);

		ArrPiece = PieceCase(x,ArrCase);
		DepPiece = PieceCase(x,DepCase);
		SetCaseDepart(x,"");
		SetCaseArrivee(x,"");
		switch(TypeDiagramme[x])
			{
			case "pb":
				if (ListeCoups[x][Coup[x]].substring(0,4)==CasesDepArr[x])
				{
				JoueCoup(x);
					if (Coup[x] < ListeCoups[x].length)
					{
					setTimeout("Avance(" + x + ")",1000);
					tini[x]=tini[x]+1;
					}
					else
					{
					tcumul[x] = tcumul[x] + tfinal[x] - tini[x];
					CalculeScore(x);
					if(CoupsIncorrects[x]==0)alert("Félicitations ! (score " + Score[x] + "/5 - temps : " + tcumul[x] + " sec.)" );
					if(CoupsIncorrects[x]==1)alert("C'est exact ! (score " + Score[x] + "/5 - temps : " + tcumul[x] + " sec.)" );
					if(CoupsIncorrects[x]>1)alert("Cette fois, vous avez bien trouvé le bon coup ! (score " + Score[x] + "/5 - temps : " + tcumul[x] + " sec.)" );
					flagtimer[x]=false;
					DiagrammeFini[x]=true;
					}
				}
				else 
				{
				alert("Ce n'est pas le meilleur coup...");
				CoupsIncorrects[x]++;
				}
			break;

			case "jeu":
				JoueCoup(x);
			break;

			}
		}

	}
}


function JoueCoup(x)
{
	var i;
	var k;
	var promotion;
	var str;

if( (CouleurPieceCase(x,DepCase)=="n" && FirstCp[x]==1) || (CouleurPieceCase(x,DepCase)=="b" && FirstCp[x]==0) )
	{

		PlacePiece(x,DepCase,"--")
		PlacePiece(x,ArrCase,DepPiece)
		str = DepPiece.substring(0,1).toUpperCase();
		if (str=="P") str = "";
		str = str + DepCase;
		if (ArrPiece != "--") str = str + "x";
		else str = str + "-";
		str=str + ArrCase;

		if (DepPiece=="rb" && DepCase=="e1" && ArrCase=="g1")
		{
			str="0-0";
			PlacePiece(x,"h1","--")
			PlacePiece(x,"f1","tb")
		}
		if (DepPiece=="rb" && DepCase=="e1" && ArrCase=="c1")
		{
			str="0-0-0";
			PlacePiece(x,"a1","--")
			PlacePiece(x,"d1","tb")
		}
		if (DepPiece=="rn" && DepCase=="e8" && ArrCase=="g8")
		{
			str="0-0";
			PlacePiece(x,"h8","--")
			PlacePiece(x,"f8","tn")
		}
		if (DepPiece=="rn" && DepCase=="e8" && ArrCase=="c8")
		{
			str="0-0-0";
			PlacePiece(x,"a8","--")
			PlacePiece(x,"d8","tn")
		}

		HistoriquePrises[x][Coup[x]]=ArrPiece;

		if (DepPiece=="pb" && ArrPiece=="--" && DepCase.substring(0,1) != ArrCase.substring(0,1))
		{
			PlacePiece(x,CaseVoisine(ArrCase,-1,0),"--")
			HistoriquePrises[x][Coup[x]]="ep";
		}
		if (DepPiece=="pn" && ArrPiece=="--" && DepCase.substring(0,1) != ArrCase.substring(0,1))
		{
			PlacePiece(x,CaseVoisine(ArrCase,1,0),"--")
			HistoriquePrises[x][Coup[x]]="ep";
		}


		if (DepPiece=="pb" && ArrCase.substring(1,2)=="8")
		{
//			promotion=prompt("Promotion en (d,c,f,t) ? ","d");
			promotion="d"
			PlacePiece(x,ArrCase,promotion+"b")

			HistoriquePrises[x][Coup[x]]=HistoriquePrises[x][Coup[x]] + "x";
		}
		if (DepPiece=="pn" && ArrCase.substring(1,2)=="1")
		{
//			promotion=prompt("Promotion en (d,c,f,t) ? ","d");
			promotion="d"
			SetCasesDepArr(x,CasesDepArr[x]+promotion);
			PlacePiece(x,ArrCase,promotion+"n")

			HistoriquePrises[x][Coup[x]]=HistoriquePrises[x][Coup[x]] + "x";
		}
		i = Coup[x] + FirstCp[x];
		if (i%2==1) str = ((i+1)/2) + "..." + str;
		else str = ((i+2)/2) + "." + str;
		if (ListeCoups[x][Coup[x]].length>4) str=str + ListeCoups[x][Coup[x]].substring(4,ListeCoups[x][Coup[x]].length).toUpperCase();
		NotationCoup[x][Coup[x]]=str;
		MajListeCoups(x,Coup[x]);

		ListeCoups[x][Coup[x]]=CasesDepArr[x];
		Coup[x]++;
	}
}


function MajListeCoups(x,numCoup)
{
var str;
var i;
		str=Commentaires[x][0];
		str+=String.fromCharCode(13);
		str+=String.fromCharCode(10);

		for(i=0;i<=numCoup;i++)
			{
			str+=NotationCoup[x][i];
			str+=" ";
			str+=Commentaires[x][i+1];
			str+=String.fromCharCode(13);
			str+=String.fromCharCode(10);
			}
		setformulaire(x,"Coups",str);
}