var u='Anonymous User'
var ue='Anonymous User'
var p='0';


var numero_grille="1";

function setNumeroGrille(i)
{
   numero_grille=i;
}

// var div = window.document.getElementById('container');

var uriCourant = document.location.pathname; 


if( uriCourant.substr(uriCourant.length-1,1) == "/")
{	
	uriCourant=uriCourant.substr(0,uriCourant.length-1);
}
else if ( uriCourant.substr(uriCourant.length-11,11) == "/index_html")
{	
	uriCourant=uriCourant.substr(0,uriCourant.length-11);
}
indiceDepart = uriCourant.lastIndexOf('/')+1; //
indiceArrivee = uriCourant.length; //
var nomPage = uriCourant.substring(indiceDepart, indiceArrivee); 


var handleSuccess = function(o){
	YAHOO.log("The success handler was called.  tId: " + o.tId + ".", "info", "example");
	if(o.responseText !== undefined){
	/*
		div.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
		div.innerHTML += "<li>HTTP status: " + o.status + "</li>";
		div.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
		div.innerHTML += "<li>HTTP headers received: <ul>" + o.getAllResponseHeaders + "</ul></li>";
		div.innerHTML += "<li>PHP response: " + o.responseText + "</li>";
		div.innerHTML += "<li>Argument object: Array ([0] => " + o.argument[0] +
						 " [1] => " + o.argument[1] + " )</li>";
	*/
		//**
		decode(o.responseText);
		//**
	}
};

var handleFailure = function(o){

/*
	if(o.responseText !== undefined){
		div.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
		div.innerHTML += "<li>HTTP status: " + o.status + "</li>";
		div.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
	}
	else
		{
			div.innerHTML += "<li>TIME OUT ?1?</li>";
		}
		*/
};

var callback =
{
  success:handleSuccess,
  failure:handleFailure,
  argument:['foo','bar'],
  timeout: 1500
};



function makeRequest(iUrl, postData){

	var request = YAHOO.util.Connect.asyncRequest('POST', iUrl, callback, postData);

	YAHOO.log("Initiating request; tId: " + request.tId + ".", "info", "example");

}

function refresh()
{ 
	location.reload(true);

}

function autoAutoRequest()
{

    if (nomPage == "partie")
    {
    	autoRequest("jeu","p="+p);
    }
    if (nomPage == "invitation")
    {
    	autoRequest("statut_prepartie","pp=0");
    	autoRequest("joueurs_prepartie","pp=0");
    }

    autoRequest('statut');
    autoRequest('invitations');

}

function autoRequest(iUrl, postData){

	makeRequest(iUrl, postData);
	setTimeout("autoRequest('"+iUrl+"','"+postData+"')",5000);

}

function affiche_scores(scores_aff_new)
{

	if (scores_aff != scores_aff_new)
	{
	
		scores_aff = scores_aff_new
		i=1
		pos = -1;
		
		elementScore = window.document.getElementById("score"+i.toString());
		while (elementScore != null)
		{
		
			pos2 = scores_aff.indexOf("|",pos+1);
			elementScore.innerHTML = scores_aff.substr(pos+1,pos2-pos-1);
			pos = pos2;			
			i++
			elementScore = window.document.getElementById("score"+i.toString());
		} 
	}
}

function affiche_bonus_malus(points_bonus_malus_aff_new) 
{

        if (points_bonus_malus_aff != points_bonus_malus_aff_new)
	{
	
		points_bonus_malus_aff = points_bonus_malus_aff_new
		i=1
		pos = -1;
		
		elementPtsBonus = window.document.getElementById("pts_bonus"+i.toString());
		
		pts="";
		
		while (elementPtsBonus != null)
		{
			pos2 = points_bonus_malus_aff.indexOf("|",pos+1);
			pts=points_bonus_malus_aff.substr(pos+1,pos2-pos-1);
			elementPtsBonus.innerHTML = pts;
			pos = pos2;			
			i++
			elementPtsBonus = window.document.getElementById("pts_bonus"+i.toString());
		} 
	}
}

