// JavaScript Document
// Fonctions relativent a une session ouverte



// -----------------------------------------------------------
// versionning
var site_version_sql = ""
var site_version_js = "07.01.09"
var site_timer_online = null;
var site_timer_attente = null;
var site_timer_encours = null;
var site_timer_viki = null;
var site_timer_chat = null;

// -----------------------------------------------------------
// initialise les timer
var timer_list_online 		= null;
var timer_list_attente 		= null;
var timer_list_encours 		= null;
var timer_play_countdown 	= null;
var timer_play_viki 		= null;
var timer_play_chat 		= null;
var timer_histo_view 		= null;
var timer_play_bot			= null;

// -----------------------------------------------------------
// initialise les equivalence des variables PHP et JS
var js_joueur_id		= null;
var js_joueur_name		= null;
var js_joueur_guest		= null;
var js_board_piece 		= null; //forme des pieces
var js_board_lightlast	= null; //option de surbrillance du dernier coup joué (1 ou 0)
var js_board_lightchess = null; //option de surbrillance des echecs et des mats (1 ou 0)
var js_case 			= null;
var js_moves	 		= null;
var js_blanc 			= null;
var js_noir 			= null;
var js_mustplay 		= null;
var js_hits		 		= null;
var js_progress 		= null;
var js_type		 		= null;
var js_timer_blanc 		= null;
var js_timer_noir 		= null;
var js_last_hit			= null;
var js_partieID			= null;
var js_chesslight		= null;
var js_chesslast		= null;
var js_inviteur			= null;
var js_versusbot		= null;
var js_reverse			= null;

// -----------------------------------------------------------
// initialise les variables de l'IA
var ia_coup = null;
var ia_deep = null;
var ia_timeout = null;			//permet de dire que le temps est ecoulé
var ia_timeoutgo = null;		//defini pour la fonction minmax qu'il faut que ca reprenne les dernieres valeurs suite a un timeout
var ia_timeoutgo2 = null;		//defini pour la fonction minmax qu'il faut que ca reprenne les dernieres valeurs suite a un timeout
var ia_timeoutcase = null;
var ia_timeouthisto = null;
var ia_timeoutdeep = null;
var ia_timeoutcp1 = null;
var ia_timeoutcp2 = null;
var ia_timeoutalpha = null;
var ia_timeoutbeta = null;
var ia_timeoutcolor = null;

var ia_taxidata = new Array(64);
var ia_distdata = new Array(64);
var ia_posPB = new Array(0, 0, 0, 0, 0, 0, 0, 0, 18, 22, 30, 38, 38, 30, 22, 18, 12, 16, 24, 32, 32, 24, 16, 12, 8, 12, 16, 24, 24, 16, 12, 8, 6, 8, 12, 16, 16, 12, 8, 6, 6, 8, 2, 10, 10, 2, 8, 6, 4, 4, 4, 0, 0, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0);
var ia_posPN = new Array(0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 0, 0, 4, 4, 4, 6, 8, 2, 10, 10, 2, 8, 6, 6, 8, 12, 16, 16, 12, 8, 6, 8, 12, 16, 24, 24, 16, 12, 8, 12, 16, 24, 32, 32, 24, 16, 12, 18, 22, 30, 38, 38, 30, 22, 18, 0, 0, 0, 0, 0, 0, 0, 0);
var ia_pos_knight = new Array(0, 4, 8, 10, 10, 8, 4, 0, 4, 8, 16, 20, 20, 16, 8, 4, 8, 16, 24, 28, 28, 24, 16, 8, 10, 20, 28, 32, 32, 28, 20, 10, 10, 20, 28, 32, 32, 28, 20, 10, 8, 16, 24, 28, 28, 24, 16, 8, 4, 8, 16, 20, 20, 16, 8, 4, 0, 4, 8, 10, 10, 8, 4, 0);
var ia_pos_bishop = new Array(14, 14, 14, 14, 14, 14, 14, 14, 14, 22, 18, 18, 18, 18, 22, 14, 14, 18, 22, 22, 22, 22, 18, 14, 14, 18, 22, 22, 22, 22, 18, 14, 14, 18, 22, 22, 22, 22, 18, 14, 14, 18, 22, 22, 22, 22, 18, 14, 14, 22, 18, 18, 18, 18, 22, 14, 14, 14, 14, 14, 14, 14, 14, 14);
var ia_mob_bishop = new Array(-4, -2, 0, 2, 4, 6, 8, 10 ,12, 14, 16, 20, 22);
var ia_mob_rook = new Array(0, 2, 4, 6, 8, 10 ,12, 14, 16, 20, 22, 24, 26);
var ia_pos_KingOpening = new Array(0, 0, -4, -10, -10, -4, 0, 0, -4, -4, -8, -12, -12, -8, -4, -4, -12, -16, -20, -20, -20, -20, -16, -12, -16, -20, -24, -24, -24, -24, -20, -16, -16, -20, -24, -24, -24, -24, -20, -16, -12, -16, -20, -20, -20, -20, -16, -12, -4, -4, -8, -12, -12, -8, -4, -4, 0, 0, -4, -10, -10, -4, 0, 0);
var ia_pos_KingEnding = new Array(0, 6, 12, 18, 18, 12, 6, 0, 6, 12, 18, 24, 24, 18, 12, 6, 12, 18, 24, 30, 30, 24, 18, 12, 18, 24, 30, 36, 36, 30, 24, 18, 18, 24, 30, 36, 36, 30, 24, 18, 12, 18, 24, 30, 30, 24, 18, 12, 6, 12, 18, 24, 24, 18, 12, 6, 0, 6, 12, 18, 18, 12, 6, 0);
var ia_pos_KingDying = new Array(0, 8, 16, 24, 24, 16, 8, 0, 8, 32, 40, 48, 48, 40, 32, 8, 16, 40, 56, 64, 64, 56, 40, 16, 24, 48, 64, 72, 72, 64, 48, 24, 24, 48, 64, 72, 72, 64, 48, 24, 16, 40, 56, 64, 64, 56, 40, 16, 8, 32, 40, 48, 48, 40, 32, 8, 0, 8, 16, 24, 24, 16, 8, 0);
var ia_isolated_pawn = new Array(-12, -16, -20, -24, -24, -20, -16, -12);
var KBNK = new Array(99, 90, 80, 70, 60, 50, 40, 40, 90, 80, 60, 50, 40, 30, 20, 40, 80, 60, 40, 30, 20, 10, 30, 50, 70, 50, 30, 10, 0, 20, 40, 60, 60, 40, 20, 0, 10, 30, 50, 70, 50, 30, 10, 20, 30, 40, 60, 80, 40, 20, 30, 40, 50, 60, 80, 90, 40, 40, 50, 60, 70, 80, 90, 99);
var ia_open_white = new Array("52:36", "51:35", "52:36", "51:35", "52:36", "51:35");
var ia_open_black = new Array("11:27", "1:18", "12:20", "6:21", "11:19", "14:22");
ia_init();
function row(y) { return ((y) >> 3);}
function column(x) { return ((x) & 7);}
function locn(x,y) { return (((y) << 3) | x);}
var _KING 	= 1200;
var _QUEEN 	= 1000;
var _ROOK 	= 550;
var _BISHOP = 355;
var _KNIGHT = 350;
var _PAWN 	= 100;

var ia_date1 = new Date();
var ia_date2 = new Date();
	

// -----------------------------------------------------------
// initialise les variables du ScrollLayer
var tbl, move = 0;
var l_online = 0;
var w_online = 0;
var l_attente = 0;
var w_attente = 0;
var l_encours = 0;
var w_encours = 0;
var l_chat = 0;
var w_chat = 0;

// -----------------------------------------------------------
// initialise les autres variables
var GL_clicdown = 0;
var tools_fenetre = null; 	// fenetre des couleurs
var play = false;			// le play du magneto
var js_hits_current = 0; 	// nbre de hits total (utile de connaitre le nombre total quand la var js_hits et a null)

// -----------------------------------------------------------
// fonctions_communes
function trim(string) { return string.replace(/(^\s*)|(\s*$)/g,''); }
function showElement(element) { document.getElementById(element).style.display='block'; }
function removeElement(element) { document.getElementById(element).style.display='none'; }



function GetHttpObject()
{
	var objXMLHttp = null; 
	 
	if(window.XMLHttpRequest) // Firefox et autres
	   objXMLHttp = new XMLHttpRequest(); 
	else if(window.ActiveXObject){ // Internet Explorer 
	   try {
                objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
	}
	else { // XMLHttpRequest non supporté par le navigateur 
	   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
	   objXMLHttp = false; 
	}
	return objXMLHttp;
}

function onunloadpage()
{
	window.clearTimeout(timer_list_encours);
	window.clearTimeout(timer_list_attente);
	window.clearTimeout(timer_list_online);
	window.clearTimeout(timer_play_countdown);
	window.clearTimeout(timer_play_viki);
	window.clearTimeout(timer_play_chat);
	window.clearTimeout(timer_histo_view);
	user_set_online(js_joueur_id, 0);
}

function onloadpage()
{
	user_set_online(js_joueur_id, 1);
	header_online_liste('init');
}

function myIndexOf(tableau, piece) //piece en lettre
{
	for (var i = 0; i < tableau.length; i++)
    	if (tableau[i].indexOf(piece) >= 0)
        	return i;

   	return -1;
}

function myIndexOf2(tableau, piece) //piece en chiffre
{
	for (var i = 0; i < tableau.length; i++)
    	if (tableau[i] == piece)
        	return i;

   	return -1;
}










//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//								   FONCTIONS DE LA PAGE DE GARDE							   \\
//						       ( concerne l'avant authentification )						   \\
//_____________________________________________________________________________________________\\


// -----------------------------------------------------------
// validsaisie [verifie que les informations d'inscription sont correctes]
function validsaisie()
{
	var erreur 	= '';
	var login	= new RegExp("[^0-9a-zA-Z]", "g");
   	var email 	= new RegExp ( "^\\w[\\w+\.\-]*@[\\w\-]+\.\\w[\\w+\.\-]*\\w$", "gi" ) ;

	// LOGIN
	document.insc.newlogin.value = trim(document.insc.newlogin.value);
	document.insc.newlogin.value = document.insc.newlogin.value.toLowerCase();
	if (document.insc.newlogin.value.length <3 || document.insc.newlogin.value.length >10 ) erreur = erreur + "\nLe champ LOGIN n'a pas la bonne taille. (entre 3 et 10)";
	if (login.test(document.insc.newlogin.value) == true) erreur = erreur + "\nLe champ LOGIN contient des caractères interdits.";

	// MDP
	if (document.insc.newmdp.value.length <3) erreur = erreur + "\nLe MDP est trop court.";

	// EMAIL
	document.insc.newemail.value = trim(document.insc.newemail.value);
	document.insc.newemail.value = document.insc.newemail.value.toLowerCase();
	if (document.insc.newemail.value.length <1) erreur = erreur + "\nLe champ EMAIL est vide.";
  	if ( (document.insc.newemail.value.length >= 1) && (document.insc.newemail.value.search(email) == -1) ) erreur = erreur + "\nLe champ EMAIL est invalide.";
	
	// ERREUR(S)
	if (erreur != '')
	{
		erreur = "Erreurs de saisie\n------------------------------------------------------------\n" + erreur;
		alert (erreur);
		return;
	}
	document.insc.submit();
}








//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//								      FONCTIONS DU HEADER									   \\
//						  ( concerne toutes les fonctions du header )						   \\
//_____________________________________________________________________________________________\\


// -----------------------------------------------------------
// header_online_liste [permet de rafraichir le tableau des joueurs online]
function header_online_liste(liste)
{
  	// kill timer s'il existe pour ne pas en lancer deux en meme temps
	window.clearTimeout(timer_list_online);
	
	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données 
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					// reinitialisation des scrolls
					l_online = 0;
					w_online = 0;
					// maj des joueurs en ligne et du timer
					document.getElementById("header_online_contenu").innerHTML = httpRequest.responseText;
					CSBfleXcroll('scrollonline');
					timer_list_online = window.setTimeout("header_online_liste('reload')",120000);
				}
			 }
		}
	}
  	httpRequest.open("GET", "ajax.php?fonction=header_online_liste", true);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// header_attente_liste [permet de rafraichir le tableau des demandes de defis]
function header_attente_liste(liste)
{
  	// kill timer s'il existe pour ne pas en lancer deux en meme temps
	window.clearTimeout(timer_list_attente);
	
	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données 
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					if (httpRequest.responseText != "")
					{
						// reinitialisation des scrolls
						l_attente = 0;
						w_attente = 0;
						var tmp = httpRequest.responseText.split("::");
						document.getElementById("header_attente_contenu").innerHTML = tmp[1];
						CSBfleXcroll('scrollattente');
						liste = tmp[0];
					}
				}
				if (liste.length = 0) liste = "retry";
				timer_list_attente = window.setTimeout("header_attente_liste('"+liste+"')",30000);
	     	}
    		}
	}
  	httpRequest.open("GET", "ajax.php?fonction=header_attente_liste&parts="+liste, true);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// header_attente_click [gere les reponses des clics sur la liste d'attente]
function header_attente_click(partieID, reponse)
{
	// les variables
	var data = "flag=attente&partieID="+partieID+"&reponse="+reponse;
  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					var tmp = httpRequest.responseText.split("|||");
					if (tmp[0] == "KO")
						alert(tmp[1]);
					else
					{
						document.getElementById("header_attente_contenu").innerHTML = tmp[1];
						CSBfleXcroll('scrollattente');
					}
					header_encours_liste('init');
					if (reponse == "OK" && tmp[0] != "KO")
						header_encours_click(partieID);
				}
			}
    		}
	}
  	httpRequest.open("POST", "ajax.php?fonction=header_attente_click", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}


// -----------------------------------------------------------
// header_encours_liste [permet de rafraichir le tableau des parties en cours]
function header_encours_liste(liste)
{
  	// kill timer s'il existe pour ne pas en lancer deux en meme temps
	window.clearTimeout(timer_list_encours);
	
	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données 
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					if (httpRequest.responseText != "")
					{
						// reinitialisation des scrolls
						l_encours = 0;
						w_encours = 0;
						var tmp = httpRequest.responseText.split("::");
						document.getElementById("header_encours_contenu").innerHTML = tmp[2];
						CSBfleXcroll('scrollencours');
						liste = tmp[0] + "::" + tmp[1];
						if (tmp[1] > 0)	document.title = "echess.fr (" + tmp[1] + ") | Jeu d'echecs gratuit en ligne" ;
						else document.title = "echess.fr | Jeu d'echecs gratuit en ligne";
					}
				}
				if (liste.length = 0) liste = "retry";
				timer_list_encours = window.setTimeout("header_encours_liste('"+liste+"')",30000);
			}
    	}
	}
  	httpRequest.open("GET", "ajax.php?fonction=header_encours_liste&parts="+liste, true);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// header_encours_click [gere les clics sur une partie]
function header_encours_click(partieID)
{
	// on arrete les timer
	window.clearTimeout(timer_play_viki);
	window.clearTimeout(timer_play_chat);
	window.clearTimeout(timer_play_countdown);
	
	// les variables
	js_partieID = partieID;
	var data = "partieID="+partieID;
	showElement("site_load");
	user_set_pageactuelle("_main_play.php" + "=" + partieID);
	
  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données
		// [0][case] ||| [1][histo_coups] ||| [2][blanc] ||| [3][noir] ||| [4][mustplay] ||| 
		// [5][coups_nbr] ||| [6][progress] ||| [7][board_forme] ||| [8][light_last] ||| [9][light_chess] ||| [10][partie type] ||| 
		// [11][timer blanc] ||| [12][timer noir] ||| [13][last hit] ||| [14][inviteur] ||| [15][bot] ||| [16][_main_play.php]
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					GL_clicdown = 0;
	     			var tmp = httpRequest.responseText.split("|||");
					js_case				= tmp[0].split("|");
					js_moves	 		= tmp[1].split("|");
					js_blanc 			= tmp[2];
					js_noir 			= tmp[3];
					js_mustplay 		= tmp[4];
					js_hits		 		= tmp[5];
					js_progress 		= tmp[6];
					js_board_piece		= tmp[7];
					js_board_lightlast	= tmp[8];
					js_board_lightchess	= tmp[9];
					js_type				= tmp[10];
					js_timer_blanc		= tmp[11];
					js_timer_noir		= tmp[12];
					js_last_hit			= tmp[13];
					js_inviteur			= tmp[14];
					js_versusbot		= tmp[15];
					document.getElementById("contenu_list_page").innerHTML = tmp[16];
				}
			game_lightlast(js_case, js_moves, js_hits, true);
			game_lightchess(js_case, js_moves, js_hits, true);
			chess_chat(0); //active le refresh du chat
			if (js_progress < 5) game_viki();  //active la surveillance [viki: cf i'm robot]
			if (js_progress == 3) game_countdown();
			removeElement("site_load");
	     	}
    	}
	}
	httpRequest.open("POST", "ajax.php?fonction=header_encours_click", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}


// -----------------------------------------------------------
// header_finie_liste [permet de rafraichir la liste des parties finies]
function header_finie_liste()
{
	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données 
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4)
	     		if (httpRequest.status == 200)
						document.getElementById("header_finie_contenu").innerHTML = httpRequest.responseText;
		}
	 }
  	httpRequest.open("GET", "ajax.php?fonction=header_finie_liste", true);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// header_page_change [affiche la page appelé par le menu]
function header_page_change(fichier)
{
	//kill timers s'ils existent pour ne pas que ca continue de tourner apres un changement de page.
	window.clearTimeout(timer_play_viki); // pour ne pas que VIKI continue de tourner
	window.clearTimeout(timer_play_chat); // pour ne pas que CHAT continue de tourner
	window.clearTimeout(timer_histo_view); // pour ne pas que HISTOVIEW continue de tourner
	window.clearTimeout(timer_play_countdown); // pour ne pas que le COMPTEUR continue de tourner

	//maj de la page actuelle dans les stats
	showElement("site_load");
	user_set_pageactuelle(fichier);
	
  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				document.getElementById("contenu_list_page").innerHTML = httpRequest.responseText;
			if (fichier == '_main_logout.php') setTimeout("window.location='index.php'",1);
			if (fichier.indexOf('_main_enigma.php', 0) >= 0) enigma_init();
	     	removeElement("site_load");
	     	}
			
    	}
	}
  	httpRequest.open("GET", fichier, true);
  	httpRequest.send(null);
}









//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//								        FONCTIONS DU USER									   \\
//					         ( relatif a toutes modification du joueur )					   \\
//_____________________________________________________________________________________________\\


// -----------------------------------------------------------
// user_set_online [permet de switcher un joueur en online/offline et vice-versa]
function user_set_online(joueurID, action)
{
	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données de la combo 2 
   		httpRequest.onreadystatechange=function(){
    		if (httpRequest.readyState == 4)
     			if (httpRequest.status == 200) 
					;
     		}
    	}
  	httpRequest.open("GET", "ajax.php?fonction=user_set_online&joueurID="+joueurID+"&action="+action, false);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// user_set_pageactuelle [inscrit le nom de la page sur laquelle est le joueur dans ses stats]
function user_set_pageactuelle(page)
{
	// fait varier la class du menu si on a choisi une page du menu
	if (document.getElementById('link_menu_accueil')) document.getElementById("link_menu_accueil").className = "link_menu_gray"; if (page.search("_main_accueil") > -1) document.getElementById("link_menu_accueil").className = "link_menu_blue";
	if (document.getElementById('link_menu_defier')) document.getElementById("link_menu_defier").className = "link_menu_gray"; if (page.search("_main_defis") > -1) document.getElementById("link_menu_defier").className = "link_menu_blue";
	if (document.getElementById('link_menu_options')) document.getElementById("link_menu_options").className = "link_menu_gray"; if (page.search("_main_tools") > -1) document.getElementById("link_menu_options").className = "link_menu_blue";
	if (document.getElementById('link_menu_stats')) document.getElementById("link_menu_stats").className = "link_menu_gray"; if (page.search("_main_stats") > -1) document.getElementById("link_menu_stats").className = "link_menu_blue";
	if (document.getElementById('link_menu_histo')) document.getElementById("link_menu_histo").className = "link_menu_gray"; if (page.search("_main_histo") > -1) document.getElementById("link_menu_histo").className = "link_menu_blue";
	if (document.getElementById('link_menu_regles')) document.getElementById("link_menu_regles").className = "link_menu_gray"; if (page.search("_main_rules") > -1) document.getElementById("link_menu_regles").className = "link_menu_blue";
	if (document.getElementById('link_menu_enigma')) document.getElementById("link_menu_enigma").className = "link_menu_red"; if (page.search("_main_enigma") > -1) document.getElementById("link_menu_enigma").className = "link_menu_blue";

	if (document.getElementById('link_menu_admin_accueil')) document.getElementById("link_menu_admin_accueil").className = "link_menu_gray"; if (page.search("_admin_accueil") > -1) document.getElementById("link_menu_admin_accueil").className = "link_menu_blue";
	if (document.getElementById('link_menu_admin_comptes')) document.getElementById("link_menu_admin_comptes").className = "link_menu_gray"; if (page.search("_admin_comptes") > -1) document.getElementById("link_menu_admin_comptes").className = "link_menu_blue";
	if (document.getElementById('link_menu_admin_parties')) document.getElementById("link_menu_admin_parties").className = "link_menu_gray"; if (page.search("_admin_parties") > -1) document.getElementById("link_menu_admin_parties").className = "link_menu_blue";
	if (document.getElementById('link_menu_admin_version')) document.getElementById("link_menu_admin_version").className = "link_menu_gray"; if (page.search("_admin_version") > -1) document.getElementById("link_menu_admin_version").className = "link_menu_blue";
	if (document.getElementById('link_menu_admin_enigma')) document.getElementById("link_menu_admin_enigma").className = "link_menu_gray"; if (page.search("_admin_enigma") > -1) document.getElementById("link_menu_admin_enigma").className = "link_menu_blue";
	if (document.getElementById('link_menu_admin_erreurs')) document.getElementById("link_menu_admin_erreurs").className = "link_menu_gray"; if (page.search("_admin_erreurs") > -1) document.getElementById("link_menu_admin_erreurs").className = "link_menu_blue";

	
	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données de la combo 2 
   		httpRequest.onreadystatechange=function(){
    		if (httpRequest.readyState == 4)
     			if (httpRequest.status == 200) 
				;
     		}
    	}
  	httpRequest.open("GET", "ajax.php?fonction=user_set_pageactuelle&page="+page, false);
  	httpRequest.send(null);
}





