/* liste des personnages sélectionnés */
var selection = [];

/* destination des personnages en mouvement */
var destinations = [];

var espaceEntrePersonnage = 6;
var largeurTotale = 530;
var nb = 0;
var nbPersonnagesMax = 10;
var cheminPictos = "";
var readonly = false;
var walk = true;
var walkStep = 5;
var nbMoving = 0;

var persos = [ { picto : "homme",  largeur: 30}, 
               { picto : "femme",  largeur: 26},
               { picto : "garcon", largeur: 24}, 
               { picto : "fille",  largeur: 28}, 
               { picto : "bebe" ,  largeur: 26}, 
               { picto : "chien",  largeur: 38}
             ];


function checkFormFamille()
{
	if( selection.length == 0 )
	{
		alert('Merci de sélectionner les membres de votre famille');
		return false;
	}
	
	var persos = "";
	
	var nbAdultes = 0;
	
	for(var i = 0; i < selection.length; i ++ )
	{
		if( persos.length > 0 )
		{
			persos += ",";
		}
		
		if( selection[i].qui == 'homme' || selection[i].qui == 'femme' )
		{
			nbAdultes ++;
		}
		
		persos += selection[i].qui;
	}
	
	if( nbAdultes == 0 )
	{
		alert('Merci de sélectionner un adulte');
		return false;
	}
	
	EL('persosForm').persos.value = persos;
	
	return true;
}

function loadSelection(persos)
{
	var p = persos.split(',');
	
	var tempo = 700;
	
	for(var i = 0; i < p.length; i ++ )
	{
		setTimeout("addPersonnage('" + p[i] + "')" , tempo * (i+1));
	}
}

function getLargeurPicto(picto)
{
	for(var i = 0; i < persos.length; i ++ )
	{
		var perso = persos[i];
		
		if( picto == perso.picto )
		{
			return perso.largeur;
		}
	}
}

function preloadImages()
{
	for(var i = 0; i < persos.length; i ++ )
	{
		var perso = persos[i];
		
		preloadImage(cheminPictos + "p-" + perso.picto + ".gif");
		
		if( walk )
		{
			preloadImage(cheminPictos + "p-" + perso.picto + "-walk.gif");
			preloadImage(cheminPictos + "p-" + perso.picto + "-walk-gauche.gif");
		}
	}
}


/**
 * Retourne la position ou doit etre placé le personnage à l'index.
 * Si pas d'index passé, retourne la position du dernier personnage ajouté
 * Cette position est calculée de telle façon que l'ensemble des personnages est centré dans la zone
 */
function getPositionPersonnage(index)
{	
	var milieu = largeurTotale / 2;
	
	var totalWidth = 0;
	
	for(var i = 0; i < selection.length; i ++ )
	{
		//totalWidth += selection[i].clientWidth;					
		totalWidth += getLargeurPicto(selection[i].qui);					
	}
	

	
	if( index == null )
	{
		totalWidth += espaceEntrePersonnage * selection.length - 1;
		
		milieu -= totalWidth / 2;
		
		return milieu;
	}
	else
	{
		totalWidth += espaceEntrePersonnage * index;
		
		var left = 0;
		
		for(var i = selection.length - 1; i > index; i -- )
		{
			//left += parseCssInt(selection[i].firstChild.clientWidth);
			left += getLargeurPicto(selection[i].qui);
			left += espaceEntrePersonnage / 2;				
		}
		
		milieu -= totalWidth / 2;
		
		return milieu + left;
	}
}

function addPersonnage(perso)
{
	if( selection.length >= nbPersonnagesMax )
	{
		return;
	}
	
	var img = document.createElement("img");
	img.src = cheminPictos + "p-" + perso + ".gif" 
	
	var span = document.createElement("span");
	span.appendChild(img);
	//span.style.marginLeft = "-40px";
	span.style.marginLeft = "-" + getLargeurPicto(perso) + "px";
	if( readonly )
	{
		span.style.cursor = "default";
	}
	else
	{
		span.onclick = function() { removePersonnage(span); } ;
	}
	span.id = "perso-" + nb;
	span.qui = perso;
	
	nb++;
	
	EL('resultat').insertBefore(span, EL('resultat').firstChild);
	
	selection.push(span);
	
	movePersonnages();		
	
	return span.id;
}

var waitingListe = [];

function addPersonnages()
{
	if( nbMoving > 0 )
	{
		return;
	}
	
	var current = [];
	
	for(var i = 0; i < selection.length; i ++ )
	{
		current.push(selection[i]);		
	}
	
	for(var i = 0; i < current.length; i ++ )
	{
		removePersonnage(current[i], true);
	}
	
	movePersonnages();
	
	for(var i = 0; i < addPersonnages.arguments.length ; i ++ )
	{
		var p = addPersonnages.arguments[i];
		
		if( i == 0 )
		{
			waitingListe.push(addPersonnage(p));
		}
		else
		{
			waitingListe.push(p);
		}
	}
	
	synchronisePersonnages();
	
}