function affiche_points_avant(points_points_avant_aff_new) 
{

        if (points_avant_aff != points_avant_aff_new)
	{
	
		points_avant_aff = points_avant_aff_new
		i=1
		pos = -1;
		
		elementPtsAvant = window.document.getElementById("pts_avant"+i.toString());
		
		while (elementPtsAvant != null)
		{
			pos2 = points_avant_aff.indexOf("|",pos+1);
			elementPtsAvant.innerHTML = "("+points_avant_aff.substr(pos+1,pos2-pos-1)+")";
			pos = pos2;			
			i++
			elementPtsAvant = window.document.getElementById("pts_avant"+i.toString());
		} 
	}
}


function affiche_tempsJeu(tempsJeu_aff_new)
{

	if (tempsJeu_aff != tempsJeu_aff_new)
	{
	
		tempsJeu_aff = tempsJeu_aff_new
		i=1
		pos = -1;
		
		elementTempsJeu = window.document.getElementById("tempsJeu"+i.toString());
		while (elementTempsJeu != null)
		{
		
			pos2 = tempsJeu_aff.indexOf("|",pos+1);
			if (pos2 != -1)
			{
				elementTempsJeu.innerHTML = tempsJeu_aff.substr(pos+1,pos2-pos-1);	
			}
			pos = pos2;		
			i++
			elementTempsJeu = window.document.getElementById("tempsJeu"+i.toString());
		} 
	}
}

function affiche_abandon(abandon_aff_new)
{

                element_abandon_msg = window.document.getElementById("abandon_msg");
                element_abandon_msg.innerHTML="" 

	if (abandon_aff != abandon_aff_new)
	{
	
		abandon_aff = abandon_aff_new

		i=1
		pos = -1;
		

		elementJoueur = window.document.getElementById("joueur"+i.toString());
		while (elementJoueur != null)
		{
		
			pos2 = abandon_aff.indexOf("|",pos+1);
			if (abandon_aff.substr(pos+1,pos2-pos-1) == "1")
			{
				if (elementJoueur.style.color!='red')
                                {
				    elementJoueur.style.color='red';
                                    element_abandon_msg.innerHTML=element_abandon_msg.innerHTML+" "+elementJoueur.innerHTML +" has abandoned the game! " ; 
                                }
			}
			pos = pos2;			
			i++
			elementJoueur = window.document.getElementById("joueur"+i.toString());
		} 
	}
	else
	{
		element_abandon_msg.innerHTML="&nbsp;"; 
	}
}


function affiche_bouton_abandonner(bouton_abandonner_new)
{

	if (bouton_abandonner != bouton_abandonner_new)
	{
		bouton_abandonner=bouton_abandonner_new;
		elementAbandonner = window.document.getElementById("abandonner");
		if (bouton_abandonner == "1")
		{
			elementAbandonner.style.display="";
		}
		else
		{
			elementAbandonner.style.display="None";
		}
	}
}



var scores_aff;
var tempsJeu_aff;
var abandon_aff;
var egaliteVainq_aff;
var points_bonus_malus_aff;
var points_avant_aff;
var bouton_abandonner="0";

var bgcBase = new Array();
var bgc = bgcBase.slice();

var bgcStr = new String();

var clicable = false;
var ordre = 0;

var x = new Array();
//alert(x.toString());
//alert(x.length);
var i=0;
for (i=0;i<x.length;i++)
{
//alert(x[i]);
}

var y = new String("000100000");
//alert(y.length);

function decode(response)
{
        type = response.substr(0,5);
        response = response.substr(5);
        
        if (type == '[jeu]')
	{
	    decode_jeu(response);
	}
        else if (type == '[inv]')
	{
	    decode_invitations(response);
	}
        else if (type == '[sta]')
	{
	    decode_statut(response);
	}
        else if (type == '[rec]')
	{
	    decode_rechercher(response);
	}
	else if (type == '[ann]')
	{
	    window.location="annuler";
	}
	else if (type == '[req]')
	{
	    decode_requete(response);
	}
	else if (type == '[jpr]')
	{
	    decode_joueurs_prepartie(response);
	}
	else if (type == '[spp]')
	{
	    decode_statut_prepartie(response);
	}
	else if (type == '[ins]')
	{
	    decode_inscription(response);
	}
	else if (type == '[cap]')
	{
	    decode_captcha(response);
	}
	else if (type == '[ctz]')
	{
	    decode_ctz(response);
	}
	else if (type == '[cnx]')
	{
	    decode_cnx(response);
	}
	else if (type == '[con]')
	{
	    decode_contact(response);
	}
}