//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//								        FONCTIONS DES OPTIONS					    		   \\
//					             ( appel à partir de la page xtools )						   \\
//_____________________________________________________________________________________________\\


// -----------------------------------------------------------
// tools_reinit [réinitialise les valeurs par défaut]
function tools_reinit()
{
	document.getElementById("information").innerHTML = '&nbsp;';
	document.profil.white.value = "#FFFFFF";
	document.profil.black.value = "#8FBEFF";
	document.profil.piece.options.selectedIndex = 7;
	document.profil.promotion.options.selectedIndex = 0;

	tools_change_forme();
	tools_change_color();
	document.getElementById("information").innerHTML = 'vous devez sauvegarder pour que les options par defaut soient prises en compte';
}	

// -----------------------------------------------------------
// tools_change_forme [change la forme des pieces]
function tools_change_forme()
{
	for (var i=0; i<18; i = i+1)
	{
		document.getElementById("img_" + i).src = document.getElementById("img_" + i).src.replace(/images\/forme%20[a-zA-Z0-9&]{2,}\//, document.profil.piece.value);
	}
}

// -----------------------------------------------------------
// tools_change_color [change la couleur des cases]
function tools_change_color()
{
	for (line=0, i=0; i<18; i = i+1)
	{
		if ( (i%6 != 0) ) line += 1;
		if (line%2 == 0) document.getElementById(i).style.backgroundColor = document.profil.white.value;
		if (line%2 != 0) document.getElementById(i).style.backgroundColor = document.profil.black.value;	
	}
}

// -----------------------------------------------------------
// tools_couleur [affiche la palette de couleurs]
function tools_couleur(formulaire, nom_champ)
{
    if (tools_fenetre && !tools_fenetre.closed) tools_fenetre.close();
    tools_fenetre = window.open("xtoolscolor.html?" + formulaire.name + "=" + nom_champ, "fenCouleurs", "width=250,height=230,resizable=1");
    if (!tools_fenetre.opener) tools_fenetre.opener = self;
}

// -----------------------------------------------------------
// tools_check [vérifie la taille des cases]
function tools_check()
{
	var erreur 	= '';
	var email 	= new RegExp ( "^\\w[\\w+\.\-]*@[\\w\-]+\.\\w[\\w+\.\-]*\\w$", "gi" ) ;
	
	//init message
	document.getElementById("information").innerHTML = '&nbsp;';
	
	// mdp
	document.profil.pass1.value = trim(document.profil.pass1.value);
	document.profil.pass2.value = trim(document.profil.pass2.value);
	if (document.profil.pass1.value != document.profil.pass2.value ) erreur = erreur + "\n vos MDP ne coincident pas.";
	if (document.profil.pass1.value.length <3) erreur = erreur + "\nLe MDP est trop court (3 car. minimum).";

	// mail
	document.profil.email.value = trim(document.profil.email.value);
	document.profil.email.value = document.profil.email.value.toLowerCase();
	if ( (js_joueur_guest=false) && (document.profil.email.value.length <1) ) erreur = erreur + "\nLe champ EMAIL est vide.";
  	if ( (js_joueur_guest=false) && (document.profil.email.value.length >= 1) && (document.profil.email.value.search(email) == -1) ) erreur = erreur + "\nLe champ EMAIL est invalide.";
	
	//notifier & lightchess & lightlast
	document.profil.notify.value = document.profil.notify.checked;
	document.profil.lightchess.value = document.profil.lightchess.checked;
	document.profil.lightlast.value = document.profil.lightlast.checked;

	// erreur(S)
	if (erreur != '')
	{
		erreur = "Erreurs\n------------------------------------------------------------\n" + erreur;
		alert (erreur);
		return;
	}
	tools_sauvegarde();
}

// -----------------------------------------------------------
// tools_sauvegarde [sauvegarde les options]
function tools_sauvegarde()
{
        // les variables
        var data =      "&passwd="+document.profil.pass1.value+
                        "&promotion="+document.profil.promotion.value+
                        "&piece="+document.profil.piece.value+
                        "&white="+document.profil.white.value+
                        "&black="+document.profil.black.value+
                        "&email="+document.profil.email.value+
						"&notify="+document.profil.notify.value+
						"&lightchess="+document.profil.lightchess.value+
						"&lightlast="+document.profil.lightlast.value ;
        //instanciation dun objet XMLHttpRequest
        var httpRequest = GetHttpObject();
        if (httpRequest)
        {
                //on attache un handler pour lévénement, qui rempliera les données
                httpRequest.onreadystatechange=function(){
                if (httpRequest.readyState == 4){
                        if (httpRequest.status == 200)
                        document.getElementById("information").innerHTML = httpRequest.responseText;
                }
                }
        }
        httpRequest.open("POST", "ajax.php?fonction=tools_sauvegarde", true);
        httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        httpRequest.send(data);
}










//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//								        FONCTIONS DES DEFIS					    		   	   \\
//					             ( appel à partir de la page _main_defis )					   \\
//_____________________________________________________________________________________________\\


// -----------------------------------------------------------
// defis_reinit [réinitialise les valeurs par défaut]
function defis_reinit()
{
	document.getElementById("information").innerHTML = '&nbsp;';
	document.challenge.radiotypeELO.checked = true;
	document.challenge.radiocamp3.checked = true;
	document.challenge.nomadv.value = "";
	document.challenge.elofrom.value = "1000";
	document.challenge.eloto.value = "2500";
	document.challenge.partie_guest.checked = true;
}


// -----------------------------------------------------------
// defis_check [verifie les valeurs entrees]
function defis_check()
{
	//init message
	var erreur 	= '';
	document.getElementById("information").innerHTML = '&nbsp;';
	document.challenge.nomadv.value = document.challenge.nomadv.value.toLowerCase();
	
	// elo
	if (document.challenge.radiotypeELO.checked == true)
	{
		if ( (isNaN(document.challenge.elofrom.value)) || (isNaN(document.challenge.eloto.value)) ) erreur = erreur + "\nMettre des chiffres entiers pour le ELO.";
		if ( parseInt(document.challenge.elofrom.value) < 500) erreur = erreur + "\nLa valeur minimum du ELO est de 500.";
		if ( parseInt(document.challenge.eloto.value) > 3000) erreur = erreur + "\nLa valeur maximum du ELO est de 3000.";
		if ( parseInt(document.challenge.elofrom.value) > parseInt(document.challenge.eloto.value) ) erreur = erreur + "\nLa valeur de depart du ELO est plus grande que celle d'arrivee !";
	}
	// name
	else
	{
		
	}

	// guest
	document.challenge.partie_guest.value = document.challenge.partie_guest.checked;

	// erreur(S)
	if (erreur != '')
	{
		erreur = "Erreurs\n------------------------------------------------------------\n" + erreur;
		alert (erreur);
		return;
	}
	defis_sauvegarde();
}

// -----------------------------------------------------------
// defis_sauvegarde [enregistre le defi avec les options]
function defis_sauvegarde()
{
	// les variables
	var cpt;
	var type;
	var adv_who;
	var adv_name;
	var adv_from;
	var adv_to;
	var camp;
	
	// type de partie
	for (cpt=0; cpt < document.challenge.partie_type.length; cpt++)
		if (document.challenge.partie_type[cpt].checked) 
			type = document.challenge.partie_type[cpt].value;

	// adversaire
	if (document.challenge.radiotypeELO.checked == true)
	{
		adv_who = 'elo';
		adv_name = "*";
		adv_from = document.challenge.elofrom.value;
		adv_to = document.challenge.eloto.value;
	}
	else
	{
		adv_who = 'name';
		adv_name = document.challenge.nomadv.value;
		adv_from = 500;
		adv_to = 3000;
	}

	// camp
	if (document.challenge.partie_camp[0].checked) camp = document.challenge.partie_camp[0].value; // blanc
	if (document.challenge.partie_camp[1].checked) camp = document.challenge.partie_camp[1].value; // noir
	if (document.challenge.partie_camp[2].checked) camp = document.challenge.partie_camp[2].value; // random


	// initialisation
	document.getElementById("information").innerHTML = '&nbsp;';
	var data = "type="+type+"&adv_who="+adv_who+"&adv_name="+adv_name+"&adv_from="+adv_from+"&adv_to="+adv_to+"&camp="+camp+"&guest="+document.challenge.partie_guest.value;
	
  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données 
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					document.getElementById("information").innerHTML = httpRequest.responseText;
					header_attente_liste('reset');
				}
			}
    		}
	}
	
  	httpRequest.open("POST", "ajax.php?fonction=defis_sauvegarde", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}

// -----------------------------------------------------------
// defis_autocompletion_name [va rechercher en fonction du texte tappé la liste des noms dispo]
function defis_autocompletion_name()
{
	//initialisation
	if (document.challenge.nomadv.value.length <1)
	{
		document.getElementById("nomadv_update").innerHTML = null;
		return;
	}
	var data = "name="+document.challenge.nomadv.value;
	
  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données 
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					document.getElementById("nomadv_update").innerHTML = httpRequest.responseText;
				}
			}
    		}
	}
	
  	httpRequest.open("POST", "ajax.php?fonction=defis_autocompletion_name", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}

// -----------------------------------------------------------
// defis_autocompletion_hide [sur perte de focus on cache la liste de completion]
function defis_autocompletion_hide()
{
	document.getElementById("nomadv_update").innerHTML = '';
}







//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//							       FONCTIONS DE LA PAGE DES STATS							   \\
//					          ( appel à partir de la page _main_stats )						   \\
//_____________________________________________________________________________________________\\


// -----------------------------------------------------------
// stats_autocompletion_name [va rechercher en fonction du texte tappé la liste des noms dispo]
function stats_autocompletion_name()
{
	//initialisation
	if (document.stats.nomjoueur.value.length <1)
	{
		
		document.getElementById("nomjoueur_update").innerHTML = null;
		return;
	}
	var data = "name="+document.stats.nomjoueur.value;

  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données 
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					document.getElementById("nomjoueur_update").innerHTML = httpRequest.responseText;
				}
			}
    		}
	}
	
  	httpRequest.open("POST", "ajax.php?fonction=stats_autocompletion_name", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}

// -----------------------------------------------------------
// stats_autocompletion_hide [sur perte de focus on cache la liste de completion]
function stats_autocompletion_hide()
{
	document.getElementById("nomjoueur_update").innerHTML = null;
}










//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//								     FONCTIONS DE LA PAGE DE JEU							   \\
//					           ( appel à partir de la page _main_play )						   \\
//_____________________________________________________________________________________________\\


// -----------------------------------------------------------
// chess_onmouse [gere les clics souris sur le plateau]
function chess_onmouse(act, numcase)
{
	if (!window['js_mustplay']) return;
	if (!window['js_progress']) return;
	if (js_progress != 3) return;
	
	var reg = (js_mustplay == js_blanc) ? (new RegExp("[b]$", "g")) : (new RegExp("[n]$", "g")) ;
	if ( (js_joueur_id == js_blanc) && (js_mustplay == js_noir) ) return ;
	if ( (js_joueur_id == js_noir) && (js_mustplay == js_blanc) ) return ;
	
	if ( (act == "over") && (GL_clicdown == 0) && (js_case[numcase].search(reg) != -1) )
	{
		document.getElementById(numcase).style.cursor="pointer";
	}

	if ( (act == "over") && (GL_clicdown == 1) && (js_case[numcase].search(reg) == -1) )
	{
		document.getElementById(numcase).style.cursor="pointer";
		document.getElementById(numcase).style.backgroundImage = "url(images/caseverte.gif)";
	}

	if ( (act == "out") && (GL_clicdown == 1) && (js_case[numcase].search(reg) == -1) )
	{
		document.getElementById(numcase).style.cursor="default";
		document.getElementById(numcase).style.backgroundImage = "";
		game_lightlast(js_case, js_moves, js_hits, true);
	}

	if ( (act == "clic") && (GL_clicdown == 0) && (js_case[numcase].search(reg) != -1) )
	{
		document.getElementById(numcase).style.backgroundImage = "url(images/caseverte.gif)";
		document.play.cp1.value = numcase;
		GL_clicdown = 1;
		return ;
	}
	
	if ( (act == "clic") && (GL_clicdown == 1) && (document.play.cp1.value == numcase) )
	{
		document.getElementById(numcase).style.backgroundImage = "";
		game_lightlast(js_case, js_moves, js_hits, true);
		game_lightchess(js_case, js_moves, js_hits, true);
		GL_clicdown = 0;
		return ;
	}

	if ( (act == "clic") && (GL_clicdown == 1) && (js_case[numcase].search(reg) == -1) )
	{
		document.play.cp2.value = numcase;
		document.getElementById(String(document.play.cp1.value)).style.backgroundImage = "";
		document.getElementById(String(document.play.cp2.value)).style.backgroundImage = "";
		for (var i = 0; i < 64; i++)
			document.getElementById(i).style.cursor="default";
		GL_clicdown = 0;
		game_lightchess(js_case, js_moves, js_hits, true);
		chess_play();
		return ;
	}
	
	if ( (act == "over") && (GL_clicdown == 1) && (document.play.cp1.value != numcase) && (js_case[numcase].search(reg) != -1) )
	{
		document.getElementById(numcase).style.cursor="default";
		return ;
	}
	
	if ( (act == "out") && (GL_clicdown == 1) && (document.play.cp1.value != numcase) && (js_case[numcase].search(reg) != -1) )
	{
		document.getElementById(numcase).style.backgroundImage = "";
		if (js_chesslight != document.play.cp1.value) game_lightchess(js_case, js_moves, js_hits, true);
		return ;
	}	
}

// -----------------------------------------------------------
// chess_play [un coup est joué]
function chess_play()
{
	// les variables
	var data = "cp1="+document.play.cp1.value+
		"&cp2="+document.play.cp2.value+
		"&chat="+document.play.chat.value+
		"&partieID="+document.play.partieID.value;
	
  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données
   		// [0][message] (si coup non authorisé)
		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					document.getElementById("status").innerHTML = "&nbsp;"+httpRequest.responseText;
					if (httpRequest.responseText.length == 0)
					{
						game_viki();
						header_encours_liste('maj');
					}
				}
	     	}
    	}
	}
	httpRequest.open("POST", "ajax.php?fonction=chess_play", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}

// -----------------------------------------------------------
// chess_timeout [Declare le joueur perdant si le timer arrive a zero]
function chess_timeout()
{
	// test preliminaire
	if (js_progress != 3) return;
	
	//creéation requete Ajax
	var httpRequest = GetHttpObject();
	if (httpRequest)
	{
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
	     		{					
					if (httpRequest.responseText.length)
					{
						window.clearTimeout(timer_play_viki);
						window.clearTimeout(timer_play_countdown);
	     				js_progress = 5;
	     				document.getElementById("status").innerHTML = "(partie finie) " + httpRequest.responseText + " est TIMEOUT";
						header_encours_liste("init");
						header_finie_liste('init');
						document.getElementById('menu_encours').className = 'display_false';
						document.getElementById('menu_finie').className = 'display_true';
					}
	     		}
	     	}
    		}
	}
  	httpRequest.open("GET", "ajax.php?fonction=chess_timeout&partieID="+js_partieID, true);
  	httpRequest.send(null);
}

// -----------------------------------------------------------
// chess_chat [rafraichissement du chat]
function chess_chat(num)
{
	if (js_progress < 2) return;
	window.clearTimeout(timer_play_chat);

  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données de la combo 2 
   		// [0][num] ||| [1][chat]
		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
	     		{
					if (httpRequest.responseText.length > 0)
					{
						var tmp = httpRequest.responseText.split("|||");
						num = tmp[0];
						document.getElementById("contenu_play_chat").innerHTML = tmp[1];
						CSBfleXcroll('scrollchat');
					}
				timer_play_chat = setTimeout("chess_chat('"+num+"')",site_timer_chat);
	      		}
	     	}
    		}
	}
  	httpRequest.open("GET", "ajax.php?fonction=chess_chat&partieID="+js_partieID+"&num="+num, true);
  	httpRequest.send(null);
}

// -----------------------------------------------------------
// chess_chat_write [ecrit un message]
function chess_chat_write(partieID, perso)
{
	if (js_progress < 3) return;
	var texte = trim(document.getElementById("texte_play_chat").value);
	if (texte.length <= 0) return;
	document.getElementById("button_play_chat").disabled = true;
	document.getElementById("button_play_perso").disabled = true;
	document.getElementById("texte_play_chat").value = "envoi en cours ... patientez!";

	var data = "partieID="+partieID+
				"&perso="+perso+
				"&texte="+texte;
				
  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données de la combo 2 
		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4)
			{
				document.getElementById("texte_play_chat").value = "";
				document.getElementById("button_play_chat").disabled = false;
				document.getElementById("button_play_perso").disabled = false;
				chess_chat(0);
	     	}
    	}
	}
  	httpRequest.open("POST", "ajax.php?fonction=chess_chat_write&partieID="+partieID+"&perso="+perso+"&texte="+texte, true);
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}

// -----------------------------------------------------------
// chess_lifeuboy [permet d'annuler le dernier coup joué]
function chess_lifeuboy()
{
	// tests preliminaires
	if (js_progress != 3) return;
	if (js_hits == 0) {document.getElementById("status").innerHTML = "Annulation du coup impossible car aucun coup n'a été joué"; return; }
	if (js_mustplay == js_joueur_id) {document.getElementById("status").innerHTML = "Annulation du coup impossible car votre adversaire a déjà joué"; return; }
	
	//ajax
	var httpRequest = GetHttpObject();
	if (httpRequest)
	{
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
	     		{
					var tmp = httpRequest.responseText.split("|||");
					if (tmp[0] == "KO")
						document.getElementById("status").innerHTML = tmp[1];
					else if (tmp[0] == "OK")
					{
						header_encours_click(document.play.partieID.value);
						header_encours_liste('');
					}
	     		}
	     	}
    		}
	}
  	httpRequest.open("GET", "ajax.php?fonction=chess_lifeuboy&partieID="+document.play.partieID.value, true);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// chess_abandon [gere l'abandon de la partie]
function chess_abandon()
{
	// msg de confirmation
	if (js_progress != 3) return;
	if (confirm("Etes-vous sur de vouloir abandonner la partie ?") == false) return;
	
	//creéation requete Ajax
	var httpRequest = GetHttpObject();
	if (httpRequest)
	{
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
	     		{
					window.clearTimeout(timer_play_viki);
					window.clearTimeout(timer_play_countdown);
	     			js_progress = 5;
	     			document.getElementById("status").innerHTML = httpRequest.responseText;
					document.getElementById('menu_encours').className = 'display_false';
					document.getElementById('menu_finie').className = 'display_true';
	     		}
				header_encours_liste("init");
				header_finie_liste('init');
	     	}
    		}
	}
  	httpRequest.open("GET", "ajax.php?fonction=chess_abandon&partieID="+document.play.partieID.value, true);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// chess_matchnul [demande un match nul a son adversaire]
function chess_matchnul()
{
	if (js_progress != 3) return;
	if (confirm("Vous etes sur le point de demander un match nul. continuez ?") == false) return;
	document.play.cp1.value = js_joueur_name + ' demande un match nul';
	
	// les variables
	var data = "cp1="+document.play.cp1.value+
		"&partieID="+document.play.partieID.value;
	
	//creéation requete Ajax
	var httpRequest = GetHttpObject();
	if (httpRequest)
	{
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
	     		{
	     			document.getElementById("status").innerHTML = httpRequest.responseText;
	     		}
	     	}
    	}
	}
	
	httpRequest.open("POST", "ajax.php?fonction=chess_matchnul", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);	
}


// -----------------------------------------------------------
// chess_matchnul_reponse [affiche la reponse]
function chess_matchnul_reponse()
{
	//creéation requete Ajax
	var httpRequest = GetHttpObject();
	if (httpRequest)
	{
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
	     		{
					document.getElementById("status").innerHTML = httpRequest.responseText;
	     		}
	     	}
    	}
	}
  	httpRequest.open("GET", "ajax.php?fonction=chess_matchnul_reponse&partieID="+document.play.partieID.value+"&reponse="+document.play.cp1.value, true);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// chess_revenge [permet de creer une partie avec les memes caracteristiques mais en inversant les camps]