function synchronisePersonnages()
{
	var ref;
	
	if( waitingListe.length == 0 )
	{
		return;
	}
	
	var finish = true;
	
	for(var i = 0; i < waitingListe.length; i ++ )
	{
		var p = waitingListe[i];
		
		if( p.indexOf('perso') > -1 )
		{
			ref = p;
		}
		else
		{
				finish = false;
				var next = waitingListe[i];
				
				var span = EL(ref);
	
				var position = parseCssInt(span.style.marginLeft);
				
				if( position > -10 )
				{
					var id = addPersonnage(next);
					waitingListe[i] = id;
				}
				
				break;
			}
	}
	
	if( !finish )
	{
		setTimeout( synchronisePersonnages , 100);
	}
}

function removePersonnage(span, dontMove)
{
	if( destinations[span.id] != null )
	{
		return;
	}
	
	movePersonnage(span, largeurTotale + 20);
	
	var persoIdx = getPersonnageIndex(span);
	
	selection = removeArrayEntry(selection, persoIdx);
	
	if( !dontMove )
	{
		movePersonnages();
	}
}

function getPersonnageIndex(span)
{
	for(var i = 0; i < selection.length; i++)
	{
		if( selection[i] == span )
		{
			return i;
		}
	}
	
	return -1;
}

function removeArrayEntry(array, index)
{
	var newarray = [];
	
	for(var i = 0; i < array.length; i ++ )
	{
		if( i == index )
		{
			continue;
		}
		
		newarray.push(array[i]);			
	}
	
	return newarray;
}

function movePersonnages()
{
	for(var i = 0; i < selection.length; i ++ )
	{
		var perso = selection[i];
		
		var position = parseCssInt(perso.style.marginLeft);
		
		var destination = getPositionPersonnage(i);
		
		/* Si le personnage est immobile et qu'il n'est pas au bon endroit, on le déplace vers la bonne position */
		if( destinations[perso.id] == null && position != destination )
		{
			movePersonnage(perso, destination);
		}
		/* Sinon (s'il bouge déjà par exemple) on mets simplement à jour sa destination */
		else
		{
			destinations[perso.id] = destination;
		}
	}
}

function changeImagePersonnage(obj, walking, droite)
{
	var img = obj.firstChild.src;
	
	var idx = img.indexOf(".gif");
	
	if( !walk )
	{
		return;
	}
	
	if( walking )
	{
		if( img.indexOf('walk') == - 1)
		{
			droite = droite ? "" : "-gauche";
			
			obj.saveImg = img;
			img = img.substring(0, idx) + "-walk" + droite + ".gif";
		}		
	}
	else
	{
		img = obj.saveImg;
	}
	
	obj.firstChild.src = img;
	obj.firstChild.width = getLargeurPicto(obj.qui);
}

function movePersonnage(obj, destination)
{
	var left = parseCssInt(obj.style.marginLeft);
	
	if( destinations[obj.id] == null )
	{
		destinations[obj.id] = destination;
		
		avance = destination > left;
		
		changeImagePersonnage(obj, true, avance);
		
		nbMoving ++;
	}
	else
	{
		destination = destinations[obj.id];
	}
	
	destination = parseInt(destination);
	
	avance = destination > left;
	
	var offset = (avance) ? walkStep : -walkStep;
	
	if( (avance && left < destination) || (!avance && left > destination) )
	{
		/* si la position actuelle + le pas est supérieur à la destination on ajuste le pas pour atteindre exactement la destination */
		if( avance && (left + offset > destination) || (!avance && (left + offset < destination))  )
		{
			offset = destination - left;
		}
		
		var nouvellePosition = (left + offset);
		
		var pictoWidth = getLargeurPicto(obj.qui);
		
		/* Gestion du clipping pour l'entrée et la sortie des personnages */
		if( nouvellePosition < pictoWidth )
		{
			obj.style.clip = 'rect(0px ' + pictoWidth +'px ' + obj.clientHeight +'px ' + ( -nouvellePosition )  + 'px)';
		}
		else if( nouvellePosition + pictoWidth > largeurTotale )
		{
			//obj.style.clip = 'rect(0px ' + ( pictoWidth - (nouvellePosition + pictoWidth - largeurTotale) - offset ) + 'px ' + obj.clientHeight +'px 0px)';
			obj.style.clip = 'rect(0px ' + ( largeurTotale - left - offset ) + 'px ' + obj.clientHeight +'px 0px)';
		}				
		else
		{
			obj.style.clip = 'rect(0px ' + pictoWidth +'px ' + obj.clientHeight +'px 0px)';
		}
		
		obj.style.marginLeft = nouvellePosition + "px";
	}
	
	/* si le perso n'est pas sur sa destination, on rappelle la méthode  */
	if( (avance && left < destination) || (!avance && left > destination) )
	{
		setTimeout(function() {movePersonnage(obj, destination)}, 50);
	}	
	/* sinon on positionne sa destination à null */
	else
	{
		destinations[obj.id] = null;
		changeImagePersonnage(obj, false);
		nbMoving--;
	}		
}