function decode_jeu(response)
{

	pos = response.indexOf(";");
	y = response.substr(0,pos);
	pos2 = response.indexOf(";",pos+1);
	clicableStr = response.substr(pos+1,pos2-pos-1);
	pos3 = response.indexOf(";",pos2+1);
	newBgcStr = response.substr(pos2+1,pos3-pos2-1);
	resetBgc(newBgcStr);
	pos4 = response.indexOf(";",pos3+1);
        joueurCourant = response.substr(pos3+1,pos4-pos3-1);
	pos5 = response.indexOf(";",pos4+1);
        tempsRestant = response.substr(pos4+1,pos5-pos4-1);
	pos6 = response.indexOf(";",pos5+1);
        terminee = response.substr(pos5+1,pos6-pos5-1);
	pos7 = response.indexOf(";",pos6+1);
        scores_aff_new = response.substr(pos6+1,pos7-pos6-1);
        affiche_scores(scores_aff_new)
	pos8 = response.indexOf(";",pos7+1);
        tempsJeu_aff_new = response.substr(pos7+1,pos8-pos7-1);
        affiche_tempsJeu(tempsJeu_aff_new)
	pos9 = response.indexOf(";",pos8+1);
        abandon_aff_new = response.substr(pos8+1,pos9-pos8-1);
        affiche_abandon(abandon_aff_new)
	pos10 = response.indexOf(";",pos9+1);
        egaliteVainq_aff = response.substr(pos9+1,pos10-pos9-1);
        
	pos11 = response.indexOf(";",pos10+1);
        bouton_abandonner_new = response.substr(pos10+1,pos11-pos10-1);
        affiche_bouton_abandonner(bouton_abandonner_new)
   
	pos12 = response.indexOf(";",pos11+1);
        points_bonus_malus_aff_new = response.substr(pos11+1,pos12-pos11-1);
        affiche_bonus_malus(points_bonus_malus_aff_new)     

	pos13 = response.indexOf(";",pos12+1);
        points_avant_aff_new = response.substr(pos12+1,pos13-pos12-1);
        affiche_points_avant(points_avant_aff_new)   

  pos14 = response.indexOf(";",pos13+1);
       terminee_aff_retour = response.substr(pos13+1,pos14-pos13-1);
       affiche_terminee(terminee_aff_retour) 


    pos15 = response.indexOf(";",pos14+1);
    affiche_dernier_coup_egalisation (response.substr(pos14+1,pos15-pos14-1))

    pos16 = response.indexOf(";",pos15+1);
    affiche_vainqueur_au_temps (response.substr(pos15+1,pos16-pos15-1))
    
        
	if (clicableStr != "0")
	{
		clicable=true;
                ordre=parseInt(clicableStr);
	}
	else
	{
		clicable=false;
	}


	if (x.length != y.length )
	{
                x=y
		location.reload(); // reload la page car la grille n'est pas a la bonne taille
	}
	else
	{
	  //var newBgc = new Array();

		var i=0;
		for (i=0;i<x.length;i++)
		{
			if (x[i] != y.charAt(i))
			{
				x[i] = parseInt( y.charAt(i) );
				//newBgc[i]="yellow";
				courante(i); // + surbrillance ...
			}
		}

		//if (newBgc.length > 0)
		//{
		//	resetBgc(newBgc);
		//}
	}


	elementJoueurTour = window.document.getElementById("joueur_tour");
        if (joueurCourant != "" && tempsRestant != "")
        {
	     
	     if (parseInt(tempsRestant) >= 5)
	     {
		     elementJoueurTour.innerHTML = joueurCourant+" has to play in the next "+tempsRestant+" seconds";
		     elementJoueurTour.style.color  = 'black';
	     }
	     else
	     {
		     elementJoueurTour.innerHTML = joueurCourant+" has to play in the next seconds before being eliminated ";
		     elementJoueurTour.style.color  = 'red';
	     }
        }
        else
        {
        	     elementJoueurTour.innerHTML = "&nbsp;";
        }
        if (terminee == '1')
        {
	     elementJoueurTour = window.document.getElementById("joueur_tour");
      	     elementJoueurTour.innerHTML = "Game over";
      	     
      	     if (egaliteVainq_aff=="0")
      	     {
      	     	elementJoueurTour.innerHTML=elementJoueurTour.innerHTML+" - TIE game"
      	     }
      	     else
      	     {
      	     	elementJoueurTour.innerHTML=elementJoueurTour.innerHTML+" - Winner: "+egaliteVainq_aff
      	     }
        }

}