function chess_revenge()
{
	if (js_progress <= 3) return;
	if (confirm("Souhaitez vous proposer la revanche ?\n(si oui elle apapraitra dans \"vos defis en attente\" le temps que l'adversaire l'accepte ou pas)") == false) return;
	
	// les variables
	var data = "partieID="+document.play.partieID.value;

	//creéation requete Ajax
	var httpRequest = GetHttpObject();
	if (httpRequest)
	{
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
	     		{
	     			document.getElementById("information").innerHTML = httpRequest.responseText;
					header_attente_liste('reload');
	     		}
	     	}
    	}
	}
	
	httpRequest.open("POST", "ajax.php?fonction=chess_revenge", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);	
}














//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//								   FONCTIONS MULTI-UTILISATIONS								   \\
//					           ( appel à partir de plusieurs pages )						   \\
//_____________________________________________________________________________________________\\


// -----------------------------------------------------------
// game_lightlast [surbrille le dernier coup joué si l'option est activé]
function game_lightlast(board, moves, hit, activate)
{
	//si l'option est desactivé
	if (js_board_lightlast == 0) return;
	//remise a zero des couleurs d'echecs
	for (var cpt=0; board[cpt]; cpt++) 
	{
		if ( (document.getElementById(cpt).style.backgroundImage.match("^.*contourbleu.*", "i")) )
			document.getElementById(cpt).style.backgroundImage = "";
	}		
	// si pas d'activation
	if (hit == 0) return;
	if (activate !== true) return;

	var last = moves[hit - 1];
	var cp1 = last.substring(0, last.indexOf("(", 0));
	var cp2 = last.substring(last.indexOf(".", 0) + 1, last.indexOf("(", 5));

	document.getElementById(cp1).style.backgroundImage = "url(images/contourbleu1.gif)";
	document.getElementById(cp2).style.backgroundImage = "url(images/contourbleu2.gif)";
}

// -----------------------------------------------------------
// game_lightchess [surbrille le roi echecs ou bien les pieces qui font mat]
function game_lightchess(board, moves, hit, activate)
{
	//si l'option est desactivé
	if (js_board_lightchess == 0) return;
	//initialisation
	var color = (hit%2 == 0) ? ("b") : ("n"); // couleur à colorier
	var rb = myIndexOf(board, "rb");		 // position du roi blanc
	var rn = myIndexOf(board, "rn");		 // position du roi noir
	var roimov = new Array();
	var lightcase = new Array();
	
	//remise a zero des couleurs d'echecs
	for (var cpt=0; board[cpt]; cpt++) 
		if (document.getElementById(cpt).style.backgroundImage.match("^.*caserouge.*", "i"))
			document.getElementById(cpt).style.backgroundImage = "";
	
	// si pas d'activation
	if (activate !== true) return;
	
	if ( game_chess(board, moves, color, null) === true)
	{
		if (game_mat(board, moves, color, null) === true)
			{
			 	roipos_64 = (color == 'n') ? (rn) : (rb);
				roipos_8x = roipos_64 % 8;
				roipos_8y = (roipos_64 - roipos_8x) / 8;
				color_adv = (color == 'b') ? ("n") : ("b");
				
				roimov[roimov.length] = roipos_64; // position sans mouvement
				if ( (roipos_8x+0 <= 7) && (roipos_8y+1 <= 7) && board[(roipos_8x+0 + ((roipos_8y+1) * 8))].substr(1,1) != color ) roimov[roimov.length] = roipos_64 + 8;
				if ( (roipos_8x+0 <= 7) && (roipos_8y-1 >= 0) && board[(roipos_8x+0 + ((roipos_8y-1) * 8))].substr(1,1) != color ) roimov[roimov.length] = roipos_64 - 8;
				if ( (roipos_8x+1 <= 7) && (roipos_8y+0 <= 7) && board[(roipos_8x+1 + ((roipos_8y+0) * 8))].substr(1,1) != color ) roimov[roimov.length] = roipos_64 + 1;
				if ( (roipos_8x-1 >= 0) && (roipos_8y+0 <= 7) && board[(roipos_8x-1 + ((roipos_8y+0) * 8))].substr(1,1) != color ) roimov[roimov.length] = roipos_64 - 1;
				if ( (roipos_8x+1 <= 7) && (roipos_8y+1 <= 7) && board[(roipos_8x+1 + ((roipos_8y+1) * 8))].substr(1,1) != color ) roimov[roimov.length] = roipos_64 + 9;
				if ( (roipos_8x-1 >= 0) && (roipos_8y+1 <= 7) && board[(roipos_8x-1 + ((roipos_8y+1) * 8))].substr(1,1) != color ) roimov[roimov.length] = roipos_64 + 7;
				if ( (roipos_8x+1 <= 7) && (roipos_8y-1 >= 0) && board[(roipos_8x+1 + ((roipos_8y-1) * 8))].substr(1,1) != color ) roimov[roimov.length] = roipos_64 - 7;
				if ( (roipos_8x-1 >= 0) && (roipos_8y-1 >= 0) && board[(roipos_8x-1 + ((roipos_8y-1) * 8))].substr(1,1) != color ) roimov[roimov.length] = roipos_64 - 9;
				
				for (cpt=0; cpt < roimov.length; cpt++)
				{
					for (tmp = 0; tmp < 64; tmp++)
						if (board[tmp].substr(1,1) == color_adv)
						{
							avant = board[roimov[cpt]];
							board[roimov[cpt]] = board[roipos_64];
							board[roipos_64] = "no";
							if ( game_valid(board, moves, color_adv, tmp, roimov[cpt]) > 0 )
								lightcase[lightcase.length] = tmp;
							board[roipos_64] = board[roimov[cpt]];
							board[roimov[cpt]] = avant;
						}
				}
				// on allume ou on eteind les cases echecs
				for (cpt=0; lightcase[cpt]; cpt++)
					document.getElementById(lightcase[cpt]).style.backgroundImage = "url(images/caserouge.gif)";		
				return;
			}
			if (color == 'b') lightcase[lightcase.length] = rb;
			if (color == 'n') lightcase[lightcase.length] = rn;
			// on allume ou on eteind les cases echecs
			for (cpt=0; lightcase[cpt]; cpt++)
				document.getElementById(lightcase[cpt]).style.backgroundImage = "url(images/caserouge.gif)";		
			return;
		}
}

// -----------------------------------------------------------
// game_chess[verifie si le roi de la couleur est echec]
function game_chess(board, moves, color, alternative)
{
	//init
	var cp2 = alternative;
	if ( (alternative == null) && (color == 'b') ) cp2 = myIndexOf(board, "rb");
	else if ( (alternative == null) && (color == 'n') ) cp2 = myIndexOf(board, "rn");

	color = (color == 'b') ? ("n") : ("b") ;
	for (var cp1 = 0; cp1 < 64; cp1++)
		if (board[cp1].substr(1,1) == color)
			if ( game_valid(board, moves, color, cp1, cp2) > 0 ) 
				return(true);

	return(false);
}

// -----------------------------------------------------------
// game_mat[verifie si la couleur est MAT]
function game_mat(board, moves, color)
{
	//init
	var i; var j;
	var m; var n;
	var retour;
	var retour2;
	
	for (i = 0; i < 64; i++)
		if (board[i].substr(1,1) == color)
			for (j = 0; j < 64; j++)
				if (board[j].substr(1,1) != color)
				{
					retour = game_valid(board, moves, color, i, j);
					if (retour == -1) continue; // coup impossible

					if (retour == 2) { board[i-1] = 'no'; } // prise en passant blanc gauche
					else if (retour == 3) { board[i+1] = 'no'; } // prise en passant blanc droite
					else if (retour == 4) { board[i-1] = 'no'; } // prise en passant noir gauche
					else if (retour == 5) { board[i+1] = 'no'; } // prise en passant noir droite
					else if (retour == 6) { board[61] = board[63]; board[63] = 'no'; } // petit roque blanc
					else if (retour == 7) { board[59] = board[56]; board[56] = 'no'; } // grand roque blanc
					else if (retour == 8) { board[5] = board[7]; board[7] = 'no'; } // petit roque noir
					else if (retour == 9) { board[3] = board[0]; board[0] = 'no'; } // grand roque noir
					else if (retour == 99) { board[i] = 'd' + color; } // promotion
					// on valide le coup
					m = board[i];
					n = board[j];
					board[j] = board[i];
					board[i] = 'no';
					
					retour2 = game_chess(board, moves, color, null);
					
					// on  annulle le coup
					board[i] = m;
					board[j] = n;
					if (retour == 2) { board[cp1-1] = 'pn'; } // prise en passant blanc gauche
					else if (retour == 3) { board[cp1+1] = 'pn'; } // prise en passant blanc droite
					else if (retour == 4) { board[cp1-1] = 'pb'; } // prise en passant noir gauche
					else if (retour == 5) { board[cp1+1] = 'pb'; } // prise en passant noir droite
					else if (retour == 6) { board[63] = board[61]; board[61] = 'no'; } // petit roque blanc
					else if (retour == 7) { board[56] = board[59]; board[59] = 'no'; } // grand roque blanc
					else if (retour == 8) { board[7] = board[5]; board[5] = 'no'; } // petit roque noir
					else if (retour == 9) { board[0] = board[3]; board[3] = 'no'; } // grand roque noir
					else if (retour == 99) { board[j] = 'p' + color; } // promotion
					
					if (retour2 == false) { return(false); }
				}
	return(true);
}