var dernier_coup_egalisation_aff='0'

function affiche_dernier_coup_egalisation(dernier_coup_egalisation) 
{
	element=window.document.getElementById('dernier_coup_egalisation')
	element2=window.document.getElementById('dernier_coup_egalisation2')
	
   if (dernier_coup_egalisation != dernier_coup_egalisation_aff)
   {
   		dernier_coup_egalisation_aff=dernier_coup_egalisation
  
   		if (dernier_coup_egalisation == '1')
   		{
   			element.style.display="";
   			element2.style.display="None";
   		}
   		else if (dernier_coup_egalisation == '2')
   		{
				element.style.display="None";
   			element2.style.display="";
   		}
   		else
   		{
   			element.style.display="none";
   			element2.style.display="None";
   		}
   		
   }

}

var vainqueur_au_temps_aff = ""
function affiche_vainqueur_au_temps(vainqueur_au_temps)
{
  if (vainqueur_au_temps != vainqueur_au_temps_aff)   
  {
  	vainqueur_au_temps_aff = vainqueur_au_temps
  	if (vainqueur_au_temps == "1")
  	{
  		window.document.getElementById('vainqueur_au_temps').style.display="";
  	}
  	else
  	{
  		window.document.getElementById('vainqueur_au_temps').style.display="none";
  	}
  }
}

function affiche_terminee(terminee) 
{
   if (terminee == 't')
   {
			element = window.document.getElementById('retour');
			element.style.display="";
   }
   else
   {
			element = window.document.getElementById('retour');
			element.style.display="None";
   }
}

var survolee = -1;

function survole(i)
{

	if (survolee != -1)
	{
			courante(survolee);
	}

	if (clicable)
	{
		//alert(x[i]);
		if (x[i] == 0)
		{
		
				element = window.document.getElementById('i'+numero_grille+'_'+i.toString());
				element.src = symbole(ordre);
				element2 = window.document.getElementById('t'+numero_grille+'_'+i.toString());
				element2.style.backgroundColor  = '#AAAAFF';
				survolee=i;
				document.body.style.cursor = 'pointer';
		}
	}
}

function courante(i)
{
	document.body.style.cursor = 'default';
	// remet la case i a sa valeur courante
	element = window.document.getElementById('i'+numero_grille+'_'+i.toString());
	var value=symbole(x[i]);

	element.src=value;
	
	element2 = window.document.getElementById('t'+numero_grille+'_'+i.toString());
	element2.style.backgroundColor  = couleur(i);

}

function symbole(k)
{
	var value="";
   	switch (k)
	{
		case 0: value = 'img/vide2'; break;
		case 1: value = 'img/croix';      break;
		case 2: value = 'img/rond';      break;
		case 3: value = 'img/carre';      break;
		case 4: value = 'img/triangle';      break;
		case 5: value = 'img/etoile';      break;
		case 6: value = 'img/diese';      break;
		// etc ...
	}
        return value;
}

function clic(i)
{
	if (clicable && x[i] == 0)
	{
		//alert(clicable);
		// requete POST
		clicable=false;
		makeRequest("jeu","p="+p+"&clic="+i.toString());
	}
}