// -----------------------------------------------------------
// game_valid [verifie si le coup est valide]
function game_valid(board, moves, color, cp1, cp2)
{
		//init
		var xTMP; var yTMP;
		var x1 = column(cp1);	var y1 = row(cp1);
		var x2 = column(cp2);	var y2 = row(cp2);
		var piece = board[cp1].substr(0,1);

		//PION BLANC
		if (board[cp1] == 'pb')
		{
			if ( (x2 == x1) && (y2 == y1-1) && (board[locn(x2,y2)] == 'no') )	return (1);	//avance de 1 (48 fois max)
			if ( (x2 == x1-1) && (y2 == y1-1) && (board[locn(x2,y2)].substr(1,1) == 'n') ) return (1); //mange a gauche (21 fois max)
			if ( (x2 == x1+1) && (y2 == y1-1) && (board[locn(x2,y2)].substr(1,1) == 'n')) return (1); //mange a droite (21 fois max)
			if ( (x2 == x1) && (y1 == 6) && (y2 == y1-2) && (board[locn(x2,y2)] == 'no') && (board[locn(x1,y1-1)] == 'no') ) return (1); //avance de 2 (8 fois max)
			if ( (y1 == 3) && (x2 == x1-1) && (y2 == y1-1) && (board[locn(x2,y2)] == 'no') && (board[locn(x1-1,y1)] == 'pn') && (moves[moves.length-1] == (cp2-8) + '(pn).' + (cp1-1) + '(no)') ) return (2); //prise en passant a gauche (8 fois max)
			if ( (y1 == 3) && (x2 == x1+1) && (y2 == y1-1) && (board[locn(x2,y2)] == 'no') && (board[locn(x1+1,y1)] == 'pn') && (moves[moves.length-1] == (cp2-8) + '(pn).' + (cp1+1) + '(no)') ) return (3); //prise en passant a droite (8 fois max)
			return (-1); //sinon erreur
		}
		//PION NOIR
		if (board[cp1] == 'pn')
		{
			if ( (x2 == x1) && (y2 == y1+1) && (board[locn(x2,y2)] == 'no') ) return (1); //avance de 1 (48 fois max)
			if ( (x2 == x1-1) && (y2 == y1+1) && (board[locn(x2,y2)].substr(1,1) == 'b')) return (1); //mange a gauche (21 fois max)
			if ( (x2 == x1+1) && (y2 == y1+1) && (board[locn(x2,y2)].substr(1,1) == 'b')) return (1); //mange a droite (21 fois max)
			if ( (x2 == x1) && (y1 == 1) && (y2 == y1+2) && (board[locn(x2,y2)] == 'no') && (board[locn(x1,y1+1)] == 'no') ) return (1); //avance de 2 (8 fois max)
			if ( (y1 == 4) && (x2 == x1-1) && (y2 == y1+1) && (board[locn(x2,y2)] == 'no') && (board[locn(x1-1,y1)] == 'pb') && (moves[moves.length-1] == (cp2+8) + '(pb).' + (cp1-1) + '(no)') ) return (4); //prise en passant a gauche (8 fois max)
			if ( (y1 == 4) && (x2 == x1+1) && (y2 == y1+1) && (board[locn(x2,y2)] == 'no') && (board[locn(x1+1,y1)] == 'pb') && (moves[moves.length-1] == (cp2+8) + '(pb).' + (cp1+1) + '(no)') ) return (5); //prise en passant a droite (8 fois max)
			return (-1); //sinon erreur
		}
		//TOUR
		if (piece == 't')
		{
			if ( (x1 == x2) && (y1 < y2) ) { for (yTMP = y1 + 1 ; ( (yTMP != y2) && (board[locn(x1,yTMP)] == 'no') ); yTMP++); if (yTMP == y2) return (1); } //en Y positif
			if ( (x1 == x2) && (y1 > y2) ) { for (yTMP = y1 - 1 ; ( (yTMP != y2) && (board[locn(x1,yTMP)] == 'no') ); yTMP--); if (yTMP == y2) return (1); } //en Y negatif
			if ( (y1 == y2) && (x1 < x2) ) { for (xTMP = x1 + 1 ; ( (xTMP != x2) && (board[locn(xTMP,y1)] == 'no') ); xTMP++); if (xTMP == x2) return (1); } //en X positif
			if ( (y1 == y2) && (x1 > x2) ) { for (xTMP = x1 - 1 ; ( (xTMP != x2) && (board[locn(xTMP,y1)] == 'no') ); xTMP--); if (xTMP == x2) return (1); } //en X negatif
			return (-1); //sinon erreur
		}
		//CAVALIER
		if (piece == 'c')
		{
			if ( (x2 == x1+1) && (y2 == y1-2) ) return (1); //1
			if ( (x2 == x1+2) && (y2 == y1-1) ) return (1); //2
			if ( (x2 == x1+2) && (y2 == y1+1) ) return (1); //3
			if ( (x2 == x1+1) && (y2 == y1+2) ) return (1); //4
			if ( (x2 == x1-1) && (y2 == y1+2) ) return (1); //5
			if ( (x2 == x1-2) && (y2 == y1+1) ) return (1); //6
			if ( (x2 == x1-2) && (y2 == y1-1) ) return (1); //7
			if ( (x2 == x1-1) && (y2 == y1-2) ) return (1); //8
			return (-1); //sinon erreur
		}
		// FOU
		if ( (piece == 'f') )
		{
			if ( (x2 > x1) && (y2 > y1) && ((x2-x1) == (y2-y1)) ) { for (xTMP = x1 + 1, yTMP = y1 + 1; ( (xTMP != x2) && (yTMP != y2) && (board[locn(xTMP,yTMP)] == 'no') ); xTMP++, yTMP++); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X positif et Y positif
			if ( (x2 < x1) && (y2 > y1) && ((x1-x2) == (y2-y1)) ) { for (xTMP = x1 - 1, yTMP = y1 + 1; ( (xTMP != x2) && (yTMP != y2) && (board[locn(xTMP,yTMP)] == 'no') ); xTMP--, yTMP++); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X negatif et Y positif
			if ( (x2 < x1) && (y2 < y1) && ((x1-x2) == (y1-y2)) ) { for (xTMP = x1 - 1, yTMP = y1 - 1; ( (xTMP != x2) && (yTMP != y2) && (board[locn(xTMP,yTMP)] == 'no') ); xTMP--, yTMP--); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X negatif et Y negatif
			if ( (x2 > x1) && (y2 < y1) && ((x2-x1) == (y1-y2)) ) { for (xTMP = x1 + 1, yTMP = y1 - 1; ( (xTMP != x2) && (yTMP != y2) && (board[locn(xTMP,yTMP)] == 'no') ); xTMP++, yTMP--); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X positif et Y negatif
			return (-1); //sinon erreur
		}
		// DAME
		if ( (piece == 'd') )
		{
			if ( (x1 == x2) && (y1 < y2) ) { for (yTMP = y1 + 1 ; ( (yTMP != y2) && (board[locn(x1,yTMP)] == 'no') ); yTMP++); if (yTMP == y2) return (1); } //en Y positif
			if ( (x1 == x2) && (y1 > y2) ) { for (yTMP = y1 - 1 ; ( (yTMP != y2) && (board[locn(x1,yTMP)] == 'no') ); yTMP--); if (yTMP == y2) return (1); } //en Y negatif
			if ( (y1 == y2) && (x1 < x2) ) { for (xTMP = x1 + 1 ; ( (xTMP != x2) && (board[locn(xTMP,y1)] == 'no') ); xTMP++); if (xTMP == x2) return (1); } //en X positif
			if ( (y1 == y2) && (x1 > x2) ) { for (xTMP = x1 - 1 ; ( (xTMP != x2) && (board[locn(xTMP,y1)] == 'no') ); xTMP--); if (xTMP == x2) return (1); } //en X negatif
			if ( (x2 > x1) && (y2 > y1) && ((x2-x1) == (y2-y1)) ) { for (xTMP = x1 + 1, yTMP = y1 + 1; ( (xTMP != x2) && (yTMP != y2) && (board[locn(xTMP,yTMP)] == 'no') ); xTMP++, yTMP++); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X positif et Y positif
			if ( (x2 < x1) && (y2 > y1) && ((x1-x2) == (y2-y1)) ) { for (xTMP = x1 - 1, yTMP = y1 + 1; ( (xTMP != x2) && (yTMP != y2) && (board[locn(xTMP,yTMP)] == 'no') ); xTMP--, yTMP++); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X negatif et Y positif
			if ( (x2 < x1) && (y2 < y1) && ((x1-x2) == (y1-y2)) ) { for (xTMP = x1 - 1, yTMP = y1 - 1; ( (xTMP != x2) && (yTMP != y2) && (board[locn(xTMP,yTMP)] == 'no') ); xTMP--, yTMP--); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X negatif et Y negatif
			if ( (x2 > x1) && (y2 < y1) && ((x2-x1) == (y1-y2)) ) { for (xTMP = x1 + 1, yTMP = y1 - 1; ( (xTMP != x2) && (yTMP != y2) && (board[locn(xTMP,yTMP)] == 'no') ); xTMP++, yTMP--); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X positif et Y negatif
			return (-1); //sinon erreur
		}
		// ROI
		if ( (piece == 'r') )
		{
			if ( (x2 == x1+0) && (y2 == y1+1) ) return (1); // deplacement simple (1)
			if ( (x2 == x1+0) && (y2 == y1-1) ) return (1); // deplacement simple (2)
			if ( (x2 == x1+1) && (y2 == y1+0) ) return (1); // deplacement simple (3)
			if ( (x2 == x1-1) && (y2 == y1+0) ) return (1); // deplacement simple (4)
			if ( (x2 == x1+1) && (y2 == y1+1) ) return (1); // deplacement simple (5)
			if ( (x2 == x1-1) && (y2 == y1+1) ) return (1); // deplacement simple (6)
			if ( (x2 == x1+1) && (y2 == y1-1) ) return (1); // deplacement simple (7)
			if ( (x2 == x1-1) && (y2 == y1-1) ) return (1); // deplacement simple (8)
			if ( (cp1 == 60) && (cp2 == 62) && (board[63] == 'tb') && (board[61] == 'no') && (board[62] == 'no') && (game_chess(board, moves, color, null) == false) && (game_chess(board, moves, color, 61) == false) && (game_chess(board, moves, color, 62) == false) && (myIndexOf(moves, "(rb)") == -1) && (myIndexOf(moves, "63(tb)") == -1) ) return (6);// petit roque blanc
			if ( (cp1 == 60) && (cp2 == 58) && (board[56] == 'tb') && (board[59] == 'no') && (board[58] == 'no') && (board[57] == 'no') && (game_chess(board, moves, color, null) == false) && (game_chess(board, moves, color, 57) == false) && (game_chess(board, moves, color, 58) == false) && (game_chess(board, moves, color, 59) == false) && (myIndexOf(moves, "(rb)") == -1) && (myIndexOf(moves, "56(tb)") == -1) ) return (7);// grand roque blanc
			if ( (cp1 == 4) && (cp2 == 6) && (board[7] == 'tn') && (board[5] == 'no') && (board[6] == 'no') && (game_chess(board, moves, color, null) == false) && (game_chess(board, moves, color, 5) == false) && (game_chess(board, moves, color, 6) == false) && (myIndexOf(moves, "(rn)") == -1) && (myIndexOf(moves, "7(tn)") == -1) ) return (8);// petit roque blanc
			if ( (cp1 == 4) && (cp2 == 2) && (board[0] == 'tn') && (board[1] == 'no') && (board[2] == 'no') && (board[3] == 0) && (game_chess(board, moves, color, null) == false) && (game_chess(board, moves, color, 1) == false) && (game_chess(board, moves, color, 2) == false) && (game_chess(board, moves, color, 3) == false) && (myIndexOf(moves, "(rn)") == -1) && (myIndexOf(moves, "0(tn)") == -1) ) return (9);// grand roque blanc
			return (-1);
		}
		return(-1);
}

// -----------------------------------------------------------
// game_viki [surveillance des actions sur un echiquier]
function game_viki()
{
	// initialisation des variables
	window.clearTimeout(timer_play_viki);
	var cases = js_case.join("|");
	var data = "partieID="+js_partieID+"&last_hit="+js_last_hit+"&cases="+cases+"&progress="+js_progress;
	
	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
		//on attache un handler pour lévénement, qui rempliera les données de la combo 2 
   		// [0][action] ||| [1][status] ||| [2][case] ||| [3][histo] ||| [4][mustplay] ||| 
		// [5][coups_nbr] ||| [6][progress] ||| [7][cases_modifiees][] ||| [8][datelastcoup] |||
		// [9][pieces_mangees] ||| [10][partie type] ||| [11][time blanc] ||| [12][time noir]
		httpRequest.onreadystatechange=function(){
			if (httpRequest.readyState == 4){
				if (httpRequest.status == 200)
				{
					var tmp = httpRequest.responseText.split("|||");
					if (tmp[0] == "MOVES")
					{
						// faire un son pour l'autre joueur qui attend
						document.getElementById("play_sound").innerHTML = "";
						if (js_mustplay != js_joueur_id && js_progress == 3)
							document.getElementById("play_sound").innerHTML = "<object type='audio/mpeg' width='0' height='0' data='sonnette2.mp3'><param name='filename' value='sonnette2.mp3' /><param name='autostart' value='true' /><param name='loop' value='false' /></object>";
						// maj des informations
						document.getElementById("information").innerHTML = "&nbsp;";
						document.getElementById("status").innerHTML = "&nbsp;"+tmp[1];
						document.getElementById("contenu_chess_date").innerHTML = tmp[8];
						document.getElementById("contenu_chess_coups").innerHTML = tmp[5];
						// assignation des valeurs aux variables
						js_case			= tmp[2].split("|");
						js_moves	 	= tmp[3].split("|");
						js_mustplay 	= tmp[4];
						js_hits		 	= tmp[5];
						js_progress 	= tmp[6];
						js_last_hit 	= tmp[8];
						js_type			= tmp[10];
						js_timer_blanc	= tmp[11];
						js_timer_noir	= tmp[12];
						// affichage des icones des joueurs en fonction du tour
						if ( (js_joueur_id == js_blanc) && (js_hits%2 == 0) ) {document.getElementById("contenu_chess_bonhommej1").className = "bonhomme_play";document.getElementById("contenu_chess_bonhommej2").className = "bonhomme_wait";}
						else if ( (js_joueur_id == js_blanc) && (js_hits%2 != 0) ) {document.getElementById("contenu_chess_bonhommej1").className = "bonhomme_wait";document.getElementById("contenu_chess_bonhommej2").className = "bonhomme_play";}
						else if ( (js_joueur_id == js_noir) && (js_hits%2 == 0) ) {document.getElementById("contenu_chess_bonhommej1").className = "bonhomme_wait";document.getElementById("contenu_chess_bonhommej2").className = "bonhomme_play";}
						else if ( (js_joueur_id == js_noir) && (js_hits%2 != 0) ) {document.getElementById("contenu_chess_bonhommej1").className = "bonhomme_play";document.getElementById("contenu_chess_bonhommej2").className = "bonhomme_wait";}
						else if ( (js_hits%2 == 0) ) {document.getElementById("contenu_chess_bonhommej1").className = "bonhomme_play";document.getElementById("contenu_chess_bonhommej2").className = "bonhomme_wait";}
						else if ( (js_hits%2 != 0) ) {document.getElementById("contenu_chess_bonhommej1").className = "bonhomme_wait";document.getElementById("contenu_chess_bonhommej2").className = "bonhomme_play";}
						// affichage du dernier coup joué
						if (tmp[7].length > 0)
						{
							var modifiees 	= tmp[7].split(";");
							for(var i = 0; i < modifiees.length; i++)
							{
								var chaq = modifiees[i].split(":");
								document.getElementById('img_' + chaq[0]).src = js_board_piece + chaq[1] + ".gif";
							}
						}
						// affichage de la derniere piece mangée si il y a lieu
						if (tmp[9] != 'no' && tmp[9].length > 0)
						{
							if ( (js_joueur_id == js_blanc) && (js_hits%2 == 0) ) {document.getElementById('contenu_chess_miamj1').innerHTML += "<img src='" + js_board_piece + tmp[9] + ".gif' width=20 height=20>";}
							else if ( (js_joueur_id == js_blanc) && (js_hits%2 != 0) ) {document.getElementById('contenu_chess_miamj2').innerHTML += "<img src='" + js_board_piece + tmp[9] + ".gif' width=20 height=20>";}
							else if ( (js_joueur_id == js_noir) && (js_hits%2 == 0) ) {document.getElementById('contenu_chess_miamj2').innerHTML += "<img src='" + js_board_piece + tmp[9] + ".gif' width=20 height=20>";}
							else if ( (js_joueur_id == js_noir) && (js_hits%2 != 0) ) {document.getElementById('contenu_chess_miamj1').innerHTML += "<img src='" + js_board_piece + tmp[9] + ".gif' width=20 height=20>";}
							else if ( (js_hits%2 == 0) ) {document.getElementById('contenu_chess_miamj1').innerHTML += "<img src='" + js_board_piece + tmp[9] + ".gif' width=20 height=20>";}
							else if ( (js_hits%2 != 0) ) {document.getElementById('contenu_chess_miamj2').innerHTML += "<img src='" + js_board_piece + tmp[9] + ".gif' width=20 height=20>";}
						}
						// mise en surbrillance du dernier coup et ou de l'echec
						game_lightlast(js_case, js_moves, js_hits, true);
						game_lightchess(js_case, js_moves, js_hits, true);
						window.clearTimeout(timer_play_countdown);
						// (re)initialisation des menus, fenetres et compteur
						if (js_progress == 3) game_countdown();
						if (js_progress == 5) header_finie_liste('init');
						if (js_progress > 3) 
						{
							document.getElementById('menu_encours').className = 'display_false';
							document.getElementById('menu_finie').className = 'display_true';
						}
					}
					else if (tmp[0] == "DEMANDE")
					{
						var decoupage = tmp[1].split(":::");
						if (decoupage[1] == " MATCHNUL ? ")
						{
							document.play.cp1.value = "OK";
							if ( confirm(decoupage[2] + "\nacceptez-vous ?") == false )
								document.play.cp1.value = "KO";
							chess_matchnul_reponse();
						}
					}
					else if (tmp[0] == "DELETED")
					{
						js_progress = 5;
						header_encours_liste('init');
						alert("la partie est annulée suite à la deconnexion de votre adversaire");
						header_page_change("_main_accueil.php");
						return;
					}
					//bot: gestion du coup
					if (js_progress == 3 && js_mustplay != js_joueur_id && js_versusbot==1 && timer_play_bot == null)	
					{
						//var botdelay=Math.random()*10;
						//botdelay=Math.floor(botdelay);
						botdelay = 0;
						timer_play_bot = setTimeout(ia_minmax, 1000 * botdelay);
					}
				}
			timer_play_viki = setTimeout("game_viki()",site_timer_viki);
			}
		}	
	}
  	httpRequest.open("POST", "ajax.php?fonction=game_viki", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}

// -----------------------------------------------------------
// game_countdown [affichage du countdown en blitz]
function game_countdown()
{
	var hrsB = 0;
	var minB = 0;
	var secB = 0;
	var hrsN = 0;
	var minN = 0;
	var secN = 0;
	var js_timerB = 0;
	var js_timerN = 0;
	var affichageB = null;
	var affichageN = null;
	
	// reinit
	window.clearTimeout(timer_play_countdown);
	
	// calcul du temps entre le dernier coup et la date actuelle
	instantT = new Date();
	instantL = new Date();
	instantL.setFullYear(js_last_hit.substring(0,4), js_last_hit.substring(5,7)-1, js_last_hit.substring(8,10));
	instantL.setHours(js_last_hit.substring(11,13), js_last_hit.substring(14,16), js_last_hit.substring(17,19));

	//assignation de la valeur restante et mise en forme pour le joueur qui doit jouer
	if (js_mustplay == js_blanc) js_timerB = js_timer_blanc - (parseInt(instantT.getTime() / 1000) - parseInt(instantL.getTime() / 1000));
	if (js_mustplay == js_noir) js_timerN = js_timer_noir - (parseInt(instantT.getTime() / 1000) - parseInt(instantL.getTime() / 1000));
	if ( (js_mustplay == js_blanc) && (js_timerB <= 0) ) {js_timerB = 0; chess_timeout();}
	if ( (js_mustplay == js_noir) && (js_timerN <= 0) ) {js_timerN = 0; chess_timeout();}
	
	//assignation de la valeur restante et mise en forme pour le joueur qui attend (ca sert lorsque tu as des secondes supp. a chaque coup, il faut afficher le temps restant remis a jour)
	if (js_mustplay == js_noir) js_timerB = js_timer_blanc;
	if (js_mustplay == js_blanc) js_timerN = js_timer_noir;
	
	
	// convertion des secondes en hrs:min:sec
	hrsB = Math.floor(js_timerB / 3600);
	minB = Math.floor((js_timerB % 3600) / 60);
	secB = js_timerB % 60;
	hrsN = Math.floor(js_timerN / 3600);
	minN = Math.floor((js_timerN % 3600) / 60);
	secN = js_timerN % 60;
	
	// mise en forme des chiffres
	if (hrsB < 100) hrsB = '0' + hrsB;
	if (hrsB < 10) hrsB = '0' + hrsB;
	if (minB < 10) minB = '0' + minB;
	if (secB < 10) secB = '0' + secB;
	if (hrsN < 100) hrsN = '0' + hrsN;
	if (hrsN < 10) hrsN = '0' + hrsN;
	if (minN < 10) minN = '0' + minN;
	if (secN < 10) secN = '0' + secN;
	if ( parseFloat(hrsB) == 0 ) affichageB = minB + "m " + secB + "s";
	else if ( parseFloat(hrsB) != 0 ) affichageB = hrsB + "h " + minB + "m " + secB + "s";
	if ( parseFloat(hrsN) == 0 ) affichageN = minN + "m " + secN + "s";
	else if ( parseFloat(hrsN) != 0 ) affichageN = hrsN + "h " + minN + "m " + secN + "s";
	
	// affichage des timers sur la page de jeu
	if ( (js_joueur_id == js_blanc) )
	{
		if (js_timerB > 90) document.getElementById('contenu_chess_timej2').className = "timer_VERT";
		if (js_timerB < 90) document.getElementById('contenu_chess_timej2').className = "timer_ORANGE";
		if (js_timerB < 30) document.getElementById('contenu_chess_timej2').className = "timer_ROUGE";
		document.getElementById('contenu_chess_timej2').innerHTML = affichageB;
		if (js_timerN > 90) document.getElementById('contenu_chess_timej1').className = "timer_VERT";
		if (js_timerN < 90) document.getElementById('contenu_chess_timej1').className = "timer_ORANGE";
		if (js_timerN < 30) document.getElementById('contenu_chess_timej1').className = "timer_ROUGE";
		document.getElementById('contenu_chess_timej1').innerHTML = affichageN;
	}
	else if ( (js_joueur_id == js_noir) )
	{
		if (js_timerN > 90) document.getElementById('contenu_chess_timej2').className = "timer_VERT";
		if (js_timerN < 90) document.getElementById('contenu_chess_timej2').className = "timer_ORANGE";
		if (js_timerN < 30) document.getElementById('contenu_chess_timej2').className = "timer_ROUGE";
		document.getElementById('contenu_chess_timej2').innerHTML = affichageN;
		if (js_timerB > 90) document.getElementById('contenu_chess_timej1').className = "timer_VERT";
		if (js_timerB < 90) document.getElementById('contenu_chess_timej1').className = "timer_ORANGE";
		if (js_timerB < 30) document.getElementById('contenu_chess_timej1').className = "timer_ROUGE";
		document.getElementById('contenu_chess_timej1').innerHTML = affichageB;
	}
	else
	{
		if (js_timerB > 90) document.getElementById('contenu_chess_timej2').className = "timer_VERT";
		if (js_timerB < 90) document.getElementById('contenu_chess_timej2').className = "timer_ORANGE";
		if (js_timerB < 30) document.getElementById('contenu_chess_timej2').className = "timer_ROUGE";
		document.getElementById('contenu_chess_timej2').innerHTML = affichageB;
		if (js_timerN > 90) document.getElementById('contenu_chess_timej1').className = "timer_VERT";
		if (js_timerN < 90) document.getElementById('contenu_chess_timej1').className = "timer_ORANGE";
		if (js_timerN < 30) document.getElementById('contenu_chess_timej1').className = "timer_ROUGE";
		document.getElementById('contenu_chess_timej1').innerHTML = affichageN;
	}
	
	// rappel toutes les secondes cette fonction d'affichage
	timer_play_countdown = setTimeout("game_countdown()",1000);
}










//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//								      FONCTIONS DE L'HISTORIQUE					    		   \\
//					             ( appel à partir de la page xhisto )						   \\
//_____________________________________________________________________________________________\\


// -----------------------------------------------------------
// histo_playback [affiche l'historique de la partie]
function histo_playback(partieID)
{
	// kill timers s'ils existent pour ne pas que ca continue de tourner apres un changement de page.
	// [OBLIGER DE METTRE CA ICI AUSSI DEPUIS QUE CETTE FONCTION PEUT ETRE APPELE DEPUIS xplay.php]
	window.clearTimeout(timer_play_viki); // pour ne pas que VIKI continue de tourner
	window.clearTimeout(timer_play_chat); // pour ne pas que CHAT continue de tourner
	window.clearTimeout(timer_play_countdown); // pour ne pas que le COMPTEUR continue de tourner
	
	// init
	js_partieID = partieID;
	var data = "partieID="+partieID;
	showElement("site_load");
	user_set_pageactuelle("_main_histoview.php" + "=" + partieID);

  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données
		// [0][case] ||| [1][histo_coups] ||| [2][blanc] ||| [3][noir] ||| [4][mustplay] ||| 
		// [5][coups_nbr] ||| [6][progress] ||| [7][board_forme] ||| [8][partie type] ||| 
		// [9][timer blanc] ||| [10][timer noir] ||| [11][last hit] ||| [12][inviteur] ||| [13][_main_play.php]
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					GL_clicdown = 0;
	     			var tmp = httpRequest.responseText.split("|||");
					js_case				= tmp[0].split("|");
					js_moves	 		= tmp[1].split("|");
					js_blanc 			= tmp[2];
					js_noir 			= tmp[3];
					js_mustplay 		= tmp[4];
					js_hits		 		= tmp[5];
					js_hits_current		= tmp[5];
					js_progress 		= tmp[6];
					js_board_piece		= tmp[7];
					js_type				= tmp[8];
					js_timer_blanc		= tmp[9];
					js_timer_noir		= tmp[10];
					js_last_hit			= tmp[11];
					js_inviteur			= tmp[12];
					document.getElementById("contenu_list_page").innerHTML = tmp[13];
				}
			game_lightlast(js_case, js_moves, js_hits, true);
			game_lightchess(js_case, js_moves, js_hits, true);
			if (js_progress < 5) game_viki();  //active la surveillance [viki: cf i'm robot]
			if (js_progress == 3) game_countdown();
			removeElement("site_load");
	     	}
    	}
	}
	httpRequest.open("POST", "ajax.php?fonction=histo_playback", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}

// -----------------------------------------------------------
// histo_draw_all [réaffiche tout le tableau]
function histo_draw_all(num)
{
	histo_draw_img(num);
	if (num < js_hits) window.clearTimeout(timer_play_viki); // pour ne pas que VIKI continue de tourner si on regarde l'histo
	if ((num == js_hits) && (js_progress == 3)) game_viki(); // permet de relancer viki si on est en derniere position
	if ( (num < 0) || (num > js_hits) ) {histo_MakeStop(); return;}
	js_hits_current = num;
	document.getElementById("contenu_chess_coups").innerHTML = js_hits_current;
	document.getElementById('contenu_chess_miamj1').innerHTML = "";
	document.getElementById('contenu_chess_miamj2').innerHTML = "";

	js_case= Array(	'tn','cn','fn','dn','rn','fn','cn','tn',
			'pn','pn','pn','pn','pn','pn','pn','pn',
			'no','no','no','no','no','no','no','no',
			'no','no','no','no','no','no','no','no',
			'no','no','no','no','no','no','no','no',
			'no','no','no','no','no','no','no','no',
			'pb','pb','pb','pb','pb','pb','pb','pb',
			'tb','cb','fb','db','rb','fb','cb','tb');

	
	for (var cpt=0; cpt < js_hits_current; cpt++)
	{
		// récupère les mouvements du coup
		var last = js_moves[cpt];
		var cp1 = last.substring(0, last.indexOf("(", 0));
		var cp2 = last.substring(last.indexOf(".", 0) + 1, last.indexOf("(", 5));
			
		// le coup engendre-t-il un roque ?
		if 	( (js_case[cp1] == 'rn') && (cp1 == 4)  && (cp2 == 2)  ) { js_case[3]  = js_case[0];  js_case[0]  = 'no'; } // NOIR grand roque
		else if ( (js_case[cp1] == 'rn') && (cp1 == 4)  && (cp2 == 6)  ) { js_case[5]  = js_case[7];  js_case[7]  = 'no'; } // NOIR petit roque
		else if ( (js_case[cp1] == 'rb') && (cp1 == 60) && (cp2 == 58) ) { js_case[59] = js_case[56]; js_case[56] = 'no'; } // BLANC grand roque
		else if ( (js_case[cp1] == 'rb') && (cp1 == 60) && (cp2 == 62) ) { js_case[61] = js_case[63]; js_case[63] = 'no'; } // BLANC petit roque
		
		// le coup engendre-t-il une prise en passant ?
		var plusun = parseInt(cp1,10) + parseInt(1,10); 
		var moinsun = parseInt(cp1,10) - parseInt(1,10);
		if 	    ( (js_case[cp1] == 'pn') && (js_case[cp2] == 'no') && (cp2 - cp1 == 7) ) { js_case[moinsun] = 'no'; js_case[cp2] = 'pb'; }
		else if ( (js_case[cp1] == 'pn') && (js_case[cp2] == 'no') && (cp2 - cp1 == 9) ) { js_case[plusun] = 'no'; js_case[cp2] = 'pb'; }
		else if ( (js_case[cp1] == 'pb') && (js_case[cp2] == 'no') && (cp1 - cp2 == 7) ) { js_case[plusun] = 'no'; js_case[cp2] = 'pn'; }
		else if ( (js_case[cp1] == 'pb') && (js_case[cp2] == 'no') && (cp1 - cp2 == 9) ) { js_case[moinsun] = 'no'; js_case[cp2] = 'pn'; }
		
		// maj de miam_chess
		if ( (cpt%2 != 0) && (js_case[cp2] != 'no') && (js_joueur_id == js_noir) ) document.getElementById('contenu_chess_miamj2').innerHTML += "<img src='" + js_board_piece + js_case[cp2] + ".gif' width=20 height=20>";
		else if ( (cpt%2 == 0) && (js_case[cp2] != 'no') && (js_joueur_id == js_noir) ) document.getElementById('contenu_chess_miamj1').innerHTML += "<img src='" + js_board_piece + js_case[cp2] + ".gif' width=20 height=20>";
		else if ( (cpt%2 != 0) && (js_case[cp2] != 'no') ) document.getElementById('contenu_chess_miamj1').innerHTML += "<img src='" + js_board_piece + js_case[cp2] + ".gif' width=20 height=20>";
		else if ( (cpt%2 == 0) && (js_case[cp2] != 'no') ) document.getElementById('contenu_chess_miamj2').innerHTML += "<img src='" + js_board_piece + js_case[cp2] + ".gif' width=20 height=20>";

		// change le tableau magneto en fonction des coups
		js_case[cp2] = js_case[cp1];
		js_case[cp1] = 'no';
		
		// promotion
		if ( ((js_case[cp2].substring(0, 1) == 'p') && (cp2 >= 0) && (cp2 <= 7)) || ((js_case[cp2].substring(0, 1) == 'p') && (cp2 >= 56) && (cp2 <= 63)) )
			js_case[cp2] = "d" + js_case[cp2].substring(1, 2);
	}
	
	for (cpt=0; cpt < 64; cpt++)
		document.getElementById('img_' + cpt).src = js_board_piece + js_case[cpt] + ".gif";
		
	if (play == true)
	{
		play = false;
		window.clearTimeout(timer_histo_view);
		histo_draw_img(num);
	}
	game_lightlast(js_case, js_moves, num, true);
	game_lightchess(js_case, js_moves, num, true);
}

// -----------------------------------------------------------
// histo_draw_all [réaffiche juste un mouvement]
function histo_draw_one(num)
{
	histo_draw_img(num);
	if (num < js_hits) window.clearTimeout(timer_play_viki); // pour ne pas que VIKI continue de tourner si on regarde l'histo
	if ((num == js_hits) && (js_progress == 3)) game_viki(); // permet de relancer viki si on est en derniere position
	if ( (num < 0) || (num > js_hits) ) {histo_MakeStop(); return;}
	js_hits_current = num
	document.getElementById("contenu_chess_coups").innerHTML = js_hits_current
	
	var last = js_moves[js_hits_current - 1];
	var cp1 = last.substring(0, last.indexOf("(", 0));
	var cp2 = last.substring(last.indexOf(".", 0) + 1, last.indexOf("(", 5));
	
	// le coup engendre-t-il un roque ?
	if 	( (js_case[cp1] == 'rn') && (cp1 == 4)  && (cp2 == 2)  ) { js_case[3]  = js_case[0];  js_case[0]  = 'no'; document.getElementById('img_3').src = js_board_piece + js_case[3] + ".gif"; document.getElementById('img_0').src = js_board_piece + js_case[0] + ".gif";} // NOIR grand roque
	else if ( (js_case[cp1] == 'rn') && (cp1 == 4)  && (cp2 == 6)  ) { js_case[5]  = js_case[7];  js_case[7]  = 'no'; document.getElementById('img_5').src = js_board_piece + js_case[5] + ".gif"; document.getElementById('img_7').src = js_board_piece + js_case[7] + ".gif";} // NOIR petit roque
	else if ( (js_case[cp1] == 'rb') && (cp1 == 60) && (cp2 == 58) ) { js_case[59] = js_case[56]; js_case[56] = 'no'; document.getElementById('img_59').src = js_board_piece + js_case[59] + ".gif"; document.getElementById('img_56').src = js_board_piece + js_case[56] + ".gif";} // BLANC grand roque
	else if ( (js_case[cp1] == 'rb') && (cp1 == 60) && (cp2 == 62) ) { js_case[61] = js_case[63]; js_case[63] = 'no'; document.getElementById('img_61').src = js_board_piece + js_case[61] + ".gif"; document.getElementById('img_63').src = js_board_piece + js_case[63] + ".gif";} // BLANC petit roque

	// le coup engendre-t-il une prise en passant ?
	var plusun = parseInt(cp1,10) + parseInt(1,10); 
	var moinsun = parseInt(cp1,10) - parseInt(1,10);
	if 	    ( (js_case[cp1] == 'pn') && (js_case[cp2] == 'no') && (cp2 - cp1 == 7) ) { js_case[moinsun] = 'no'; js_case[cp2] = 'pb'; document.getElementById('img_' + moinsun).src = js_board_piece + js_case[moinsun] + ".gif"; }
	else if ( (js_case[cp1] == 'pn') && (js_case[cp2] == 'no') && (cp2 - cp1 == 9) ) { js_case[plusun] = 'no'; js_case[cp2] = 'pb'; document.getElementById('img_' + plusun).src = js_board_piece + js_case[plusun] + ".gif"; }
	else if ( (js_case[cp1] == 'pb') && (js_case[cp2] == 'no') && (cp1 - cp2 == 7) ) { js_case[plusun] = 'no'; js_case[cp2] = 'pn'; document.getElementById('img_' + plusun).src = js_board_piece + js_case[plusun] + ".gif"; }
	else if ( (js_case[cp1] == 'pb') && (js_case[cp2] == 'no') && (cp1 - cp2 == 9) ) { js_case[moinsun] = 'no'; js_case[cp2] = 'pn'; document.getElementById('img_' + moinsun).src = js_board_piece + js_case[moinsun] + ".gif"; }

	// maj de miam_chess
	if ( (num%2 == 0) && (js_case[cp2] != 'no') && (js_joueur_id == js_noir) ) document.getElementById('contenu_chess_miamj2').innerHTML += "<img src='" + js_board_piece + js_case[cp2] + ".gif' width=20 height=20>";
	else if ( (num%2 != 0) && (js_case[cp2] != 'no') && (js_joueur_id == js_noir) ) document.getElementById('contenu_chess_miamj1').innerHTML += "<img src='" + js_board_piece + js_case[cp2] + ".gif' width=20 height=20>";
	else if ( (num%2 == 0) && (js_case[cp2] != 'no') ) document.getElementById('contenu_chess_miamj1').innerHTML += "<img src='" + js_board_piece + js_case[cp2] + ".gif' width=20 height=20>";
	else if ( (num%2 != 0) && (js_case[cp2] != 'no') ) document.getElementById('contenu_chess_miamj2').innerHTML += "<img src='" + js_board_piece + js_case[cp2] + ".gif' width=20 height=20>";
	
	// change le tableau magneto en fonction des coups
	js_case[cp2] = js_case[cp1];
	js_case[cp1] = 'no';

	// promotion
		if ( ((js_case[cp2].substring(0, 1) == 'p') && (cp2 >= 0) && (cp2 <= 7)) || ((js_case[cp2].substring(0, 1) == 'p') && (cp2 >= 56) && (cp2 <= 63)) )
			js_case[cp2] = "d" + js_case[cp2].substring(1, 2);
	
	document.getElementById('img_' + cp1).src = js_board_piece + js_case[cp1] + ".gif";
	document.getElementById('img_' + cp2).src = js_board_piece + js_case[cp2] + ".gif";
	
	if (play == true) 
	{
		window.clearTimeout(timer_histo_view);
		timer_histo_view = setTimeout("histo_draw_one(js_hits_current+1)", 2000);
	}
	
	game_lightlast(js_case, js_moves, num, true);
	game_lightchess(js_case, js_moves, num, true);

}

// -----------------------------------------------------------
// histo_MakePlayStop [gere le bouton play/stop]
function histo_MakePlayStop()
{
	if (play == true) 
	{
		play = false;
		window.clearTimeout(timer_histo_view);
		document.getElementById('img_play').src = "images/magneto.play.png";
		return;
	}
	play = true;
	timer_histo_view = setTimeout("histo_draw_one(js_hits_current+1)", 100);
	document.getElementById('img_play').src = "images/magneto.stop.png";
}

// -----------------------------------------------------------
// histo_MakeStop [gere le bouton stop]
function histo_MakeStop()
{
	play = false;
	window.clearTimeout(timer_histo_view);
	document.getElementById('img_play').src = "images/magneto.play.png";
}

// -----------------------------------------------------------
// histo_draw_img [affichage du magnetoscope]
function histo_draw_img(num)
{
	document.getElementById('img_first').src = "images/magneto.first.enable.png";
	document.getElementById('img_rew').src = "images/magneto.rew.enable.png";
	document.getElementById('img_fwd').src = "images/magneto.fwd.enable.png";
	document.getElementById('img_last').src = "images/magneto.last.enable.png";
	if (num <= 0)
	{
		document.getElementById('img_first').src = "images/magneto.first.disable.png";
		document.getElementById('img_rew').src = "images/magneto.rew.disable.png";
	}
	if (num >= js_hits)
	{
		document.getElementById('img_fwd').src = "images/magneto.fwd.disable.png";
		document.getElementById('img_last').src = "images/magneto.last.disable.png";
	}
	if (play == true) document.getElementById('img_play').src = "images/magneto.stop.png";
	else document.getElementById('img_play').src = "images/magneto.play.png";
}














//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//								         FONCTIONS DE L'IA				    		  		   \\
//					             	 ( fonctions pour l'I.A. )			 					   \\
//_____________________________________________________________________________________________\\


// -----------------------------------------------------------
// ia_play [un coup est joué par le bot]
function ia_play(cp1, cp2)
{
	// les variables
	var data = "cp1="+cp1+
		"&cp2="+cp2+
		"&partieID="+document.play.partieID.value;
	
  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données
   		// [0][message] (si coup non authorisé)
		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					//alert(httpRequest.responseText);
				}
	     	}
    	}
	}
	httpRequest.open("POST", "ajax.php?fonction=ia_play", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}

// -----------------------------------------------------------
// ia_minmax [N-IA joue son coup]
function ia_minmax()
{
	//init
	var color 		= (js_hits%2 ==0) ? "noir" : "blanc";
	var ia_case 	= ia_transform_case();//js_case.slice(0);
	var ia_histo 	= ia_transform_histo();//js_moves.slice(0);
	ia_deep = 2;
	ia_timeout = false;
	ia_timeoutgo = false;
	ia_timeoutgo2 = false;
	ia_date1 = new Date();
	
	//--------------
	// recherche du meilleur coup
	if (js_hits <= 1) ia_ouverture();
	else ia_negamax(ia_case, ia_histo, -100000, 100000, ia_deep, color);
	
	//------------------------------ DEBUG
	//ia_date2 = new Date();
	//alert(((ia_date2 - ia_date1)));
	//alert(ia_coup);
	//alert(ia_timeoutcp1);
	//------------------------------
	
	//si timeout alors on va continuer les recherches
	if (ia_timeout == true)
	{
		timer_play_bot = setTimeout(ia_timeoutminmax, 100);
		return;
	}

	
	//envoie le coup si pas de timeout
	var tmp = ia_coup.split(":");
	ia_play(tmp[0], tmp[1]);
	timer_play_bot = null;
}

// -----------------------------------------------------------
// ia_minmax [N-IA joue son coup]
function ia_timeoutminmax()
{
	//init
	ia_timeout = false;
	ia_timeoutgo = true;
	ia_timeoutgo2 = true;
	ia_date1 = new Date();
	
	// recherche du meilleur coup
	ia_timeoutcolor = (ia_timeoutcolor == 'blanc') ? ("noir") : ("blanc") ;
	ia_negamax(ia_timeoutcase, ia_timeouthisto, ia_timeoutalpha, ia_timeoutbeta, ia_timeoutdeep, ia_timeoutcolor);
	
	//------------------------------ DEBUG
	//ia_date2 = new Date();
	//alert(((ia_date2 - ia_date1)));
	//alert(ia_coup);
	//------------------------------
	
	//si timeout alors on va continuer les recherches
	if (ia_timeout == true)
	{
		timer_play_bot = setTimeout(ia_timeoutminmax, 1);
		return;
	}
	
	//envoie le coup si pas de timeout
	var tmp = ia_coup.split(":");
	ia_play(tmp[0], tmp[1]);
	timer_play_bot = null;
	
}


// -----------------------------------------------------------
// ia_negamax [fonction negamax]
function ia_negamax(ia_case, ia_histo, alpha, beta, deep, color)
{
	//init
	var HUMAN = (js_hits%2 == 0) ? 'noir' : 'blanc';
	var ORDI =  (js_hits%2 == 1) ? 'noir' : 'blanc';
	var estimation;
	var cp1;
	var cp2;

	//reprise du CP1 apres timeout
	cp1 = 0;
	if (ia_timeoutgo == true){ ia_timeoutgo = false; cp1 = ia_timeoutcp1;	}
	
	//estimation extreme
	if (ia_chess(ia_case, ia_histo, ORDI) == true) if (ia_mat(ia_case, ia_histo, ORDI) == true) return (-99999);
	if (ia_chess(ia_case, ia_histo, HUMAN) == true) if (ia_mat(ia_case, ia_histo, HUMAN) == true) return (-99999);
	if (ia_pat(ia_case, ia_histo, HUMAN) == true) return (0); //verifie si on a un match nul : si OUI, donne EstimationNUL
	if (ia_pat(ia_case, ia_histo, ORDI) == true) return (0); //verifie si on a un match nul : si OUI, donne EstimationNUL
	if (deep <= 0) return (-ia_heuristique(ia_case, ia_histo, color)); //estime le jeu a la profondeur max
	
	//si le delai est depassé alors on arrete tout (Car parfois pour les PC pas tres puissant un msg apparait en demandant d'arreter le script...)
	ia_date2 = new Date();
	if ( ((ia_date2 - ia_date1)) >= 250) {	ia_timeout = true; return (100000);	}
	
	//coups possibles
	color = (color == 'blanc') ? ("noir") : ("blanc") ;
	for (; cp1 < 64; cp1++)
		if ( (ia_case[cp1] > 0 && color == 'blanc') || (ia_case[cp1] < 0 && color == 'noir') )
		{
			//reprise du CP2 apres timeout
			cp2 = 0;
			if (ia_timeoutgo2 == true)	{ia_timeoutgo2 = false;	cp2 = ia_timeoutcp2;}
			
			for (; cp2 < 64; cp2++)
				if ( (ia_case[cp2] >= 0 && color == 'noir') || (ia_case[cp2] <= 0 && color == 'blanc') )
				{
					// enregistrement pour les timout
					if (ia_timeout == false && deep==2) 
					{ 
						ia_timeoutdeep = deep;
						ia_timeoutcp1 = cp1;
						ia_timeoutcp2 = cp2;
						ia_timeoutcase = ia_case;
						ia_timeouthisto = ia_histo;
						ia_timeoutalpha = alpha;
						ia_timeoutbeta = beta;
						ia_timeoutcolor = color;
					}
		
					// validation du coup
					var retour = ia_valid(ia_case, ia_histo, color, cp1, cp2);
					if (retour <= 0) continue;
					if ( (Math.abs(ia_case[cp1]) == 1) && ( ((cp2 >= 0) && (cp2 <= 7)) || ((cp2 >= 56) && (cp2 <= 63)) ) ) retour = 99; //promotion
					
					// algo min-max
					ia_faitlecoup(ia_case, ia_histo, color, cp1, cp2, retour);
					if (ia_chess(ia_case, ia_histo, color) == true) { ia_annullecoup(ia_case, ia_histo, color, cp1, cp2, retour); continue; }
					estimation = -ia_negamax(ia_case, ia_histo, -beta, -alpha, deep-1, color);
					
					ia_annullecoup(ia_case, ia_histo, color, cp1, cp2, retour);
					
					//elagage alpha-beta
					if (estimation >= alpha) 
					{ 
						alpha = estimation; 
						if (deep == ia_deep) 
							ia_coup = cp1 + ":" + cp2; 
					}
				}
		}
	return alpha;
}

// -----------------------------------------------------------
// ia_ouverture [permet de varier les ouvertures]
function ia_ouverture()
{
	var ran_unrounded=Math.random()*6;
	var ran_number=Math.floor(ran_unrounded); 
	
	if (js_hits == 0) ia_coup = ia_open_white[ran_number];
	if (js_hits == 1) ia_coup = ia_open_black[ran_number];
}


// -----------------------------------------------------------
// ia_valid [verifie si le coup est valide]
function ia_valid(ia_case, ia_histo, color, cp1, cp2)
{
		//init
		var xTMP; var yTMP;
		var x1 = column(cp1);	var y1 = row(cp1);
		var x2 = column(cp2);	var y2 = row(cp2);
		var piece = Math.abs(ia_case[cp1]);

		//PION BLANC
		if (ia_case[cp1] == 1)
		{
			if ( (x2 == x1) && (y2 == y1-1) && (ia_case[locn(x2,y2)] == 0) )	return (1);	//avance de 1 (48 fois max)
			if ( (x2 == x1-1) && (y2 == y1-1) && (ia_case[locn(x2,y2)] < 0) ) 	return (1); //mange a gauche (21 fois max)
			if ( (x2 == x1+1) && (y2 == y1-1) && (ia_case[locn(x2,y2)] < 0)) 	return (1); //mange a droite (21 fois max)
			if ( (x2 == x1) && (y1 == 6) && (y2 == y1-2) && (ia_case[locn(x2,y2)] == 0) && (ia_case[locn(x1,y1-1)] == 0) ) return (1); //avance de 2 (8 fois max)
			if ( (y1 == 3) && (x2 == x1-1) && (y2 == y1-1) && (ia_case[locn(x2,y2)] == 0) && (ia_case[locn(x1-1,y1)] == -1) && (ia_histo[ia_histo.length-1] == (cp2-8) + '(pn).' + (cp1-1) + '(no)') ) return (2); //prise en passant a gauche (8 fois max)
			if ( (y1 == 3) && (x2 == x1+1) && (y2 == y1-1) && (ia_case[locn(x2,y2)] == 0) && (ia_case[locn(x1+1,y1)] == -1) && (ia_histo[ia_histo.length-1] == (cp2-8) + '(pn).' + (cp1+1) + '(no)') ) return (3); //prise en passant a droite (8 fois max)
			return (-1); //sinon erreur
		}
		//PION NOIR
		if (ia_case[cp1] == -1)
		{
			if ( (x2 == x1) && (y2 == y1+1) && (ia_case[locn(x2,y2)] == 0) ) return (1); //avance de 1 (48 fois max)
			if ( (x2 == x1-1) && (y2 == y1+1) && (ia_case[locn(x2,y2)] > 0)) return (1); //mange a gauche (21 fois max)
			if ( (x2 == x1+1) && (y2 == y1+1) && (ia_case[locn(x2,y2)] > 0)) return (1); //mange a droite (21 fois max)
			if ( (x2 == x1) && (y1 == 1) && (y2 == y1+2) && (ia_case[locn(x2,y2)] == 0) && (ia_case[locn(x1,y1+1)] == 0) ) return (1); //avance de 2 (8 fois max)
			if ( (y1 == 4) && (x2 == x1-1) && (y2 == y1+1) && (ia_case[locn(x2,y2)] == 0) && (ia_case[locn(x1-1,y1)] == 1) && (ia_histo[ia_histo.length-1] == (cp2+8) + '(pb).' + (cp1-1) + '(no)') ) return (4); //prise en passant a gauche (8 fois max)
			if ( (y1 == 4) && (x2 == x1+1) && (y2 == y1+1) && (ia_case[locn(x2,y2)] == 0) && (ia_case[locn(x1+1,y1)] == 1) && (ia_histo[ia_histo.length-1] == (cp2+8) + '(pb).' + (cp1+1) + '(no)') ) return (5); //prise en passant a droite (8 fois max)
			return (-1); //sinon erreur
		}
		//TOUR
		if (piece == 4)
		{
			if ( (x1 == x2) && (y1 < y2) ) { for (yTMP = y1 + 1 ; ( (yTMP != y2) && (ia_case[locn(x1,yTMP)] == 0) ); yTMP++); if (yTMP == y2) return (1); } //en Y positif
			if ( (x1 == x2) && (y1 > y2) ) { for (yTMP = y1 - 1 ; ( (yTMP != y2) && (ia_case[locn(x1,yTMP)] == 0) ); yTMP--); if (yTMP == y2) return (1); } //en Y negatif
			if ( (y1 == y2) && (x1 < x2) ) { for (xTMP = x1 + 1 ; ( (xTMP != x2) && (ia_case[locn(xTMP,y1)] == 0) ); xTMP++); if (xTMP == x2) return (1); } //en X positif
			if ( (y1 == y2) && (x1 > x2) ) { for (xTMP = x1 - 1 ; ( (xTMP != x2) && (ia_case[locn(xTMP,y1)] == 0) ); xTMP--); if (xTMP == x2) return (1); } //en X negatif
			return (-1); //sinon erreur
		}
		//CAVALIER
		if (piece == 3)
		{
			if ( (x2 == x1+1) && (y2 == y1-2) ) return (1); //1
			if ( (x2 == x1+2) && (y2 == y1-1) ) return (1); //2
			if ( (x2 == x1+2) && (y2 == y1+1) ) return (1); //3
			if ( (x2 == x1+1) && (y2 == y1+2) ) return (1); //4
			if ( (x2 == x1-1) && (y2 == y1+2) ) return (1); //5
			if ( (x2 == x1-2) && (y2 == y1+1) ) return (1); //6
			if ( (x2 == x1-2) && (y2 == y1-1) ) return (1); //7
			if ( (x2 == x1-1) && (y2 == y1-2) ) return (1); //8
			return (-1); //sinon erreur
		}
		// FOU
		if ( (piece == 2) )
		{
			if ( (x2 > x1) && (y2 > y1) && ((x2-x1) == (y2-y1)) ) { for (xTMP = x1 + 1, yTMP = y1 + 1; ( (xTMP != x2) && (yTMP != y2) && (ia_case[locn(xTMP,yTMP)] == 0) ); xTMP++, yTMP++); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X positif et Y positif
			if ( (x2 < x1) && (y2 > y1) && ((x1-x2) == (y2-y1)) ) { for (xTMP = x1 - 1, yTMP = y1 + 1; ( (xTMP != x2) && (yTMP != y2) && (ia_case[locn(xTMP,yTMP)] == 0) ); xTMP--, yTMP++); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X negatif et Y positif
			if ( (x2 < x1) && (y2 < y1) && ((x1-x2) == (y1-y2)) ) { for (xTMP = x1 - 1, yTMP = y1 - 1; ( (xTMP != x2) && (yTMP != y2) && (ia_case[locn(xTMP,yTMP)] == 0) ); xTMP--, yTMP--); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X negatif et Y negatif
			if ( (x2 > x1) && (y2 < y1) && ((x2-x1) == (y1-y2)) ) { for (xTMP = x1 + 1, yTMP = y1 - 1; ( (xTMP != x2) && (yTMP != y2) && (ia_case[locn(xTMP,yTMP)] == 0) ); xTMP++, yTMP--); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X positif et Y negatif
			return (-1); //sinon erreur
		}
		// DAME
		if ( (piece == 5) )
		{
			if ( (x1 == x2) && (y1 < y2) ) { for (yTMP = y1 + 1 ; ( (yTMP != y2) && (ia_case[locn(x1,yTMP)] == 0) ); yTMP++); if (yTMP == y2) return (1); } //en Y positif
			if ( (x1 == x2) && (y1 > y2) ) { for (yTMP = y1 - 1 ; ( (yTMP != y2) && (ia_case[locn(x1,yTMP)] == 0) ); yTMP--); if (yTMP == y2) return (1); } //en Y negatif
			if ( (y1 == y2) && (x1 < x2) ) { for (xTMP = x1 + 1 ; ( (xTMP != x2) && (ia_case[locn(xTMP,y1)] == 0) ); xTMP++); if (xTMP == x2) return (1); } //en X positif
			if ( (y1 == y2) && (x1 > x2) ) { for (xTMP = x1 - 1 ; ( (xTMP != x2) && (ia_case[locn(xTMP,y1)] == 0) ); xTMP--); if (xTMP == x2) return (1); } //en X negatif
			if ( (x2 > x1) && (y2 > y1) && ((x2-x1) == (y2-y1)) ) { for (xTMP = x1 + 1, yTMP = y1 + 1; ( (xTMP != x2) && (yTMP != y2) && (ia_case[locn(xTMP,yTMP)] == 0) ); xTMP++, yTMP++); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X positif et Y positif
			if ( (x2 < x1) && (y2 > y1) && ((x1-x2) == (y2-y1)) ) { for (xTMP = x1 - 1, yTMP = y1 + 1; ( (xTMP != x2) && (yTMP != y2) && (ia_case[locn(xTMP,yTMP)] == 0) ); xTMP--, yTMP++); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X negatif et Y positif
			if ( (x2 < x1) && (y2 < y1) && ((x1-x2) == (y1-y2)) ) { for (xTMP = x1 - 1, yTMP = y1 - 1; ( (xTMP != x2) && (yTMP != y2) && (ia_case[locn(xTMP,yTMP)] == 0) ); xTMP--, yTMP--); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X negatif et Y negatif
			if ( (x2 > x1) && (y2 < y1) && ((x2-x1) == (y1-y2)) ) { for (xTMP = x1 + 1, yTMP = y1 - 1; ( (xTMP != x2) && (yTMP != y2) && (ia_case[locn(xTMP,yTMP)] == 0) ); xTMP++, yTMP--); if ((xTMP == x2) && (yTMP == y2)) return (1); }// en X positif et Y negatif
			return (-1); //sinon erreur
		}
		// ROI
		if ( (piece == 6) )
		{
			if ( (x2 == x1+0) && (y2 == y1+1) ) return (1); // deplacement simple (1)
			if ( (x2 == x1+0) && (y2 == y1-1) ) return (1); // deplacement simple (2)
			if ( (x2 == x1+1) && (y2 == y1+0) ) return (1); // deplacement simple (3)
			if ( (x2 == x1-1) && (y2 == y1+0) ) return (1); // deplacement simple (4)
			if ( (x2 == x1+1) && (y2 == y1+1) ) return (1); // deplacement simple (5)
			if ( (x2 == x1-1) && (y2 == y1+1) ) return (1); // deplacement simple (6)
			if ( (x2 == x1+1) && (y2 == y1-1) ) return (1); // deplacement simple (7)
			if ( (x2 == x1-1) && (y2 == y1-1) ) return (1); // deplacement simple (8)
			if ( (cp1 == 60) && (cp2 == 62) && (ia_case[63] == 4) && (ia_case[61] == 0) && (ia_case[62] == 0) && (ia_chess(ia_case, ia_histo, color) == false) && (ia_chess(ia_case, ia_histo, color, 61) == false) && (ia_chess(ia_case, ia_histo, color, 62) == false) && (myIndexOf(ia_histo, "(6)") == -1) && (myIndexOf(ia_histo, "63(4)") == -1) ) return (6);// petit roque blanc
			if ( (cp1 == 60) && (cp2 == 58) && (ia_case[56] == 4) && (ia_case[59] == 0) && (ia_case[58] == 0) && (ia_case[57] == 0) && (ia_chess(ia_case, ia_histo, color) == false) && (ia_chess(ia_case, ia_histo, color, 57) == false) && (ia_chess(ia_case, ia_histo, color, 58) == false) && (ia_chess(ia_case, ia_histo, color, 59) == false) && (myIndexOf(ia_histo, "(6)") == -1) && (myIndexOf(ia_histo, "56(4)") == -1) ) return (7);// grand roque blanc
			if ( (cp1 == 4) && (cp2 == 6) && (ia_case[7] == -4) && (ia_case[5] == 0) && (ia_case[6] == 0) && (ia_chess(ia_case, ia_histo, color) == false) && (ia_chess(ia_case, ia_histo, color, 5) == false) && (ia_chess(ia_case, ia_histo, color, 6) == false) && (myIndexOf(ia_histo, "(-6)") == -1) && (myIndexOf(ia_histo, "7(-4)") == -1) ) return (8);// petit roque blanc
			if ( (cp1 == 4) && (cp2 == 2) && (ia_case[0] == -4) && (ia_case[1] == 0) && (ia_case[2] == 0) && (ia_case[3] == 0) && (ia_chess(ia_case, ia_histo, color) == false) && (ia_chess(ia_case, ia_histo, color, 1) == false) && (ia_chess(ia_case, ia_histo, color, 2) == false) && (ia_chess(ia_case, ia_histo, color, 3) == false) && (myIndexOf(ia_histo, "(-6)") == -1) && (myIndexOf(ia_histo, "0(-4)") == -1) ) return (9);// grand roque blanc
			return (-1);
		}
		return(-1);
}


// -----------------------------------------------------------
// ia_chess[verifie si le roi de la couleur est echec]
function ia_chess(ia_case, ia_histo, color, alternative)
{
	//init
	var cp2 = alternative;
	
	if ( (alternative == null) && (color == 'blanc') ) cp2 = myIndexOf2(ia_case, 6);
	else if ( (alternative == null) && (color == 'noir') ) cp2 = myIndexOf2(ia_case, -6);
	
	color = (color == 'blanc') ? ("noir") : ("blanc") ;	
	for (var cp1 = 0; cp1 < 64; cp1++)
		if ( (ia_case[cp1] > 0 && color == 'blanc') || (ia_case[cp1] < 0 && color == 'noir') )
			if ( ia_valid(ia_case, ia_histo, color, cp1, cp2) > 0 ) 
				return(true);

	return(false);	
}


// -----------------------------------------------------------
// ia_mat[verifie si la couleur est MAT]
function ia_mat(ia_case, ia_histo, color)
{
	//init
	var i; var j;
	var m; var n;
	var retour;
	
	for (i = 0; i < 64; i++)
		if ( (ia_case[i] > 0 && color == 'blanc') || (ia_case[i] < 0 && color == 'noir') )
			for (j = 0; j < 64; j++)
				if ( (ia_case[j] >= 0 && color == 'noir') || (ia_case[j] <= 0 && color == 'blanc') )
				{	
					retour = ia_valid(ia_case, ia_histo, color, i, j);
					if (retour == -1) continue; // coup impossible
					ia_faitlecoup(ia_case, ia_histo, color, i, j, retour);
					if ( ia_chess(ia_case, ia_histo, color) == false )
						{ ia_annullecoup(ia_case, ia_histo, color, i, j, retour); return(false); }
					ia_annullecoup(ia_case, ia_histo, color, i, j, retour);
				}
	return(true);
}


// -----------------------------------------------------------
// ia_pat[verifie si la partie est PAT]
function ia_pat(ia_case, ia_histo, color)
{
	//init
	var i; var j;
	var m; var n;
	var retour; var restante;

	// si mouvement impossible sans etre echecs
	for (i = 0; i < 64; i++)
		if ( (ia_case[i] > 0 && color == 'blanc') || (ia_case[i] < 0 && color == 'noir') )
			for (j = 0; j < 64; j++)
				if ( (ia_case[j] >= 0 && color == 'noir') || (ia_case[j] <= 0 && color == 'blanc') )
				{
					retour = ia_valid(ia_case, ia_histo, color, i, j);
					if (retour == -1) continue; // coup impossible
					ia_faitlecoup(ia_case, ia_histo, color, i, j, retour);
					if ( ia_chess(ia_case, ia_histo, color) == false )
						{ ia_annullecoup(ia_case, ia_histo, color, i, j, retour); return(false); }
					ia_annullecoup(ia_case, ia_histo, color, i, j, retour);
				}
	// retour a true si aucune solution trouvé
	return(true);
}


// -----------------------------------------------------------
// ia_faitlecoup []
function ia_faitlecoup(ia_case, ia_histo, color, cp1, cp2, retour)
{
	if (retour == 2) { ia_case[cp1-1] = 0; } // prise en passant blanc gauche
	else if (retour == 3) { ia_case[cp1+1] = 0; } // prise en passant blanc droite
	else if (retour == 4) { ia_case[cp1-1] = 0; } // prise en passant noir gauche
	else if (retour == 5) { ia_case[cp1+1] = 0; } // prise en passant noir droite
	else if (retour == 6) { ia_case[61] = ia_case[63]; ia_case[63] = 0; } // petit roque blanc
	else if (retour == 7) { ia_case[59] = ia_case[56]; ia_case[56] = 0; } // grand roque blanc
	else if (retour == 8) { ia_case[5] = ia_case[7]; ia_case[7] = 0; } // petit roque noir
	else if (retour == 9) { ia_case[3] = ia_case[0]; ia_case[0] = 0; } // grand roque noir
	else if (retour == 99) { if (color == 'blanc') ia_case[cp1] = 5; else ia_case[cp1] = -5; } // promotion

	// on valide le coup
	ia_histo.push(cp1 + "(" + ia_case[cp1] + ")." + cp2 + "(" + ia_case[cp2] + ")");
	ia_case[cp2] = ia_case[cp1];
	ia_case[cp1] = 0;
}

// -----------------------------------------------------------
// ia_annullecoup []
function ia_annullecoup(ia_case, ia_histo, color, cp1, cp2, retour)
{
	if (retour == 2) { ia_case[cp1-1] = -1; } // prise en passant blanc gauche
	else if (retour == 3) { ia_case[cp1+1] = -1; } // prise en passant blanc droite
	else if (retour == 4) { ia_case[cp1-1] = 1; } // prise en passant noir gauche
	else if (retour == 5) { ia_case[cp1+1] = 1; } // prise en passant noir droite
	else if (retour == 6) { ia_case[63] = ia_case[61]; ia_case[61] = 0; } // petit roque blanc
	else if (retour == 7) { ia_case[56] = ia_case[59]; ia_case[59] = 0; } // grand roque blanc
	else if (retour == 8) { ia_case[7] = ia_case[5]; ia_case[5] = 0; } // petit roque noir
	else if (retour == 9) { ia_case[0] = ia_case[3]; ia_case[3] = 0; } // grand roque noir
	else if (retour == 99) { if (color == 'blanc') ia_case[cp2] = 1; else ia_case[cp2] = -1; } // promotion

	// on valide le coup
	ia_case[cp1] = ia_case[cp2];
	ia_case[cp2] = ia_histo[ia_histo.length-1].substring(ia_histo[ia_histo.length-1].lastIndexOf("(")+1, ia_histo[ia_histo.length-1].length-1);
	ia_histo.pop();
}

// -----------------------------------------------------------
// ia_heuristique [evalue la partie a une profondeur donnee]
function ia_heuristique(ia_case, ia_histo, color)
{
	// init
	var total = 0;
	var restant = my_array_count_values(ia_case);
	var total_blanc = (restant[6] * _KING) + (restant[5] * _QUEEN) + (restant[4] * _ROOK) + (restant[3] * _KNIGHT) + (restant[2] * _BISHOP) + (restant[1] * _PAWN);
	var total_noir = (restant[-6] * _KING) + (restant[-5] * _QUEEN) + (restant[-4] * _ROOK) + (restant[-3] * _KNIGHT) + (restant[-2] * _BISHOP) + (restant[-1] * _PAWN);

	// evaluation	
	if ( (total_blanc == _KING) || (total_noir == _KING) )
	{
		// evaluation de finition
		var totalBLANC = ia_finish_blanc(ia_case, ia_histo, color, total_blanc);
		var totalNOIR = ia_finish_noir(ia_case, ia_histo, color, total_noir);
	}
	else
	{
		// evaluation par couleur
		var totalBLANC = ia_heuri_blanc(ia_case, ia_histo, color, total_blanc);
		var totalNOIR = ia_heuri_noir(ia_case, ia_histo, color, total_noir);
	}
	
	// retour suivant la couleur du noeud final
	if (color == 'blanc') total = totalBLANC - totalNOIR;
	else if (color == 'noir') total = totalNOIR - totalBLANC;
	return total;
}


// -----------------------------------------------------------
// ia_finish_blanc [evalue les positions pour les blancs contre le roi noir seul]
function ia_finish_blanc(ia_case, ia_histo, color, total)
{
	var therb = myIndexOf2(ia_case, 6);
	var thern = myIndexOf2(ia_case, -6);
	var xRB = column(therb);	var yRB = row(therb);
	var xRN = column(thern);	var yRN = row(thern);
	var restant = my_array_count_values(ia_case);
	
	// si plus que le roi return total
	if (total == _KING) {total += ia_pos_KingDying[therb]; return total;}
	
	// si plus que des pions
	if (total - (restant[1] * _PAWN) == _KING)
	{
		total += (total == _KING + _PAWN) ? 50 : 120;
		for (var tt1 = 0; tt1 < 64; tt1++)
		{
			if (ia_case[tt1] == 1)
			{
				var r = row(tt1);
				if (row(thern) <= r && ia_distdata[tt1][thern] < r+1 )	total += 10 * (7 - row(tt1));
				else total += 500 + (7 - row(tt1));
				var tt2 = tt1;
				if (row(tt1) > 1) tt2 += 8;
      			else  if (row(tt1) == 1) tt2 += 8;
				total += 8 * (ia_taxidata[thern][tt2] - ia_taxidata[therb][tt2]);
			}
		}
		return total;
	}

	// si plus que roi+cavalier+fou
	if ( (restant[6] == 1) && (restant[3] == 1) && (restant[2] == 1) && (total == _KING + _BISHOP + _KNIGHT) )
	{
		total -= 300;
		var fou 		= myIndexOf2(ia_case, 2);
		var cavalier 	= myIndexOf2(ia_case, 3);
		if (row(fou) % 2 == column(fou) % 2 ) total += KBNK[thern];
		else total += KBNK[locn(row(thern), 7 - column(thern))];
		total -= ia_taxidata[therb][thern];
  		total -= ia_distdata[fou][thern];
  		total -= ia_distdata[cavalier][thern];
		return total;
	}
	
	//roi+pieces sans pions
	if (total > _BISHOP)
	{
		total += 500 - 2 * ia_distdata[therb][thern];
	}
	
	return total;

}




// -----------------------------------------------------------
// ia_finish_noir [evalue les positions pour les noirs contre le roi blanc seul]
function ia_finish_noir(ia_case, ia_histo, color, total)
{
	var therb = myIndexOf2(ia_case, 6);
	var thern = myIndexOf2(ia_case, -6);
	var xRB = column(therb);	var yRB = row(therb);
	var xRN = column(thern);	var yRN = row(thern);
	var restant = my_array_count_values(ia_case);
	
	// si plus que le roi return total
	if (total == _KING) {total += ia_pos_KingDying[thern]; return total;}
	
	// si plus que des pions
	if (total - (restant[-1] * _PAWN) == _KING)
	{
		total += (total == _KING + _PAWN) ? 50 : 120;
		for (var tt1 = 0; tt1 < 64; tt1++)
		{
			if (ia_case[tt1] == -1)
			{
				var r = row(tt1);
				if (row(therb) >= r && ia_distdata[tt1][therb] < 8-r )	total += 10 * (row(tt1));
				else total += 500 + (row(tt1));
				var tt2 = tt1;
				if (row(tt1) > 1) tt2 -= 8;
      			else  if (row(tt1) == 1) tt2 -= 8;
				total += 8 * (ia_taxidata[therb][tt2] - ia_taxidata[thern][tt2]);
			}
		}
		return total;
	}

	// si plus que roi+cavalier+fou
	if ( (restant[-6] == 1) && (restant[-3] == 1) && (restant[-2] == 1) && (total == _KING + _BISHOP + _KNIGHT) )
	{
		total -= 300;
		var fou 		= myIndexOf2(ia_case, -2);
		var cavalier 	= myIndexOf2(ia_case, -3);
		if (row(fou) % 2 == column(fou) % 2 ) total += KBNK[therb];
		else total += KBNK[locn(row(therb), 7 - column(therb))];
		total -= ia_taxidata[thern][therb];
  		total -= ia_distdata[fou][therb];
  		total -= ia_distdata[cavalier][therb];
		return total;
	}
	
	//roi+pieces sans pions
	if (total > _BISHOP)
	{
		total += 500 - 2 * ia_distdata[therb][thern];
	}
	
	return total;
}


// -----------------------------------------------------------
// ia_heuri_blanc [evalue les positions pour les blancs]
function ia_heuri_blanc(ia_case, ia_histo, color, total)
{
	//init
	var tmp = 0;
	var cpt = 0;
	var pawncol = new Array();
	var therb = myIndexOf2(ia_case, 6);
	var thern = myIndexOf2(ia_case, -6);
	var xRB = column(therb);	var yRB = row(therb);
	var xRN = column(thern);	var yRN = row(thern);
	
	// eval : roi
	var kingpos = 1; 									// King Opening
	if (total == _KING) var kingpos = 3; 				// King Dying
	else if (total <= _KING + 500) var kingpos = 2; 	// King Ending
	if (kingpos == 1)	total += ia_pos_KingOpening[therb];
	if (kingpos == 2)	total += ia_pos_KingEnding[therb];
	if (kingpos == 3)	total += ia_pos_KingDying[therb];
	
	// eval : roi roque ou move sans roque
	if ( (myIndexOf(ia_histo, '60(6).62(0)') >= 0) || (myIndexOf(ia_histo, '60(6).58(0)') >= 0) )
		total += 10;
	if ( (myIndexOf(ia_histo, '60(6).62(0)') == -1) && (myIndexOf(ia_histo, '60(6).58(0)') == -1) && (myIndexOf(ia_histo, '(6)') >= 0) )
		total -= 40;

	// init : pawn par colonne
	for (var tt1 = 0; tt1 <= 63; tt1++)
	{
		var xAI = column(tt1);
		if (ia_case[tt1] ==  -1) pawncol[xAI] += 1;
	}

	for (var tt1 = 0; tt1 <= 7; tt1++)
	{
		var pn=0; var pb=0; var fb=0; var fn=0; var tb=0; var tn=0;
		for (var tt2 = 0; tt2 <= 63; tt2 += 8)
		{
			var tt3 = tt1+tt2;
			var xAI = column(tt3);	var yAI = row(tt3);
			if (ia_case[tt3] ==  1) pb += 1;
			if (ia_case[tt3] == -1) pn += 1;
			if (ia_case[tt3] ==  2) fb += 1;
			if (ia_case[tt3] == -2) fn += 1;
			if (ia_case[tt3] ==  4) tb += 1;
			if (ia_case[tt3] == -4) tn += 1;
	
			// eval : position des pieces sur l'echiquier
			if (ia_case[tt3] ==  1)	total += ia_posPB[tt3];
			if (ia_case[tt3] ==  2)	total += ia_pos_bishop[tt3];
			if (ia_case[tt3] ==  3)	total += ia_pos_knight[tt3];
				
			// eval : pion du centre bloqué au place d'origine
			if ((ia_case[tt3] == -1) && ((tt3 == 51) || (tt3 == 52)) && (ia_case[tt3-8] < 0))
				total -= 15;
	
			// eval : tour et dame distance roi adverse
			if (ia_case[tt3] == 4)
				total += 14 - ia_taxidata[tt3][thern];
			
			// eval : dame distance roi adverse
			if (ia_case[tt3] == 5)
			{
				total += 14 - ia_taxidata[tt3][thern];
				if (ia_distdata[tt3][thern] < 3) total += 12;
      		}
			
			// eval : cavalier distance des deux rois
			if (ia_case[tt3] == 3)
			{
				total += 5 - ia_distdata[tt3][therb];
    			total += 5 - ia_distdata[tt3][thern];
			}
						
			// eval : BISHOP square mobility (traverse les pieces exceptées les pions)
			if (ia_case[tt3] == 2)
			{
				cpt = 0;
				for (xTMP = xAI + 1, yTMP = yAI + 1; ( (xTMP <= 7) && (yTMP <= 7) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP++, yTMP++) cpt += 1; // en X positif et Y positif
				for (xTMP = xAI - 1, yTMP = yAI + 1; ( (xTMP >= 0) && (yTMP <= 7) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP--, yTMP++) cpt += 1; // en X negatif et Y positif
				for (xTMP = xAI - 1, yTMP = yAI - 1; ( (xTMP >= 0) && (yTMP >= 0) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP--, yTMP--) cpt += 1; // en X negatif et Y negatif
				for (xTMP = xAI + 1, yTMP = yAI - 1; ( (xTMP <= 7) && (yTMP >= 0) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP++, yTMP--) cpt += 1; // en X positif et Y negatif
				if (cpt > 12) cpt = 12;
				total += ia_mob_bishop[cpt];
				
				if (ia_valid(ia_case, ia_histo, color, tt3, myIndexOf2(ia_case, -4)) > 0) total += 18;
				if (ia_valid(ia_case, ia_histo, color, tt3, myIndexOf2(ia_case, -5)) > 0) total += 18;
				if (ia_valid(ia_case, ia_histo, color, tt3, myIndexOf2(ia_case, -6)) > 0) total += 18;
				
				if ( (xRN + 0 <= 7) && (yRN - 1 >= 0) ) { tmp = ((xRN + 0) + ((yRN - 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN + 1 <= 7) && (yRN - 1 >= 0) ) { tmp = ((xRN + 1) + ((yRN - 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN + 1 <= 7) && (yRN - 0 >= 0) ) { tmp = ((xRN + 1) + ((yRN - 0) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN + 1 <= 7) && (yRN + 1 <= 7) ) { tmp = ((xRN + 1) + ((yRN + 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN + 0 <= 7) && (yRN + 1 <= 7) ) { tmp = ((xRN + 0) + ((yRN + 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN - 1 >= 0) && (yRN + 1 <= 7) ) { tmp = ((xRN - 1) + ((yRN + 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN - 1 >= 0) && (yRN + 0 <= 7) ) { tmp = ((xRN - 1) + ((yRN - 0) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN - 1 >= 0) && (yRN - 1 >= 0) ) { tmp = ((xRN - 1) + ((yRN - 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				
			}
			
			// eval : ROOK square mobility (traverse les pieces exceptées les pions)
			if (ia_case[tt3] == 4)
			{
				cpt = 0;
				for (xTMP = xAI, yTMP = yAI + 1; ( (yTMP <= 7) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); yTMP++) cpt += 1; //en Y positif
				for (xTMP = xAI, yTMP = yAI - 1; ( (yTMP >= 0) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); yTMP--) cpt += 1; //en Y negatif
				for (xTMP = xAI + 1, yTMP = yAI; ( (xTMP <= 7) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP++) cpt += 1; //en X positif
				for (xTMP = xAI - 1, yTMP = yAI; ( (xTMP >= 0) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP--) cpt += 1; //en X negatif
				if (cpt > 12) cpt = 12;
				total += ia_mob_rook[cpt];
			}
			
			// eval : isolated pawn
			if (ia_case[tt3] ==  1)
		 		if ((xAI == 0 || pawncol[xAI - 1] == 0) && (xAI == 7 || pawncol[xAI + 1] == 0)) ia_isolated_pawn[xAI];
			
			// eval : fourchette du cavalier
			if (ia_case[tt3] == 3)
			{
				cpt = 0;
				if ( (xAI+1 <= 7) && (yAI-2 >= 0) && (ia_case[locn(xAI+1, yAI-2)] < 0) ) {cpt += 1; if (ia_case[locn(xAI+1, yAI-2)] == -6) cpt += 10; } //1
				if ( (xAI+2 <= 7) && (yAI-1 >= 0) && (ia_case[locn(xAI+2, yAI-1)] < 0) ) {cpt += 1; if (ia_case[locn(xAI+2, yAI-1)] == -6) cpt += 10; } //2
				if ( (xAI+2 <= 7) && (yAI+1 <= 7) && (ia_case[locn(xAI+2, yAI+1)] < 0) ) {cpt += 1; if (ia_case[locn(xAI+2, yAI+1)] == -6) cpt += 10; } //3
				if ( (xAI+1 <= 7) && (yAI+2 <= 7) && (ia_case[locn(xAI+1, yAI+2)] < 0) ) {cpt += 1; if (ia_case[locn(xAI+1, yAI+2)] == -6) cpt += 10; } //4
				if ( (xAI-1 >= 0) && (yAI+2 <= 7) && (ia_case[locn(xAI-1, yAI+2)] < 0) ) {cpt += 1; if (ia_case[locn(xAI-1, yAI+2)] == -6) cpt += 10; } //5
				if ( (xAI-2 >= 0) && (yAI+1 <= 7) && (ia_case[locn(xAI-2, yAI+1)] < 0) ) {cpt += 1; if (ia_case[locn(xAI-2, yAI+1)] == -6) cpt += 10; } //6
				if ( (xAI-2 >= 0) && (yAI-1 >= 0) && (ia_case[locn(xAI-2, yAI-1)] < 0) ) {cpt += 1; if (ia_case[locn(xAI-2, yAI-1)] == -6) cpt += 10; } //7
				if ( (xAI-1 >= 0) && (yAI-2 >= 0) && (ia_case[locn(xAI-1, yAI-2)] < 0) ) {cpt += 1; if (ia_case[locn(xAI-1, yAI-2)] == -6) cpt += 10; } //8
				if (cpt >= 10) total += 30;
				else if (cpt >= 1) total += 8;
			}
		}
	
		// eval : pieces et lignes
		if ( (tb > 0) && (pb == 0) ) total += 10;
		if ( (tb > 0) && (pn == 0) ) total += 4;
		if (tb >= 2) total += 25;
		if (fb >= 2) total += 15;
		if (pb >= 2) total -= 10;
	}
	
	// eval : aucun pion autour du roi = penalite
	if ( (xRB + 0 <= 7) && (yRB - 1 >= 0) && (ia_case[locn(xRB+0, yRB-1)] == 1) ) tmp = 1;
	else if ( (xRB + 1 <= 7) && (yRB - 1 >= 0) && (ia_case[locn(xRB+1, yRB-1)] == 1) ) tmp = 1;
	else if ( (xRB + 1 <= 7) && (yRB - 0 >= 0) && (ia_case[locn(xRB+1, yRB-0)] == 1) ) tmp = 1;
	else if ( (xRB + 1 <= 7) && (yRB + 1 <= 7) && (ia_case[locn(xRB+1, yRB+1)] == 1) ) tmp = 1;
	else if ( (xRB + 0 <= 7) && (yRB + 1 <= 7) && (ia_case[locn(xRB-0, yRB+1)] == 1) ) tmp = 1;
	else if ( (xRB - 1 >= 0) && (yRB + 1 <= 7) && (ia_case[locn(xRB-1, yRB+1)] == 1) ) tmp = 1;
	else if ( (xRB - 1 >= 0) && (yRB + 0 <= 7) && (ia_case[locn(xRB-1, yRB+0)] == 1) ) tmp = 1;
	else if ( (xRB - 1 >= 0) && (yRB - 1 >= 0) && (ia_case[locn(xRB-1, yRB-1)] == 1) ) tmp = 1;
	if (tmp == 0) total -= 8;
	
	// eval : Un pion mangé n'est peut etre pas une perte s'il est bien protegé derriere :D
	if (color == 'noir')
	{
		var Phisto1 = ia_histo[ia_histo.length-1].substring(ia_histo[ia_histo.length-1].indexOf("(")+1, ia_histo[ia_histo.length-1].indexOf(")"));
		var Phisto2 = ia_histo[ia_histo.length-1].substring(ia_histo[ia_histo.length-1].lastIndexOf("(")+1, ia_histo[ia_histo.length-1].length-1);
		if ( (Phisto2 != 0) && (value_pieces(Phisto2) <= value_pieces(Phisto1)) )
		{
			var num = ia_histo[ia_histo.length-1].substring(ia_histo[ia_histo.length-1].lastIndexOf(".")+1, ia_histo[ia_histo.length-1].lastIndexOf("(") );
			var valeur = ia_protect_attack(ia_case, ia_histo, num);
			total += valeur;
		}
	}
		
	return total;
}


// -----------------------------------------------------------
// ia_heuri_noir [evalue les positions pour les blancs]
function ia_heuri_noir(ia_case, ia_histo, color, total)
{
	//init
	var tmp = 0;
	var cpt = 0;
	var pawncol = new Array();
	therb = myIndexOf2(ia_case, 6);
	thern = myIndexOf2(ia_case, -6);
	var xRB = column(therb);	var yRB = row(therb);
	var xRN = column(thern);	var yRN = row(thern);
	
	// eval : roi
	var kingpos = 1; 							// King Opening
	if (total == _KING) var kingpos = 3; 		// King Dying
	else if (total <= _KING + 500) var kingpos = 2; 	// King Ending
	if (kingpos == 1)	total += ia_pos_KingOpening[thern];
	if (kingpos == 2)	total += ia_pos_KingEnding[thern];
	if (kingpos == 3)	total += ia_pos_KingDying[thern];
	
	// eval : roi roque ou move sans roque
	if ( (myIndexOf(ia_histo, '4(-6).6(0)') >= 0) || (myIndexOf(ia_histo, '4(-6).2(0)') >= 0) )
		total += 10;
	else if ( (myIndexOf(ia_histo, '4(-6).6(0)') == -1) && (myIndexOf(ia_histo, '4(-6).2(0)') == -1) && (myIndexOf(ia_histo, '(-6)') >= 0) )
		total -= 40;
	
	// init : pawn par colonne
	for (var tt1 = 0; tt1 <= 63; tt1++)
	{
		var xAI = column(tt1);
		if (ia_case[tt1] ==  -1) pawncol[xAI] += 1;
	}

	for (var tt1 = 0; tt1 <= 7; tt1++)
	{
		var pn=0; var pb=0; var fb=0; var fn=0; var tb=0; var tn=0;
		for (var tt2 = 0; tt2 <= 63; tt2 += 8)
		{
			var tt3 = tt1+tt2;
			var xAI = column(tt3);	var yAI = row(tt3);
			if (ia_case[tt3] ==  1) pb += 1;
			if (ia_case[tt3] == -1) pn += 1;
			if (ia_case[tt3] ==  2) fb += 1;
			if (ia_case[tt3] == -2) fn += 1;
			if (ia_case[tt3] ==  4) tb += 1;
			if (ia_case[tt3] == -4) tn += 1;

			// eval : position des pieces sur l'echiquier
			if (ia_case[tt3] == -1)	total += ia_posPN[tt3];
			if (ia_case[tt3] == -2)	total += ia_pos_bishop[tt3];
			if (ia_case[tt3] == -3)	total += ia_pos_knight[tt3];
			
			// eval : pion du centre bloqué au place d'origine
			if ((ia_case[tt3] == -1) && ((tt3 == 11) || (tt3 == 12)) && (ia_case[tt3+8] > 0))
				total -= 15;
				
			// eval : tour distance roi adverse
			if (ia_case[tt3] == -4)
				total += 14 - ia_taxidata[tt3][therb];
			
			// eval : dame distance roi adverse
			if (ia_case[tt3] == -5)
			{
				total += 14 - ia_taxidata[tt3][therb];
				if (ia_distdata[tt3][therb] < 3) total += 12;
      		}
			
			// eval : cavalier distance des deux rois
			if (ia_case[tt3] == -3)
			{
				total += 5 - ia_distdata[tt3][therb];
    			total += 5 - ia_distdata[tt3][thern];
			}
			
			// eval : BISHOP square mobility (traverse les pieces exceptées les pions)
			if (ia_case[tt3] == -2)
			{
				cpt = 0;
				for (xTMP = xAI + 1, yTMP = yAI + 1; ( (xTMP <= 7) && (yTMP <= 7) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP++, yTMP++) cpt += 1; // en X positif et Y positif
				for (xTMP = xAI - 1, yTMP = yAI + 1; ( (xTMP >= 0) && (yTMP <= 7) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP--, yTMP++) cpt += 1; // en X negatif et Y positif
				for (xTMP = xAI - 1, yTMP = yAI - 1; ( (xTMP >= 0) && (yTMP >= 0) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP--, yTMP--) cpt += 1; // en X negatif et Y negatif
				for (xTMP = xAI + 1, yTMP = yAI - 1; ( (xTMP <= 7) && (yTMP >= 0) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP++, yTMP--) cpt += 1; // en X positif et Y negatif
				if (cpt > 12) cpt = 12;
				total += ia_mob_bishop[cpt];
				
				if (ia_valid(ia_case, ia_histo, color, tt3, myIndexOf2(ia_case, 4)) > 0) total += 18;
				if (ia_valid(ia_case, ia_histo, color, tt3, myIndexOf2(ia_case, 5)) > 0) total += 18;
				if (ia_valid(ia_case, ia_histo, color, tt3, myIndexOf2(ia_case, 6)) > 0) total += 18;
				
				if ( (xRN + 0 <= 7) && (yRN - 1 >= 0) ) { tmp = ((xRN + 0) + ((yRN - 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN + 1 <= 7) && (yRN - 1 >= 0) ) { tmp = ((xRN + 1) + ((yRN - 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN + 1 <= 7) && (yRN - 0 >= 0) ) { tmp = ((xRN + 1) + ((yRN - 0) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN + 1 <= 7) && (yRN + 1 <= 7) ) { tmp = ((xRN + 1) + ((yRN + 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN + 0 <= 7) && (yRN + 1 <= 7) ) { tmp = ((xRN + 0) + ((yRN + 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN - 1 >= 0) && (yRN + 1 <= 7) ) { tmp = ((xRN - 1) + ((yRN + 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN - 1 >= 0) && (yRN + 0 <= 7) ) { tmp = ((xRN - 1) + ((yRN - 0) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				if ( (xRN - 1 >= 0) && (yRN - 1 >= 0) ) { tmp = ((xRN - 1) + ((yRN - 1) * 8)); if (ia_valid(ia_case, ia_histo, color, tt3, tmp) > 0 ) total += 5; }
				
			}
			
			// eval : ROOK square mobility (traverse les pieces exceptées les pions)
			if (ia_case[tt3] == -4)
			{
				cpt = 0;
				for (xTMP = xAI, yTMP = yAI + 1; ( (yTMP <= 7) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); yTMP++) cpt += 1; //en Y positif
				for (xTMP = xAI, yTMP = yAI - 1; ( (yTMP >= 0) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); yTMP--) cpt += 1; //en Y negatif
				for (xTMP = xAI + 1, yTMP = yAI; ( (xTMP <= 7) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP++) cpt += 1; //en X positif
				for (xTMP = xAI - 1, yTMP = yAI; ( (xTMP >= 0) && (ia_case[locn(xTMP, yTMP)] != 1) && (ia_case[locn(xTMP, yTMP)] != -1) ); xTMP--) cpt += 1; //en X negatif
				if (cpt > 12) cpt = 12;
				total += ia_mob_rook[cpt];
			}
			
			// eval : isolated pawn
			if (ia_case[tt3] == -1)
	 			if ((xAI == 0 || pawncol[xAI - 1] == 0) && (xAI == 7 || pawncol[xAI + 1] == 0)) ia_isolated_pawn[xAI];
				
			// eval : fourchette du cavalier
			if (ia_case[tt3] == -3)
			{
				cpt = 0;
				if ( (xAI+1 <= 7) && (yAI-2 >= 0) && (ia_case[locn(xAI+1, yAI-2)] > 0) ) {cpt += 1; if (ia_case[locn(xAI+1, yAI-2)] == 6) cpt += 10; } //1
				if ( (xAI+2 <= 7) && (yAI-1 >= 0) && (ia_case[locn(xAI+2, yAI-1)] > 0) ) {cpt += 1; if (ia_case[locn(xAI+2, yAI-1)] == 6) cpt += 10; } //2
				if ( (xAI+2 <= 7) && (yAI+1 <= 7) && (ia_case[locn(xAI+2, yAI+1)] > 0) ) {cpt += 1; if (ia_case[locn(xAI+2, yAI+1)] == 6) cpt += 10; } //3
				if ( (xAI+1 <= 7) && (yAI+2 <= 7) && (ia_case[locn(xAI+1, yAI+2)] > 0) ) {cpt += 1; if (ia_case[locn(xAI+1, yAI+2)] == 6) cpt += 10; } //4
				if ( (xAI-1 >= 0) && (yAI+2 <= 7) && (ia_case[locn(xAI-1, yAI+2)] > 0) ) {cpt += 1; if (ia_case[locn(xAI-1, yAI+2)] == 6) cpt += 10; } //5
				if ( (xAI-2 >= 0) && (yAI+1 <= 7) && (ia_case[locn(xAI-2, yAI+1)] > 0) ) {cpt += 1; if (ia_case[locn(xAI-2, yAI+1)] == 6) cpt += 10; } //6
				if ( (xAI-2 >= 0) && (yAI-1 >= 0) && (ia_case[locn(xAI-2, yAI-1)] > 0) ) {cpt += 1; if (ia_case[locn(xAI-2, yAI-1)] == 6) cpt += 10; } //7
				if ( (xAI-1 >= 0) && (yAI-2 >= 0) && (ia_case[locn(xAI-1, yAI-2)] > 0) ) {cpt += 1; if (ia_case[locn(xAI-1, yAI-2)] == 6) cpt += 10; } //8
				if (cpt >= 10) total += 30;
				else if (cpt >= 1) total += 8;
			}
		}
	
		// eval : pieces et lignes
		if ( (tn > 0) && (pn == 0) ) total += 10;
		if ( (tn > 0) && (pb == 0) ) total += 4;
		if (tn >= 2) total += 25;
		if (fn >= 2) total += 15;
		if (pn >= 2) total -= 10;
	}

	// eval : aucun pion autour du roi = penalite
	if ( (xRN + 0 <= 7) && (yRN - 1 >= 0) && (ia_case[locn(xRN+0, yRN-1)] == -1) ) tmp = 1;
	else if ( (xRN + 1 <= 7) && (yRN - 1 >= 0) && (ia_case[locn(xRN+1, yRN-1)] == -1) ) tmp = 1;
	else if ( (xRN + 1 <= 7) && (yRN - 0 >= 0) && (ia_case[locn(xRN+1, yRN-0)] == -1) ) tmp = 1;
	else if ( (xRN + 1 <= 7) && (yRN + 1 <= 7) && (ia_case[locn(xRN+1, yRN+1)] == -1) ) tmp = 1;
	else if ( (xRN + 0 <= 7) && (yRN + 1 <= 7) && (ia_case[locn(xRN-0, yRN+1)] == -1) ) tmp = 1;
	else if ( (xRN - 1 >= 0) && (yRN + 1 <= 7) && (ia_case[locn(xRN-1, yRN+1)] == -1) ) tmp = 1;
	else if ( (xRN - 1 >= 0) && (yRN + 0 <= 7) && (ia_case[locn(xRN-1, yRN+0)] == -1) ) tmp = 1;
	else if ( (xRN - 1 >= 0) && (yRN - 1 >= 0) && (ia_case[locn(xRN-1, yRN-1)] == -1) ) tmp = 1;
	if (tmp == 0) total -= 8;

	// eval : Un pion mangé n'est peut etre pas une perte s'il est bien protegé derriere :D
	if (color == 'blanc')
	{
		var Phisto1 = ia_histo[ia_histo.length-1].substring(ia_histo[ia_histo.length-1].indexOf("(")+1, ia_histo[ia_histo.length-1].indexOf(")"));
		var Phisto2 = ia_histo[ia_histo.length-1].substring(ia_histo[ia_histo.length-1].lastIndexOf("(")+1, ia_histo[ia_histo.length-1].length-1);
		if ( (Phisto2 != 0) && (value_pieces(Phisto2) <= value_pieces(Phisto1)) )
		{
			var num = ia_histo[ia_histo.length-1].substring(ia_histo[ia_histo.length-1].lastIndexOf(".")+1, ia_histo[ia_histo.length-1].lastIndexOf("(") );
			var valeur = ia_protect_attack(ia_case, ia_histo, num);
			total += valeur;
		}
	}
	
	return total;
}


// -----------------------------------------------------------
// ia_protect_attack [evalue le nombre de protection pour la piece NUM]
function ia_protect_attack(ia_case, ia_histo, num)
{
	//init
	if (ia_case[num] == 0) return 0;
	var color1 = (ia_case[num]<0) ? "noir" : "blanc";
	var color2 = (ia_case[num]<0) ? "blanc" : "noir";
	var val1 = ia_histo[ia_histo.length-1].substring(ia_histo[ia_histo.length-1].indexOf("(")+1, ia_histo[ia_histo.length-1].indexOf(")") );
	var val2 = ia_histo[ia_histo.length-1].substring(ia_histo[ia_histo.length-1].lastIndexOf("(")+1, ia_histo[ia_histo.length-1].length-1 );
	var val1 = Math.abs(parseInt(val1, 10));
	var pa_ia = new Array();
	var pa_hu = new Array();
	pa_hu.push(val1);
	var perte_ia = 0;
	var perte_hu = 0;

	//boucle de test
	for (var tmp = 0; tmp < 64; tmp++)
	{
		// IA attaque NUM
		if ( (((ia_case[tmp] > 0) && (color1 == "noir")) || ((ia_case[tmp] < 0) && (color1 == "blanc"))) && (tmp != num) )
				if ( ia_valid(ia_case, ia_histo, color1, tmp, num) > 0 )
					pa_ia.push(Math.abs(ia_case[tmp]))

		// HU protege NUM
		if ( (((ia_case[tmp] > 0) && (color1 == "blanc")) || ((ia_case[tmp] < 0) && (color1 == "noir"))) && (tmp != num) )
		{
				ia_case[num] = -ia_case[num];
				if ( ia_valid(ia_case, ia_histo, color2, tmp, num) > 0 )
					pa_hu.push(Math.abs(ia_case[tmp]));
				ia_case[num] = -ia_case[num];
		}
	}
	
	// test préventif
	if (pa_ia.length == 0) return 0;
	
	// tri des tableaux
	pa_hu.sort(tri_nombres);
	pa_ia.sort(tri_nombres);

	// boucle
	for (var i=0; i < pa_ia.length && i < pa_hu.length; i++)
	{
		perte_hu += value_pieces(pa_hu[i]);
		if (pa_hu[i+1]) perte_ia += value_pieces(pa_ia[i]);
	}
	var total = perte_hu - perte_ia;
	return total;
}


function tri_nombres(a,b)
{ return a-b; }


// -----------------------------------------------------------
// ia_transform_case [transofromation du tableau des pions en chiffre afin d'accelerer l'IA]
function ia_transform_case()
{
	var newtable = new Array();
	for (var i = 0; i < js_case.length; i++)
	{
		switch (js_case[i])
		{
			case "no": newtable[i] = 0; break;
			case "pb": newtable[i] = 1; break;
			case "fb": newtable[i] = 2; break;
			case "cb": newtable[i] = 3; break;
			case "tb": newtable[i] = 4; break;
			case "db": newtable[i] = 5; break;
			case "rb": newtable[i] = 6; break;
			case "pn": newtable[i] = -1; break;
			case "fn": newtable[i] = -2; break;
			case "cn": newtable[i] = -3; break;
			case "tn": newtable[i] = -4; break;
			case "dn": newtable[i] = -5; break;
			case "rn": newtable[i] = -6; break;
			default: newtable[i] = 0; break;
		}
	}
	return newtable;
}

// -----------------------------------------------------------
// ia_transform_histo [transofromation de l'histo pour rester compatible avec les chiffres]
function ia_transform_histo()
{
	var newtable = js_moves.slice(0);
	
	for (var i = 0; i < newtable.length; i++)
	{
		newtable[i] = newtable[i].replace(/no/, 0);
		newtable[i] = newtable[i].replace(/pb/, 1);
		newtable[i] = newtable[i].replace(/fb/, 2);
		newtable[i] = newtable[i].replace(/cb/, 3);
		newtable[i] = newtable[i].replace(/tb/, 4);
		newtable[i] = newtable[i].replace(/db/, 5);
		newtable[i] = newtable[i].replace(/rb/, 6);
		newtable[i] = newtable[i].replace(/pn/, -1);
		newtable[i] = newtable[i].replace(/fn/, -2);
		newtable[i] = newtable[i].replace(/cn/, -3);
		newtable[i] = newtable[i].replace(/tn/, -4);
		newtable[i] = newtable[i].replace(/dn/, -5);
		newtable[i] = newtable[i].replace(/rn/, -6);
	}
	return newtable;
}

// -----------------------------------------------------------
// ia_translate_piece [transformation des chiffres en lettres]
function ia_translate_piece(piece)
{
	switch (piece)
	{
		case  0: return "no"; break;
		case  1: return "pb"; break;
		case  2: return "fb"; break;
		case  3: return "cb"; break;
		case  4: return "tb"; break;
		case  5: return "db"; break;
		case  6: return "rb"; break;
		case -1: return "pn"; break;
		case -2: return "fn"; break;
		case -3: return "cn"; break;
		case -4: return "tn"; break;
		case -5: return "dn"; break;
		case -6: return "rn"; break;
		default: return "no"; break;
	}
	return "no";
}


// -----------------------------------------------------------
// my_array_count_values [compte les pions restants]
function my_array_count_values(tableau)
{
	var restant = new Array();
	restant[0] = 0;
	restant[6] = 0;restant[5] = 0;restant[4] = 0;restant[3] = 0;restant[2] = 0;restant[1] = 0;
	restant[-6] = 0;restant[-5] = 0;restant[-4] = 0;restant[-3] = 0;restant[-2] = 0;restant[-1] = 0;
	for (i = 0; i < tableau.length; i++)
	{
		restant[tableau[i]] += 1;
	}
	return restant;
}

// -----------------------------------------------------------
// value_pieces [retourne la valeur d'une piece passé en parametre]
function value_pieces(nom)
{
	var valeur;
	switch (Math.abs(nom))
	{
		case 1: valeur = _PAWN; break;
		case 2: valeur = _BISHOP; break;
		case 3: valeur = _KNIGHT; break;
		case 4: valeur = _ROOK; break;
		case 5: valeur = _QUEEN; break;
		case 6: valeur = _KING; break;
		default: valeur = 0; break;
	}
	return valeur;
}

// -----------------------------------------------------------
// ia_init [permet d'initialiser un tableau taxicab (evaluation des distances)]
function ia_init()
{
	for (var a = 0; a < 64; a++)
	{
		ia_taxidata[a] = new Array(64); 
		ia_distdata[a] = new Array(64); 
    	for (var b = 0; b < 64; b++)
    	{
			var d = Math.abs(column(a) - column(b));
			var di = Math.abs(row(a) - row(b));
			ia_taxidata[a][b] = d + di;
			ia_distdata[a][b] = (d > di ? d : di);
    	}
	}
}











//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//								         FONCTIONS DES ENIGMES				      	     	   \\
//					             ( fonctions de gestion des enigmes )			  	           \\
//_____________________________________________________________________________________________\\




// -----------------------------------------------------------
// enigma_init [initialise les valeurs ]
function enigma_init()
{
	js_partieID = document.enigma.enigmaID.value;
	js_case = document.enigma.enigmaCase.value.split("|");
	js_board_piece = document.enigma.boardPiece.value;
	js_moves = new Array();
	js_hits = 0
	js_progress = 3;
	
	//si mode reverse
	js_reverse = document.enigma.reverse.value;
	if (js_reverse == 1)
	{
		js_blanc = 0;
		js_noir = js_joueur_id;
		js_mustplay = js_blanc;
		enigma_play();
	}
	else
	{
		js_blanc = js_joueur_id;
		js_noir = 0;
		js_mustplay = js_blanc;
	}
	enigma_liste();
}


// -----------------------------------------------------------
// enigma_liste [rafraichissement de la liste des defis]
function enigma_liste()
{
  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données
   		// [0][liste]
		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
	     		{
					document.getElementById("contenu_enigma_liste").innerHTML = httpRequest.responseText;
					CSBfleXcroll('scrollenigma');
				}
	      	}
	     }
	}
  	httpRequest.open("GET", "ajax.php?fonction=enigma_liste&enigmaID="+js_partieID, true);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// enigma_winner [enigme reussi, on ajoute le nom du joueur a la liste des gagnants]
function enigma_winner()
{
  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données
   		// [0][liste]
		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
	     		{
					if (httpRequest.responseText.length > 0) document.getElementById("contenu_enigma_winner").innerHTML = httpRequest.responseText;
				}
				enigma_liste();
	      	}
	     }
	}
  	httpRequest.open("GET", "ajax.php?fonction=enigma_winner&enigmaID="+js_partieID, true);
  	httpRequest.send(null);
}

// -----------------------------------------------------------
// enigma_onmouse [gere les clics souris sur les enigmes (different de chess_onmouse car ici en fait on ne joue pas les coups)]
function enigma_onmouse(act, numcase)
{
	if (!window['js_mustplay']) return;
	if (!window['js_progress']) return;
	if (js_progress != 3) return;

	var reg = (js_mustplay == js_blanc) ? (new RegExp("[b]$", "g")) : (new RegExp("[n]$", "g")) ;
	if ( (js_joueur_id == js_blanc) && (js_mustplay == js_noir) ) return ;
	if ( (js_joueur_id == js_noir) && (js_mustplay == js_blanc) ) return ;

	if ( (act == "over") && (GL_clicdown == 0) && (js_case[numcase].search(reg) != -1) )
	{
		document.getElementById(numcase).style.cursor="pointer";
	}

	if ( (act == "over") && (GL_clicdown == 1) && (js_case[numcase].search(reg) == -1) )
	{
		document.getElementById(numcase).style.cursor="pointer";
		document.getElementById(numcase).style.backgroundImage = "url(images/caseverte.gif)";
	}

	if ( (act == "out") && (GL_clicdown == 1) && (js_case[numcase].search(reg) == -1) )
	{
		document.getElementById(numcase).style.cursor="default";
		document.getElementById(numcase).style.backgroundImage = "";
		game_lightlast(js_case, js_moves, js_hits, true);
	}

	if ( (act == "clic") && (GL_clicdown == 0) && (js_case[numcase].search(reg) != -1) )
	{
		document.getElementById(numcase).style.backgroundImage = "url(images/caseverte.gif)";
		document.enigma.cp1.value = numcase;
		GL_clicdown = 1;
		return ;
	}
	
	if ( (act == "clic") && (GL_clicdown == 1) && (document.enigma.cp1.value == numcase) )
	{
		document.getElementById(numcase).style.backgroundImage = "";
		game_lightlast(js_case, js_moves, js_hits, true);
		game_lightchess(js_case, js_moves, js_hits, true);
		GL_clicdown = 0;
		return ;
	}

	if ( (act == "clic") && (GL_clicdown == 1) && (js_case[numcase].search(reg) == -1) )
	{
		document.enigma.cp2.value = numcase;
		document.getElementById(String(document.enigma.cp1.value)).style.backgroundImage = "";
		document.getElementById(String(document.enigma.cp2.value)).style.backgroundImage = "";
		for (var i = 0; i < 64; i++)
			document.getElementById(i).style.cursor="default";
		GL_clicdown = 0;
		game_lightchess(js_case, js_moves, js_hits, true);
		enigma_play();
		return ;
	}
	
	if ( (act == "over") && (GL_clicdown == 1) && (document.enigma.cp1.value != numcase) && (js_case[numcase].search(reg) != -1) )
	{
		document.getElementById(numcase).style.cursor="default";
		return ;
	}
	
	if ( (act == "out") && (GL_clicdown == 1) && (document.enigma.cp1.value != numcase) && (js_case[numcase].search(reg) != -1) )
	{
		document.getElementById(numcase).style.backgroundImage = "";
		if (js_chesslight != document.enigma.cp1.value) game_lightchess(js_case, js_moves, js_hits, true);
		return ;
	}	
}

// -----------------------------------------------------------
// enigma_play [joue le coup du joueur]
function enigma_play()
{
	//initialisation avant le coup
	var cp1 = document.enigma.cp1.value
	var cp2 = document.enigma.cp2.value
	var ia_case = ia_transform_case();
	var ia_histo = ia_transform_histo();
	var color = (js_hits%2 ==0) ? "blanc" : "noir";
	
	//on test la validité du coup
	var retour = ia_valid(ia_case, ia_histo, color, cp1, cp2)
	if (retour <= 0) return;
	if ( (Math.abs(ia_case[cp1]) == 1) && ( ((cp2 >= 0) && (cp2 <= 7)) || ((cp2 >= 56) && (cp2 <= 63)) ) ) retour = 99; //promotion
	ia_faitlecoup(ia_case, ia_histo, color, cp1, cp2, retour);
	if (ia_chess(ia_case, ia_histo, color) == true) { ia_annullecoup(ia_case, ia_histo, color, cp1, cp2, retour); return; }

	
	//on joue le coup avec la prise en compte des coups speciaux
	//	roque
	if 	( (js_case[cp1] == 'rn') && (cp1 == 4)  && (cp2 == 2)  ) { js_case[3]  = js_case[0];  js_case[0]  = 'no'; document.getElementById('img_3').src = js_board_piece + js_case[3] + ".gif"; document.getElementById('img_0').src = js_board_piece + js_case[0] + ".gif";} // NOIR grand roque
	else if ( (js_case[cp1] == 'rn') && (cp1 == 4)  && (cp2 == 6)  ) { js_case[5]  = js_case[7];  js_case[7]  = 'no'; document.getElementById('img_5').src = js_board_piece + js_case[5] + ".gif"; document.getElementById('img_7').src = js_board_piece + js_case[7] + ".gif";} // NOIR petit roque
	else if ( (js_case[cp1] == 'rb') && (cp1 == 60) && (cp2 == 58) ) { js_case[59] = js_case[56]; js_case[56] = 'no'; document.getElementById('img_59').src = js_board_piece + js_case[59] + ".gif"; document.getElementById('img_56').src = js_board_piece + js_case[56] + ".gif";} // BLANC grand roque
	else if ( (js_case[cp1] == 'rb') && (cp1 == 60) && (cp2 == 62) ) { js_case[61] = js_case[63]; js_case[63] = 'no'; document.getElementById('img_61').src = js_board_piece + js_case[61] + ".gif"; document.getElementById('img_63').src = js_board_piece + js_case[63] + ".gif";} // BLANC petit roque
	//	prise en passant
	var plusun = parseInt(cp1,10) + parseInt(1,10); 
	var moinsun = parseInt(cp1,10) - parseInt(1,10);
	if 	    ( (js_case[cp1] == 'pn') && (js_case[cp2] == 'no') && (cp2 - cp1 == 7) ) { js_case[moinsun] = 'no'; js_case[cp2] = 'pb'; document.getElementById('img_' + moinsun).src = js_board_piece + js_case[moinsun] + ".gif"; }
	else if ( (js_case[cp1] == 'pn') && (js_case[cp2] == 'no') && (cp2 - cp1 == 9) ) { js_case[plusun] = 'no'; js_case[cp2] = 'pb'; document.getElementById('img_' + plusun).src = js_board_piece + js_case[plusun] + ".gif"; }
	else if ( (js_case[cp1] == 'pb') && (js_case[cp2] == 'no') && (cp1 - cp2 == 7) ) { js_case[plusun] = 'no'; js_case[cp2] = 'pn'; document.getElementById('img_' + plusun).src = js_board_piece + js_case[plusun] + ".gif"; }
	else if ( (js_case[cp1] == 'pb') && (js_case[cp2] == 'no') && (cp1 - cp2 == 9) ) { js_case[moinsun] = 'no'; js_case[cp2] = 'pn'; document.getElementById('img_' + moinsun).src = js_board_piece + js_case[moinsun] + ".gif"; }
	//	change les tableaux
	js_moves[js_moves.length] = cp1 + "(" + js_case[cp1] + ")." + cp2 + "(" + js_case[cp2] + ")";
	js_case[cp2] = js_case[cp1];
	js_case[cp1] = 'no';
	
	//	promotion
	if ( ((js_case[cp2].substring(0, 1) == 'p') && (cp2 >= 0) && (cp2 <= 7)) || ((js_case[cp2].substring(0, 1) == 'p') && (cp2 >= 56) && (cp2 <= 63)) )
		js_case[cp2] = "d" + js_case[cp2].substring(1, 2);
	
	
	//bouge la piece
	document.getElementById('img_' + cp1).src = js_board_piece + js_case[cp1] + ".gif";
	document.getElementById('img_' + cp2).src = js_board_piece + js_case[cp2] + ".gif";
	js_hits = js_hits + 1;
	game_lightlast(js_case, js_moves, js_hits, true);
	game_lightchess(js_case, js_moves, js_hits, true);
	js_mustplay = ( js_mustplay == js_noir) ? (js_blanc) : (js_noir);
	
	//on test si la partie est finie (MAT ou PAT)
	ia_case = ia_transform_case();
	ia_histo = ia_transform_histo();
	color = (js_hits%2 ==0) ? "blanc" : "noir";
	if (ia_chess(ia_case, ia_histo, color) == false && ia_pat(ia_case, ia_histo, color) == true)
	{
		js_hits = Math.ceil(js_hits / 2);
		document.getElementById("information").innerHTML = 'pat en ' + js_hits + ' coup(s) ... je prefererai un MAT';
		js_progress = 5;
		return
	}
	if (ia_chess(ia_case, ia_histo, color) == true && ia_mat(ia_case, ia_histo, color) == true)
	{
		js_progress = 5;
		js_hits = Math.ceil(js_hits / 2);
		if (document.enigma.enigmaMax.value == js_hits && js_reverse == 0)
		{
			document.getElementById("information").innerHTML = '<span style=\'color:#11DD11\'>MAT en ' + js_hits + ' coup(s). Felicitation !!</span><br><span style=\'color:#DD1111\'>mode reverse debloqu&eacute;. Tu peux jouer avec les noirs <br>(cf. menu apres un reload de l\'enigme)</span>';
			enigma_winner();
			document.getElementById("contenu_enigma_status").innerHTML = "<img src='images/icon.ok.png'>";
		}
		return
	}

	//si pas finie alors c'est a l'IA de jouer
	if (js_mustplay == js_noir && js_reverse == 0) enigma_ia()
	if (js_mustplay == js_blanc && js_reverse == 1) enigma_ia()
	
	
	if (js_reverse == 0 && (Math.floor(js_hits / 2)) == document.enigma.enigmaMax.value)
	{
		document.getElementById("information").innerHTML = 'nombre de coup depass&eacute;<br>(rechargement de la partie dans 2 secondes)';
		setTimeout(enigma_reload, 2000);
		return;
	}

}

// -----------------------------------------------------------
// enigma_reload [recharge l'enigme]
function enigma_reload()
{
	header_page_change('_main_enigma.php?enigmaID=' + js_partieID + '&reverse=0')
}

// -----------------------------------------------------------
// enigma_ia [N-IA joue son coup]
function enigma_ia()
{
	//init
	ia_timeoutcolor = (js_hits%2 ==0) ? "noir" : "blanc";
	ia_timeoutcase 	= ia_transform_case();
	ia_timeouthisto = ia_transform_histo();
	ia_timeoutdeep = 2;
	ia_deep = 2
	ia_timeout = false;
	ia_timeoutgo = false;
	ia_timeoutgo2 = false;
	ia_timeoutalpha = -100000
	ia_timeoutbeta = 100000
	ia_timeoutcp1 = 0
	ia_timeoutcp2 = 0
	
	//--------------
	// recherche du meilleur coup
	enigma_timeoutminmax();
}

// -----------------------------------------------------------
// enigma_timeoutminmax [N-IA joue son coup]
function enigma_timeoutminmax()
{
	//init
	ia_timeout = false;
	ia_timeoutgo = true;
	ia_timeoutgo2 = true;
	ia_date1 = new Date();

	// recherche du meilleur coup
	if (ia_timeoutcp1 != 0 || ia_timeoutcp2 != 0 || ia_timeoutdeep != 2 ) 
		ia_timeoutcolor = (ia_timeoutcolor == 'blanc') ? ("noir") : ("blanc") ;
	ia_negamax(ia_timeoutcase, ia_timeouthisto, ia_timeoutalpha, ia_timeoutbeta, ia_timeoutdeep, ia_timeoutcolor);
	
	//si timeout alors on va continuer les recherches
	if (ia_timeout == true)
	{
		
		timer_play_bot = setTimeout(enigma_timeoutminmax, 1);
		return;
	}
	
	//envoie le coup si pas de timeout
	var tmp = ia_coup.split(":");
	document.enigma.cp1.value = tmp[0]
	document.enigma.cp2.value = tmp[1]
	timer_play_bot = null;
	enigma_play();
}


// -----------------------------------------------------------
// ia_play [un coup est joué par le bot]
function enigma_resolved()
{
	// les variables
	var data = "partieID="+document.enigma.enigmaID.value;
	
  	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données
   		// [0][message] (si coup non authorisé)
		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					//alert(httpRequest.responseText);
				}
	     	}
    	}
	}
	httpRequest.open("POST", "ajax.php?fonction=enigma_resolved", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}














//_____________________________________________________________________________________________\\
//_____________________________________________________________________________________________\\
//								    FONCTIONS DE L'ADMINISTRATION				    		   \\
//					             	( fonctions speciales admin )			 				   \\
//_____________________________________________________________________________________________\\



// -----------------------------------------------------------
// admin_test_version [test la version du site et du fichier JS]
function admin_test_version()
{
	if (site_version_sql != site_version_js)
	{
		// kill timer s'il existe pour ne pas en lancer deux en meme temps (pas vraiment necessaire car le onunload le fera)
		window.clearTimeout(timer_list_encours);
		window.clearTimeout(timer_list_attente);
		window.clearTimeout(timer_list_online);
		window.clearTimeout(timer_play_countdown);
		window.clearTimeout(timer_play_viki);
		window.clearTimeout(timer_play_chat);
		window.clearTimeout(timer_histo_view);
		// reload toute la page
		window.location.reload(true)
	}
}


// -----------------------------------------------------------
// admin_change_version [change dans la base la version du site]
function admin_change_version()
{
	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données 
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
					header_page_change("_admin_version.php");
			}
    	}
	}
	httpRequest.open("GET", "../ajax.php?fonction=admin_change_version&version="+document.getElementById("version").value, true);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// admin_backhit [annule le dernier coup de la partie]
function admin_backhit(partieID)
{
	showElement("site_load");
	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données 
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
					header_page_change("_admin_parties.php?partie="+partieID);
			removeElement("site_load");
			}
    	}
	}
  	httpRequest.open("GET", "../ajax.php?fonction=admin_backhit&partieID="+partieID, true);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// admin_delerror [supprime le log de l'erreur]
function admin_delerror(errorID)
{
	showElement("site_load");
	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données 
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
					header_page_change("_admin_erreurs.php");
			removeElement("site_load");
			}
    	}
	}
  	httpRequest.open("GET", "../ajax.php?fonction=admin_delerror&errorID="+errorID, true);
  	httpRequest.send(null);
}


// -----------------------------------------------------------
// admin_enigma_drawpiece [affiche la piece dans la case dediee]
function admin_enigma_drawpiece(formePiece, ID)
{
	document.getElementById("img_"+ID).src="../" + formePiece + document.admin_enigma.piece.value + ".gif";
	document.getElementById(ID).value = document.admin_enigma.piece.value;
}


// -----------------------------------------------------------
// admin_enigma_create [creation de l'enigme]
function admin_enigma_create()
{
	// les variables
	var ID;
	var pieces;

	// creation du tableau
	pieces = "";
	for (ID=0; ID<=63; ID++)
	{
		if (pieces.length > 0)  pieces = pieces + "|";
		if (document.getElementById(ID).value == null) document.getElementById(ID).value = 'no';
		pieces = pieces + document.getElementById(ID).value;
	}	

	// initialisation
	var data = "enigma_pieces="+pieces+"&enigma_date="+document.getElementById("enigma_date").value+"&enigma_description="+document.getElementById("enigma_description").value+"&enigma_hitmax="+document.getElementById("enigma_hitmax").value+"&enigma_soluce="+document.getElementById("enigma_soluce").value+"&enigma_difficulty="+document.getElementById("enigma_difficulty").value;
	
	//instanciation dun objet XMLHttpRequest
  	var httpRequest = GetHttpObject();
  	if (httpRequest)
	{
   		//on attache un handler pour lévénement, qui rempliera les données 
   		httpRequest.onreadystatechange=function(){
	    	if (httpRequest.readyState == 4){
	     		if (httpRequest.status == 200)
				{
					alert("enigme cree");
					header_page_change("_admin_enigma.php");
				}
			}
    	}
	}

  	httpRequest.open("POST", "../ajax.php?fonction=admin_enigma_create", true);
  	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  	httpRequest.send(data);
}