function resetBgc(newBgcStr)
{
	if (newBgcStr != bgcStr)
	{
		var i=0;
		for (i=0;i<bgc.length;i++)
		{
       if (bgc[i]!=0)
       {
       	 element = window.document.getElementById('t'+numero_grille+'_'+i.toString());
       	 element.style.backgroundColor  = 'white';
       }
		}
		bgc = bgcBase.slice();
		for (i=0;i<newBgcStr.length;i++)
		{
			 bgc[i]=parseInt(newBgcStr.charAt(i));
       if (bgc[i]!=0)
       {
	       	 element = window.document.getElementById('t'+numero_grille+'_'+i.toString());
	       	 element.style.backgroundColor  = couleur(i);
	       }
		}
		bgcStr=newBgcStr;
	}

}

function couleur(i)
{
	  value = "";

	  switch (bgc[i])
		{
			case 0: value = 'white';      break;
			case 1: value = 'yellow';      break;
			case 2: value = '#BFFFBF';      break;

			// etc ...
		}
		return value;
}





function decode_statut(response)
{

    if (response != "")
    {
       if (window.location != response)
       {
	       window.location=response;
	}
    }
        
 }


function annuler()
{
    makeRequest("annuler_prepartie");
}


function abandon()
{
	// requete POST
	clicable=false;
	makeRequest("jeu","p="+p+"&abandon=1");
}

function init_aff()
{
	try
	{
		i=1
		element = window.document.getElementById('symbole'+i.toString());
		while (element != null)
		{
			element.src = symbole(i);			
			i++
			element = window.document.getElementById("symbole"+i.toString());
		}		
		element = window.document.getElementById('retour');
		element.style.display="none";
					
	}
	catch(err)
	{
		
	}

	
}

		
function recherche()
{
champ=window.document.getElementById('recherche');

  //if (champ.value.length >= 3)
  //{
      makeRequest("recherche_joueurs","r="+champ.value);
  //}
}

var joueurs_invit = new Array();

function ajoute_joueur(j)
{
   if (joueurs_invit.length >= 10){ return; }
   for (i=0;i<joueurs_invit.length;i++)
   {
       if (joueurs_invit[i] == j){ return; }
   }
   joueurs_invit.push(j);
   affiche_joueurs_invit()
}

function enleve_joueur(j)
{
     tmp=joueurs_invit
     joueurs_invit=[]
     i=0;
     for (i=0;i<tmp.length;i++)
     {
      if (i != j)
      {
         joueurs_invit.push(tmp[i])
      }
     }
     affiche_joueurs_invit()
}

function affiche_joueurs_invit()
{
   champ=window.document.getElementById('invit_joueurs');  
   texte=""
   i=0;
   for (i=0;i<joueurs_invit.length;i++)
   {
        texte=texte+"<li>"+joueurs_invit[i];
        if (joueurs_invit[i] != u && joueurs_invit[i] != ue)
        {
             texte=texte+" <img style='cursor: pointer; ' src='img/icons/delete' alt='remove' onclick='javascript:enleve_joueur(\""+i.toString()+"\")  ' />"
        }
        texte=texte+"</li>";
   }
   champ.innerHTML=texte;
}



function affichage_utilisateur(response,pos,pos2,pos0)
{
              l=""
              if ( response.substr(pos2+1,pos-pos2-1) == "DIS")
              { l="<img alt='available' src='img/icons/bullet_green' width=16 height=16/>"+l; }
              else if ( response.substr(pos2+1,pos-pos2-1) == "ND")
              { l="<img alt='not available' src='img/icons/bullet_yellow' width=16 height=16/>"+l; }
              else if ( response.substr(pos2+1,pos-pos2-1) == "NC")
              { l="<img alt='off line' src='img/icons/bullet_red' width=16 height=16/>"+l; }
              else
              { l="<img alt='' src='img/vide2' width=16 height=16/>"+l; }
//
              l=l+response.substr(pos0,pos2-pos0); 
// pour prepartie invitation
              if ( response.substr(pos2+1,pos-pos2-1) == "OK")
              { l=l+" <img alt='accepted invitation' src='img/icons/accept' width=16 height=16/>"; }
              if ( response.substr(pos2+1,pos-pos2-1) == "NON")
              { l=l+" <img alt='refused invitation' src='img/icons/cross' width=16 height=16/>"; }
//
   return l;

}

function decode_rechercher(response)
{

    //if (response != "")
    //{
        pos0 = 0;
	pos = response.indexOf("|");
 
        t="";

        while (pos != -1)
        { 
            pos2=response.indexOf(":",pos0)
            if (pos2 != -1)
            {
              l=affichage_utilisateur(response,pos,pos2,pos0)

              l=l+" <img style='cursor: pointer; ' src='img/icons/add' alt='add' onclick='javascript:ajoute_joueur(\""+response.substr(pos0,pos2-pos0)+"\")  ' />"
              t=t+"<li>"+l+"</li>";
              pos0 = pos+1;
       	      pos = response.indexOf("|",pos+1);
            }
            
        }
        window.document.getElementById('joueurs_recherche').innerHTML=t; 
   // }
        
 }

var error_id = "";

function decode_requete(response)
{
   if (error_id != "")
   {
      window.document.getElementById(error_id).innerHTML="";
   }
   pos = response.indexOf(":");
   if (pos!=-1)
   {
      error_id='error_'+response.substr(0,pos);
      window.document.getElementById('error_'+response.substr(0,pos)).innerHTML=response.substr(pos+1);
   }   

   if (response==""){ window.location="invitation_lancee"; }
}

joueurs_inner=""

var encours=false;
var encours_def=false;

function decode_joueurs_prepartie(response)
{

    if (response != "")
    {
        pos0 = 0;
	pos = response.indexOf("|");
 
        t="";

        while (pos != -1)
        { 
            pos2=response.indexOf(":",pos0)
            if (pos2 != -1)
            {
              l=affichage_utilisateur(response,pos,pos2,pos0)
              t=t+"<li>"+l+"</li>";

  	      elementAccepter = window.document.getElementById('accepter');
  	      elementRefuser = window.document.getElementById('refuser');

              if ( response.substr(pos0,pos2-pos0) == u && encours_def )
              {
                 if ( response.substr(pos2+1,pos-pos2-1) == "NON" || !encours )                  
                 { elementAccepter.style.display="None"; elementRefuser.style.display="None"; }
                 else if ( response.substr(pos2+1,pos-pos2-1) == "OK")                  
                 { elementAccepter.style.display="None"; elementRefuser.style.display=""; }
                 else
                 { elementAccepter.style.display=""; elementRefuser.style.display=""; }
              }


              pos0 = pos+1;
       	      pos = response.indexOf("|",pos+1);
            }
            
        }
        if ( joueurs_inner!=t ) 
        {
           joueurs_inner=t;
           window.document.getElementById('joueurs').innerHTML=t; 
        }
    }
        
}
function accepter()
{
        elementAccepter.style.display="None"; elementRefuser.style.display="None";
    	makeRequest("accepter_invitation","p=0");
}
function refuser()
{
        elementAccepter.style.display="None"; elementRefuser.style.display="None";
    	makeRequest("refuser_invitation","p=0");
}



var statut_invitation_inner = "";

function decode_statut_prepartie(response)
{


   elementRetour = window.document.getElementById('retour2');

      if (response != "")
    {
        s=response.substr(0,1)


        if (s=="0"){   elementRetour.style.display="";}
        else      {   elementRetour.style.display="None"; }

        response=response.substr(1)

        t="";
        encours=false;
        encours_def=true;

        if (response == 'a'){t="Game canceled"; }
        else if (response.substr(0,1) == 'e'){t="Partie Ã  venir ("+response.substr(1)+")"}
        else if (response == 'l'){t="Partie started";}
        else if (response.substr(0,1) == 'd' && parseInt(response.substr(1)) >= 0 ){encours=true; t="Answer of the players expected before "+response.substr(1)+" seconds."}
        if ( statut_invitation_inner!=t ) 
        {
           statut_invitation_inner=t;
           window.document.getElementById('statut_invitation').innerHTML=t; 
        }

    } 
        
}


